Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
in django ecommerce project, the question is I can't display category and sub category in template html
how can display category and sub category in product template what is missing in bellow code this is a part of View.py according product view, shows filtering category and subcategory from model.py class ProductView(View): def get(self,request,*args,**kwargs): categories=Categories.objects.filter(is_active=1) categories_list=[] for category in categories: sub_category=SubCategories.objects.filter(is_active=1,category_id=category.id) categories_list.append({"category":category,"sub_category":sub_category}) merchant_users=MerchantUser.objects.filter(auth_user_id__is_active=True) return render(request,"admin_templates/product_create.html",{"categories":categories_list,"merchant_users":merchant_users}) this is part of model.py according model after migrate, class Products(models.Model): id=models.AutoField(primary_key=True) url_slug=models.CharField(max_length=255) subcategories_id=models.ForeignKey(SubCategories,on_delete=models.CASCADE) product_name=models.CharField(max_length=255) brand=models.CharField(max_length=255, default="") product_max_price=models.CharField(max_length=255) product_discount_price=models.CharField(max_length=255) product_description=models.TextField() productTemplate.html <div class="col-lg-6"> <label>Category</label> <select name="sub_category" class="form-control"> {% for category in categories %} <optgroup label={{ category.category.title }}> {% for sub_cat in category.sub_category %} <option value="{{ sub_cat.id }}">{{ sub_cat.title }}</option> {% endfor %} </optgroup> {% endfor %} </select> </div> -
Can we use longest common subsequene algorithm(LCS) for searches?
LCS in searches? Websites like olx which has search bar to search item for buyer.So,like that if i want build some application which is similar to olx.Can i use LCS for searching any item?if no,what else can you all suggest? -
Weaseyprint, Cairo, Dajngo on Pythonanywhere 25MAY21 can not pass a warning
Sorry I know there seems to be a lot about this topic. But I do not see a real resolution? I am trying to place a Django ecommerce pizza shop for learning Django on the website. Locally this works great no issues. I matched my environment locally to that on the ENV for the server. I got this issue resolved locally when I updated Cairo on my computer. So the emulated server works great. Python 3.8.0 Server Pythonanywhere Here is the error and follow on info. Error from error log on ther server. 2021-05-28 16:13:41,156: /home/williamc1jones/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/weasyprint/document.py:35: UserWarning: There are known rendering problems and missing features with cairo < 1.15.4. WeasyPrint may work with older versions, but please read the note about the needed cairo version on the "Install" page of the documentation before reporting bugs. http://weasyprint.readthedocs.io/en/latest/install.html views.py file in order app import weasyprint from django.urls import reverse from django.shortcuts import render, redirect from django.contrib.admin.views.decorators import staff_member_required from django.shortcuts import get_object_or_404 from django.conf import settings from django.http import HttpResponse from django.template.loader import render_to_string from cart.cart import Cart from .models import OrderItem, Order from .forms import OrderCreateForm from .tasks import order_created def order_create(request): cart = Cart(request) if request.method == 'POST': form = … -
I'm trying to get my data from database in React-Native app
If I put .then(data =>{console.log(data)}), I can see the data but is not displayed in my app. What should I do? Thanks function Home(props) { const [data, setData] = useState([]); const [loading, setLoading] = useState(true); const loadData = () => { fetch(url, { method: "GET" }) .then(resp => resp.json()) .then(data => { setData(data) setLoading(false) }) .catch(error => Alert.alert('error', error.message)) }; useEffect(() => { loadData(); }, []) {/* return ( <View style={styles.homeText}> <FlatList data={data} renderItem={({ item }) => { return renderData(item) }} onRefresh={() => loadData()} refreshing={loading} keyExtractor={item => `${item.id}`} /> )} My model in Django view is: view.py class MeasurementsViewSets(viewsets.ModelViewSet): queryset = Measurements.objects.all() serializer_class = MeasurementsSerializer My urls.py is: router = DefaultRouter() router.register('measurements', MeasurementsViewSets) #router.register(r'measurements', views.MeasurementsViewSets) // this doesn't work either In Django I get: "GET /api/measurements/ HTTP/1.1" 200 -
ckeditor upload image option not showing up in django
I know this question has been asked many times and I have tried to apply the solutions. Still, the image upload option won't show up and allow me to upload an image in my post. Please help on how to fix this here are the files: settings.py INSTALLED_APPS = [ 'jobs_app', 'django_extensions', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'ckeditor_uploader', ] STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') CKEDITOR_UPLOAD_PATH = 'uploads/' urls.py from django.conf import settings from django.conf.urls.static import static from django.urls import path from django.conf.urls import include from . import views urlpatterns = [ path('', views.home, name="home"), path('login/', views.user_login, name="login"), path('ckeditor', include('ckeditor_uploader.urls')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to close a css stylesheet?
I am working on a project which uses multiple templates. This means I have to load multiple stylesheets in my project. A lot of them are copied from the internet. Some of these css stylesheets have overlapping styling like more than 1 sheets will contain styling for a p or a body tag. And if I load one css sheet I only want it to work on a part of website and then close itself. However I cant find a way to close a stylesheet. -
Django migration is creating extra table
I am beginner for Django and i am working on my final year project but i am stuck at one thing. here is my model.py class MatchList(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="user") matches = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="matches") class Meta: app_label = "matchsystem" Also my here is my migration file as well. class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='MatchRequest', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('is_active', models.BooleanField(default=True)), ('times_tamp', models.DateTimeField(auto_now_add=True)), ('receiver', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='receiver', to=settings.AUTH_USER_MODEL)), ('sender', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sender', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='MatchList', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('matches', models.ManyToManyField(blank=True, related_name='matches', to=settings.AUTH_USER_MODEL)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='user', to=settings.AUTH_USER_MODEL)), ], ), ] but when i migrate the data it create an extra table with added name. I want the first table but it doesnt have the correct columns Any response is much appricated. -
Django Template Language Shows Up In Webpage
My Django template language tags are showing up when the webpage is run on the test server. Does anyone know why that may be happening? (Everything else on the webpage is displaying properly, and the tags are even doing their jobs. I just don't know why the text is there. The page's html: <% extends "base.html" %> <% block page_title %> Challenges <% endblock %> <% block content %> <ul> {% for month in months%} <li> <a href="{% url 'month-challenge' month %}">{{month|title}} </a></li> {% endfor %} </ul> <% endblock %> The template that the page is inheriting from: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block page_title %} {% endblock %}</title> </head> <body> {% block content %} {% endblock %} </body> </html> What the output looks like: I've looked at similar posts on here and none of those fixes seemed to apply here (opening the html doc directly, Leaving a space between the { and %, etc. -
Unable to authenticate using factory-boy Django
I'm quite new to factory-boy and I'm trying to send a request to an API endpoint in my unit test, which requires a user to be authenticated. I've looked at a few examples online and this is what I've come up with so far in my unit test: test_user.py class UserFactory(factory.Factory): class Meta: model = user username = factory.LazyAttribute(lambda t: "myuser") password = factory.PostGenerationMethodCall('set_password', 'my_super_secret') is_staff = True is_active = True class UserViewSetTest(TestCase): def setUp(self): pwd = 'my_super_secret' self.user = UserFactory(password=pwd) self.client = Client() self.assertTrue(self.client.login(username=self.user.username, password=pwd)) def test_user_list(self): response = self.client.get(reverse('user', kwargs={'fromdate': '2017-01-01', 'todate': '2017-04-01'})), format='json') self.assertEqual(response.status_code, 200) The initial error is the fact that this assertion self.assertTrue(self.client.login(username=self.user.username, password=pwd)) is false so the test fails right away. Even if I remove that line, the API call returns a 401 because the authentication isn't successful. How can I successfully authenticate a user in this API call with factory-boy? -
Use existing django users with Auth0
I'm trying to connect Auth0 with django, but I want to use the users that already exists in the system. I want them to sync by their email, but Auth0 creates new users. I used the Auth0 documentation to do so. https://auth0.com/docs/quickstart/webapp/django/01-login -
in python django if else not working either showing both or only the first field is showing
I am working in Django python and written these two statements to check if email or username exists in database or not but the message is coming from both email is taken and username is taken but I want it should show it seperately if enter any one if I give input in my sign up form if User.objects.filter(email=email).exists(): # error_message = '' email_error = ('', 'Email is taken. ')[User.objects.filter(email=email).exists()] messages.success(request, email_error) elif User.objects.filter(username=username).exists(): username_error = ('', 'Username is taken. ')[User.objects.filter(username=username).exists()] messages.success(request, username_error) return redirect('/register/') -
There is a link in django but not found in heroku
i have a link to admin in urls.py. i have tried to change and re deploy in heroku but it's always seems like that. but when i try in another project with same code it will running urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('api.urls')), path(r'admin/', admin.site.urls), ] but when i deploy in heroku, it says [1]: https://i.stack.imgur.com/pMllj.png this is my code in setting.py setting.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-ce0poynbkw!0s^-=1u783+utj^s$%f66@*cew&@oc==epcrdl#' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['project-2-anisa.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'api' ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ], } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'api.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'api.wsgi.application' # Database # … -
Redirecting error in Python Django while using NEXT parameter
website used to redirect as www.example.com/login/?next=/ but now its redirecting as www.example.com/login/?next=/login/ didn't make any changes in the code but now the problem has been created as throwing ERR_TOO_MANY_REDIRECTS, redirected too many times. as I was using NEXT parameter I tried changing to **@login_required(/login) to @login_required** , but changes are not reflecting, couldn't understand why, its throwing "GET /login/?next=/login/ HTTP/1.1" 302 0 have used django.contrib.auth hope someone could help, thanks in advance -
Celery doesn`t start task python django
My application doesn`t call celery task my settings.py: CLICKHOUSE_HOST = '127.0.0.1' CLICKHOUSE_PORT = '6379' CELERY_BROKER_URL = 'redis://' + CLICKHOUSE_HOST + ':' + CLICKHOUSE_PORT + '/0' CELERY_BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 60} CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = "Australia/Tasmania" CELERY_TASK_TRACK_STARTED = True CELERY_TASK_TIME_LIMIT = 30 * 60 CELERY_RESULT_BACKEND = 'django-db' CELERY_CACHE_BACKEND = 'django-cache' Here is init.py in referal_app directory: from __future__ import absolute_import from .celery import app as celery_app __all__ = ('celery_app',) Here is my view that must call celery task: class DefineView(View): def get(self, request): create_points.delay(1, 2) return render(request, 'main/homepage.html', {}) Here is my task (just test for working): from celery import shared_task from referal_app.celery import app @shared_task def create_points(a, b): with open('e:\\txt.txt', 'w') as file: for _ in range(1): file.write(f'{a + b}') return 1 Here is celery settings in referal_app directory: from __future__ import absolute_import import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'referal_app.settings') app = Celery('referal_app') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') -
How to send data from python client to Django web server?
I'd like python3 program to send JSON data to Django web server and print them on web page. This is what I have in Views.py: def receive_json(request): if request.method == 'POST': received_data = json.loads(request.body.decode("utf-8")) return StreamingHttpResponse('it was post request: ' + str(received_data)) return StreamingHttpResponse('it was get request') And the python code: import requests import json url = "http://127.0.0.1:8000/" data = {"data": [{'key1':'val1'}, {'key2':'val2'}]} headers = {'content-type':'application/json'} r = requests.post(url, data=json.dumps(data), headers=headers) r.text However, it shows this message: Forbidden (CSRF cookie not set.): / [28/May/2021 16:51:31] "POST / HTTP/1.1" 403 2864 -
Pending request on Django
I'm building a website using Django. I have the register and login sessions working, so any user can create an account and login. But now I want a situation whereby when someone creates an account, the account will be inactive and pending until the admin accepts the user. However, I haven't implemented any code that does that before and I want to know if Django has a built-in package for that. If not, how do I go about it? -
Django stop restarting the server if change in html
I created a website using django, in the webpage I linked a refresh button, when a user clicks the refresh button, it runs python script and update the static html page. But what happening is, the django server restarts after each change in the html and that leads to user unable to access during that particular time, because the service is down at that particular time. Could someone please tell me, how can I disable restarting the django if any change in html. I'm starting django server as follows. python manage.py runserver -
How to upload file to s3 bucket with django rest framework api
I am trying to upload a file to AWS bucket in Django project @api_view(['POST']) def upload_image(request): image = request.FILES['image'] file_name = request.POST.get('file_name') access_key = settings.AWS_ACCESS_KEY_ID access_secret_key = settings.AWS_SECRET_ACCESS_KEY bucket_name = settings.AWS_STORAGE_BUCKET_NAME # bucket_name value is "https://s3.region.amazonaws.com/bucket_name/sub_bucket_name/" # I am not sure if it is correct way to give bucket name where I want my file to be uploaded client_s3 = boto3.client( 's3', aws_access_key_id = access_key, aws_secret_access_key= access_secret_key ) client_s3.upload_file( file_name, bucket_name, image ) url = f'{end_point}{bucket_name}/{file_name}' return Response({'success': True, 'message': "File has been uploaded", 'url': url }, status=status.HTTP_200_OK) and this is how I am passing the file and file name to the api through the postman. The error that I am getting is - "FileNotFoundError: [Errno 2] No such file or directory: "name of file"" I have read the tutorial, It is fairly simple to uploading a file to s3 bucket with boto3. some how I am able to upload the file. -
Django Rest Framework - Delete API CORS error in production mode (OVH web cloud)
I know this is a classic issue but I did not find a solution for my particular case. All APIs work fine, while the DELETE API fails with CORS error. This happens only in production environment (OVH web cloud) This is my python backend code: class UserDetail(APIView): permission_classes = (IsAuthenticated,) def get_object(self, pk): try: return User.objects.get(pk=pk) except User.DoesNotExist: raise Http404 def get(self, request, pk, format=None): userSet = User.objects.filter(id=pk) serializer = UserSerializer(userSet, many=True) return Response(serializer.data) def post(self, request, pk, format=None): userSet = self.get_object(pk) serializer = UserUpdateSerializer(userSet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): user = self.get_object(pk) user.delete() return Response({'deleted user': pk}, status=status.HTTP_204_NO_CONTENT) This is the .htaccess file put in django root folder: If needed, I also share the response header content as displayed by the browser : -
How to access extra form field inside the model's overriden save function? DJANGO
I have a model as class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True) and form as class UserRegisterForm(UserCreationForm): email = forms.EmailField() city = forms.CharField(initial=get_location()) class Meta: model = User1 # model that is being affected is this model, .save will save to this and next is the fields to be displayed in the order fields = ['username', 'email', 'password1', 'password2', 'city'] Now when I override Profile's save method, I need to access the 'city' variable and create an object of Location model, which I will later attach to the instance of User, to be accessed in the signal function of creating a profile. I can also override the init of form to add the extra field, but not able to access the 'city' variable at all I can do this in a normal view function by request.POST, but how do I access the extra 'city' variable I created in form meta, inside the overriden model save or in overriden form init?? -
Invalid Block Tag - base.html. expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? Django & Bootstrap Project
I've decided to switch my project Bootstrap from 3.3.7 to 4.0.0 and when I wrote my code this error popped up. What is the problem here? I'm a beginner, I know it isn't that hard. base.html <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top" role="navigation" id="navbar"> <div class="container"> <a class="navbar-brand mr-4" href="{% url 'home' %}">Chat & Write</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> {% if user.is_authenticated %} <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="{% url 'profile' %}">Profil</a> <a class="nav-item nav-link" href="{% url 'writers:all' %}">Scriitori</a> </div> </div> {% endif %} <div class="navbar-nav"> {% if user.is_authenticated %} <a class="nav-item nav-link" href="{% posts:create %}">Postare</a> <a class="nav-item nav-link" href="{% groups:all %}">Grupuri</a> <a class="nav-item nav-link" href="{% groups:create %}">Creaaza grup</a> <a class="nav-item nav-link" href="{% polls:polls %}">Polluri</a> <a class="nav-item nav-link" href="{% accounts:logout %}">Log Out</a> {% else %} <a class="nav-item nav-link" href="{% groups:all %}">Vezi grupurile</a> <a class="nav-item nav-link" href="{% accounts:login %}">Login</a> <a class="nav-item nav-link" href="{% accounts:logout %}">Log Out</a> {% endif %} </div> </div> </div> </nav> </header> -
How to overload get method in the same view in DRF?
I am trying to overload the get request method in my view but it's not working. The view class HomeworkListView(APIView): def get(self, request, teacher): hws = Homework.objects.filter(teacher__user__username=teacher) if not hws.exists(): return Response({'message': 'No homework given by this teacher.'}, status=status.HTTP_204_NO_CONTENT) serializer = HomeworkSerializer(hws, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def get(self, request, school_id, class_name): hws = Homework.objects.filter(school_id__school_id__username=school_id, class_name__class_name=class_name) if not hws.exists(): return Response({'message': 'Homework for this class does not exist.'}, status=status.HTTP_204_NO_CONTENT) serializer = HomeworkSerializer(hws, many=True) return Response(serializer.data, status=status.HTTP_200_OK) urls.py urlpatterns = [ path('list/<slug:teacher>', HomeworkListView.as_view()), path('list/<slug:school_id>/<slug:class_name>', HomeworkListView.as_view()), ] The second get method method is working but the first one throws a TypeError: get() got an unexpected keyword argument 'teacher'. I am guessing if I change the order of the URLs then the first one will work but not the second one. Am I missing something or this is just not possible at all? -
What is the purpose of 'pop' in python?
I ended up having to use this in my django app within a ModelForm. Of what I have researched it picks and removes an attribute, but why would we want to ever remove data like this? class SomeView(FormView): def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['request'] = self.request return kwargs class SomeForm(ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super().__init__(*args, **kwargs) ... ... I figured out that in this case it makes the function work because the init function isn't expecting that value even though I need it. But this feels kinda hacky, throwing it in a view earlier on and then popping it out so it doesn't cause problems. Wouldn't we want to just find a more clean way to do this, or is this considered the best way? -
Django Rest framework cant join tables
I am trying to fetch related data from a parent table using an API. I am trying to get the details from the operator table which has a one-to-one field with the user table. After going through various answers I understood how to join tables but due to some reason I am unable to fetch the user data serializer.py class OpDetailsSerializer(DynamicFieldsModelSerializer): user = UserSerializer(source="operator_details",many=False, read_only=True) print(user.data) class Meta: model = OperatorDetails fields = ('gst_no','pan','user') models.py class OperatorDetails(models.Model): operator=models.OneToOneField(settings.AUTH_USER_MODEL,related_name="operator_details",on_delete=models.CASCADE,primary_key=True) pan = models.CharField(max_length=10, unique=True, null=True,blank=True) gst_no = models.CharField(max_length=15, unique=True,null=True,blank=True) def __str__(self): return str(self.operator) views.py def view_operator_info(request): fields = ('operator','pan','gst_no','user') operator = OperatorDetails.objects.get(operator__id=request.user.id) serializer = OpDetailsSerializer(operator,fields=fields) content = { "status": True, "response": status.HTTP_200_OK, "message": "Operator details", "data":serializer.data } return Response(content) Actual Output { "status": true, "response": 200, "message": "Operator details", "data": { "gst_no": "test", "pan": "test" } } expected Output { "status": true, "response": 200, "message": "Operator details", "data": { "gst_no": "test", "pan": "test", "user":{ "email":..... //data from user table } }} can anyone help. Thanks in advance -
get() returned more than one Product -- it returned 14
I am a student currently learning Django. When I register the product, I want to complete the product registration by specifying the product option, and I want to get the product_code of the option model from get. I wrote this code, but the get_object part keeps getting errors. There are currently 14 registered products, so I think there is an error like above, so please tell me how to solve it. I would appreciate it if you could let me know. I'd like to ask you very much. views.py from django.shortcuts import render, redirect, get_object_or_404 from zeronine.models import * from .forms import ProductForm, OptionForm # Create your views here. def product_upload(request): current_category = None categories = Category.objects.all() products = Product.objects.all() slug = Product.slug if request.method == "POST": form = ProductForm(request.POST, request.FILES) if form.is_valid(): product = Product() product.name = form.cleaned_data['name'] product.benefit = form.cleaned_data['benefit'] product.detail = form.cleaned_data['detail'] product.target_price = form.cleaned_data['target_price'] product.start_date = form.cleaned_data['start_date'] product.due_date = form.cleaned_data['due_date'] product.category_code = form.cleaned_data['category_code'] product.image = request.FILES['image'] product.username = request.user product.slug = slug product.save() if request.method == "POST": form = OptionForm(request.POST) if form.is_valid(): option = Option() option.name = form.cleaned_data['option_name'] option.product_code = get_object_or_404(Product) option.save() return render(request, 'zeronine/list.html', {'form': form, 'current_category': current_category, 'products': products, 'categories': categories, 'slug': slug}) else: …