Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which code is better for readability? Is this a bad practice?
Hello I have a code that looks more or less like this (in views) if request.method == "POST": formset1 = Formset1( request.POST, form_kwargs={"id": id}, prefix="form1" ) formset2 = Formset2( request.POST, form_kwargs={"id": id}, prefix="form2" ) if ( form.is_valid() and formset1.is_valid() and formset2.is_valid() ): service = Service() try: service.save(form, formset1, formset2) except ValidationError as e: form.add_error("some error", e) context = { "form": form, "formset1": formset1, "formset2": formset2, } return render(request, "form.html", context) return redirect("list") else: formset1 = Formset1( prefix="form1", form_kwargs={"id": id}, queryset=items1.all(), ) formset2 = Formset2( prefix="form2", form_kwargs={"id": id}, queryset=items2.all(), ) context = { "form": form, "formset1": formset1, "formset2": formset2, } return render(request, "form.html", context) However I think the code would be more readable like this: if request.method == "POST": formset1 = Formset1( request.POST, form_kwargs={"id": id}, prefix="form1" ) formset2 = Formset2( request.POST, form_kwargs={"id": id}, prefix="form2" ) if ( form.is_valid() and formset1.is_valid() and formset2.is_valid() ): try: service = Service() service.save(form, formset1, formset2) return redirect("list") except ValidationError as e: form.add_error("some error", e) else: formset1 = Formset1( prefix="form1", form_kwargs={"id": id}, queryset=items1.all(), ) formset2 = Formset2( prefix="form2", form_kwargs={"id": id}, queryset=items2.all(), ) context = { "form": form, "formset1": formset1, "formset2": formset2, } return render(request, "form.html", context) The second option is better in my opinion since there's less … -
Import-Export with "multilevel" models
I am figuring how can I manage this situation with import export using the same excel and differents models with differents djangoapps. I have the following models: # employees/models.py class Employee(models.Model): name = models.CharField(max_length=100) job = models.ForeignKey(Job, on_delete=models.SET_NULL, null=True, blank=True) # jobs/models.py class Job(models.Model): value = models.CharField(max_length=100) department = models.ForeignKey(Department, verbose_name='Departamento', on_delete=models.SET_NULL, null=True, blank=True) place = models.ForeignKey(Place, verbose_name='Centro de trabajo', on_delete=models.SET_NULL, null=True, blank=True) class Department(models.Model): value = models.CharField(max_length=100) business = models.ForeignKey(Business, verbose_name='Departamento', on_delete=models.SET_NULL, null=True, blank=True) class Place(models.Model): value = models.CharField(max_length=100) business = models.ForeignKey(Business, verbose_name='Departamento', on_delete=models.SET_NULL, null=True, blank=True) class Business(models.Model): name = models.CharField(max_length=100) On excel I have following values: xls_employee_name, xls_employee_job, xls_business_name I know how to import employee name and his job because Job is directly related by ForeignKey. But how can I import business name? Below is the code for employee name and his job: # employees/resource.py class EmpleadoResource(resources.ModelResource): name = fields.Field(attribute='nombre', column_name='Nombre') job = fields.Field( column_name='xls_employee_job', attribute='job', widget=ForeignKeyWidget( Job, field='value' )) class Meta: model = Employee fields = ('name','job',) skip_unchanged = True def before_import_row(self, row, **kwargs): self.job = row["xls_employee_job"] def after_import_instance(self, instance, new, row_number=None, **kwargs): Job.objects.get_or_create(name=self.job) Is it possible to import business name using one excel? I appreciate if someone could guide me. I'm also pretty new with django. -
QuerySet throwing error when calling mode_to_dict
Getting below error when Calling API from Postman. Is it models problem? Error 'QuerySet' object has no attribute '_meta' Internal Server Error: /candidates/CandidateSummary Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 511, in dispatch self.response = self.finalize_response(request, response, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 423, in finalize_response assert isinstance(response, HttpResponseBase), ( AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` [10/Mar/2022 20:21:23] "GET /candidates/CandidateSummary HTTP/1.1" 500 77831 Unauthorized: /candidates/CandidateSummary [10/Mar/2022 20:21:39] "GET /candidates/CandidateSummary HTTP/1.1" 401 58 'QuerySet' object has no attribute '_meta' Internal Server Error: /candidates/CandidateSummary Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-** packages/rest_framework/views.py", line 511, in dispatch self.response = self.finalize_response(request, response, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 423, in finalize_response assert isinstance(response, HttpResponseBase), ( … -
Why Can't I Add Azure DB Extension on Mac?
I am following this guide: https://docs.microsoft.com/en-us/azure/app-service/tutorial-python-postgresql-app?tabs=bash%2Cclone&pivots=postgres-single-server After successfully completing Step 1 and Step 2, I get to Step 3: "Install the db-up extension for the Azure CLI: az extension add --name db-up" Yet, when I run this command, I receive the following output: X@Y-MacBook-Pro djangoapp % az extension add --name db-up Failed to delete '/Users/X/.azure/cliextensions/db-up': [Errno 2] No such file or directory: '/Users/X/.azure/cliextensions/db-up'. Retrying ... Failed to delete '/Users/X/.azure/cliextensions/db-up': [Errno 2] No such file or directory: '/Users/X/.azure/cliextensions/db-up'. Retrying ... Failed to delete '/Users/X/.azure/cliextensions/db-up': [Errno 2] No such file or directory: '/Users/X/.azure/cliextensions/db-up'. Retrying ... Failed to delete '/Users/X/.azure/cliextensions/db-up': [Errno 2] No such file or directory: '/Users/X/.azure/cliextensions/db-up'. You may try to delete it manually. An error occurred. Pip failed with status code 1. Use --debug for more information. Any ideas here? I've tried some of the solutions to similar errors I've found on Stack/GitHub, but so far no luck. The goal is to get a Django app deployed to Azure with a connected DB also on Azure. Thanks! -
django custom function for filter query
I've a field in my model called, test_data = models.TextField(...), and the model is called MyOrm and this test_data contains data which is actually string, some holds JSON data, and some reference to blob-url. Now I'm trying to streamline my data. So I want to filter all the MyOrm object whose test_data ain't JSON. I'm just storing/trying to store some meta-data along with url, then I will convert them. Can anyone suggest me a way to do so?? pseudocode: select all my-orm where is_not_json(my-orm.test-data) -
How to compare data from two models in Modelform Django
I'm creating an ebay like auction site where users can bid on an item they like and if the bid is higher than the last bid, the bid amount displayed would update to the newest bid. I want to run validation on the modelform to compare the first amount (that the person that created the listing) inputted with the last bid (that the new user inputted). The problem is that they are in two different models and I'm not sure how to validate both without an error FORMS.PY class BidForm(forms.ModelForm): class Meta: model = Bids fields = ['new_bid'] labels = { 'new_bid': ('Bid'), } def clean_new_bid(self): new_bid = self.cleaned_data['new_bid'] current_bid = self.cleaned_data['current_bid'] if new_bid <= current_bid: error = ValidationError("New bid must be greater than the previous bid") self.add_error('new_bid', error) return new_bid MODELS.PY class Auction(models.Model): title = models.CharField(max_length=25) description = models.TextField() current_bid = models.IntegerField(null=False, blank=False) image_url = models.URLField(verbose_name="URL", max_length=255, unique=True, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) category = models.ForeignKey(Category, max_length=12, null=True, blank=True, on_delete=models.CASCADE) is_active = models.BooleanField(default=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class Meta: ordering = ['-created_at'] class Bids(models.Model): auction = models.ForeignKey(Auction, on_delete=models.CASCADE, related_name='bidding', null=True) user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='bidding') new_bid = models.IntegerField() done_at = models.DateTimeField(auto_now_add=True) VIEWS.PY @login_required def make_bid(request, … -
when admin updates user profile how to access that obj in views and perform some task in django
when admin updates user profile how to access that obj in views and perform some task in django i have user model and when user creates new account by default his id is deactivated but when admin activate their account from admin panel by change the user model field "is_active" to True the i want to send that user an email and some other task also so how to get that user's object that activated by admin -
Django Python: Why does decrypting a file fail?
I'm using https://github.com/eblocha/django-encrypted-files to encrypt files uploaded through Django. It uses AES in CTR mode to encrypt files via an upload handler. I'm trying to manually test the file encryption and decryption by uploading a file via Django form and the retrieving the file via FTP and decrypting it locally. But I find I can't decrypt the file locally using the python shell; the decrypted file is the same as the encrypted file, except the encrypted file has about 15 more characters at the beginning of the file. I've installed cryptography 36.0.1 https://pypi.org/project/cryptography/ locally, and pip is up to date. This is what I'm trying: $ python3 >>> AES_KEY = b'\x1......8f\xdd' // same key as in Django >>> AES_KEY.hex() '1a3ef8c....7e8fdd' // output >>> full = open ("decrypt.txt", 'rb') >>> save=open("decrypted.txt", "wb") >>> read = full.read() >>> save.write(read[16:]) >>> read[:16].hex() '69djeu....9b' // output >>> exit() At this point, the file decrypted.txt is saved, but it's the same as the encrypted file, except the encrypted file has about 15 more characters at the beginning of the file. How can I decrypt the file decrypt.txt to decrypted.txt? Should I use a different Python library locally other than cryptography? -
Coverage html report in django python application created htmlcov folder with files, however each file has strange prefix
i am learning how to use coverage package for evaluating which statements in django/python application are covered by unit tests and which are not. I ran command: coverage run --source "APP" manage.py test && coverage report && coverage html , which created htmlcov folder and multiple html-files inside it. Each file corresponds to the .py file, however in the beginning of each file-name , i see a strange prefix, something like this: "d_10d11d93a0707d03_example_py.html" instead of expected "example_py.html". I wasn't able to google any explanations to this. Please help if you know why is this happening and how to avoid this prefix if at all possible. Thanks! -
Textinput with ModelChoiceField
I yesterday asked this question without success but I have still been working on the problem. Save user input which is a string as object in db . In short the question yesterday described how I wanted to have a registration key in my registration form to be able to restrict who can register themselves. What I have done now is in the forms.py file have I created a key field as a ModelChoiceField with a textinput as the widget. When I write a key which exists in the DB I get the following error: "Select a valid choice. That choice is not one of the available choices.". I can't use Select as the widget as that would display the keys for the users. I tried both methods in this post but without any success. So the question know is, how can I have a TextInput with a ModelChoiceField? -
Wagtail RichTextField - Make admin edit field wider/taller and allow resizing
I recently came across a setting that changes the RichTextField in Wagtail admin to be "full size", ie it was wider and taller, and it maybe even allowed the user to resize the field (not sure about that). I cannot recall what that setting was or where it was used. I believe it was a settings.py feature but I am not having any luck finding it. How can I enable the "full size" Wagtail RichTextField? -
How to display data in the same column of two fields of the model depending on the option chosen from the radio button in Django?
I have a question. It turns out that I have a form that when you click on a radio button, certain inputs are enabled, and when you click on another radio button option, other inputs appear. The inputs save different information depending on the option you chose in the radio buttons, for example, in one input you have to put the name of the person, in another input it is the name of the corporation. When displaying the information in the list, I would like a column to say 'Name' and either the client name or the corporation name to appear. I would not like to place two columns, one that says client name and another corporation name, but in only one that says name, they appear. How can I do that? This is how i have my html and this is how I would like it to be html <form method="post"> {% csrf_token %} <div class="d-flex justify-content-between"> <a href="{% url 'Clientes:clientes_add' %}"> <button type="button" class="btn btn-success mb-3 waves-effect waves-light" onclick="addNewCustomer()">Add new</button> </a> <div class="col-md-6 mb-3 d-flex align-items-center"> <label class="m-0 col-md-2 text-right">Date range:&nbsp;&nbsp;</label> <input type="date" name="fromdate" class="form-control"> <input type="date" name="todate" class="form-control"> <input type="submit" value="Search" class="btn btn-light"> </div> </div> <div class="card"> … -
Django Elastic Beanstalk to RDS MySQL problems connecting
I'm trying to connect my Django Elastic Beanstalk to my RDS MySQL. My Django works with my RDS MySQL through localhost, but when trying to upload my Django to Elastic Beanstalk I get "failed to deploy application" and AWS shows errors (below). My project has mysqlclient in requirements.txt, like here: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-rds.html According to that page, that should be enough. I've of course tried to search for similar questions but haven't had success so far. I've noticed that many questions refer to needing a packages.config file inside .ebextensions, I tried many of those suggestions without success. Is that the problem? Why wouldn't that be mentioned on the AWS page? × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] /bin/sh: mysql_config: command not found /bin/sh: mariadb_config: command not found /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-r0dz9d2g/mysqlclient_f2b5c53e43a648c284b06f7af63d9855/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-r0dz9d2g/mysqlclient_f2b5c53e43a648c284b06f7af63d9855/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-r0dz9d2g/mysqlclient_f2b5c53e43a648c284b06f7af63d9855/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs [end of output] -
How to handle open sourcing elastic beanstalk Django applications / should .ebextensions be in my .gitigore?
I am building my personal website using Django (I'm a beginner) and I am learning how to deploy my application to AWS, the tutorial I am following tells me to create the .ebextentions folder with the django.config file inside of it. Is it safe/does it make sense to have this inside a github repo or not? Thank you in advance! -
Calling Django view does not execute the function when called more than once
Spring function in Django Views is executed well when called once, but not executed when called twice. Any help would be appreciated. views.py The below is Spring function in views.py. "spring: try starts" is printed when the function is called once but nothing appears in terminal when the function is called for the second time. @api_view(['GET']) def spring(request): try: print("spring: try starts") pc = seasonCheck("spring") return StreamingHttpResponse(gen("spring",pc), content_type='multipart/x-mixed-replace; boundary=frame') except Exception as ex: return HttpResponse(ex) seasonTest The below is where Spring function is called. Whenever the user clicks the button, seasonTest has to be executed. As mentioned above, however, Spring function is not executed when the user clicks the button more than once. function seasonTest(season) { if (season == "spring") { setImg('http://localhost:8000/spring/'); } } -
Retrieve filter data on DjangoObjectType
Good morning, I have created with graphene django a DjangoObjectType that returns several pieces of information. Among which I have integrated django_filters to filter the data. Is it possible to retrieve the values of the filters inserted on the frontend side to read them in DjangoObjectType and so return some information? thanks -
Updating the model instances in a particular order
I am working on a django application. I have a process flow in which I have steps and their respective status. I have a model for steps. Below is my flow diagram As soon as the status of step 1 changes to complete, status of all the following steps gets updates. I wrote a post_save signal for the status change of the steps. @receiver(post_save, sender=WorkflowStep) def updateWorkflowStep(sender, instance, created, **kwargs): # updated step 2, step 5, and step 8 statuses Problem: As soon as I will update the status of step "2", the post_save signal will get triggered and update the status of Step "3", followed by step "4". So my. step "5" and step "8" will never get updated as by the time code could update their status, post_save again got triggered because of step "2" status change. How can I make sure that all the three branches gets updated in sequence. Say first step 2, step 3 and step 4 gets updated. Then step 5, 6, and 7. And then step 8, 9, and 10. These are my models: class WorkflowStep(models.Model): name = models.CharField(max_length=200) workflow = models.ForeignKey('Workflow', null=True, blank=True, on_delete=models.CASCADE) step_type = models.ForeignKey('WorkflowStepType', null=True, blank=True, on_delete=models.SET_NULL) allowed_status = … -
access multiple many to many relationships in a django template
class Account(models.Model): accountId = models.CharField(max_length=20, primary_key=True) username = models.CharField(max_length=30) def __str__(self): return self.username class Project(models.Model): projectId = models.CharField(max_length=20, primary_key=True, default=idgen) projectName = models.CharField(max_length=20) projectOwner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner") projectSize = models.IntegerField(default=25) projectGuests = models.ManyToManyField(User, related_name="guests") projectAccounts = models.ManyToManyField(Account, "accounts") def __str__(self): return self.projectId In this code, users can have multiple projects and projects can have multiple accounts. Is there any way to pass just the 'user' to the template (or without passing anything since we can get the user using the request) to get all the accounts in all the projects that the user owns? for example, if the user had 2 projects and each project had 2 accounts... is there any way to get the final value 4 in the template just using the user object? -
Django mysql sphinxsearch 'SELECT @@SQL_AUTO_IS_NULL' returns empty error and fails with 'invalid literal for int() with base 10: ''
I have a new setup with DJango and sphinxsearch. When mysql backend initializes connection it calls is_sql_auto_is_null_enabled, which fails with "invalid literal for int() with base 10: ''". Within mysql the query executes as following: mysql> SELECT @@SQL_AUTO_IS_NULL; +--------------------+ | @@sql_auto_is_null | +--------------------+ | | +--------------------+ 1 row in set (0.00 sec) It looks like fetched empty string value is being converted into integer and an exception is thrown. My sphinxsearch version is: Sphinx 2.2.11-id64-release (95ae9a6) I also have a working setup, where the same query returns no rows: mysql> SELECT @@SQL_AUTO_IS_NULL; Query OK, 0 rows affected (0.00 sec) There, sphinxsearch version is: Sphinx 2.2.10-id64-release (2c212e0) Both setups have the same mysqlclient version: mysqlclient==1.3.13 Is there a way to fix this by making SELECT @@SQL_AUTO_IS_NULL return no rows? Or is there another way around this problem? -
Why one url the doesn't require an auth asks for token when placed below a url that requires auth
I obeserved a weird error(maybe) while testing my apis. I have three views handleing the api requests. Two doen't require auth (searchListing, listListing) and on requires auth (retrieveListing). Weirdly if I keep the 'search' below the 'str:slug'' url (urlpatern_1) it says Authentication credentials were not provided. However if I move the search above the 'str:slug'' it works perfectly. urlpatterns_1 = [ path('', views.listListing , name= 'listListing'), path('<str:slug>', views.retrieveListing , name= 'retrieveList'), path('search', views.searchListing , name= 'searchList'), ] urlpatterns_2 = [ path('', views.listListing , name= 'listListing'), path('search', views.searchListing , name= 'searchList'), path('<str:slug>', views.retrieveListing , name= 'retrieveList'), ] But weirdly again the 'listListing' is unaffected by its position. Please explain me why is this happening views.py @api_view(['GET']) def listListing(request): pass @api_view(['GET']) @permission_classes([IsAuthenticated]) def retrieveListing(request, slug): pass @api_view(['GET']) def searchListing(request): pass -
Blog style pages in Django with different content types. Best model structure
I'm relatively new to Django development. I'm building a website where there is a section with tutorials. Lets say for my question a tutorial for Linked List. Since all the tutorials will be basically the same outline, it looks like that templates will do a good job here. What I want to achieve is that I can create new pages (tutorial entries ) in the admin panel, with text fields and so on (kind of like a blog without the relevance of the dates rather then the tutorials content). The challenge for me is, that there is a different amount of different types of data in one tutorial entries. For example one might have the structure: text code text image text code and another one: text image code And if I made a new entry it should get generated with a template as it is done usually in Django. I thought about three ways to meet this dynamic behavior but I see difficulties in each and want to know what the best practice would be. So the structure would be similar to a Blog: class TutorialPost(models.Model): title = models.CharField(max_length=200, unique=True) text_content = models.TextField() code_block = models.TextField() #.... The problem here … -
How to get queryset of objects in many to many field in Django
I have two models Student and Classroom in models.py class Classroom(models.Model): classroom_subject = models.CharField(max_length=100) classroom_code = models.CharField(max_length= 5, default = '00000') teacher = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) student_name = models.CharField(max_length=100) classes = models.ManyToManyField(Classroom, blank = True) I have three tables in my database student: user_id student_name 1 4 2 4 3 1 classroom: id classroom_subject classroom_code 1 maths 12345 2 english 12345 3 biology 12345 student_classes: id student_id classroom_id 1 4 1 2 4 2 3 1 1 In my views.py class StudentClassesView(ListView): model = Classroom template_name = 'student_classroom_list.html' context_object_name = 'classroom_list' def get_queryset(self): student_id = self.request.user.id return Student.classes.through.objects.filter( ) This code returns all the classrooms in student_classes, but i want it to return all the classrooms where the student_id = self.request.user.id So for example self.request.user.id returns 4, I want all the classrooms in student_classes table where student_id = 4. -
Django: To combine and retrieve rows from different models
1.We have two similar models, and I would like to be able to retrieve these at the same time and sort them by posting date and time, etc. Is it possible? 2.Or should both redundant fields be combined into one model? # 1. class Model1(models.Model): title = ... thumbnail = ... description = ... ... class Model2(models.Model): title = ... image_url = ... product_id = ... reivew = ... # 2. Combine into one model class Model(models.Model) title = ... thumbnail = ... description = ... image_url = ... product_id = ... reivew = ... -
Filter rows from Excel on import with Django Import-Export
I have a new Django web-application (My first one in python) and im using Import-export in the admin section to take an excel file and upload it to my database.the upload works perfectly, but I need to add two features: Is there a way to truncate all the existing data in the application database table before the upload? What is the best way to filter out rows from the Excel file that don't match a condition (if column value of a row != X) I have read the documentation and it seems like for question 2, the only option is to implement an for_delete method. I find it hard to believe this is the best way, but im brand new to python and Django. -
MultipleObjectsReturned at /sport/1/ get() returned more than one Product -- it returned 3
I am sorting products by categories. When I am viewing product's details, the program outputs following error: MultipleObjectsReturned at /default/1/ get() returned more than one Product -- it returned 2! Users/artemiikhristich/PycharmProjects/Eshop-original/store/views.py, line 114, in product_detail product = get_object_or_404(Product, slug=slug) product.html This template is used for viewing product details % extends "store/main.html" %} {% block content %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Tutorial</title> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet"> <!-- CSS --> <link href="static/css/style.css" rel="stylesheet"> <meta name="robots" content="noindex,follow" /> </head> <body> <main class="container"> <!-- Left Column / Headphones Image --> <!-- Right Column --> <div class="right-column"> <!-- Product Description --> <div class="product-description"> <span></span> <h1>{{product.name}}</h1> <div class="left-column"> <img data-image="black" src="{{ product.imageURL }}"> </div> <p>"{{product.description}}"</p> </div> <!-- Product Configuration --> </div> <!-- Product Pricing --> <div class="product-price"> <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> <div class="product-configuration"> <a href="#">How to take the measurements</a> </div> </div> </div> </main> <!-- Scripts --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js" charset="utf-8"></script> <script src="static/js/script.js" charset="utf-8"></script> </body> </html> {% endblock %} views.py Here I have views for product_detail and category_detail class ProductList(ListView): model = Product def product_detail(request, category_slug, slug): product = get_object_or_404(Product, slug=slug) context = …