Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pylint does not ignore migrations
I use Pylint and run it via pre-commit hook. It doesn't ignore my migrations folders. What should I add to configuration? repos: - repo: https://github.com/PyCQA/pylint rev: pylint-2.5.2 hooks: - id: pylint name: pylint entry: pylint language: system types: [python] args: - --rcfile=./backend/.pylintrc - --load-plugins=pylint_django And .pylintrc [MASTER] init-hook='import sys; sys.path.append("./backend")' max-line-length=120 disable= missing-module-docstring, missing-function-docstring, missing-class-docstring, too-few-public-methods, no-self-use, fixme, ignore=migrations -
Chart.js - Multiple bar Charts - Only Show Last Chart
Chart.js - Multiple Bar Charts - Only Show Last Chart.Basically data comes from django and is rendered in the template.Data is proper but only one of 2 charts are being rendered. I also tried changing ctx but it did not worked HTML Code <div class="container"> <div id="container" class="col-6"> <canvas id="indiacanvas"></canvas> </div> <div id="container" class="col-6"> <canvas id="usacanvas"></canvas> </div> </div> Basically data comes from django and is rendered in the template.Data is proper but only one of 2 charts are being rendered. I also tried changing ctx but it did not worked Script.js //BAR CHART USD var barChartData = { labels: [{% for item in listyear1 %}'{{item| date:"Y"}}', {% endfor %}], datasets: [ { label: "Total amount", backgroundColor: "lightblue", borderColor: "blue", borderWidth: 1, data: [{% for inr in USATOTAL %}'{{inr}}', {% endfor %}], }, { label: "Amount Recieved", backgroundColor: "lightgreen", borderColor: "green", borderWidth: 1, data: [{% for rinr in RUSDS %} '{{rinr}}', {% endfor %}], }, { label: "Amount Left", backgroundColor: "pink", borderColor: "red", borderWidth: 1, data: [{% for linr in LUSDS %} '{{linr}}', {% endfor %}], }, ], }; var chartOptions = { responsive: true, legend: { position: "top", }, title: { display: true, text: "YearWise Summary USD", }, scales: { … -
Cheapest Python / Django Web Hosting in UK? [closed]
Where is the cheapest Python / Django Web Hosting in UK? Preferably shared hosting (which is usually cheapest). Any recommendation? -
What is the best data structure for this sensordata?
I'm currently working on a project to store sensordata in a database using the Django framework. I'm receiving a data object that has 19 data fields, which can be interpreted differently depending on the type of measurement. For the sake of this question, I'm going to simplify the data fields to five fields. The received data looks like the following example: { "data type": 1 "values":[12, 18.4, 14, 15, 1] } The data values can be interpreted depending on the data type. So for example, the lookup table might look something like this: Data type 1: Climate control | field | description | unit | | --- | --- | --- | | 1 | Room temperature | C | | 2 | Desired temperature | C | | 3 | Cooler power percentage | % | | 4 | Valve position | % | | 5 | Power supply | kWh | Each of these data types might have a different interpretation of the given data. The question How would I go about storing this data in the best way possible? Do I: Store the raw values in the database, and define the context of the values in the … -
Alter data in django tables via views.py
I am creating an eCommerce site and need to reduce the stock of products available when a user purchases them. This is done via views.py and without any forms involved. I am currently doing... product = ProductItem.objects.filter(id=4).first() product.quantity_available -= items.get('quantity') product.save() Where items.get('quantity') shows the quantity of the number of items that a user has bought of that product. However, for some reason, this code doesn't seem to work. Is there any error in this? Any help would be greatly appreciated. Thanks! -
Djano: How to query on json field to get string values stored as json
I have a JSONField column in a data model like this one: class SomeModel(models.Model): extra_data = JSONField(null=True, blank=True) records in the database contain values of mixed types: actual objects and strings. Like this one: id extra_data 1 '{"a":1}' 2 {"a": 1} Notice the extra quotation marks on the first row. I want to query only those string records. How can I achieve this? I tried to find out how can I achieve this within postgres too, looking at this postgres page I could not find any means. -
Django-SES: InvalidClientTokenId - The security token included in the request is invalid
I have been trying to set up django-ses for my Django application, but I keep getting the following error: Error: unable to send email BotoServerError: 403 Forbidden <ErrorResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/"> <Error> <Type>Sender</Type> <Code>InvalidClientTokenId</Code> <Message>The security token included in the request is invalid.</Message> </Error> <RequestId>c59883a9-c3fd-48c1-ada5-0a97d607a83e</RequestId> </ErrorResponse> Here are parts of my code that may help in decoding the issue: Environment Variables AWS_ACCESS_KEY_ID='<Key from My Security Credentials in AWS (root user)>' AWS_SECRET_ACCESS_KEY='<Secret from My Security Credentials in AWS (root user)>' AWS_SES_REGION_NAME=ap-south-1 AWS_SES_REGION_ENDPOINT=email.ap-south-1.amazonaws.com I have also set up my custom send_email function which I am using in my views: def send_email(receiver, email_message, subject, reply_to=None, **kwargs): sender = "noreply@xxx.com". # Verified email ID by AWS if type(receiver) == list or type(receiver) == tuple: receivers = list(receiver) else: receivers = [receiver] init = time.time() try: # smtp_server.sendmail(sender, receivers, msg.as_string()) for rec in receivers: recipient = [rec] msgtoUser = EmailMultiAlternatives(subject=subject, body=email_message, from_email=sender, to=recipient, reply_to=reply_to) msgtoUser.attach_alternative(email_message, "text/html") msgtoUser.send() print("Successfully sent email") except Exception as e: print("Error: unable to send email", e) finally: pass print("send email took " + str(time.time() - init) + " secs") Even after going through the steps in the way that the documentation of django-ses recommends, I end up with the same error about the … -
Add filed to serializer if user is admin django rest
I have following Serializer class PersonSerializer(serializers.ModelSerializer): comments = serializers.SerializerMethodField('paginated_comments') images = ImageSerializer(source='image_set', many=True) class Meta: model = Person exclude = ('paid', 'status', 'register_date', 'paid_date') def paginated_comments(self, obj): page_size = self.context['request'].query_params.get('size') or 12 paginator = Paginator(obj.comment_set.all(), page_size) page_number = self.context['request'].query_params.get('page') or 1 comments = paginator.page(page_number) serializer = CommentSerializer(comments, many=True) return OrderedDict( [ ('count', len(serializer.data) if serializer.data else 0), ('next', comments.has_next()), ('previous', comments.has_previous()), ('results', serializer.data) ] ) Which return info about user id": "718b309c-864d-4c26-a80e-2e744ac3102a", "comments": {}, "images": [], "name": "piwщ", "city": "piwщ", } I want to add to result field is_admin:True if user is admin, but i not, i don't want to add this field to result -
can you help me, why my {% extends %} command in django project doesnt work
I tried to redirect my todolist.html to base.html on higher directory using line {% extends 'base.html' %} and I've got the following error: *Request Method: GET Request URL: http://127.0.0.1:8000/todolist/ Django Version: 2.1.7 Python Version: 3.8.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todolist_app'] Installed 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'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.filesystem.Loader: C:\Users\cypri\pydjango\django-project\taskmate\templates\base.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\cypri\pydjango\tmenv\lib\site-packages\django\contrib\admin\templates\base.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\cypri\pydjango\tmenv\lib\site-packages\django\contrib\auth\templates\base.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\cypri\pydjango\django-project\taskmate\todolist_app\templates\base.html (Source does not exist) Template error: In template C:\Users\cypri\pydjango\django-project\taskmate\todolist_app\templates\todolist.html, error at line 1 base.html 1 : {% extends 'base.html' %} 2 : Exception Type: TemplateDoesNotExist at /todolist/ Exception Value: base.html* -
Inherit from parent class and form, then i want a listview
//i have a modelform class Parrent(forms.ModelForm): someTest = forms.CharField(max_length=20) // i have a child form class Child(Parrent): someTestChild = forms.CharField(max_length=20) // i want a listview for the child form, this is my url.py path('Testing/', views.Child.as_view(),name="child"), //but i get an error saying that this class has no .as_view possibility. Is it possible to create an list and detailview on the child form. -
How to merge field names in django admin?
I want to merge field names of a model in Django admin, In my case I have multiple roles for the Parent Roles . But I want to select any role and assign it to the Parent role from the list. I followed some blogs https://hakibenita.medium.com/how-to-add-custom-action-buttons-to-django-admin-8d266f5b0d41 but not able make it happen. class ParentRole(models.Model): parent_role = models.CharField(max_length=285, blank= True,null=True) role = models.CharField(max_length=285, blank= True,null=True) date_added = models.DateTimeField(null=True, blank= True,auto_now_add=True) date_modified= models.DateTimeField(null=True, blank= True, auto_now=True) modified_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return str(self.role) admin.py class ParentRoleAdmin(admin.ModelAdmin): list_display = ('id','parent_role', 'role') search_fields = ['id', 'parent_role','role' ] ordering = ['-date_modified'] def save_model(self, request, obj, form, change): obj.modified_by = request.user obj.save() admin.site.register(ParentRole, ParentRoleAdmin) -
How to login to django rest-framework using djoser?
I am using Djoser and JWT for authentication from reactJS, but when I called API view which have permission class of isAuthenticated are not accessible, as user is not logged into rest-framework I want to access the current user or user from whom the request came... so, is there any way? or I have to send a token of each request and get user in my API endpoint, if yes then how...I tried to find any resource regarding it but got nothing -
How to get count of objects in a ManyToManyField with 'self' / its own model in django?
I'm trying to implement a network where users can follow each other in django like so: > class User(AbstractUser): > followings = models.ManyToManyField('self', related_name='followers', symmetrical=False) So the followings field is going to contain all the users a user is following, and I would also like to be able to access all of the user's followers, thus the related_name. My question is, if I have a user's username, how can I make a query to retrieve that user object, with the annotation of its number of followings and number of followers? Here's what I've tried: data = User.objects.annotate(number_of_followers=Count('followers'), number_of_followings=Count('followings')).get(username=user) It seems alright to me, but somehow it's showing values that doesn't match the real numbers as in the actual database, as I've checked using the django admin app. -
django admin, select Supplier and add multiples Product with stackedinline
models.py : class Supplier(models.Model): name = models.CharField(blank=True, max_length=50,) city = models.CharField(blank=True, max_length=50) email = models.CharField(blank=True, max_length=50) class Product(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) description = models.CharField(blank=True, max_length=100) DDT = models.FileField(upload_to="DDT/%Y/%m/%d") fattura = models.FileField(upload_to="DDT/%Y/%m/%d") admin.py class AddProductModelAdmin(admin.StackedInline): model = Product extra = 1 @admin.register(Supplier) class SupplierModelAdmin(admin.ModelAdmin): inlines = [AddProductModelAdmin] model = Supplier @admin.register(Product) class ProductModelAdmin(admin.ModelAdmin): model = Product In this way, (when i add a supplier) i can add a supplier and add multiple products. I would (when i add a product) select a supplier from menù and after add multiple product -
Django filter all assigned foreing keys
Hello I would like to ask how to filter all assigned ForeignKeys of the object. My models looks like: class Person(models.Model): name = models.CharField(max_length=250) class VirtualProject(models.Model): project_name = models.CharField(max_length=250) owner = models.ForeignKey(Person) class Hours(models.Model): hours = models.FloatField() assigned_virtual_project = ForeignKey(VirtualProject) date = models.DateField() I am sending GET request with owner and dateRange parameters and I would like to filter all virtual projects assigned to the owner (this is no issue, I can get this) AND also get all hours objects assigned to the virtual projects and sum all hours in specified date range. How I can do that? For frontend I am using React, so I am using django rest framework. What I got so far in views: class GetDataView(viewsets.ModelViewSet): serializer_class = DataSerializer def get_queryset(self): owner = self.request.query_params.get('owner') dateRange = self.request.query_params.get('dateRange') queryset = VirtualProject.objects.filter(owner=owner) return queryset -
how to display register values in another page in django?
enter image description here I want to display fullname , email and phone number from registration page how can i display this is my code def index(request): if request.method == 'POST': member = Member( fullname=request.POST.get('fullname'), companyname=request.POST.get('companyname'),Email=request.POST.get('email'),password=request.POST.get('password'),contactno=request.POST.get('contactno'),role=request.POST.get('role'),) member.save() context = {'msg': 'Registred successfuclly'} return render(request, 'web/index.html', context) return redirect('/') else: return render(request, 'web/index.html') -
Template doest not exist at /
I am new to Django. I made a folder named templates in my project and "Home.html" inside it, After running the server, I am getting error "TemplateDoesNotExist at /". My Views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post [enter image description here][1] class HomeView(ListView): model = Post template_name = 'Home.html' My Urls.py from django.urls import path,include # from . import views from .views import HomeView urlpatterns = [ # path('', views.IndexView, name='IndexView') path("", HomeView.as_view(), name='home'), ] My Settings.py """ Django settings for icoderblog project. Generated by 'django-admin startproject' using Django 3.1.4. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # 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.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '7z!v$&wlvkyu8vwg@m2pv7umaedm+c3$9w%5a3m)ly(=kbp)w_' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'theblog' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', … -
searching with choice text in django admin interface
I am extending user model with AbstractUser and added CharField with choices to it. code looks like this Location_choices = ( ('IN', 'India'), ('USA', 'America'), ('O', 'Other Country') ) class User(AbstractUser): location = models.CharField(choices=Location_choices, max_length=3) def __str__(self): return self.username And registered in admin.py like below class AdminUser(admin.ModelAdmin): search_fields = ('username', 'email', 'id', 'location') # Register your models here. admin.site.register(User, AdminUser) The problem is I am able to search with location choices like (IN, USA, O) But I want to search with choice text india or america How do I achieve It. Thanks in advance -
Performance considerations for serializing a related field very often
Suppose I have an API based on the Django Rest Framework. Most Django models used by the application have a reference to the User model (E.g. uploaded_by, updated_by, approvedd_by, etc.). When calling the API to retrieve instances it is often useful to not only know the ID of the user but also the name. However, an ID is often more useful when making comparisons. For example, to check whether a Task was uploaded by you or by another user. I am not sure how to tackle this kind of "pattern" where both the ID and the name representation are useful under different circumstances. I would really appreciate it if someone could explain what would be the best option for performance here. Currently I do the following: TaskSerializer(serializers.ModelSerializer): uploaded_by_name = serializers.StringRelatedField(source='uploaded_by') Meta: model = models.Task fields = '__all__' read_only_fields = ['uploaded_by_name'] While this obviously works, I was wondering whether this is the best solution when considering performance or whether there are other options that I should consider as well. My main concern here is that for almost any call (since all models have user references) the user table must be hit. Another option would be: In my current project, users call … -
How to serialize each foreign key object with different serializer class in django rest framework
So I'm wondering if it is possible to serialize each foreign key object with different serializer in django rest framework. What I mean is: I have my models like class KingdomModel(models.Model): kingdom_name = models.CharField(max_length=32) owner = models.OneToOneField(User, on_delete=models.CASCADE) faction = models.CharField(max_length=10) class CityModel(models.Model): kingdom = models.ForeignKey(KingdomModel, on_delete=models.CASCADE, related_name="cities") city_name = models.CharField(max_length=32) owner = models.ForeignKey(User, on_delete=models.CASCADE) """ ... other fields aswell """ class ArmyModel(models.Model): home_city = models.ForeignKey(CityModel, on_delete=models.CASCADE, null=True, related_name="own_troops") current_city = models.ForeignKey(CityModel, on_delete=models.CASCADE, null=True, related_name="all_troops", blank=True) status = models.CharField(max_length=32) action_done_time = models.DateTimeField(default=None, null=True, blank=True) target_city = models.ForeignKey(CityModel, on_delete=models.CASCADE, null=True, related_name="incoming_troops", default=None, blank=True) # Shared troops settlers = models.IntegerField(default=0) # Gaul troops pikemen = models.IntegerField(default=0) swordmen = models.IntegerField(default=0) riders = models.IntegerField(default=0) # Roman troops legionaries = models.IntegerField(default=0) praetorian = models.IntegerField(default=0) And I am trying to serialize the armies based on the kingdoms faction. Which works fine when talking about own_troops because they are always going to be serialized with the same serializer, like so. class CitySerializer(serializers.ModelSerializer): own_troops = serializers.SerializerMethodField() incoming_troops = serializers.SerializerMethodField() def get_own_troops(self, city_obj): if(KingdomModel.objects.get(owner=city_obj.owner).faction == "Gaul"): return GaulTroopsSerializer(instance=city_obj.own_troops, context=self.context, many=True, required=False, read_only=False).data elif(KingdomModel.objects.get(owner=city_obj.owner).faction == "Roman"): return RomanTroopsSerializer(instance=city_obj.own_troops, context=self.context, many=True, required=False, read_only=False).data class RomanTroopsSerializer(serializers.ModelSerializer): class Meta: model = ArmyModel fields = ['id', 'home_city', 'current_city', 'target_city', 'status', 'action_done_time', 'settlers', 'legionaries', 'praetorian'] … -
I have some sort of weird bug that is affecting the functionality
When I create an add and click the button, it is supposed to take me to the browse ads page, instead it is rendering the contents of browse ads page in the createad url, such that as if there is 2 browse ads page, and when I refresh the page the same post request is processed again and there we go having multiple ads that are the same. views.py: @login_required(login_url='/login') def createAd(request): if request.method == "POST": item = Ad() item.seller = request.user.username item.seller_contact = request.user.phone item.title = request.POST.get('title') item.description = request.POST.get('description') item.starting_price = request.POST.get('starting_price') item.category = request.POST.get('category') item.condition = request.POST.get('condition') try: item.save() except ValueError: return render(request, "auctions/createAd.html", { "message": "Invalid starting price" }) ad = Ad.get_all_ads() # products = Ad.objects.all() empty = False if len(ad) == 0: empty = True return render(request, "auctions/activeAds.html", { "ads": ad, "empty": empty }) #get else: return render(request, "auctions/createAd.html") urls.py: `urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("viewAd/<int:product_id>", views.viewAd, name="viewAd"), path("dashboard", views.dashboard, name="dashboard"), path("activeAds", views.activeAds, name="activeAds"), path("createAd", views.createAd, name="createAd"), path("addtofavorites/<int:product_id>", views.addtofavorites, name="addtofavorites"), path("closebid/<int:product_id>", views.closebid, name="closebid"), ]` html part: <form action="{% url 'createAd' %}" method="POST"> {% csrf_token %} <div class="form-group"> <input class="form-control" autofocus type="text" name="title" placeholder="Title" required> </div> … -
Unable to prevent modal displaying if form is not valid: problem with order sequence with ajax
I have a Django app with a form (id = form_unblind_form) with valid button (id = unblind_edit). I want to display a modal with informations from database using ajax query. And it works but there is an anormal behavior. The problem is that as modal.sow() is called in success ajax return, modal is displayed even if form is not valid and that is not a correct behavior But I can find the right algo to do that thanks for help //1. first form submission is prevented until OK button on modal is clicked $("#form_unblind_edit").submit(function (event) { if (!prevent_edit) { event.preventDefault(); } }); //2. I query database to recovered information for modal $("#unblind_edit").on("click", function (event) { var csrftoken = getCookie('csrftoken'); var patient = $("#id_pat").val(); var treatment = $("#id_unb_num").val(); $.ajax({ type: "POST", url: '/unblind/already_unblind/', data: { csrfmiddlewaretoken: csrftoken, 'patient': patient, 'treatment': treatment }, dataType: 'html', success: function (data) { $("#popup").html(data); $('#unblindconfirm').modal('show'); //<- PROBLEM HERE as modal is always displayed }, }); }); //3. If user click on OK button, form is finally submitted $("body") .on('click', '#edit_button_OK', function (event) { $('#edit_button_OK').attr("disabled", "disabled"); prevent_edit = true; $("#form_unblind_edit").submit(); }) -
how to convert <QuerySet [<Course: BME108_JUL2020>]> to 'BME108' in python?
I use django2 with python3.6 in windows 10. I want to query the sqlite database in Django. when I tried to add condition to the query, I should use the condition passed by the last query. However, the result of the last query is: <QuerySet [<Course: BME108_JUL2020>]>. The condition I need is 'BME108' How could I convert <QuerySet [<Course: BME108_JUL2020>]> to 'BME108'? -
Django Dynamic Form depending on database values
I'm pretty new to Django, and i'm struggling a bit (since 2 days) to make dynamic form depending on database. Here is my model : from django.db import models class DataElement(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class PathElement(models.Model): name = models.CharField(max_length=150) path = models.TextField() data_element = models.ManyToManyField(DataElement) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=150) path = models.TextField() path_element = models.ManyToManyField(PathElement) def __str__(self): return self.name I have a dropdown with Categories, and, when the user select the category, i want the form to have one dropdown per pathelement listing all the dataelement. Thx in advance -
Django OperationalError at new model object
I created a system with Django. My model was working until I added a new field but when I add new field it gives an error. My new field is owner_id OperationalError at /pdfs/ no such column: financial_analysis_pdf.owner_id_id How Can I fix it? models.py class Pdf(models.Model): CHOICES = [ .. ] STAT = [ ... ] id = models.AutoField(primary_key=True) title = models.CharField(max_length=200) pdf = models.FileField(upload_to=user_directory_path) type = models.CharField(max_length=200, default='Select', choices=CHOICES) year = models.CharField(max_length=200, default='Select') created_date = models.DateTimeField(default=datetime.now()) owner_id = models.ForeignKey(Customer, on_delete=models.CASCADE) def __str__(self): return self.title pdfs.html <tbody id="myTable"> {% for pdf in pdfs %} <tr> <td><a href="/ocr" >{{ pdf.title }} </a></td> <td>{{ pdf.year }}</td> <td>{{ pdf.type }}</td> <td> <i class="fas fa-check-circle" style="color: #71ca51"></i></td> <td> <a href="{{ pdf.pdf.url }}" class="btn btn-primary btn-sm" target="_blank">Download</a> </td> <td> <form method="post" action="{% url 'pdf_delete' pdf.pk %}"> {% csrf_token %} <button class="btn btn-danger btn-sm" type="submit" onclick="return confirm('Are you sure you want to delete this analyse?');"><i class="fas fa-trash"></i></button> </form> </td> </tr> {% endfor %} </tbody> </table> views.py def pdf_list(request): pdfs = Pdf.objects.all().order_by('-year') return render(request, 'pdf_list.html', {'pdfs': pdfs}) traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/pdfs/ Django Version: 3.1.4 Python Version: 3.8.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'register', 'customer', 'financial_analysis', 'ocr', 'crispy_forms', 'ckeditor'] Installed Middleware: …