Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to reduce ram usage when you load a model
when I try to load the model in my views.py the RAM usage get higger after that it gets normal, So how to make it always on normal usage ? I am using model Wave2Vec2Inference("facebook/hubert-xlarge-ls960-ft",cuda_flag = True) can anyone help me out -
How to implement reject/approve functionality with Django
For example, a model called Request, this model has a status field, status is by default "Awaiting", I want to make it possible for someone to change that through a form to "Approved" or "Rejected" I tried using some methods but they all didn't work. -
How to simplify phone_number field update Process in django including verification
Problem Description: We have a User model where Phone number is been set as username and its unique=True, We also have a field where to represent verified/unverified users. And we verify users by OTP verification to phone number. So now we need to add a new feature where user can replace his phone_number and then he will go to verification process and then we will change his number. And also We need to preserve his previous number (which he already verified) until this new number is verified. If for some reason user decides to go back without verification we delete newly added number and keeps his old number as username. So what would be the best way to approach this problem What I'm considering to have another Model linked with ForeignKey to User class AlternativeNumber(models.Model): user = User() # forignkey number = Charfield is_verfied = BooleanField So we will be verifying users number and replacing his original number from his alternativenumber_set Do you think we can simply it more. Do you think it might have some flaws or we go with a better appraoch ? thanks. -
Print several separate tables from one HTML document
I did the work and was able to render the data into tables. Now I have the following structure on the page: <div class="report-table-container mt-5" id="**current_pko_table**"> *some data* </div> <div class="report-table-container mt-5" id="**current_report_table**"> *some data* </div> <div class="report-table-container mt-5" id="**current_refund_to_customers_table**"> *some data* </div> Can anyone suggest a solution to make the "print all" button so that it only prints: current_pko_table, current_refund_to_customers_table, current_refund_to_customers_table? And also offer to separate the pages for printing, so that each of these documents is on a separate page when printed. I will be glad for any help. My whole project is built on django, but my experience with JS small. I will be glad for any help! -
thon310\lib\os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'CELERY_BROKER_URL'
we are facing key error while executing File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\os.py", line 679, in getitem raise KeyError(key) from None KeyError: 'CELERY_BROKER_URL' -
How to use remote user authentication using simple-jwt in Django Rest Framework?
I have two django projects/microservices which uses two separate databases: Todo auth - built for authentication - todo auth database Todo project - built to view todo information specific to a user - todo database What I basically require is, Once a user login using the todo auth project and get a token, When using the token in the todo project, the user should be authenticated and created (if the use does not exist) in the todo database with the help of Remote user authentication. I followed the below document in order to get what i achieve https://auth0.com/docs/quickstart/backend/django/01-authorization The problem is the document uses drf-jwt, i want to use simple jwt to achieve this. Please let me know how I can achieve this using simple jwt. Many thanks. Ps: Im running the two projects/microservices separately in the same develpopment server on two different ports -
Failed to Fetch when the request didn't fail and code seemingly executes fine
I am using elasticsearch-dsl to construct 2 complex queries and execute them over multiple indices at the same time with MultiSearch. It is working fine in 99% of cases but rarely fails for some input parameters with such an error printed on backend (Django): 2022-09-29 03:37:23,592 ERROR: https://aws_instance_name.us-east-1.es.amazonaws.com:443 For such input params it never is executed successfully, so its definitely dependent upon the inputs. The backend Django python code executes fine until the response is actually returned which I observe with logger.info statements, but the error is there. When I set the response to an empty one to exclude issues further down the line with the specificity of the response, it still fails, so it's as if it's not the issue of the response. I executed both queries separately (on backend they are executed together in one with MultiSearch, so it could potentially be some issue inside the MultiSearch itself) over the very same indices in AWS Kibana and both are returning results fine in a matter of a couple of seconds. I wonder if there is a way to print out detailed info about the issue and not just ERROR:aws_instance message that is useless. What else could go wrong … -
Table sort by the sum of aother related table
I have two tables name table name number memberA 1002 memberB 1003 memberC 1004 score table number score 1002 20 1002 30 1003 60 1003 60 1004 80 What I want to get is The member lists orderby total score For example memberA total score is 50 memberB total score is 120 memberC total score is 80 SO what I want to get is sorted name table memberB memberC memberA How can I do this? by django queryset? NameTable.objects.orderby('sum???') -
How To Convert Free Heroku Django To Paid App
Some time ago I created my first training Python Django Web application on Heroku because I could do it for free. It is a typical CRUD application with a persistent database. I have enjoyed showing it to others since then. I just received notice from Heroku that I need to convert it to a paid application. I having indeed spent hours pouring over the documentation cited about the conversion, but I am still confused about what exactly I need to do. I believe that the best path is to change the dyno status from "free" to "eco". That would cost only $5 a month. I am not sure about the database. Is that included, or would that need also to be converted to a paid "mini" postgres for an additional $5 a month? And would I have to do all the data conversion work manually, or does that happen automatically behind the scenes? Answers to these questions are key to understand if Heroku will still be a home for my application, or will I need to move it to another platform. Thank you. -
When I include a hidden field in my modelform, the modelform is not submitted
I am trying to build up a posting webpage. This is how it works: you click a button, the posting form will appear, you fill in the form, you click the submit button, and the process is complete. And when the form is submitted, a url parameter will be passed as the value of a hidden input in the modelform in the views.py. Everything had been working fine until I added in my modelform the 'username' field which has the HiddenInput as a widget. It seems like modelform is not submitted at all. Here are my codes: models.py from django.db import models from django.db.models import CharField, TextField, DateField class Post(models.Model): username = CharField(max_length=30) content = TextField() dt_created = DateField(auto_now_add=True) dt_modified = DateField(auto_now=True) def __str__(self): return self.content forms.py from django import forms from django.forms import Textarea, HiddenInput from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ['content', 'username'] widgets = { 'content': Textarea(attrs={ 'class': 'write_input', 'placeholder': 'write your story here...' }), 'username': HiddenInput(attrs={ 'value': ' ' }) } labels = { 'content': '' } views.py from django.shortcuts import render, redirect from .forms import PostForm from .models import Post def account_main(request, username): context = dict() if request.method == … -
Get seperate task id in celery chain in Django
I am running a scraper in background using celery chain. I have 2 task that should run in a synchronous manner. result = chain(taskOne.si(data= data), taskTwo(data = data)).delay() This code works,as i can see the return data in the terminal. However, i could not get the task id for each individual task. I tried assigning a variable into them but it will not trigger the celery chain. result = chain(taskOneData = taskOne.si(data= data), taskTwoData = taskTwo(data = data)).delay() if i print 'result' it will only show me the task id of the last task. -
Programming Error creating automatic instance
I am using django and I encountered an error. I want to create to IncidentGeneral automatically when a UserReport was created. How can I achieve it? Error: ProgrammingError at /admin/incidentreport/userreport/add/ column incidentreport_incidentgeneral.user_report_id does not exist LINE 1: SELECT "incidentreport_incidentgeneral"."user_report_id", "i.. class UserReport(models.Model): PENDING = 1 APPROVED = 2 REJECTED = 3 STATUS = ( (PENDING, 'Pending'), (APPROVED, 'Approved'), (REJECTED, 'Rejected') ) user = models.ForeignKey(User, on_delete=models.SET_DEFAULT, default='Anonymous') description = models.TextField(max_length=250, blank=True) location = models.CharField(max_length=250) upload_photovideo = models.ImageField(default='user.jpeg', upload_to='incident_report/image') date = models.DateField(auto_now_add=True) time = models.TimeField(auto_now_add=True) status = models.PositiveSmallIntegerField(choices=STATUS, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def get_status(self): if self.status == 1: incident_status = 'Pending' elif self.status == 2: incident_status = 'Approved' elif self.status == 3: incident_status = 'Rejected' return incident_status def __str__(self): return self.user.username class IncidentGeneral(models.Model): WEATHER = ( (1, 'Clear Night'), (2, 'Cloudy'), (3, 'Day'), (4, 'Fog'), (5, 'Hail'), (6, 'Partially cloudy day'), (7, 'Partially cloudy night'), (8, 'Rain'), (9, 'Rain'), (10, 'Wind'), ) LIGHT = ( (1, 'Dawn'), (2, 'Day'), (3, 'Dusk'), (4, 'Night'), ) SEVERITY = ( (1, 'Damage to Property'), (2, 'Fatal'), (3, 'Non-Fatal'), ) user_report = models.OneToOneField(UserReport, on_delete=models.CASCADE, primary_key=True) accident_factor = models.OneToOneField(AccidentCausation, on_delete=models.CASCADE) collision_type = models.OneToOneField(CollisionType, on_delete=models.CASCADE) crash_type = models.OneToOneField(CrashType, on_delete=models.CASCADE) weather = models.PositiveSmallIntegerField(choices=WEATHER, blank=True, null=True) … -
How to set a form as submitted while being inside a form loop in a Django Project?
I have a Log model with a LogForm form as following: class Log(models.Model): submitted = models.BooleanField(default=False) log_order = models.IntegerField(.......) log_weight = models.FloatField(........) log_repetitions = models.IntegerField(.....) class LogForm(forms.Form): log_order = forms.IntegerField() log_weight = forms.IntegerField() log_repetitions = forms.IntegerField() I have a for loop in my template which because I have a table with different information I have a loop of forms generating in this case for simplicity I have 3 forms to insert different log infomration it is as following: {% for e in exercises %} {% for b in e.breakdowns.all %} <form action="{% url 'my_gym:addlog' workout.id %}" method="post"> {% csrf_token %} <input hidden type="number" name="log_order" value="{{ b.order}}" required id="id_log_order"> <div> <input type="number" name="log_weight" required id="id_log_weight"> <input type="number" name="log_repetitions" required id="id_log_repetitions"> </div> <div> {% if Log.submitted %} <button> Already Submitted </button> {% else %} <button type="submit" id="submitlog"> Click to Submit </button> {% endif %} </div> </form> {% endfor %} {% endfor %} Here is the view: class workout_details(DetailView): model = Workout template_name = 'template.html' context_object_name = 'workout' def get_context_data(self, **kwargs): exercises = Exercise.objects.filter(workout_id=self.object) p = Log.objects context = super().get_context_data(**kwargs) context['exercises'] = exercises context['form'] = LogForm() context['p'] = p return context def addlog(request, id): url = request.META.get('HTTP_REFERER') if request.method == 'POST': form = … -
How do you get the DJango form data that were appended?
How do you get all row data of the forms that were appended? I have a form with 5 numbers per row, and some 'N' number of rows that are selected by the user is appended. Form: class locker(forms.Form): num0 = forms.IntegerField(label='', min_value=1, max_value=25, required=True) num1 = forms.IntegerField(label='', min_value=1, max_value=25, required=True) num2 = forms.IntegerField(label='', min_value=1, max_value=25, required=True) num3 = forms.IntegerField(label='', min_value=1, max_value=25, required=True) num4 = forms.IntegerField(label='', min_value=1, max_value=25, required=True) View: # Render form ... count = 3 newForm = locker() context.update({ 'locker': newForm, 'lockerCount': range(count) }) ... Template: # Display form ... <div class="lockers"> <form name="longForm" action="" method="post"> {% csrf_token %} {% for i in lockerCount %} {{ locker }}<br /> {% endfor %} <br /> <input type="submit" value="submit" class="small-button"> </form> </div> ... I've tried various methods searched from google, and the closest I got was: ... data = form.cleaned_data.items() for q in data: ... but it's getting only the last row of numbers. Looking at the console, I do see all the data (below). I'm trying to get all rows of the form, each row containing 5 sets of integers. Please help. [29/Sep/2022 23:19:42] "POST /main/ HTTP/1.1" 200 10113 [29/Sep/2022 23:20:43] "GET /main/?csrfmiddlewaretoken=w3YIsEf1Af2hX4IRfPIVShZCdUjh9EEnbu2o8UGbI8XFbcTif6f1FlviC3KoHDM8&num0=7&num1=6&num2=21&num3=5&num4=11&num0=22&num1=4&num2=6&num3=19&num4=10&num0=9&num1=14&num2=20&num3=3&num4=25 HTTP/1.1" 200 7687 -
How to return calculations to a template for all objects in a class model in Django
I am trying to build a simple form which calculates which machine would run a film width the quickest, the parameters and capabilities of each machine are held in a django model. The width of the film and how much of it will be entered in the form and the quantity needed. The function should work out which machine(s) can run it, what the max speed is and the average speed over the machines that are capable. I want to return the values of the calculation and maybe run a for loop and display the values for each machine in a results.html template in a table. I also want to display average times across machines capable of running the widths of film. I had some success with lists but would like to use a class that I can use in the template and do away with the lists. Any help with this would be much appreciated as I am getting pretty lost in it! I have only started on the 'Layflat Tubing' function in the hope that I can get it right and just copy down to the other functions. from django.views.generic.base import TemplateView from django.shortcuts import render import math, … -
How do I invert in Django the pretty "yes", "no" icons of a BooleanField in the Admin site?
When your model has a BooleanField, the Django Admin site displays circular icons: a green checkmark for "True" a red X for "False" The Django docs call those icons "pretty": If the field is a BooleanField, Django will display a pretty “yes”, “no”, or “unknown” icon instead of True, False, or None. it looks great! but my BooleanField is called "pending" so if pending = True , I want Django Admin site to display a red X instead of a green checkmark. Because green means "good" and red means "bad". Most of my entries are not pending, so the list is full of red X icons, it looks bad, I want them to be mostly green checkmarks instead. I know I could add a def in the model with a return not self.pending but that displays the words "True" and "False" instead, I want the icons. -
How to specify table class with django_tables2
I am wanting to use the bootstrap table design shown here:https://getbootstrap.com/docs/4.0/content/tables/ The table class is called "" My issue is I dont understand how to implement this with a django_tables2 table. I have utilized the bootstrap templates that they give in their documentation but none of them look very good. How would I use these other table class options given by bootstrap? class PersonTable(tables.Table): class Meta: model = player_hardware template_name = "django_tables2/bootstrap-responsive.html" -
Python ldap3.core.exceptions.LDAPSocketOpenError when django app is deployed on ecs, but not on local
I have a django api that streams data from an Active directory source and processes it. My connection looks something like this from ldap3 import Server, Connection server = Server(url, get_info=ALL) conn = Connection(server, username, password, auto_bind=True) I put this app on a container, the dockerfile is simple and looks like this FROM python:3.9 EXPOSE 8002 # Install Dependencies ADD requirements.txt . RUN pip install -r requirements.txt ADD . . CMD ./server.sh Server.sh is also fairly simple: #!/usr/bin/env bash aws s3 cp s3://some_creds . python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:80 Now, on local, and on gitpod this connection has no issues. I go on to do searches on the conn without problems. However, when I deploy the same container on ecs via ecr I was running on local, I get this error: <class 'ldap3.core.exceptions.LDAPSocketOpenError'>, LDAPSocketOpenError('socket connection error while opening: [Errno 110] Connection timed out'), ('xxx.xxx.xxx.xxx', xxx))]) This may be a side effect of accessing the api from ssl, but if that is the case, I simply cannot replicate it on locale. This error occurs only on POST requests; any other request goes through as expected. -
How can I search my entire Users model for users that already have the requested email/phone?
I am new to rest framework, so forgive me if this is an obvious answer. I am using serializers with querysets in my views. The whole thing is locked down with JWT auth from Firebase What is the best way to search my database for a user that has a certain email or phone and return a JSON response of True or False depending on if that email / phone already exists in the database? What I have tried so far... class getuserid(viewsets.ModelViewSet): queryset = UserProfile.objects.all() serializer_class = GetUserIdSerializer lookup_field = 'phone' class GetUserIdSerializer(serializers.ModelSerializer): class Meta: model=UserProfile fields=['user'] The problem with this method is if I use a JWT that is not associated with the user who has that phone number in their database model, I get a invalid token error/forbidden. Obviously this is not a very secure way to do it, anyways, even if rest framework allowed me to. Here is the serializer where I create my user's profile in my database... class UserProfileSerializer(serializers.ModelSerializer): class Meta: model=UserProfile fields=['company','email','name','phone','image','account_type','password','sub_user_of','sub_pending','products_read','products_write','restock_read','restock_write','expenses_read','expenses_write','banking_read','banking_write','admins'] class UserSerializer(serializers.ModelSerializer): userprofile = UserProfileSerializer() def update(self, instance,validated_data): if(not instance.username == self.context['request'].user.username): raise exceptions.PermissionDenied('You do not have permission to update') profile_data = validated_data.pop('userprofile') if(not hasattr(instance,'userprofile')): instance.userprofile = UserProfile.objects.create(user=instance,**profile_data) else: instance.userprofile.company = … -
How to use axios to consume API Rest en Django specifically the list method in Model ViewSet?
Cheers, I'm trying do a request from Vue.js through axios to Django but the console show a error in the acccess to XMLHttpRequest. This is the error: enter image description here My code in Vue.js is the following: <template> <div class="main_container_cita"> <div class="panelIzquierdoCita"> <div class="panelVerticalCita"> <img src="../img/cita.png" alt=""> <h1>Mis citas</h1> </div> </div> <div class="panelDerechoCita" id="panelDerechoCita"> <table> <tr> <td>Fecha</td> <td>Hora</td> <td>Lugar</td> <td>Cliente</td> <td>Servicio</td> </tr> <tr v-for="(cita, index) in citas" :key="index"> <td v-text="cita.fecha"></td> <td v-text="cita.hora"></td> <td v-text="cita.lugar"></td> <td v-text="cita.cliente"></td> <td v-text="cita.servicio"></td> </tr> </table> </div> </div> </template> <script> import axios from "../utils/axios"; export default { name: "Cita", data: function () { return { citas: [] } }, methods: { getCita: async function(){ await this.verifyToken(); let token = localStorage.getItem("token_access"); axios.get(`cita`, {headers: {"Authorization": `Bearer ${token}`}}) .then(result => { this.citas = result.data }).cath((error)=>{ alert('Erorr en el get',error) }) }, verifyToken: function(){ let refresh = localStorage.getItem("token_refresh");//recuperar datos del LocalStorage return axios.post("refresh/", {refresh}) .then(result => { localStorage.setItem("token_access", result.data.access) }).catch(()=>{ this.$emit("logout"); }) } }, mounted(){ this.getCita(); } }; </script> Finally my code in Django is the following: class CitaView(viewsets.ModelViewSet): serializer_class = CitaSerializer queryset = Cita.objects.all() permission_classes = (IsAuthenticated,) def list(self, request): serializer = CitaSerializer(self.queryset.order_by("fecha").filter(cliente=1), many=True) return Response({'data': serializer.data}) I'll hope answers, I need to complete a project. -
Block Dates in Django Datepicker
I am using fengyuanchen's datepicker and am trying to create an array of dates from my Django model and filter (or block) the dates from the array out of the datepicker widget. I have a solid python background, but my JS knowledge is minimal, so I am hoping I can get some guidance on how to pass this data correctly. <head> <!-- jQuery --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <!-- Fengyuan Chen's Datepicker --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.min.css" integrity="sha256-b88RdwbRJEzRx95nCuuva+hO5ExvXXnpX+78h8DjyOE=" crossorigin="anonymous" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.min.js" integrity="sha256-/7FLTdzP6CfC1VBAj/rsp3Rinuuu9leMRGd354hvk0k=" crossorigin="anonymous"></script> </head> <script> var array = [ {% for x in listing_reservations %} {{ x.start_date }} {% endfor %} ] $(function () { $("#id_start_date").datepicker({ filter: function(date) { if (array) { return false; } } }); }); </script> -
Redirection in PyTest Django doesn't work
I am trying to create tests for my login and signup process in my Django App with Pytest. When you signup ("/signup", home/register.html) you should be redirected to login page ("/login", home/login.html). After successfull login you shoul be redirected do welcome page ("", home/welcome.html). I created 2 tests for signup and it works. Unfortunetly I have problem with login and checking redirection to welcome page. Here is my test: @pytest.mark.django_db def test_login_redirect_to_welcome_for_authenticated_user(client): user = User.objects.create_user('Test', 'test@test.pl', 'password') client.login(username=user.username, password='password') response = client.get(path='/login', follow = True) assert response.status_code == 200 assert 'home/welcome.html' in response.template_name I logged the user on login page, set follow to true. And now I want to check if I am redirected to Welcome Page. Unfortunetly I have got this error: client = <django.test.client.Client object at 0x1030db460> @pytest.mark.django_db def test_login_redirect_to_welcome_for_authenticated_user(client): user = User.objects.create_user('Test', 'test@test.pl', 'password') client.login(username=user.username, password='password') response = client.get(path='/login', follow = True) assert response.status_code == 200 > assert 'home/welcome.html' in response.template_name E assert 'home/welcome.html' in ['home/login.html'] E + where ['home/login.html'] = <TemplateResponse status_code=200, "text/html; charset=utf-8">.template_name home/tests/test_login.py:18: AssertionError FAILED home/tests/test_login.py::test_login_redirect_to_welcome_for_authenticated_user - assert 'home/welcome.html' in ['home/login.html'] Do you know how I can fix this? -
Django, Mock keeps only last call args to itself
Using Django==3.2.15, mock==3.0.5, Python ~3.7 I have been noticing that the mock does not keep all the call_args from the different calls made to it, and they are all with the signature of the last call made to it. My code: This is a snippet that resembles where the service mock will be called, downstream. object_ids is a list of integer object IDs, I am sending to the service to handle. max_allotted_size is an integer, stands for the "chunks" I want to divide the service interaction. message_body is defined before the loop and contains other information the service requires from location.of.service import MyService my_service = MyService() num_iterations, leftover = divmod(len(object_ids), max_allotted_size) log_ids = [] for i in range(num_iterations): message_body['object_ids'] = object_ids[prev:curr] print( "iteration: {}, IDS count: {}, IDS: {}".format( i, len(object_ids[prev:curr]), object_ids[prev:curr], ) ) _, error = my_service.send_payload_to_some_other_service(message_body) if not error: log_ids += object_ids[prev:curr] prev = curr curr += max_allotted_size There is also code that picks up the leftover: if leftover: message_body['object_ids'] = object_ids[prev:] print( "leftover IDS count: {}, IDS: {}".format( len(object_ids[prev:]), object_ids[prev:], ) ) _, error = my_service.send_payload_to_some_other_service(message_body) if not error: log_ids += object_ids[prev:] There is also a print at the end to show the log_ids gathered with each … -
django ORM left join unrelated QuerySet
Here below is very simplified example of what I want to do with django ORM. Please do not concentrate on how to make models better (I try to make it simple and illustrative) but how to get data from presented situation. So, lets assume two models. First class Car(models.Model): brand = models.TextField() model = models.TextField() segment = models.TextField() stores all cars from dealer parking (different brand and segment). From time to time dealer make some special offer for car from given segment which are store in second table class Discount: car_segment = models.TextField() price_cut = models.IntegerField() Now we want to show all cars from brand selected by the user sorted by discount. Note that most of the cars have regular price (no price_cut, no "corresponding" entry in Discount table. In plane SQL this what I want to achieve is sth like: select * from (select * from Car where brand = "Toyota") left join Discount on segment=car_segment order by price_cut, segment; How to do this using django ORM? For example we have Car: brand model segment toyota aygo A toyota yaris B toyota corolla C toyota raw4 4x4 kia picanto A kia rio C and discounts car_segment price_cut A 1000 … -
Login in django failing after adding css to login page
I have a basic django website running on a postgres database. The login page code was structured as follows, {% extends "_base.html" %} {% load crispy_forms_tags %} {% block title %}Log In{% endblock title %} {% block content %} <h2>Log In</h2> <div class="container text-center"> <div class="row justify-content-center"> <div class="col-4"> <form method="post"> {% csrf_token %} {{ form | crispy }} <button class="btn btn-primary " type="submit">Log In</button> </form> </div> </div> </div> {% endblock content %} and _base.html as <!-- additional css content for navbar --> <div class="container-fluid full-height p-0"> {% block content %} {% endblock content %} <!-- similar footer content --> And then I decided to add some css from the bootstrap in the form of a just so my login page would look cleaner. Therefore I added some css in this form. {% extends "_base.html" %} {% load crispy_forms_tags %} {% block title %}Log In{% endblock title %} {% block content %} <div class="bg-dark vh-100 d-flex align-items-center justify-content-center"> <div class="col-3 p-5 border bg-light rounded-2"> <h2>Log In</h2> <form method=" post"> {% csrf_token %} {{ form | crispy }} <button class="btn btn-primary " type="submit">Log In</button> </form> </div> </div> {% endblock content %} with _base.html as follows <div class="container-fluid p-0"> {% block content …