Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Groupby using Django's ORM to get a dictionary of lists between two models
I have two models, User and Gift: class User(models.Model): name = models.CharField(max_length=150, null=True, blank=True) ... class Gift(models.Model): user = models.ForeignKey( "User", related_name="users", on_delete=models.CASCADE, ) ... Now I want to create a dictionary of lists to have a list of gifts for every user, so that I can lookup pretty fast the ids of gifts that some users have, in a for loop, without having to query the database many times. I came up with this: from itertools import groupby gifts_grouped = { key: [v.id for v in value] for key, value in groupby(gifts, key=lambda v: v.user_id) } Now every time I wish to lookup the gifts of a user, I can simply do: gifts_grouped[id_of_a_user] And it'll return a list with ids of gifts for that user. Now this feels like a Python solution to a problem that can easily be solved with Django. But I don't know how. Is it possible to achieve the same results with Django's ORM? -
Google chart not showing up on Django
so, I'm sending this data to the frontend from my view: data = [["Name", "Ammount"], ["x", 0], ["y", 2], ["z", 1]] And I'm trying to show this as a bar graph to my user, but nothing is showing up (literally, It's blank where the graphic was supposed to be). My html looks like this: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="description" content="" /> <meta name="author" content="" /> <!-- Favicon--> <link rel="icon" type="image/x-icon" href={% static "assets/icon.ico" %} /> <!-- Core theme CSS (includes Bootstrap)--> <link href={% static "css/styles.css" %} rel="stylesheet" /> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['bar']}); google.charts.setOnLoadCallback(drawChart_decision_type); function drawChart_decision_type() { var data3 = google.visualization.arrayToDataTable({{ my_data|safe }}); var options3 = { chart: { title: 'Stuff', subtitle: 'Test', }, backgroundColor: '#FFFFFF', bars: 'horizontal' // Required for Material Bar Charts. }; var chart3 = new google.charts.Bar(document.getElementById('barchart_materia')); chart3.draw(data3, google.charts.Bar.convertOptions(options3)); } </script> </head> <body> <div class="card_view"> <div id="barchart_material" style="width: 700px; height: 300px;"></div> </div> <!-- Bootstrap core JS--> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script> <!-- Core theme JS--> <script src={% static "js/scripts.js" %} ></script> </body> </html> There are other things on my html code, but nothing that comes to mind as important. Just some hyperlinks that … -
How can I authenticate a user in a FastAPI application using Django's user authentication?
I have a userbase in a Django application and I've created a separate FastAPI application that will live on another server. What I would like to do is have users authenticate on the FastAPI application with their Django credentials. I've followed the FastAPI security documentation to at least get the ground work setup for OAuth2. Looking in that documentation they explicitly provide tips that this setup allows for reading and verifying passwords created by Django (First tip in that link). However, I'm failing to find further resources on how to set that up in a complete loop. Do I need to configure my Django application to also utilize OAuth2 or is their default authentication sufficient? I assume the FastAPI app would have to send a request over to the Django app OR have access to the Django database in order to make the verification. But I'm not quite sure on the proper(secure) steps to implement. Any resources or guidance on how to implement this is greatly appreciated. -
Bootstrap-select not working with HTMX partials
I am trying to use Bootstrap-select with HTMX partials in Django. When a specific element is changed, htmx will return a partial html containing only the dropdown, such as: <select id="myDropdown" class="selectpicker"> <option>Mustard</option> <option>Ketchup</option> <option>Barbecue</option> </select> When loading the main page initially which contains the CDNs alongside myDropdown, selectpicker works fine. However, later when myDropdown gets returned by HTMX, selectpicker doesn't work, getting a display: None !important. This behaviour is exactly as if when rendering the partial html, the CDNs are not available for usage. If instead of using class="selectpicker I use $(function(){ $('#myDropdown').selectpicker();}); it does work. The problem now is that there is a second where myDropdown isn't styled at all, before the JS function kicks in. Does anyone know how to fix this problem or bypass it in a clever way? -
How to use RabbitMQ in production with Kubernetes?
the question may be very simple but still I couldn't find the answer. I am currently developing an application with Django. In this project, I have consumer.py and producer.py files. I need to run consumer.py separately. How can I handle this in production with Kubernetes? Do I need to create a separate service for the consumer? But that doesn't make much sense. Can someone provide information on this? -
Change field value in clean() after negative validation
I have a problem that I don't know how to solve. I don't know if that's even possible :( I have a form that has four fields for simplicity (check, select, time1, time2). When the checkbox is active, the time field is displayed, otherwise select (using JS). class Form(forms.Form): check = forms.BooleanField(required=False, initial=False, widget=forms.CheckboxInput(attrs={'style':'width:20px;height:20px;'})) select = forms.ChoiceField(choices=[], required=False) time1 = forms.TimeField(required=False) time2 = forms.TimeField(required=False) def __init__(self, *args, **kwargs): select = kwargs.pop('select', None) super(Form, self).__init__(*args, **kwargs) self.fields['select'].choices = select def clean(self): cleaned_data = super(Form, self).clean() time1 = cleaned_data.get("time1") time2 = cleaned_data.get("time2") select = cleaned_data.get("select") check = cleaned_data.get("check") if check: if time1 is None or time2 is None: raise forms.ValidationError( {'time1': ["error!", ], 'time2': ["error!", ]} ) else: if select is None: raise forms.ValidationError( {'select': ["error!", ]} ) I don't know how to change the value of the check field to True when the time fields are not filled.I can't use cleaned_data["check"] = True with return because it won't throw an exception -
Can't pass project ID to function
I have the below view: def gdpr_status(request, orgid, pid, status): user = request.user if people.objects.filter(orgid=org.objects.get(orgid=orgid), personid=user).count() > 0: t = project.objects.get(projectid=project.objects.get(projectid=pid), orgid=org.objects.get(orgid=orgid)) t.status = status t.save() url_to_redirect = '/projects/'+orgid return redirect(url_to_redirect) and the below URLs path('gdpr_status/<orgid>/<pid>/<status>', views.gdpr_status, name='gdpr_status'), when I pass the URL 'http://localhost:8082/gdpr_status/1/5/rejected', I get the below error: Field 'projectid' expected a number but got <project: project object (5)>. I don't understand because the project ID is project 5, i'm not passing an object, I am passing an ID for the record I want to update. Can anyone help me please? -
Factory-boy fuzzy DateTimeField always the same date when using create_batch
I am using factory-boy for creating instances of a Django model, and I am always getting the same value returned when using factory.fuzzy.FuzzyDateTime. Minimal example: # factory class class FooFactory(DjangoModelFactory): class Meta: # models.Foo has a dt_field that is a DateTimeField model = models.Foo # creation of object, in unit tests # I can't move the dt_field declaration # into the factory definition since different # unit tests use different start / end points # for the datetime fuzzer now = datetime.datetime.now(tz=pytz.timezone("America/New_York")) one_week_ago = now - datetime.timedelta(days=7) FooFactory.create_batch( 10, dt_field=factory.fuzzy.FuzzyDateTime( start_dt=one_week_ago, end_dt=now ) ) When inspecting the Foo models after factory creation, the dt_field has the same date: >>> [r.dt_field for r in Foo.objects.all()] >>> [datetime.datetime(2022, 12, 10, 20, 15, 31, 954301, tzinfo=<UTC>), datetime.datetime(2022, 12, 10, 20, 15, 31, 961147, tzinfo=<UTC>), datetime.datetime(2022, 12, 10, 20, 15, 31, 967383, tzinfo=<UTC>), ...] -
Check if logged in user is the author of a post | Django | If-else doesn't work
I want to check if the logged in user is the author of a post in my Forum. I have written some code to figure that out: <div class="right-section-posts"> user: {{ user }} <!--Output: Admin--> author: {{ post.author }} <!--Output: Admin--> {% if user == post.author %} <form action="DELETE"> {% csrf_token %} <button type="submit" class="delete-btn" name="post-id" value="{{ post.id }}">Delete</button> </form> <a href=""><button class="edit-btn">Edit</button></a> {% endif %} </div> They both output the same but the statement returns false! Why? Models.py class Post(models.Model): vote_count = models.IntegerField(default=0) id = models.BigAutoField(primary_key=True) created_at = models.DateField(default=date.today) title = models.CharField(max_length=100) description = models.CharField(max_length=1000) tags = models.CharField(max_length=200) author = models.CharField(max_length=100, default="none") def __str__(self): return str(self.id) + ' ' + self.title I tried different ways to get the Current user and the author. Doesn't work to. (I think you might say that I should use ForeignKey instead of ´CharField´, when using that I get this Error: ERROR: Column forum_app_post.author_id does not exist. LINE 1: ...app_post". "description", "forum_app_post". "tags", "forum_app... ^ HINT: Perhaps the intention was to refer to the "forum_app_post.author" column. ) -
How do I use Django's Related Lookups?
I notice that Django's relational fields register 7 lookups: fk.get_lookups() 'in' : <class 'django.db.models.fields.related_lookups.RelatedIn'>, 'exact' : <class 'django.db.models.fields.related_lookups.RelatedExact'>, 'lt' : <class 'django.db.models.fields.related_lookups.RelatedLessThan'>, 'gt' : <class 'django.db.models.fields.related_lookups.RelatedGreaterThan'>, 'gte' : <class 'django.db.models.fields.related_lookups.RelatedGreaterThanOrEqual'>, 'lte' : <class 'django.db.models.fields.related_lookups.RelatedLessThanOrEqual'>, 'isnull' : <class 'django.db.models.fields.related_lookups.RelatedIsNull'>} defined in https://github.com/django/django/blob/stable/3.2.x/django/db/models/fields/related_lookups.py registered in https://github.com/django/django/blob/stable/3.2.x/django/db/models/fields/related.py I'm familiar with how to use __exact (aka =), __in, and __isnull with relations, but there's no mention in the docs of what it means to apply lt / lte / gt / gte to a relation. Are they set comparisons? -
How can I set the Type of an Unpickled Object?
I am unpickling an object (chocolate) that belongs to the class Food via: chocolate = pickle.loads(chocolate_pickled) Assuming I have a Food import at the top of my file, how can I tell python that chocolate belongs to the Food class? -
Getting error in my resume field in django in admin panel when made even made it optional
I have to input a resume field in a interview form website using django which is optional in the form and the form is getting submitted well on the front end but when I am opening the admin panel it is showing errors in the registation in the admin panel if the resume is not uploaded. ` admin.py: class RegAdmin(ImportExportModelAdmin, admin.ModelAdmin): list_display = ('name', 'email', 'branch', 'phone_number', 'terms_confirmed') search_fields = ('name', 'email', 'branch', 'phone_number') def resume_url(self, instance): resume = instance.resume.url if resume: return mark_safe('<a target="_blank" href="%s">Resume Link</a>' % (resume)) else: return '-' ` forms.py resume = models.FileField( upload_to='resumes/', validators=[ file_size, FileExtensionValidator(allowed_extensions=["pdf", "docx"]) ], blank=True, null=True) -
getting an error while trying to start psql server
Hello I'm getting the below error while trying to start psql server on win 10 is there any recommendation? pg_ctl -D C:\Users\Islam.Fayez\AppData\Local\Programs\pgsql\pgdata -l logfile start unrecognized win32 error code: 123unrecognized win32 error code: 123unrecognized win32 error code: 123unrecognized win32 error code: 123waiting for server to start....Access is denied. stopped waiting pg_ctl: could not start server Examine the log output. -
how can i render base.html in one app's view?
i want create a footer info model and use base.html in static folder and why its not work? models.py class FooterContactInfo(models.Model): phoneumber1=models.CharField(max_length=15) phoneumber2=models.CharField(max_length=15) email_help =models.EmailField() address=models.CharField(max_length=100) views.py def FooterContactInfo_view(request): footer = FooterContactInfo.objects.all().last() return render(request, 'base.html',context={'footer':footer}) base.html <li> <a href="#0"><i class="fas fa-phone-alt"></i>{{footer.phoneumber1}}</a> </li> <li> -
Django: LoginView redirects me to accounts/profile instead of the previous page
My page has a navigation bar that is visible on all pages. There is a "Sign In/Sign Up" button. After signing in I would like to redirect the user to the previous page. Example: I'm currently looking to buy vinyl at http://127.0.0.1:8000/vinyls/. I press "Sign In" and I type my credentials. After clicking the Submit button, I would like to get back to /vinyls/. The same goes for /record_labels/, /events/ etc. I tried using <input type="hidden" name="next" value="{{ next }}"> in my sign-in template but I get redirected to /accounts/profile. Then I tried using <a id="nav-a" href="{% url 'sign in' %}?next={{ request.path }}">Sign Up/Sign In</a> but I'm redirected to /accounts/profile. This is my SignInView: class SignInView(auth_views.LoginView): template_name = 'sign-in.html' This is my sign-in.html: <h1>Sign in</h1> <form method="post" action="{% url 'sign in' %}"> {{ form.as_p }} <input type="hidden" name="next" value="{{ next }}"> <p> <button type="submit">Sign in</button> {% csrf_token %} </p> <p>Not a member? <a href="{% url 'sign up' %}">Sign up now</a></p> </form> -
Matching query doesn't exist error when logging in as different user on different tabs on a browser
I am currently work on small project on djnago and it's almost finished. But from the beginning I have been facing a problem that, when I run the webpage on multiple tabs and logs in, only the last logged in user's full data is seen, when I go to the previously logged in user's tab it throws "MATCHING QUERY DOESN'T EXIST!". This makes me to log in with that particular user's data to be seen simultaneously the last logged in user's tab throws the previously mentioned error. My requirement is "It should be able to login different users on different tabs on same browsers and without any error on djnago framework". Please let me know if there is any way. Thanks in advance -
Django is unable to use the SMTP server in the tests environment
I am running a Django (4.1) app in Docker. As part of our test suite, I would like to make use of a development SMTP server which is also running in a Docker container (see docker-compose.yml below). I am using a Selenium driver to run the tests against a Django LiveServer instance. I am also using 1secmail as a temporary mailbox for the tests. The SMTP server is working nicely with Django (i.e. Django is able to send emails with it) only if Django is not running from a LiveServer. Whenever I try to programmatically test a scenario where SMTP is involved (with a Selenium driver), the email never gets sent (see the failing test below). The question is simple: how do I make Django and the SMTP server talk to each other in the tests environment? My docker-compose.yml version: '3.8' services: myapp: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - ./:/usr/src/app/ ports: - 8009:8000 env_file: - ./.env.dev links: - selenium-chrome - dev-smtp-server myapp-db: image: postgres:14-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=blabla - POSTGRES_PASSWORD=blabla - POSTGRES_DB=blabla selenium-chrome: image: selenium/standalone-chrome ports: - 4444:4444 # actual Selenium - 5900:5900 # VNC server dev-smtp-server: image: bytemark/smtp restart: always volumes: postgres_data: My test … -
Issues with poetry when deploying Django app to Render
I am following the “Getting Started With Django on Render” tutorial (https://render.com/docs/deploy-django#update-your-app-for-render) and all was going well until I got to “Configure Django for PostgreSQL”. I have everything copied correctly but I am getting errors now when I run python manage.py runserver this is the error: File "/Users/user/Desktop/First_Program/Portfolio_Projects/Charter_Django_App/Charter_Django_App/config/settings.py", line 14, in <module> import dj_database_url ModuleNotFoundError: No module named 'dj_database_url' even though when I run poetry show it clearly says it is installed asgiref 3.5.2 ASGI specs, helper code, and adapters brotli 1.0.9 Python bindings for the Brotli compression library dj-database-url 1.0.0 Use Database URLs in your Django Application. dj-email-url 1.0.6 Use an URL to configure email backend settings in your Django Application. django 3.2.16 A high-level Python Web framework that encourages rapid development and clean, pragmatic design. django-cache-url 3.4.2 Use Cache URLs in your Django application. environs 9.5.0 simplified environment variable parsing gunicorn 20.1.0 WSGI HTTP Server for UNIX marshmallow 3.19.0 A lightweight library for converting complex datatypes to and from native Python datatypes. packaging 22.0 Core utilities for Python packages psycopg2-binary 2.9.5 psycopg2 - Python-PostgreSQL Database Adapter python-dotenv 0.21.0 Read key-value pairs from a .env file and set them as environment variables pytz 2022.6 World timezone definitions, modern and … -
TypeError. can only concatenate str (not "User") to str
How do I convert request.user.username to a string So far ive tried username = str(request.user.username), username = request.user.get_username() -
Function for returns X times same result
Im new at python and django, i need this function for work if someboyd can help me i'll appreciate it so much. This function has to return in a json file all the different results with the function 'for' but instead it returns 1 result X times the same one X times. @login_required def oferta_reporte_json(request): ofertas_efectiva = OfertaEfectiva.objects.count() ofertas_efectivas = OfertaEfectiva.objects.filter(oferta__completa=True, oferta__activa=True, oferta__finalizada=True) nombre_ofertas = [] # ocurrencias = 0 for efectiva in ofertas_efectivas: nombre_oferta = dict() postulado = dict() entrevistado = dict() seleccionado = dict() entrevistados = [] postulados = [] seleccionados = [] cand_seleccionados = ListaFinal.objects \ .filter(interesado__id_oferta=efectiva.oferta.id) seleccionados_ids = cand_seleccionados.values_list('interesado_id', flat=True) cand_postulados = Postulados.objects \ .filter(interesado__id_oferta=efectiva.oferta.id) \ .exclude(interesado_id__in=seleccionados_ids) postulados_ids = cand_postulados.values_list('interesado_id', flat=True) cand_entrevistados = Entrevistados.objects \ .filter(interesado__id_oferta=efectiva.oferta.id) \ .exclude(interesado_id__in=postulados_ids) #DATOS #MÉTODO PARA VER CUANTAS OFERTAS NO TIENEN 1 ATRIBUTO# # if efectiva.oferta.region is None: # print(efectiva.oferta.id), # print(efectiva.oferta.titulo), # print(efectiva.oferta.nombre_empresa) # ocurrencias = ocurrencias + 1 # print("TOTAL = " + str(ocurrencias)) nombre_oferta['id_oferta'] = efectiva.oferta.id nombre_oferta['titulo_oferta'] = efectiva.oferta.titulo nombre_oferta['nombre_completo_owner'] = efectiva.oferta.owner.first_name + ' ' + efectiva.oferta.owner.last_name nombre_oferta['descripción'] = efectiva.oferta.descripcion nombre_oferta['cargo'] = efectiva.oferta.cargo nombre_oferta['vacantes'] = efectiva.oferta.vacantes nombre_oferta['nombre_empresa'] = efectiva.oferta.nombre_empresa nombre_oferta['descripción_empresa'] = efectiva.oferta.descripcion_empresa nombre_oferta['cultura'] = efectiva.oferta.cultura_empresa nombre_oferta['negocio'] = efectiva.oferta.negocio_empresa nombre_oferta['funciones'] = efectiva.oferta.principales_funciones nombre_oferta['industria'] = efectiva.oferta.industria.nombre nombre_oferta['linea_funcional'] = efectiva.oferta.linea_funcional.nombre nombre_oferta['nivel_cargo'] … -
Django for loop working on one template page, but disappears elsewhere?
I have written a Django for loop that iterates over each instance of my Supplier model to render each instance in my navigation bar. However for some reason it only outputs on one of my templates and not the main page. This is the loop in question: <ul class="nav-drop"> {% for supplier in suppliers %} <li> <a href="{% url 'supplier' pk=supplier.pk %}">{{ supplier.name }}</a> </li> {% endfor %} </ul> here is my views.py file: from django.shortcuts import render from . models import Supplier # Create your views here. def suppliers(request): suppliers = Supplier.objects.all() context = {'suppliers': suppliers} return render(request, 'suppliers/suppliers.html', context) def supplier(request, pk): supplier = Supplier.objects.get(id=pk) context = {'supplier': supplier} return render(request, 'suppliers/supplier.html', context) from django.urls import path from . import views urlpatterns = [ path('suppliers/', views.suppliers, name='suppliers'), path('supplier/<str:pk>/', views.supplier, name='supplier') ] and the model in question: class Supplier(models.Model): name = models.CharField(max_length=200, blank=True, null=True) logo_image = models.ImageField(null=True, blank=True, upload_to='models/', default="models/default.jpg") marketing_image = models.ImageField(null=True, blank=True, upload_to='models/', default="models/default.jpg") description = models.TextField(blank=True, null=True) short_description = models.TextField(max_length=200, blank=True, null=True) social_facebook = models.CharField(max_length=200, blank=True, null=True) social_twitter = models.CharField(max_length=200, blank=True, null=True) social_instagram = models.CharField(max_length=200, blank=True, null=True) social_youtube = models.CharField(max_length=200, blank=True, null=True) social_linkedin = models.CharField(max_length=200, blank=True, null=True) social_website = models.CharField(max_length=200, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) id … -
Is it a good practice to use variables by 'with' tag in django template on global scope
I need to use more times some custon variables (e.g. one of them) with total=business.employees.count But I have a very lot of lines in my code and I think is constant use of them in different parts is not good. So is it good to insert these tags at the very beginning and close at the very end of the file? For example {% load static %} {% with total=business.employees.count %} <html> a lot of lines of code </html> {% endwith %} I need some advice -
Is there a solution to "does not appear to have any patterns in it." problem?
Have a nice day! While I was building my django project, I faced this error. Error: The included URLconf '<module 'posts.urls' from "D:\Created apps\My project\posts\urls.py">' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. So, here's given my project files. -------- posts/urls.py: ---------- ` from django.urls import path from .views import BlogListView, BlogDetailView url_patterns = [ path('', BlogListView.as_view(), name='index'), path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'), ] ` ----------- posts/views.py: ----------- ` from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post class BlogListView(ListView): model = Post template_name = 'index.html' class BlogDetailView(DetailView): model = Post template_name = 'post_detail.html' ` ------------- config/urls.py: ---------- ` """config URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) … -
how do I get value of dictionary 1 by key of dictionary 2 in Django templates
I have 2 dictionaries dict1 and dict2. I'm trying to get the value by the dict1 key to the dict2 key but it getting nothing, is there any way to get the value of dict2 by the dict1 key? always both dictionaries will be the same length? dict1 = {0:[1,2,3],1:[4,5,6]} dict2 = {0:'data1',1:'data2'} {% for key, value in dict1.items %} {{dict2.key}} {% endfor %} -
I ruined the admin page, how do I fix it? ( Django 4.1 )
I have followed the steps from the django tutorial ( https://docs.djangoproject.com/en/4.1/intro/tutorial01/ ) and once I'd finished all the steps I stopped developing the project for 2 weeks at least without giving it much thought. Once I've decided to check how the pages were looking like that's when I found this: The admin page And I don't know how I did it. Here's how the documentation looks like: meuSite/ __init__.py settings.py urls.py asgi.py wsgi.py polls/ migrations/ static/ templates/ admin/ base.html polls/ detail.html index.html results.html __init__.py admin.py apps.py models.py tests.py urls.py views.py db.sqlite3 manage.py SETTINGS: meuSite/settings.py INSTALLED_APPS = [ 'polls.apps.PollsConfig', "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", ] URLS: # meuSite/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path("admin/", admin.site.urls), path("polls/", include('polls.urls')), ] # polls/urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:question_id>/', views.DetailView.as_view(), name='detail'), path('<int:question_id>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote') ] If there's something else that I didn't show that may have the root of the problem, please tell me I tried solving it by deleting the templates/admin directory, but it didn't change how the page looks