Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ordering of related models by a field
I'm stuck in the ordering of a queryset and looking here for inputs I have two models such as - class Groups(models.Model): participants = models.ManyToManyField(User, related_name='group_member') def __str__(self): return str(self.id) and the second one as - class GroupViews(models.Model): group = models.ForeignKey(Groups, related_name="abc", on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now=True) I have to sort Groups in the reverse order of timestamp - (latest first) My approach till now - First way - grps = Groups.objects.filter(participants__id = userId) orderedGrp = grps.order_by("-abc__timestamp").distinct() .distinct() doesn't work here and I get multiple instances because Groups is used as one-to-many in GroupVIews Second way - grps = Groups.objects.filter(participants__id = userId) da = [] //get the last element because timsestamp depends on last for each in grps: da.append(GroupViews.objects.values_list("id", flat=True).filter(group = each).last()) //get the orderer values of Group from here orderedValues = GroupViews.objects.values_list("group", flat=True).filter(id__in = da).order_by('-timestamp') // here I have ordered Id of Groups, How can I run a query to get Groups in the same order ( values of OrderValues) Anyone ? Thanks!! -
Not getting the required interface everytime i search using/admin ,
I am following a yt tutorial on django(https://www.youtube.com/watch?v=sm1mokevMWk) where the tutor searches http://127.0.0.1:8000/admin and gets the required interface (It starts around 49:00) everytime i search http://127.0.0.1:8000/admin i get a DoesNotExist at /admin but when i search http://127.0.0.1:8000/admin/login/?next=/admin/nw/ i get the required interface A question exactly same as mine has been asked before but the thing is i did not make the same error as that person did this is my views.py from django.shortcuts import render from django.http import HttpResponse from .models import ToDoList,Items def index(response,name): ls=ToDoList.objects.get(name=name) item=ls.items_set.get(id=1) return HttpResponse("<h1>%s</h1><br></br><p>%s</p>"%(ls.name,str(item.text))) # Create your views here. this is my urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include("main.url")), ] this is my models.py from django.db import models class ToDoList(models.Model): name=models.CharField(max_length=200) def __str__(self): return self.name class Items(models.Model): todolist=models.ForeignKey(ToDoList,on_delete=models.CASCADE) text=models.CharField(max_length=300) complete=models.BooleanField() def __str__(self): return self.text -
How to use autocomplete-light with taggit?
What's suggested in the documentation doesn't work, so it can be assumed that no documentation exists. I tried what it suggests: models.py from django.db import models from taggit.managers import TaggableManager class SomeModel(models.Model): name = models.CharField(max_length=200) tags = TaggableManager() def __str__(self): return self.name views.py from dal import autocomplete from taggit.models import Tag class TagAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Tag.objects.none() qs = Tag.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs which doesn't work and results in an empty query set with an authenticated user. To be fixed, Tag.objects has to be changed to SomeWorkingModel.objects. Followed by registering endpoints: path( 'some-model-autocomplete/$', SomeModelAutocomplete.as_view(), name='some-model-autocomplete', ), which works fine when reversed or queried in browser. Then I place a TagField in the form: tags = TagField(label='', widget=TaggitSelect2('some-model-autocomplete')) and in the template, I include these at the end <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> {{ form.media }} The result: a useless, large text area in the middle of the form that doesn't do or respond to anything. I don't care if a solution exists in assembly language as long as it works and it can be proven it works with this setup, suggestions for alternatives … -
TypeError when creating superiser in Django using custom users app
I am building a custom users app in Django for the web application I am making and tried to create a superuser (using this command: python manage.py createsuperuser), I added the username, email and phone number but when I enter the password (letters and numbers) I got the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/john/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/john/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/john/venv/lib/python3.6/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/john/venv/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/home/john/venv/lib/python3.6/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/john/venv/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/home/john/users/models.py", line 47, in create_superuser return self._create_user(username, phone_number, email, password, True, True, **extra_fields) File "/home/john/users/models.py", line 29, in _create_user user.set_password(password) File "/home/john/venv/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 99, in set_password self.password = make_password(raw_password) File "/home/john/venv/lib/python3.6/site-packages/django/contrib/auth/hashers.py", line 79, in make_password % type(password).__qualname__ TypeError: Password must be a string or bytes, got int. this is the model.py script for the users model import random from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core import validators from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager, … -
I am creating an jobsearch website in django. where jobseekers can find jobs and recruiters can post the jobs,
I have three diffrent apps in my django project, Home, jobseeker and recruiter. and each app have different subdomain. Home => localhost:8000, jobseeker => jobseeker.localhost.8000, and for recruiter => recruiter.localhost:8000. i have an registration form in my Home app(localhost:8000) when i submitting the form i am getting.. Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: Origin checking failed - null does not match any trusted origins. how can i solve this? here is my hosts.py file from django_hosts import patterns, host host_patterns = patterns('', host(r'^(?:www\.)?$', 'Home.urls', name='perfectpesha'), host(r'jobseeker', 'jobseeker.urls', name='jobseeker'), host(r'recruiter', 'recruiter.urls', name='recruiter'), ) here is my registration form {% extends "layout.html" %} {% load i18n %} {% load hosts %} {% load static %} {% load tz %} {% block content %} <form class="form-horizontal" method="POST" action="{% host_url "jobseekerRegister" host "jobseeker" %}"> {% csrf_token %} <div class="formrow"> <input type="text" name="name" class="form-control" required="required" placeholder="Full Name" {% if form.name.errors %}style="border: 1px solid #FE0004"{% endif %}> {% if form.name.errors %} {% for error in form.name.errors %} <span class="help-block-error"> <strong>{{ error }}</strong></span> {% endfor %} {% endif %} </div> <div class="formrow"> <input type="email" name="email" class="form-control" required="required" placeholder="Email" {% if form.email.errors %}style="border: 1px solid #FE0004"{% endif %}> {% if form.email.errors %} … -
Passing Context Processors as parameters in decorator call in django
Is there a way that I can access a context processor value and pass it as parameters to a decorator. Or can I pass request object as parameter to this decorator call. For example like this: @method_decorator(csp_replace(FRAME_ANCESTORS=[context_processor]),name="dispatch") -
Can't connect to Django Websocket
I'm in the process of creating a django websocket and trying to test the simplest version of it with postman ExpState is the name of my app ExpState/routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r"ws/expstate/", consumers.ExpState.as_asgi()), ] ExpState/consumers.py import json from channels.generic.websocket import WebsocketConsumer class ExpState(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] self.send(text_data=json.dumps({"message": message})) My_Project/asgi.py import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") # Initialize Django ASGI application early to ensure the AppRegistry # is populated before importing code that may import ORM models. django_asgi_app = get_asgi_application() import chat.routing application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(chat.routing.websocket_urlpatterns)) ), } ) I'm trying to connect to the websocket with postman on ws://127.0.0.1:8000/ws/expstate/ the error postman is giving me is Error: Unexpected server response: 200 -
Using Graphql with Django : Reverse Foreign key relationship using related name for all objects
I'm working with graphene-django ,graphql and django and i want to use the reverse foreign key concept of drf using related name but currently i facing difficulty in achieving that i have put up the models, code and also the output screenshot below import asyncio asyncio.set_event_loop(asyncio.new_event_loop()) import graphene from graphene_django import DjangoObjectType from .models import Category, Book, Grocery, FileUpload from django.db.models import Q from graphene_file_upload.scalars import Upload import decimal class BookType(DjangoObjectType): class Meta: model = Book fields = ( 'id', 'title', 'author', 'isbn', 'pages', 'price', 'quantity', 'description', 'status', 'date_created', ) class FileUploadType(DjangoObjectType): class Meta: model = FileUpload fields = ('id', 'file') class GroceryType(DjangoObjectType): class Meta: model = Grocery # fields = ( # 'product_tag', # 'name', # 'category', # 'price', # 'quantity', # 'imageurl', # 'status', # 'date_created', # ) class CategoryType(DjangoObjectType): grocery = graphene.List(GroceryType) class Meta: model = Category fields = ('id', 'title', 'grocery') class Query(graphene.ObjectType): books = graphene.List( BookType, search=graphene.String(), first=graphene.Int(), skip=graphene.Int(), ) categories = graphene.List(CategoryType) # books = graphene.List(BookType) groceries = graphene.List(GroceryType) files = graphene.List(FileUploadType) # def resolve_books(root, info, **kwargs): # # Querying a list # return Book.objects.all() def resolve_books(self, info, search=None, first=None, skip=None, **kwargs): qs = Book.objects.all() if search: filter = ( Q(id=search) | Q(title__icontains=search) ) … -
ValueError: Cannot assign "'A0A0B2SJI5'": "Protein.protein" must be a "ProteinSequence" instance
I'm trying write a python script to add data from a .csv file (django and sqlite) and I'm stuck on this issue since days. My django model looks like this: class Protein(models.Model): protein = models.ForeignKey(ProteinSequence, on_delete=models.DO_NOTHING, null=True, blank=True, db_constraint=False) protein_taxonomy = models.ForeignKey(Taxonomy, on_delete=models.DO_NOTHING) protein_length = models.IntegerField(null=True, blank=True) protein_domains = models.ForeignKey(ProteinFamily, on_delete=models.DO_NOTHING) def __str__(self): return self.protein.protein_id class ProteinSequence(models.Model): protein_id = models.CharField(max_length=10, null=False, blank=False) protein_sequence = models.TextField(null=True) def __str__(self): return self.protein_id Python script: for entry in protein: if entry[0] in proteinSequence_rows: row = Protein.objects.create(protein=proteinSequence_rows[entry[0]],protein_length=entry[1],protein_domains=proteinFamily_rows[entry[2]],protein_taxonomy=taxonomy_rows[entry[3]]) row.save() else: row = Protein.objects.create(protein=entry[0],protein_length=entry[1],protein_domains=proteinFamily_rows[entry[2]],protein_taxonomy=taxonomy_rows[entry[3]]) row.save() I've added 'db_constraint=False' to the protein field, when I try to run the script, it still gets stuck on the line that it cannot find in the ProteinSequence model. ValueError: Cannot assign "'A0A0B2SJI5'": "Protein.protein" must be a "ProteinSequence" instance. Any pointers how to fix this? I don't want to enforce the foreign key constraint but I still need it, when it exists. Entries get written in the database before the script finds a protein_id that doesn't have a matching pair in the proteinSequence table. I have also tried deleting the database and migration files and migrate again, still the same. -
django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
I am working on a Django project without docker, and I am using Mysql database for local and production environements. I am using windows 10 OS and I also have WSL on my windows. My Python version for windows is 3.9.10 and my python version for WSL is 3.8.10. When I was working with 3.9.10 using Windows command line, there was no issue with mysql connection and project was running successfully, however, I lost some requirement dependencies. I was not allowed to loose those dependecies by my client. So I asked my client about python version they were already using and it was python3.8.10 and it worked using WSL and I didn't lose any requirement dependency. My Problem: Now the problem is I am facing issue of django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket when I run python3 manage.py runserver after installing all the requirements successfully. I have searched a lot and I came to know that there is something wrong in my.cnf file. I searched for my.cnf file in MySql/etc/my.cnf folder but there is no file in the whole mysql folder. Can I create a my.cnf file manually? NOTE: Mysql8 is already running. How can I … -
Upload file and convert on the fly- django
I have this file in txt that am cleaning and converting it to excel which have been able to, i just wanted to make an in interface for the user to do the conversion instead of using the raw code.. I have tried to upload the file but now unable to connect the 'dots' -
What do I do to fix my PostgreSQL database connection problem in Django?
I am trying to connect my Django project to a PostgreSQL database I created on AWS but I keep getting this error message each time I run py manage.py runserver. Here is the error message: django.db.utils.OperationalError: connection to server at "database-1.ce7oz69tjzjc.us-east-1.rds.amazonaws.com" (52.3.150.111), port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections? I followed the tutorial on w3school and followed all instructions. I created a PostgreSQL database then I updated my settings with the following: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'codekeen', 'USER': 'baseuser', 'PASSWORD': 'database', 'HOST': 'database-1.ce7oz69tjzjc.us-east-1.rds.amazonaws.com', 'PORT': '5432' } } as I was told to, but I keep getting the error each time try migrating or running the server. What do I do to fix this? -
Import .VCF file directly without downloading to storage
5 I am creating a HTML page with JavaScript, I want it to work at both iOS and Android, when my button is clicked, the browser should ask to open this .vcf by “contact”, or default opening by “contact” and user can save it. Especially for Android, An Android phone need to import manually the VCF by opening “contact” and select “import from” storage. That isn’t user friendly! I am wondering if the code itself can request automatically the inbuilt “contact”app. Open vCard with Javascript this is similar question but did not solve for android I tried window.open() and it download my VCF on chrome instead of opening it, I will test on phone tomorrow but probably same situation will happen because browser can’t recognize VCF format -
Can't able to load the api monkeydev in java script
I am trying to make a chat bot using java script by using the django framework just to ;load the content, but i am getting the console error : Access to XMLHttpRequest at 'https://api.monkedev.com/fun/chat?msg=hi' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. GET https://api.monkedev.com/fun/chat?msg=hi net::ERR_FAILED 200 Uncaught (in promise) D {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …} here is my html: ChatBot AI ChatBot Send here is the cdn for axios: https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.2/axios.min.js here is my javascript code: function init() { let res_elm = document.createElement("div"); res_elm.innerHTML="Hello Myself AI, How can I help you?" ; res_elm.setAttribute("class","left"); document.getElementById('msg').appendChild(res_elm); } document.getElementById('reply').addEventListener("click", async (e) => { e.preventDefault(); var req = document.getElementById('msg_send').value ; if (req == undefined || req== "") { } else{ var res = ""; await axios.get(`https://api.monkedev.com/fun/chat?msg=${req}`).then(data => { res = JSON.stringify(data.data.response) }) let data_req = document.createElement('div'); let data_res = document.createElement('div'); let container1 = document.createElement('div'); let container2 = document.createElement('div'); container1.setAttribute("class","msgCon1"); container2.setAttribute("class","msgCon2"); data_req.innerHTML = req ; data_res.innerHTML = res ; data_req.setAttribute("class","right"); data_res.setAttribute("class","left"); let message = document.getElementById('msg'); message.appendChild(container1); message.appendChild(container2); container1.appendChild(data_req); container2.appendChild(data_res); document.getElementById('msg_send').value = ""; function scroll() { var scrollMsg = document.getElementById('msg') scrollMsg.scrollTop = scrollMsg.scrollHeight ; } scroll(); } }); -
get original file name and extension for TemporaryUploadedFile for django
i am uploading file from react form to django rest framework.In django, i am using following code to get uploaded files array. images_data =dict((self.context['request'].data).lists()).get('images', None) in settings.py file, i am using TemporaryFileUploadHandler FILE_UPLOAD_HANDLERS = ['django.core.files.uploadhandler.TemporaryFileUploadHandler'] i want to know the original name of the file that was sent to server. in name i just get a random string with no extension. i want to save the file with original extension and name. how can i get the original name and extension of the file? i am using python 3.7.12 -
How to add Likes without asking user for Authentication?
I have a pretty simple Django app for quotes. I want to add likes to every single quote but I don't want user to login for that. How can I achieve this without Logging in the user? I tried to uniquely identify users without logging in. -
Django Return the rank of each subject for each student
in my django project I have a model like this using SQLite database class assessment(models.Model): className = models.ForeignKey(classArmTeacher, on_delete=models.CASCADE, null=True) student = models.ForeignKey(students, on_delete=models.CASCADE, null=True) subjectName = models.ForeignKey(allsubject, on_delete=models.CASCADE, null=True) firstCa = models.IntegerField(default=0) secondCa = models.IntegerField(default=0) exam = models.IntegerField(default=0) i would like to a query that will return the List of each student the SUM of firstCa ,secondCa and exam for each subject offered by each student The rank of each sum for each student here is what i have which gives me the sum examtotal as expected but i cant get the Rank subjectRank to work student_ids = students.objects.filter(id__in=assessment.objects.filter(className=self.kwargs['pk']).values('student_id')) context["all_students"] = student_ids.annotate( examtotal=Sum(F('assessment__firstCa') + F('assessment__secondCa') + F('assessment__exam'), output_field=FloatField()), subjectRank= Window(expression=Rank(), order_by=F('examtotal').desc()), ) -
How to remove label of `ModelSelect2Multiple` widget?
Here's a form using django-autocomplete-light from dal import autocomplete from django import forms from core.models import TModel class TForm(forms.ModelForm): class Meta: model = TModel fields = ('name', 'test') widget = autocomplete.ModelSelect2Multiple( 'select2_many_to_many_autocomplete' ) widgets = {'test': widget} which generates the view below I want to remove Test: from the second field, how can I do so? -
Is Django application affected by the server timezone?
I have the below settings: TIME_ZONE = UTC USE_TZ = True My server timezone is UTC+1 and the end user's timezone is UTC+2. Should I care about the server timezone or it is not related at all? -
Is current time zone detected by default if USE_TZ=True
It is mentioned in docs that the current time zone should be activated. You should set the current time zone to the end user’s actual time zone with activate(). Otherwise, the default time zone is used However, I see that the values are parsed in my local timezone in the forms correctly without activating it from my side, and TIME_ZONE is UTC which is different from my local timezone. -
HTML convert to PDF not wysiwyg in Django
I'm trying to convert HTML to PDF using xhtml2pdf in django. I use ckeditor to input and in HTML it's look wysiwyg like this. But after i convert to PDF, it looks like this. Why in PDF is not same like in HTML ? -
calculate percentages over ArrayAgg column
I am trying to calculate the percentages of an aggregate column using this model function: def get_data(self, e_type, district, s_id): a = ( self.select_related("modelC") .select_related("modelP") .values("date_e", "e_type", "a_name", "a_type") .filter( e_type__iexact=e_type, a_name__iexact=district, s_id=s_id ) .annotate(c_ids=ArrayAgg("modelC__c_name")) .annotate(all_v=ArrayAgg("t_v")) .annotate(p_ids=ArrayAgg("modelP__p_name")) .order_by("-date_e") ) Say I get this value for all_v {2,3,4,5}, if I need to generate a new Aggregate column for each value in all_v, i.e. {14%, 21%, 29%, 36%}, how can I extend what I currently have or (rewrite it if that is the only option) to get percentages as well? I know I can get the aggregate sum of all_v by adding .annotate(percentages=(Sum("t_v"))), but not sure how to get percentages from there. -
Django: The view core.create_bet.PredictionCreate didn't return an HttpResponse object. It returned None instead in django?
I am creating an update view that would perform some calculations an return some result based on the calculations, however i keep getting this error whenever i try submitting my form. class PredictionCreate(LoginRequiredMixin, ProductInline, CreateView): ... def form_valid(self, form): new_form = form.instance user = self.request.user if user.profile.wallet_balance > new_form.amount: if new_form.amount >= 10: user.profile.wallet_balance -= new_form.amount user.profile.save() else: messages.warning(self.request, "Your bet amount cannot be less than $10.") return redirect("core:dashboard") else: messages.warning(self.request, "You don't have enough fund to create this bet, fund your wallet and try again.") return redirect("core:dashboard") -
Django {% include %} tag does not behave as expected
I have a post form that I want to include in my profile template using another template (post_template.html). I created the template and try to render it from post view, but when I try to include it in my parent template, is not including the form, just the button. forms.py class PostForm(forms.Form): title = forms.CharField() tag = forms.ChoiceField(choices=tags) date_time = forms.DateTimeField() description = forms.CharField(widget=forms.Textarea(attrs={'name': 'body', 'rows': 2, 'cols': 40})) post_file = forms.FileField() class Meta: model = Posts fields = ['title', 'tag', 'date_time', 'description', 'post_file'] exclude = ['post_relation'] view.py @login_required(login_url='login_user') def post(request): user = request.user user_id = request.user.id post_form = PostForm() if request.method == 'POST': post_form = PostForm(request.POST, request.FILES) if post_form.is_valid(): post_file = post_form.cleaned_data.get('post_file') title = post_form.cleaned_data.get('title') tag = post_form.cleaned_data.get('tag') date_time = post_form.cleaned_data.get('date_time') description = post_form.cleaned_data.get('description') post_form.save() if not Posts.objects.filter(id=get_id): post_data = Posts(post_relation_id=user_id, title=title, tag=tag, date_time=date_time, description=description, post_file=path_post_file) post_data.save() else: return redirect("feed") return http.HttpResponseRedirect(reverse(f"user_profile", kwargs={"username": str(user.username)})) else: print("Post form is not valid!") return render(request, "includes/post_template.html", {'post_form': post_form}) post_template.html <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in post_form %} <div class="post_form_class"> {{ field.label_tag }} {{ field }} </div> {% endfor %} <button class="post_button" id="post_button_id" name="post_btn" type="submit">Done</button> </form> Parent template. {% include "includes/post_template.html" with post_form=post_form %} {% include "includes/post_template.html" only … -
Getting a 404 page not found, The current path, product/, matched the last one
urls.py from django.urls import path from . import views urlpatterns = [ path('', views.product, name='products-page'), path('add-product', views.ProductAddView.as_view(), name='add-product'), path('<int:pk>/delete/', views.ProductDeleteView.as_view(), name='product-delete'), # path('product/<int:id>', views.product_detail, name='product-detail-page'), # path('product/<int:pk>', views.SingleProductView.as_view(), name='product-detail-page'), path('<int:pk>/', views.ProductUpdateView.as_view(), name='product-update'), ] Views.py def product(request): try: products_all = Product.objects.all() num_products = products_all.count() product_dict = { "data":products_all, "total": num_products } return render(request, 'products/product.html', context=product_dict) except: # Http404 will automatically look for a 404 html in templates raise Http404() Seems to be something related to the query to the database. If I print the results to the console and remove the results from the context, the page loads.