Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django channels Async Websocket throwing Error while trying to use database query
I don't get it. Even though I've converted all the required fields in async await. But still I'm getting the following error: HTTP GET /chat/8/ 200 [0.02, 127.0.0.1:51354] WebSocket HANDSHAKING /ws/chat/8/ [127.0.0.1:51356] Exception inside application: You cannot call this from an async context - use a thread or sync_to_async. Traceback (most recent call last): File "/media/fahadmdkamal/WORK/B-DOPS/api/env/lib/python3.8/site-packages/channels/sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "/media/fahadmdkamal/WORK/B-DOPS/api/env/lib/python3.8/site-packages/channels/middleware.py", line 41, in coroutine_call await inner_instance(receive, send) File "/media/fahadmdkamal/WORK/B-DOPS/api/env/lib/python3.8/site-packages/channels/consumer.py", line 58, in __call__ await await_many_dispatch( File "/media/fahadmdkamal/WORK/B-DOPS/api/env/lib/python3.8/site-packages/channels/utils.py", line 51, in await_many_dispatch await dispatch(result) File "/media/fahadmdkamal/WORK/B-DOPS/api/env/lib/python3.8/site-packages/channels/consumer.py", line 73, in dispatch await handler(message) File "/media/fahadmdkamal/WORK/B-DOPS/api/env/lib/python3.8/site-packages/channels/generic/websocket.py", line 175, in websocket_connect await self.connect() File "/media/fahadmdkamal/WORK/B-DOPS/api/chat/consumers.py", line 23, in connect other_user = await sync_to_async(User.objects.get(id=others_id)) File "/media/fahadmdkamal/WORK/B-DOPS/api/env/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/media/fahadmdkamal/WORK/B-DOPS/api/env/lib/python3.8/site-packages/django/db/models/query.py", line 411, in get num = len(clone) File "/media/fahadmdkamal/WORK/B-DOPS/api/env/lib/python3.8/site-packages/django/db/models/query.py", line 258, in __len__ self._fetch_all() File "/media/fahadmdkamal/WORK/B-DOPS/api/env/lib/python3.8/site-packages/django/db/models/query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/media/fahadmdkamal/WORK/B-DOPS/api/env/lib/python3.8/site-packages/django/db/models/query.py", line 57, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/media/fahadmdkamal/WORK/B-DOPS/api/env/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1150, in execute_sql cursor = self.connection.cursor() File "/media/fahadmdkamal/WORK/B-DOPS/api/env/lib/python3.8/site-packages/django/utils/asyncio.py", line 24, in inner raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. WebSocket DISCONNECT /ws/chat/8/ [127.0.0.1:51356] The error says I … -
Django REST framework: data not posting to database
So i've been banging my head against a wall for a good few hours, thinking I understoodthe django rest framework but I clearly don't. when I try adding an entry via the todo-create api it gives me {'list_item': None, 'complete': False} when I print the serializer without the .data it recognises that there was something inputted into the list_item, but it won't send to the database: TodoSerializer(data=<QueryDict: {'_content_type': ['application/json'], '_content': [' {\r\n "list_item": "test item",\ r\n "complete": false\r\n }']}>): list_item = CharField(allow_null=True, max_length=100, required=False) complete = BooleanField(required=False) I am also getting the following in the terminal: Method Not Allowed: /project2/todo/todo-create/ [14/Sep/2020 23:49:55] "GET /project2/todo/todo-create/ HTTP/1.1" 405 8987 View.py from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import TodoSerializer @api_view(['GET']) def apiOverview(request): api_urls = { 'List': '/todo-list/', 'Detail View': '/todo-detail/<str:pk>/', 'Create': '/todo-create/<str:pk>/', 'Update': '/todo-update/<str:pk>/', 'Delete': '/todo-delete/<str:pk>/', } return Response(api_urls) @api_view(['GET']) def todoList(request): todo = Todo_list.objects.all() serializer = TodoSerializer(todo, many=True) return Response(serializer.data) @api_view(['GET']) def todoDetail(request, pk): todo = Todo_list.objects.get(id=pk) serializer = TodoSerializer(todo, many=False) return Response(serializer.data) @api_view(['POST']) def todoCreate(request): serializer = TodoSerializer(data=request.data) if serializer.is_valid(): serializer.save() else: print("issue with data") print(serializer.errors) print(serializer.data) return Response(serializer.data) @api_view(['POST']) def todoUpdate(request, pk): todo = Todo_list.objects.get(id=pk) serializer = TodoSerializer(instance=todo, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) settings.py INSTALLED_APPS … -
Django Form Get Foreign Key Data In Add Form
I am trying to add a "note" to an "applicant," but in the create note form I would like the applicant's name to show above the form. Right now the tags ( {{ applicant.full_name }} ) are not working in the create form template. Here is part of my CreateNote view currently. Thank you for any assistance. def form_valid(self, form): applicant_pk = self.kwargs['pk'] applicant = Applicant.objects.get(pk=applicant_pk) self.object = form.save(commit=False) self.object.applicant = applicant self.object.save() return super(NoteCreate, self).form_valid(form) -
Blog content doesn't show on the html blog page
[Blog content doesn't show on the html page][1] [1]: https://i.stack.imgur.com/SH4OQ.jpg`Hello Blog this is Zee's blog for python {% for blog in blogs %} {{ blog.title }} {{ blog.date }} {{ blog.description }} {{ blog.summary }} {% endfor %}` -
django custom user model form widgets working only for email and name field
in my custom user model that is created with AbstractBaseUser when i try to add widgets which lets me add classes or place holders or input type etc.. it works only for the full_name and email fields but not for password1 and password2 in my models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.conf import settings class MyAccountManager(BaseUserManager): def create_user(self, email, full_name, password=None): if not email: raise ValueError('Users must have an email address') if not full_name: raise ValueError('Users must have a name') user = self.model( email=self.normalize_email(email), full_name=full_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, full_name, password): user = self.create_user( email=self.normalize_email(email), full_name=full_name, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField(verbose_name="Email",max_length=250, unique=True) username = models.CharField(max_length=30, unique=True, null=True) date_joined = models.DateTimeField(verbose_name='Date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='Last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) full_name = models.CharField(verbose_name="Full name", max_length=150, null=True) profile_pic = models.ImageField(null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name'] objects = MyAccountManager() def __str__(self): return self.full_name # For checking permissions. def has_perm(self, perm, obj=None): return self.is_admin # For which users are able to view the app (everyone is) def has_module_perms(self, app_label): … -
How to delete all empty tags in admin with Taggit in Django?
I'm using tags with Taggit and I want to delete an empty tag if it's not associated with a post. This works for the user view but for the admin it doesn't. If I delete a tag from a post in the admin and that tag has 0 posts associated with it, it still exists. Any way to accomplish this for the admin? I was thinking of a function that would run every time the admin dashboard loads and deletes all the empty tags. Admin.py from django.contrib import admin from FileUpload.models import Uploaded class UploadedAdmin(admin.ModelAdmin): list_display = ('name', 'time_uploaded', 'file', 'tag_list') list_filter = ['time_uploaded', 'tags'] class Media: pass def get_queryset(self, request): return super().get_queryset(request).prefetch_related('tags') def tag_list(self, obj): tags = obj.tags.all() return u", ".join(o.name for o in tags) # Register your models here. admin.site.register(Uploaded, UploadedAdmin) -
In which case should I use nosql (mongodb) and in which case postqresql?
1-) I'm building a real estate site. There will be notification, messaging and posting models. Which of these models should I use with which databases? 2-) I'm using express and vue js. Should I use Nuxt.js? I have a chance to use Django. But I can't use channels successfully in django. Can I do this by using node js and django together? -
All the REST API endpoint calls logged in a log file
what is best way to logged in all REST API endpoint calls in a log file ? any kind of help would be highly appericated -
TypeError & AssertionError when clicking on buttons in Django
Apologies for the long post, I am trying to implement a simple button which either add or remove an item from a watchlist. While I initially managed to implement the "addwatchlist" function appropriately, I tinkered my code for a few hours and I somewhat am unable to wrap my head around it again. Here is the error that I receive when pressing the "Add to Watchlist" button : TypeError at /addwatchlist/10 Field 'id' expected a number but got <Listing: "Gloss + Repair Spray">. Request Method: GET Request URL: http://127.0.0.1:8000/addwatchlist/10 Django Version: 3.1.1 Exception Type: TypeError Exception Value: Field 'id' expected a number but got <Listing: "Gloss + Repair Spray">. TRACEBACK : watchlist.save() ▼ Local vars Variable Value id 10 request <WSGIRequest: GET '/addwatchlist/10'> watchlist Error in formatting: TypeError: Field 'id' expected a number but got <Listing: "Gloss + Repair Spray">. Here is the error that I receive when pressing the "Remove from Watchlist" button, note that this is the exact same error I initially received which in turn forced me to try and tweak the way "Add to Watchlist" function : AssertionError at /removewatchlist/1 Watchlist object can't be deleted because its id attribute is set to None. Request Method: GET … -
AttributeError at /sitemap.xml [closed]
'function' object has no attribute 'values' urls.py [sitemaps.py][2]P.png -
Cannot assign "<User: user.name>: must be a "User" instance
I am having an issue writing a custom django migration where I am trying to set a field value for a model to a user. The model in question is shown below (CustomerMachine). This model uses the django-simple-history module to track changes in model instances. I am attempting to query the instance history in the migration and set the review_submitter value to the last user which edited the instance. The result of the history query history_user returns a <class 'django.contrib.auth.models.User'> type, but when I try to set the review_submitter to that value I get the following error: ValueError: Cannot assign "<User: user.name>": "CustomerMachine.review_submitter" must be a "User" instance. Any insight into whats going on here? simplified class example class CustomerMachine(models.Model): review_submitter = models.ForeignKey(settings.AUTH_USER_MODEL, default=None) history = HistoricalRecords() custom migration from __future__ import unicode_literals from __future__ import absolute_import from django.conf import settings from django.db import migrations, models from django.contrib.auth.models import User from acceptance.models import CustomerMachine def set_submitter(apps, schema_editor): machines = apps.get_model('acceptance', 'CustomerMachine') for machine in machines.objects.all(): history = CustomerMachine.history.filter(serial=machine.serial) if history: history_user = history.last().history_user machine.review_submitter = history_user machine.save() def reverse_func(apps, schema_editor): pass # code for reverting migration, if any class Migration(migrations.Migration): dependencies = [ ('acceptance', '0031_auto_20200914_1611'), ] operations = [ migrations.RunPython(set_submitter, … -
Django Admin multiple count issue
I have an issue with duplicated call of count method from Django Admin. Here is my code. class AdminPaginator(Paginator): @property def count(self): cursor = connection.cursor() cursor.execute("SELECT reltuples FROM pg_class WHERE relname = %s", [query.model._meta.db_table]) count = int(self.cursor.fetchone()[0]) return count ... Code from Admin Model list_per_page = 50 show_full_result_count = False def get_queryset(self, request): """ Overrides default query to exclude test entities. """ qs = super().get_queryset(request) active_entities = qs.filter(is_active=False) return qs.exclude(id__in=active_entities) count method calls for 4 times and I don't know why. Thanks for your help! -
Django can't get REMOTE_USER
I need to create SSO Authentication using Kebreros in my Django project. I faced with problem when tried to get username from request.META['REMOTE_USER']. KeyError happens. It seems that variable REMOTE_USER is not set but I don't understand why. I added RemoteUserMiddleWare and RemoteUserBackend as it's said in docs. 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.auth.middleware.PersistentRemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',] AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.RemoteUserBackend',] Apache config: <VirtualHost *:80> ServerName test.wit.net ServerAlias test.wit.net DocumentRoot /var/www/test.wit.net/public_html ProxyPass / http://localhost:8000/ ProxyPassReverse / http://localhost:8000/ ProxyPreserveHost On ProxyTimeout 300 RequestHeader set X-Forwarded-Proto "http" <Location "/"> # Kerberos authentication: AuthType Kerberos AuthName "SRV-APP auth" KrbMethodNegotiate on KrbMethodK5Passwd off KrbServiceName HTTP/test.wit.net@WIT.NET KrbAuthRealms WIT.NET Krb5Keytab /etc/krb5.keytab KrbLocalUserMapping On Require valid-user </Location> SSO works Apache authentificate user successfully, but I can't pass REMOTE_USER to Django. What could be wrong? -
Create new models from an existing one
need some help with the next issue: I got this model in Django: class myModel(models.Model): Name = models.CharField(max_length=50) parameter1 = models.IntegerField(null=True) parameter2 = models.IntegerField(null=True) # # parametern = models.IntegerField(null=True) The "Name" field is limited to 5, and it gets data to update the rest of the fields, giving as result a main table with n entries wich repeat name but have differents parameters. I want to create 2 table from this main one as follow: The first table has to group up the data by names adding the values of each parameter. The result should be a table with 5 names and the total of each parameter. The second table is the same, but giving the average for each parameter. One solution may be to create and delete each table every time the main table its updated, but im not sure if this is the best way to do it. appreciate any help! Thx to everyone! -
Ajax Upload Image files- Django Forms
I try to upload image, using Ajax with django forms. It not return errors.(This field is requred). So Please help me any one, Here is my code. forms.py class RegistrationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) class Meta: model = Employee fields = ( 'name', 'photograph', ) models.py photograph = models.FileField(upload_to="employee/") Ajax $(document).ready(function () { $('#saveEmployee').click(function (e) { var serializedData = $("#employee").serialize() e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "empcheckurl" %}', data: serializedData, success: function (data) { alert('data.successMessage'); } }); return false; }); }); views.py def post(request): form = RegistrationForm() if request.method=="POST": form = RegistrationForm(request.POST, request.FILES) print(form.errors) if form.is_valid(): alldata = form.save() return JsonResponse({'alldata': model_to_dict(alldata),'successMessage':'Employee resisters successfully'}, status=200) else: return redirect('registeredusers') -
restore postgreSQL database on Django project
I'm working on an application that runs on Ubuntu 18.04, it consists of Django App and PostgreSQL server, each on runs in a separate Docker container. I created a backup for my database, so I can keep it and runs it on a test server for test cases. Now I'm moving my backup database to another test server, but the problem is when I run: docker-compose -f production.yml up both containers of Django & PostgreSQL run fine, the problem is which should I do first to make everything working on the test server, like everything working on the production server? should I restore backup database first then run: python manage.py migrate or should I migrate then restore backup database, actually I ran both, and each time after successfully end both I got this error: ProgrammingError at /accounts/login/ so what should I do to restore backup database? Anther question: I tried to ignore the backup database and just run: python manage.py migrate and create a database from scratch but I got the same error as before!!! I'm there is something common I'm wrong with, so help me with any information on the theory of backup database, please. -
string indices must be integers while passing ObjectId through URL in Django
I am building a website in django and using mongodb as a database. I want to pass the objectID of mongodb document through url. I am applying the custom filter on it, but I am keep getting this error "string indices must be integers" on 'object|mongo_id' what am I doing wrong? Here is my code: user.html {% load get_id %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <title>Document</title> </head> <body> <nav class="navbar navbar-inverse"> <div style="padding-left: 1200px;" class="container-fluid"> <button class="btn btn-danger navbar-btn"><a href="{% url 'login_view' %}">Log Out</a></button> </div> </nav> <br> <div style="padding-left: 1100px;"> <button type="button" class="btn btn-success"> <a href="{% url 'new_job' object|mongo_id %}">Post Job</a> </button> </div> </body> </html> get_id.py from django import template register=template.Library() @register.filter(name="mongo_id") def mongo_id(value): return str(value['_id']) -
Taggit in list_filter doesn't refresh if any of the tags is deleted in Django
I'm using Taggit for tagging a post in my Django app. I've added list_diplay and list_filter for the Admin model view and both are working. The problem is that if I go and delete a tag as an Admin, the list_filter won't refresh and stop showing that tag. If I add another tag, the list will refresh and work. Admin.py class UploadedAdmin(admin.ModelAdmin): list_display = ('name', 'time_uploaded', 'file', 'tag_list') list_filter = ['time_uploaded', 'tags'] def get_queryset(self, request): return super().get_queryset(request).prefetch_related('tags') def tag_list(self, obj): return u", ".join(o.name for o in obj.tags.all()) # Register your models here. admin.site.register(Uploaded, UploadedAdmin) -
Passing slug into ListView URL
I wanted to pass slug into ListView. But it was not as simple as passing it to DetailView. That's because, ListView doesn't have built-in slug support. I found answer of my question and I want to share with you, guys. -
TypeError when Django authenticate function tries to bind to custom authenticate function
I am attempting to implement an authentication method where: the user submits their email I generate a token for that user that is stored in the database, or I retrieve the token if it already exists I generate a link to log in and email it to the user, with the token as an HTTP parameter The token is extracted from the link and used to search for an active user The user info is passed to the template Note that this isn't for any mission-critical production software - I'm reading the Obey The Testing Goat O'Reilly book and this is the authentication method the author has us implement. So when the user clicks the link in their email, this is the view function that handles it: from django.contrib.auth import authenticate, login def login(request): uid = request.GET.get('uid') user = authenticate(uid=uid) if user is not None: login(request, user) return redirect('/') In that view function, we call the authenticate function that is provided by django.contrib.auth. Here is that function: def authenticate(request=None, **credentials): """ If the given credentials are valid, return a User object. """ for backend, backend_path in _get_backends(return_tuples=True): backend_signature = inspect.signature(backend.authenticate) try: backend_signature.bind(request, **credentials) except TypeError: # This backend doesn't accept … -
Unable to resolve Reverse for 'create_order' with no arguments not found
The issue is already been discussed here... Reverse for 'create_order' with no arguments not found i get an error. django.urls.exceptions.NoReverseMatch but there is nothing mentioned on how to solve the issue. can somebody help? This is code iam getting an error .. dashboard.html <div class="col-md-7"> <h5>LAST 5 ORDERS</h5> <hr> <div class="card card-body"> <a class="btn btn-primary btn-sm btn-block" href="{% url 'create_order' customer.id %}">Create Order</a> <table class="table table-sm"> <tr> <th>Product</th> <th>Date Orderd</th> <th>Status</th> <th>Update</th> <th>Remove</th> </tr> {% for order in orders %} <tr> <td>{{order.product}}</td> <td>{{order.date_created}}</td> <td>{{order.status}}</td> <td><a class="btn btn-sm btn-info" href="{% url 'update_order' order.id %}">Update</a></td> <td><a class="btn btn-sm btn-danger" href="{% url 'delete_order' order.id %}">Delete</a></td> </tr> {% endfor %} </table> </div> // When i remove the link href ( i,.e create order ) then the URL works fine Corresponding views def createOrder(request, pk): #def createOrder(request): OrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status'), extra = 10 ) customer = Customer.objects.get(id=pk) formset = OrderFormSet(queryset=Order.objects.none(),instance=customer) if request.method == 'POST': #form = OrderForm(request.POST) formset = OrderFormSet(request.POST,instance=customer) if formset.is_valid(): formset.save() return redirect('/') context = {'formset':formset} return render(request, 'accounts/order_form.html', context) there some one told the create order button is commented, but nothing. This the part of the exception iam getting Tracee Error Internal Server Error: / Traceback (most recent call … -
A Coroutine is returning a coroutine after await
I'm writing tests for a fastAPI on django with an ASGI server (adapted this tutorial). My fastAPI side of the test keeps returning errors and I'm trying in vain to fix it. My need is about creating a user to test the API. @sync_to_async async def _create_user(self, username, email): try: return User.objects.create(username=username, email=email) except Exception as e: await print(e) return None async def setUp(self): task = asyncio.create_task(self._create_user(username="user", email="email@email.com")) self.user = await task Running this test, it turn out that self.user is a coroutine and it's impossible to access the attributes I expect. How to solve this ? -
problem on loading tensorflow models in django website backend in pythonanywhere hsoting
I trained few tensorflow models and saved them using h5 extension.I am trying to load them in django backend in a view.All versions that i use are latest for django,tf and python. models['1'] = load_model("static/car_model.h5",compile=False) models['2'] = load_model("static/model1.h5",compile=False) models['3'] = load_model("static/model2.h5",compile=False) models['4'] = load_model("static/model3.h5",compile=False) models['5'] = load_model("static/model4.h5",compile=False) This code worked for me in testing.BUt when i try to host it in pythonanywhere First i got errors on path as model not found.Later I tried to change path to os.get_dir("static")+modelname.h5 After running it there is a error message saying could not load backend "Error code: 502-backend" I am confused what to change and where is actual problem.please help thanks. -
pdfkit : header containing watermark not repeating
In my Django project, I need to add watermark on all the pages of the pdf document being generated. I initially tried with regular css but ended up getting multiple watermarks per page. To work around it, i created a template only for header and mapped it against a url. my header.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <style> #watermark { position: fixed; z-index: 99; opacity: 0.5; top: 300px; } </style> </head> <body> <div id="watermark"> <img src="/media/images/policy_cancel.png" style=" width: 650px; height: 414px;"> </div> </body> </html> in my urls.py re_path(r'^header/$', views.header), I'm passing this as options in pdfkit as follows : _options = { 'cookie': [ ('csrftoken', options.get('csrftoken','none')), ('sessionid', options.get('session_key','none')), ], 'footer-center': 'Page [page] of [topage]', 'footer-right': DOC_VERSION.get(doctype,''), 'footer-font-size': '9', 'header-html': 'http://127.0.0.1:8000/b/header/', } ISSUE : when pdf is generated, the header is getting printed only on the first page and the footer related configurations have been lost. -
How can i get the name of the Foreign Key on Django List View with qyery returns None
I want to display on the page the name of categoria When there is at least one series, I can get the name. Otherwise, it just returns none! I am trying to create a new context variable to pass the categoria name. But I fell I am doing something wrong... and complicated also... Can someone help me to pass the categoria name into template even if there is no series returned? Thanks... Error Displayed DoesNotExist at /categoria/15 Categoria matching query does not exist. Request Method: GET Request URL: http://localhost:8000/categoria/15 Django Version: 3.1 Exception Type: DoesNotExist Exception Value: Categoria matching query does not exist. view.py class CatergoriasSeriesView(ListView): model = Serie template_name = 'categorias_series_of.html' paginate_by = 10 def get_queryset(self): return Serie.objects.filter(categoria=self.kwargs['categoria']) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['cat'] = self.kwargs['categoria'] context['cat_name'] = Categoria.objects.get(categoria=self.kwargs['categoria']) return context models.py class Categoria(models.Model): categoria = models.CharField( max_length=200, verbose_name="Nome da categoria", help_text="colocar aqui o texto de ajuda") class Meta: verbose_name_plural = "Categorias" verbose_name = "categoria" def get_absolute_url(self): return reverse('series_da_categoria', kwargs={'pk': self.pk}) class Serie(models.Model): serie = models.CharField( max_length=200, verbose_name="Série", help_text="colocar aqui o texto de ajuda") categoria = models.ForeignKey( Categoria, default=1, on_delete=models.SET_DEFAULT) HTML template {% if object_list %} {% for serie in object_list %} <div> {% if forloop.first %} <h1 …