Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Remember Me" option when logging in with Django + DRF + Djoser + Nuxt
I've got a site that uses Django as a backend and Nuxt for frontend. I'd like to implement the commonly-seen "Remember Me" checkbox when a user logs in. If unchecked, the user should only be logged in for that session and has to log in again the next time they open their browser. If checked, they should stay logged in indefinitely unless they manually log out. The backend is using Django, with Django Rest Framework and Djoser for authentication. Currently using DRF's TokenAuthentication, and not JWT stuff. The frontend is using Nuxt, which is using the Nuxt Auth module with the local strategy for logging in. This is saving the token in localStorage, which never expires. How would I go about adding this "Remember Me" functionality? I'm not even sure which part to modify - either the backend or the frontend. -
Frontend + NGINX can't make a request to backend endpoints (2 different docker containers)
I am having issues making requests to a backend Django container from a frontend app that is reverse proxied by NGINX. I have a backend Django server which serves database information, carries out authenticated etc. It is containerised thru a docker container. This is locally served on http://127.0.0.1:8000/. I then have NGINX project.conf as follows: server { listen 80; server_name docker_flask_gunicorn_nginx; location / { proxy_pass http://my_app:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /static { rewrite ^/static(.*) /$1 break; root /static; }} There are a few different endpoints in the backend app, but it fails at the first hurdle which is trying to authenticate at /api/token/. When the frontend app makes a request to http://127.0.0.1:8000/api/token/ the following error is returned: HTTPConnectionPool(host='127.0.0.1', port=8000): Max retries exceeded with url: /api/token/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fc3208f6910>: Failed to establish a new connection: [Errno 111] Connection refused')) For completeness the docker-compose for the frontend / NGINX setup is: version: '3' services: my_app: container_name: my_app-frontend restart: always build: ./my_app ports: - "8080:8080" command: gunicorn -w 2 -b :8080 app:server env_file: - ./my_app/.env nginx: container_name: nginx restart: always build: ./nginx ports: - "80:80" depends_on: - my_app From what I can see … -
Django: on visiting page I get an alert with dictionary values in it. What is causing this?
New to Django and python, been following a tutorial and playing around with creating a user to user messaging functionality. So far all works great except that when I visit the messages page I always get an alert like: {'user': <User: test2>, 'last': datetime.datetime(2022, 12, 15, 20, 21, 19, 109214, tzinfo=datetime.timezone.utc), 'unread': 0} alert Any ideas on what is causing this and how can I remove it? urls.py from django.urls import path from . import views as user_views app_name = 'chat' urlpatterns = [ path('messages/', user_views.inbox , name='messages'), path('messages/<username>', user_views.Directs , name='directs'), path('messages/send/', user_views.SendDirect , name='send_direct'), ] views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .models import Message from django.http import HttpResponse, HttpResponseBadRequest from django.template import loader from django.contrib.auth.models import User @login_required def inbox(request): messages = Message.get_messages(user=request.user) active_direct = None directs = None if messages: message = messages[0] active_direct = message['user'].username directs = Message.objects.filter(user=request.user, recipient=message['user']) directs.update(is_read=True) for message in messages: if message['user'].username == active_direct: message['unread'] = 0 context = { 'directs': directs, 'messages': messages, 'active_direct': active_direct, } template = loader.get_template('chat.html') return HttpResponse(template.render(context, request)) @login_required def Directs(request, username): user = request.user messages = Message.get_messages(user=user) active_direct = username directs = Message.objects.filter(user=user, recipient__username=username) directs.update(is_read=True) for message in messages: if message['user'].username … -
Nginx calling directories that don't exist
I'm trying to fix my static files not been served. I finally found out how to access the error log and it turns out that Nginx is searching a category that does not exist. It is requesting: /home/dave/mhprints/static/styles/html-body-styles.css /static/styles/html-body-styles.css My actual path /home/dave/mhprints/static/css/html-body-styles.css /static/css/html-body-styles.css My HTML templates Any ideas why nginx is doing this? I've been trying to fix this problem for my static and images for over 48 hours now. Thank you in advance. -
How to remove a useless "UPDATE" query when overriding "response_change()" in Django Admin?
In PersonAdmin():, I overrode response_change() with the code to capitalize the name which a user inputs on Change person as shown below: # "store/person" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): def response_change(self, request, obj): # Here obj.name = obj.name.capitalize() obj.save() return super().response_change(request, obj) Then, I input david to Name: on Change person as shown below: Then, the name was successfully changed from John to David capitalized as shown below: But according to PostgreSQL logs, there is a useless UPDATE query as shown below. *I use PostgreSQL and you can check On PostgreSQL, how to log queries with transaction queries such as "BEGIN" and "COMMIT": So, how can I remove the useless UPDATE query as shown above? -
import files to django project
sorry for the nooby question . but i got an MNIST project as a college homework and i'm trying to deploy it in a django website so far i made the HTML canvas , the jpg to base64 converter so i transfer the image in a django form, the script to read the base64 string and guess the number and tested them on another project , but my only problem is that i can't make the model folder/file (.model) visible to django . it's my first time working on django and i just want the model to be read by the script i made all the script in view.py folder cuz it ain't much + don't know how to add modules to django view.py : from django.shortcuts import render from django import forms import base64 import io import re from PIL import Image import cv2 import numpy as np import tensorflow as tf ## this isn't visible model = tf.keras.models.load_model(STATIC_URL+'handwriting.model') class Form(forms.Form): cv = forms.CharField(label='') def testable(msg): base64_data = re.sub('^data:image/.+;base64,', '', msg) byte_data = base64.b64decode(base64_data) image_data = io.BytesIO(byte_data) img = Image.open(image_data) img = img.resize((28, 28), resample=Image.Resampling.BILINEAR) a = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2GRAY) a = np.array([a]) recon = model.predict(a) print(f'this is a {np.argmax(recon)} … -
Django queryset hide value of object
I have the following (simplified) Model: class Order(models.Model): is_anonymized = models.BooleanField(default=False) billing_address = models.ForeignKey('order.BillingAddress', null=True, blank=True) I want to hide the billing_address for objects where the customer chosen to do so by setting is_anonymized=True. My best approach so far was to do that in the init: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.is_anonymized: self.billing_address = None self.billing_address_id = None This works fine in the Admin BUT... anywhere in the code there are select_related-QuerySets for Orders: queryset = Order._default_manager.select_related('billing_address') All places where the select_related-querysets are used, the billing_address is accidentally shown. Elsewhere (like in the admin), it isn't. How can I ensure to remove the billing_address everywhere for objects with is_anonymized = True? I thought about overwriting the queryset in the manager but i couldn't overwrite the billing_address field by condition. Using the getter-setter pattern was not a good solution because it breaks the admin at multiple places (there are many attributes to cloak like billing_address). -
Why can't I log in after upgrading Django from 2.2 to 3.2?
I just upgraded my Django 2.2 project to 3.2, and now I cannot login with any user in the database. I am so confused because I'm not getting any error messages, but continually being redirected to the login page after successfully authenticating and logging in. Here are the steps that I am taking: Enter username/password into the login form (works great in 2.2) The python file uses user = authenticate(username=username, password=password) and then login(request, user) I can confirm that the username/password are correct, and printing request.user immediately after the login call logs the correct user. When I inspect the cookies in the browser, a value for sessionid is set. After successful login, the server sends a redirect to an auth-protected route. However, when getting the protected route, printing the request.user is AnonymousUser, and then I am redirected back to the login page. This appears to be an issue with the sessions. I can see that the cookies are being set, and even when I manually set the sessionid cookie to be the value returned by request.session.session_key right after the call to login it still does not recognize the authorized user. I have followed the recommendations in the release notes to … -
getting pk of item in test unit
there is a test unit that gets request and pk of an item in Form and the problem that i cant figure how to create a new item in the data base and get the pk from it in the test unit function. class test_editTransfer_admin(TestCase): def test_editTransfer_page_open(self): url = reverse(views.editTransfer) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'admin_u/editTransfer.html') def test_editTransfer_view_deployed_to_page(self): factory = RequestFactory() request = factory.get('admin_u/editTransfer') response = views.editTransfer(request, #pk here ) self.assertEqual(response.status_code, 200) i tried to defined a setUp function that creates the product but without success.. -
Add search control to django-leaflet admin map. GEODJANGO
I'm totally new to this, I want to add a search bar like the one on the OpenStreetMap website, to search for coordinates, streets, or any location on the django-leaflet admin map, but I have no idea how to do it. It is somewhat difficult to find locations on this map, my idea is to look for the coordinates in google maps to be able to add a marker at the desired location. OpenStreetMap: enter image description here My Django Admin enter image description here I tried to follow some tutorials, but I don't understand. how to add leaflet-geosearch control in django admin -
(1062, "Duplicate entry '1' for key 'usuario_id'") en django
i a The problem here is that after all this happens I wanted to try creating a new superuser and it gives me the error in the title, if someone could help me I would appreciate it update this is the traceback File "c:\proyectos\first-proyect\gastos\users\views.py", line 24, in sing_up form.save() File "c:\proyectos\first-proyect\venv\lib\site-packages\django\contrib\auth\forms.py", line 143, in save user.save() File "c:\proyectos\first-proyect\venv\lib\site-packages\django\contrib\auth\base_user.py", line 68, in save super().save(*args, **kwargs) File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\models\base.py", line 812, in save self.save_base( File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\models\base.py", line 863, in save_base updated = self._save_table( File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\models\base.py", line 1006, in _save_table results = self._do_insert( File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\models\base.py", line 1047, in _do_insert return manager._insert( File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\models\query.py", line 1790, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1660, in execute_sql cursor.execute(sql, params) File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\backends\utils.py", line 103, in execute return super().execute(sql, params) File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers( File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\backends\utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute with self.db.wrap_database_errors: File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "c:\proyectos\first-proyect\venv\lib\site-packages\django\db\backends\mysql\base.py", line 75, in execute return self.cursor.execute(query, args) File "c:\proyectos\first-proyect\venv\lib\site-packages\MySQLdb\cursors.py", line 206, in execute res = self._query(query) File "c:\proyectos\first-proyect\venv\lib\site-packages\MySQLdb\cursors.py", line 319, … -
Django is rendering an awkward result
Basically, I am working on a django project, and whenever I insert data into the database, the result is weirdly formatted. this is my model customer.py class Customer(models.Model): user = models.OneToOneField(User,null=True,blank=True,on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email= models.CharField(max_length=200, null=True) phone_number= models.CharField(max_length=200, null=True) def __str__(self): return self.name Now, say I have saved a new customer new_customer = Customer.objects.create(name="Henry",email="henry@mail.com",phone_number="+330145786259") new_customer.save() when i try to retrieve the customer name i get this: print(new_customer.name) >('henry',) Anyone has any insight for me??? I tried to recreate the model on a new project but still having the same result -
How to store product and pricing history in a Django product database?
I have a single product table DB containing various fields in a Django project, including the product mspr and current_price fields. For each product in the database, the current_price field is auto-updated periodically to detect changes. My problem is that I want to also store the historical price data of each product every time it is changed, but I am not sure how to restructure this current single table product DB below. class Product(models.Model): name = models.CharField(max_length=250) manufacturer = models.CharField(max_length=250) msrp = models.DecimalField(null=True, max_digits=10, decimal_places=2) current_price = models.DecimalField(null=True, max_digits=10, decimal_places=2) # and other product data fields I am certain that I have to create a second table so there will be two tables in the DB as shown below. But other than a DB class I took years back in college, I don't have much experience with creating databases, so please briefly explain how the primary/foreign key relationship for this use case only will work using the example below. It should be a one (product) to many (production historical price changes) correct?: class Product(models.Model): name = models.CharField(max_length=250) manufacturer = models.CharField(max_length=250) # and other product data fields class ProductPrice(models.Model): msrp = models.DecimalField(null=True, max_digits=10, decimal_places=2) current_price = models.DecimalField(null=True, max_digits=10, decimal_places=2) price_change_date = … -
Import channels for a WebSocket connection in Django not accessed
I am trying to add a WebSocket to my project. I have installed channels and read through the documentation online on how to properly configure everything. For some reason, any dependency I am trying to make that is related to channels library is not recognised in my project. I have uninstalled and installed the channels library many times, but with no luck. Me and my project partner have googled and asked around, but have found nothing useful yet. Does anyone know what could be the issue? This is what I get when I reinstall channels(So after it's uninstalled first with pip uninstall channels): Requirement already satisfied: Django>=3.2 in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (from channels) (4.1.3) Requirement already satisfied: asgiref<4,>=3.5.0 in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (from channels) (3.5.2) Requirement already satisfied: sqlparse>=0.2.2 in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (from Django>=3.2->channels) (0.4.3) Installing collected packages: channels Successfully installed channels-4.0.0 Versions: Django 4.1.3 Python: 3.11.0 I am also using corsheaders and rest framework libraries. -
How to change a ModelChoiceField's query set before sending the form to user in a view?
I have this form: class CategoryForm(forms.Form): category = forms.ModelChoiceField(queryset=Category.objects.filter(parent=None)) And a view: def category_select(request, pk): if request.method == "POST": # ... else: form = CategoryForm() # I want to change category field's queryset here. return render( request, "ads/select-category.html", { "form": form, }, ) In this view, I want to change queryset of category field in form (based on pk which it gets from the url as a parameter). -
Python django filter get all records modified within Last 10 Minutes
Using django I attempting to get All records that are modified based on modificationtime field in last 10 minutes class Status(models.Model): . . . modificationtime = models.DateTimeField(verbose_name="modificationtime", null=True, blank=True, ) setttings.py consists of following entries TIME_ZONE = 'UTC' USE_TZ = True ten_minutes_ago = datetime.now() - timedelta(minutes=10) changedstatuslist = Status.objects.filter(Q(modificationtime__lte=ten_minutes_ago)) but changedstatuslist does not appears to be showing correct data. what modification/correction is needed above code so as to get all status objects records that are modified in last 10 minutes. -
Django send json formatted logs to logstash
I am trying to send logs to logstash with python-logstash package and i need logs to be in json format. I wrote custom json formatter for my logstash handler. My settings logging configuration: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'main_formatter': { '()': CustomJsonFormatter, }, }, 'handlers': { 'file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, "debug.log"), }, 'info_logger_file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, "development.log"), 'formatter': 'main_formatter', }, 'logstash': { 'level': 'INFO', 'class': 'logstash.UDPLogstashHandler', 'host': 'logstash.example.com', 'port': 8080, 'version': 1, 'message_type': 'logstash', 'fqdn': False, 'tags': ['app'], 'formatter': 'main_formatter', } }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True, }, 'info_logger': { 'handlers': ['info_logger_file', 'logstash'], 'level': 'INFO', 'propagate': True, }, }, } my CustomJsonFormatter: from pythonjsonlogger import jsonlogger class CustomJsonFormatter(jsonlogger.JsonFormatter): def add_fields(self, log_record, record, message_dict): super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict) if not log_record.get('timestamp'): # this doesn't use record.created, so it is slightly off now = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ') log_record['timestamp'] = now if log_record.get('level'): log_record['level'] = log_record['level'].upper() else: log_record['level'] = record.levelname log_record['application'] = 'production' But when i'm trying to log something, it throws exception: import logging log = logging.getLogger('info_logger') log.info("test") -
How to setup django-q in a IIS server for async views?
I have a Django app that runs i a IIS server and now i need to use django-q package on it, how can i setup IIS to do this since i can't run python manage.py qcluster? [Q] INFO Enqueued 8 Async view don't run without python manage.py qcluster. -
Pass additional data in DetailView Django
I have FBV where I am calculating time delta (td) and passing it in my context: def update_moc(request, pk): moc = get_object_or_404(Moc, pk=pk) today = datetime.date.today() time = moc.initiation_date time_delta = today - time td=str(time_delta) initiator = moc.initiator status = moc.moc_status coordinator = moc.coordinators.filter(coordinator_name=request.user) if request.user.is_superuser or (initiator == request.user or coordinator) and status == 'draft': form = MocUpdateForm(request.POST or None, instance=moc) today = datetime.date.today() time = moc.initiation_date time_delta = today - time td=str(time_delta) if form.is_valid(): moc.initiator = request.user form.save() return HttpResponseRedirect(reverse('moc_content_detail', kwargs={'pk': pk})) else: return render(request, 'moc/moc_content.html', context={'moc':moc, 'form':form, 'td': td}) else: raise Http404() However for DetailView I am having CBV and want to pass same time_delta (td) as additional context, but failing how I can do it... I tried few approaches to pass class MocDetailView(LoginRequiredMixin, DetailView): model = Moc template_name = 'moc/moc_detail.html' def get_context_data(self, *args, **kwargs): context = super(MocDetailView, self).get_context_data(*args, **kwargs) context['td'] = # This is where I need help def get_object(self, queryset=None): obj = super(MocDetailView, self).get_object(queryset=queryset) confidential = obj.confidential initiator = obj.initiator ..... if self.request.user.is_superuser or initiator == self.request.user or verifier or coordinator or reviewer or approver or preimplement or authorizer or postimplement or closer and confidential == True: return obj elif not confidential: return obj else: … -
location of source code of django.contrib.admin module
I want to figure out how the value for Django's admin.site.urls is generated. Where can I find the source code for django.contrib.admin module? $ find . -name "admin.py" ./opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/rest_framework/authtoken/admin.py ./opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/contrib/sites/admin.py ./opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/contrib/redirects/admin.py ./opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/contrib/auth/admin.py ./opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/contrib/flatpages/admin.py ./opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/contrib/contenttypes/admin.py -
Creating a hypertable with timescaleDB and django fails
I am running a django project and I am trying to integrate timescaleDB. Unfortunately this is not plug and play since django does not support timescaleDB officially. What needs to be done is some manual migrations. I tried two ways, but both ways are not working for me. Both are not working because my manually written SQL is not working: Adjusting migration manually (Problem: Unique restraint is not removed) I am following this tutorial (https://blog.ashtonhudson.com/adding-timescale-to-django.html) which is exactly my use case. I first create my models with timestamp as pk from django.db import models from django.db.models.fields import DateTimeField class Metric(models.Model): drinks = models.CharField(max_length=200) class TimeData(models.Model): # NOTE: We have removed the primary key (unique constraint) manually, since # we don't want an id column. timestamp = DateTimeField(primary_key=True) metric = models.ForeignKey(Parameter, on_delete=models.RESTRICT) value = models.FloatField(null=False) I then run the migrations and manually add two SQL statements to remove the unique constraint from the timestamp primary key: class Migration(migrations.Migration): operations = [ ... migrations.CreateModel( name="TimeData", fields=[ ("timestamp", models.DateTimeField(primary_key=True, serialize=False)), ("value", models.FloatField()), ( "metric", models.ForeignKey( on_delete=django.db.models.deletion.RESTRICT, to="myapp.drinks", ), ), ], ), migrations.RunSQL( "ALTER TABLE myapp_timedata DROP CONSTRAINT myapp_timedata_pkey;" ), migrations.RunSQL( "SELECT create_hypertable('myapp_timedata', 'timestamp', chunk_time_interval => INTERVAL '5 days');" ), ] This creates a … -
Selenium not working with Vite, possibly due to HMR
I am trying to use Selenium with a Django backend using Vite for JS stuff but for some reason the JS stuff isn't running when, for example, I tell Selenium to click a button. I think it has to do with Vite's HMR, because when I build the JS and link the bundled file in my Django templates it works fine. How can I get Selenium to work properly without having to use the bundled file? -
When should I use class based view and function based view in django?
Django views can be written in both class as well as function approach. In which situation we should use class based view and In which situation we should opt for function based views. -
How a loggedin user can view other user profile using django
I am working on a django project. When a user logs in, the user will be redirected to the profile page where he can view his username, email, profile picture, and list of blogpost created by him. This is the user profile page - blog/researcher-profile.html {% extends 'users/base.html' %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile_pic.url }}" width="125" height="125"> <div class="media-body"> <h2 class="account-heading" style="margin-left: 30px">{{ user.username }}</h2> <p class="text-secondary" style="margin-left: 30px">{{ user.email }}</p> <a href="{% url 'user-update' %}" class="btn btn-secondary btn-sm" style="margin-left: 30px;"> Edit Profile </a> </div> </div> <!-- FORM HERE --> </div> {% for post in posts %} {% if post.approved %} <div class="card mb-3"> <img class="card-img-top" src="{{ post.image.url }}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ post.title|truncatechars:70 }}</h5> <p class="card-text">{{ post.content|truncatechars:200|safe }}</p> <a href="{% url 'post-detail' post.aid %}" class="btn btn-primary"> See Details </a> </div> <div class="card-footer text-secondary"> <a class="mr-2" href="{% url 'researcher-profile' %}">{{ post.author }}</a>|| {{ post.created|date:"F d, Y" }} </div> </div> {% endif %} {% endfor %} {% endblock content %} urls.py from django.contrib import admin from django.urls import path from users import views as user_views from django.contrib.auth import views as auth_views from blog.views import UserPostListView from django.conf import settings from … -
Why is Django giving did you forget to register or load this tag error?
I have a working Django app that has started giving me a template block error on my Windows 11 development PC: Invalid block tag on line 17: 'endblock', expected 'endblock' or 'endblock stylesheets'. Did you forget to register or load this tag? I looked at this stackoverflow article: Invalid block tag : 'endblock'. Did you forget to register or load this tag?, but I don't have the typo that that article discusses. It is in a base.html template: <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" href="{% static 'assets/img/orange-img.png' %}" type="image/x-icon"> <title> Clever - {% block title %}{% endblock %} </title> <!-- Specific Page CSS goes HERE --> <link rel="stylesheet" href="{% static 'assets/css/blue_theme.css' %}"> {% block stylesheets %} {% endblock stylesheets %} </head> <body class="hold-transition {% block body_class %}{% endblock body_class %}; w3-theme-l4"> {% block content %}{% endblock content %} <div style="text-align: center"> {% include 'includes/footer.html' %} </div> <!-- Specific Page JS goes HERE --> {% block javascripts %} {% endblock javascripts %} {% include 'session_security/all.html' %} </body> </html> The error gets generated on line 17: {% endblock stylesheets %}. I have tried putting the block and endblock on the same …