Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Displaying Django model field in template
Sorry if this is duplicate, I've found a lot of scattered info on this, but not sure how to put this together. In my model I have: class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) webbody = models.TextField() # models.FileField(upload_to='webcontent/projects') image = models.ImageField(upload_to='img/projects') def __str__(self): return self.title I can type HTML in webbody and display it in the template using admin no problem: {{project.webbody | safe}} But what I originally had was instead of a TextField, the commented line with filefield. I can upload the file through admin and that works nicely, but for the love of me I can't then display it in the template. I tried: {{project.webbody.url}} {% include project.webbody %} How does one properly handles external HTML files in django templates? -
Django problem with authenticated in html
why when I click on the link on the profile of another user, the option to log in is highlighted in the top menu, as if I had not authenticated (in the navbar it is possible to log in, the condition {% if user.is_authenticated%} is written there. If I open another page again everything is fine, the user is authenticated. navbar <div class=""> {% if user.is_authenticated %} <a class="navbar-brand" href="{% url 'account' %}"> <img src="{{user.profile.avatar.url}}" alt="" width="50" height="50" class="d-inline-block" /> </a> {% else %} <div class="signin"> <a href="{% url 'login' %}" type="button" class="btn btn-primary btn-rounded" > <div class="mx-auto">login</div> </a> <a href="{% url 'register' %}" type="button" class="btn btn-success btn-rounded" > <div class="mx-auto">register</div> </a> </div> vviews.py def list_users(request): users = Profile.objects.all() context = {'users':users} return render(request, 'profiles/list_users.html', context) def profile_detail(request, pk): user = Profile.objects.get(id=pk) context = {'user':user} return render(request, 'profiles/profile_detail.html', context) enter code here when going to this page, the user is not authenticated {% extends 'base/base.html' %} {% block content %} <div> <h1>HELLOOOO</h1> {{user.user}} </div> {% endblock %} url urlpatterns = [ path('', views.list_users, name='list_users'), path('account/', views.account, name='account'), path('profile_detail/<int:pk>/', views.profile_detail, name='profile_detail'), -
I keep getting this error in Django, its called "local variable referenced before assignment"
I am making this to-do list website with Django, but I keep getting this error in my "create" function in views.py file. here's the code : def create(response): if response.method == "POST": form = CreateNewList(response.POST) if form.is_valid(): n = form.cleaned_data["name"] t = ToDoList(name=n) t.save() return HttpResponseRedirect("/%i" %t.id) here's the error : local variable 't' referenced before assignment -
Is any solution in django to compare a foreign key column with primary key inside template, i need specific matchs in my project
My View.py it just render the objects thats fine. {% ifequal food_ing.f_name food.f_name %} {{ food_ing.f_name }} --> inside for loop i check this value, and it's (Pizza). {{ food.f_name }} -- this is also (Pizza) inside for loop in template, but i really don't know why condition equals to False... My file.html {% for food in foods %} {% for food_ing in food_ings %} **{% ifequal food_ing.f_name food.f_name %} <---> i need this statement to work** {% if food_ing.grm_amount == 0 %} <tr> <th>{{ food_ing.ing_name }}: &nbsp;&nbsp;</th><td class="text-muted font-weight-light">{{ food_ing.ltr_amount }} l</td> </tr> {% endif %} {% if food_ing.ltr_amount == 0 %} <tr> <th>{{ food_ing.ing_name }}: &nbsp;&nbsp;</th><td class="text-muted font-weight-light">{{ food_ing.grm_amount }} g</td> </tr> {% endif %} **{% endifequal %}** {% endfor %} {% endfor %} My models.py class IngFoodName(models.Model): ing_food_name = models.CharField(max_length=255, null=True) def __str__(self): return self.ing_food_name class Food(models.Model): f_photo = models.ImageField(upload_to='food_pics', blank=True) f_name = models.CharField(max_length=40, null=False) f_price = models.IntegerField(null=False) f_description = models.CharField(max_length=255, null=True) p_duration = models.IntegerField(null=False) def __str__(self): return self.f_name class FoodIngredients(models.Model): f_name = models.ForeignKey(Food, on_delete=models.CASCADE, null=True) ing_name = models.ForeignKey(IngFoodName,on_delete=models.CASCADE, null=True) ltr_amount = models.IntegerField(default=0, null=True) grm_amount = models.IntegerField(default=0, null=True) def __str__(self): return "Food {0} Ingredient {1} Litre Amount {2} Gram Amount {3}".format(self.f_name, self.ing_name, self.ltr_amount, self.grm_amount) Thanks, if anyone … -
Pass context to ModelSerializer field in Django Rest Framework
I am trying to pass a variable from my view to the serializer via context. The Serializer should be able to get the context variable and use it in a field that contains a nested serializer. Since the nested serializer field cannot be read_only, I cannot use serializerMethodField. This is how I pass the context to the serializer: class MyListCreateAPIView(generics.ListCreateAPIView): # [...] def get_serializer_context(self): return { 'request': self.request, 'format': self.format_kwarg, 'view': self, 'asTime': '2021-02-04 16:40:00', # <-- This is my context variable } This is my serializer: class MySerializer(serialisers.ModelSerializer): child = MyChildSerializer(read_only=False, asTime= ??) # <-- here I want to pass the context variable class Meta: model = MyModel fields = '__all__' I know that I can access the context variable with self.context.get('asTime') but I can't access self in MySerializer attributes (child). How do I do it? -
DoesNotExist: Category matching query does not exist
Why is my redirect not working. Everything works until the redirect statement I am receiving this error: DoesNotExist: Category matching query does not exist. The room url is made of 2 slugs. Type 1 slug is the slug from the category model and type 2 slug is from the room model. The same redirect statement was used for my delete message code and it worked. Not sure why this doesn't def edit_own_messsage(request, room_id): message = get_object_or_404(Message, id=room_id) if request.method == 'POST': form = UpdateMessageForm(request.POST or None, instance=message) if form.is_valid(): obj = form.save(commit=False) obj.save() return redirect(reverse("community:room", kwargs={'type1_slug': message.category.slug, 'type2_slug': message.room.slug })) models.py class Category(models.Model): categories = models.CharField(max_length=80, null=False, blank=False, unique=True) slug = models.SlugField(blank=True, unique=True) class Room(models.Model): categorical = models.ForeignKey(Category, related_name='categorical', on_delete=models.CASCADE) slug = models.SlugField(blank=True) class Message(models.Model): category = models.ForeignKey(Category, related_name='category', on_delete=models.CASCADE) room = models.ForeignKey(Room, related_name='messages', on_delete=models.CASCADE) name = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='naming', on_delete=models.CASCADE) urls.py path('<slug:type1_slug>/<slug:type2_slug>/', room_view , name= "room"), -
How can I delete multiple object in Django?
I’ve a list view, for show on the screen a list of object... In the view template, I created a table where I put a checkbox for each item... I would like to delete the selected objects, how can I do that? Thanks -
Djnago integration with built html template
I have built a complete front-end portfolio using HTML, CSS, and js. There is a a email contact form in the webpage and I want to send an email using Django through that contact form. when I tried to integrate it the index page is rendering but the CSS file is not accessible and all the design is disorganized. In this way my project files are organised This is the actual design But after rendering through Django it looks like this -
duplicate key value violates unique constraint "unique_followuser"
class FollowUserModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='followers') profile = models.ForeignKey(User,on_delete=models.CASCADE,related_name='following') timestamp = models.DateTimeField(auto_now_add=True) class Meta: constraints = [models.UniqueConstraint(fields=['author', 'profile'],name='unique_followuser')] What i want to do is basically i want an asymmetrical follow function. Like if: user1 follows user2, user2 should be able to follow user1 too. But the problem is that when user1 follows user2,user2 can't follow user1 asymmetrically because of unique constraint. Is there any solution for this? -
no module named "app" while trying to install a boilerplate Django
I'm trying to install a boilerplate in my personal computer but I'm getting this error: ModuleNotFoundError: No module named 'app' The boilerplate I'm trying to install is this one: https://github.com/jayfk/launchr The error happens specifically when I introduce this command: docker-compose run app python manage.py migrate -
Django multiple databases ... all models are created in second db despite router, is my router not good?
Django 2.2.18 I want to split the models of one app to a second database. The relevant app is named "dear_zoho_analytics", which I assume is the 'app_label'. The original database is "default". I have only one dbrouter, and it has code like this: class DbRouter(object): route_app_labels = ["dear_zoho_analytics", ] def db_for_read(self, model, **hints): . . . def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == "dear_analytics" return None when I do this: python3 ./manage.py migrate --database=dear_analytics I get the tables of every app created in the new database. python3 ./manage.py migrate dear_zoho_analytics --database=dear_analytics does what I want. However, this sort of implies that my allow migrate is not working because it appears to do nothing useful. -
Django Rest Framwork - Image Upload serializer not working but is valid and saving
I've tried everything but I cannot figure out why my images for an Avatar won't save to the media folder in Django. I am happy the front end is passing form data to the AvatarAPIView and I get the following when I print out the data being passed to the view. <QueryDict: {'myFile': [<InMemoryUploadedFile: 1965.jpg (image/jpeg)>]}> [07/Feb/2021 10:48:54] "PUT /api/profile/avatar/ HTTP/1.1" 200 31 view.py from profiles.api.serializers import (UserDisplaySerializer, SubscriptionSerializer, AvatarSerializer) from profiles.models import CustomUser from rest_framework import status, viewsets from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.generics import UpdateAPIView, GenericAPIView from rest_framework import mixins from rest_framework.parsers import MultiPartParser, FileUploadParser from django.http import HttpResponse class CurrentUserAPIView(APIView): def get(self, request): serializer = UserDisplaySerializer(request.user) return Response(serializer.data) def patch(self, request): serializer = UserDisplaySerializer(request.user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class UserUpdateAPIView(UpdateAPIView): queryset = CustomUser.objects.all() serializer_class = UserDisplaySerializer class AvatarAPIView(APIView): parser_class = (MultiPartParser) def get(self, request): serializer = AvatarSerializer(request.user) return Response(serializer.data) def put(self, request, *args, **kwargs): serializer = AvatarSerializer(request.user, data=request.data) print(request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.py from rest_framework import serializers from profiles.models import CustomUser, Subscription class SubscriptionSerializer(serializers.ModelSerializer): class Meta: model = Subscription exclude = ('id', 'user', ) class UserDisplaySerializer(serializers.ModelSerializer): subscription = SubscriptionSerializer(read_only=True, many=False) class … -
Why there is wsgi in django admin
I cannot understand why there is a wsgi in Django admin: django.core.wsgi As far as I understand django cannot react on request directly, so wsgi works as an interface there. How can I see that it really works? When I am searching how to use nginx with django, I see all tutorials using nginx -> uwsgi -> django. But why not built-in Djangos wsgi? I actually managed to run nginx together with django without doing anything with uwsgi or wsgi, does it stil exist somewhere in between, how do i see it? I have wsgi.py file in django settings folder, but I think it is not called at any time: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.production') application = get_wsgi_application() Can someone please point me to the correct place where I can read it? My search did not help me.. -
How to display a status based on the model data
I need to indicate the level of the average of my data model. for example: I have a model. class Test(models.Model): level = models.CharField() lets say my level values are, apple dog cat if there are 20 apples over 30 entries. my html will display <h1>{{ critical }}</h1> else if there are 20 dogs over 30 entries, my html will display <h1>{{ light }}</h1> how can i do that? thanks! -
Python Crash Course, chapter 19, registration
I am a noob, currently on the chapter 19 of this book by No Starch Press. Try to build a registration option in my blog but sadly the version I have of the book is not updated on the latest version of Django. I already checked for support on other sites but I am really lost since all the info I get are related to different versions of Django . When I try to run the server I get an error about the line from django.contrib.auth.forms import UserCreationFormfrom django.shortcuts import render the function I wrote in the views section of the app is.. from django.shortcuts import render from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from django.contrib.auth import login from django.contrib.auth.forms import UserCreationFormfrom django.shortcuts import render from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from django.contrib.auth import login from django.contrib.auth.forms import UserCreationForm def register(request): """Register a new user.""" if request.method != 'POST': # Display blank registration form. form = UserCreationForm() else: # Process completed form. form = UserCreationForm(data=request.POST) if form.is_valid(): new_user = form.save() # Log the user in and then redirect to home page. login(request, new_user) return redirect('learning_logs:index') # Display a blank or invalid form. context … -
Django models.py
I created an App called order whose models.py (model name create_order) contain fields like "order_created_by, cloth_type, clothe colour, size, delivery_date, order_created_date". Now in models.py of wherehouse app I want to see all the field of created_order model. How can I do that. And can do this all using first importing models in views.py of wherehouse and the creating function then retuning the Http Response using models.objects.all(). But I want to see these all fields of create_order in admin.py of wherehouse app. -
Django: Save html entries in mysql db
I'm trying to follow this open source project to learn more about Django and crispy. For that I try to extend this open source project I downloaded the project from GitHub and got it running :). However, the models.py is missing and I thought I'll try to add it, and push the html form data into my local mysql db. So basically I'm trying to extend that existing code. I was able to add the models.py and create the table in mysql. Issue: If I press the submit button, no data appears in mysql. What I think I figured out is, I need some "save()" command. But where? I found postings on google about codlins in forms.py and view.py. But either it did not resolve it or cause error. Any ideas how to overcome this? models.py from django.db import models from mysite.core.choice import STATES class Address(models.Model): email = models.CharField(max_length=100, blank=True) password = models.CharField(max_length=100, blank=True) address_1 = models.CharField(max_length=100, blank=True) address_2 = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=100, blank=True) zip_code = models.CharField(max_length=100, blank=True) state = models.IntegerField(default=1, choices=STATES, blank=True) check_me_out = models.BooleanField(default=False) forms.py --> Also with comments about what I changed vs. the original from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout … -
how to store count value in python(django)?
I am trying to implement an upload limit functionality. I found that Everything is working as expected except the count value. Please find the below views.py code. def CTA_upload(request): i = 1 count = [0,] print('Counter value at starting::::::::: :', len(count)) allcts = CTS.objects.all() try: if len(count) <= 14: if request.method == 'POST': movie_resource = CTAResource() print('movie_resource', movie_resource) dataset = Dataset() new_movie = request.FILES['file'] if not new_movie.name.endswith('xls'): messages.info(request, 'Sorry Wrong File Format.Please Upload valid format') return render(request, 'apple/uploadcts.html') messages.info(request, 'stage1 fired:Processing file type is Okay :)...') imported_data = dataset.load(new_movie.read(), format='xls') print('abcdefghijk:', type(imported_data)) messages.info(request, 'Stage2 fired:*** Now checking data inside imported data :)') for data in imported_data: value = CTA( data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], ) print('Value 1 ::::', value) print('Final Count After entering < = 15:', len(count)) messages.info(request, 'Stage3 fired:*** Now entering to check count <= :)') i = i + 1 count.append(i) print('Count After Appending Value:',count) value.save() else: print('Final ***else Count when > = is equal to 15:', len(count)) messages.info(request, 'Sorry you are uploading more than 15 records so records') print('Final count jo hai variable me store:', count) messages.info(request, 'Sleeping For 10 sec and then it will clear count value. so you can upload extra … -
How to include Duo Authentication to Django UI after Windows Authentication
i have a code which performs uploading of file to certain destination , and i have already include windows authentication as first phase of authentication and wanted to include Duo Security as second authentication . So i referred few of the git and other platforms regarding duo security and edited my settings.py and Urls.py as below Settings.py INSTALLED_APPS = [ 'duo_auth', ] MIDDLEWARE = [ # ... 'duo_auth.middleware.DuoAuthMiddleware', ] DUO_CONFIG = { 'DEFAULT': { 'HOST': '<api-host-url>', 'IKEY': '<integration_key>', 'AKEY': '<app_secret_key>', 'SKEY': '<secret_key>', 'FIRST_STAGE_BACKENDS': [ 'django.contrib.auth.backends.ModelBackend', ] } } and URLS.py as urlpatterns = [ path('admin/', admin.site.urls), path('duo/', include('duo_auth.urls')), path('', views.home,name='home'), path('create', views.create,name='create'), path('files', views.files,name='files'), ]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and installed django-duo-auth and is successfully installed , i migrated the change and ran server , restarted app . But this is throwing me error 500 . So i really don know whether any change other than this is required or anything is to be added or removed . i didn't find any relative paper or article which i can read and solve this issue . Kindly help me solve this issue . -
How to upload a django project to heroku?
I have been trying to upload my Django app to the Heroku for 3 hours but it is showing me an error. I am doing everything as shown in the documentation but I am getting this error. error: src refspec master does not match any error: failed to push some refs to 'https://git.heroku.com/share-good.git' could anyone help me with that please?? -
Nginx reverse proxy to django application, images styles are not showing
Hello i have a complete django app which I'll be hosting on aws ec2 with gunicorn and nginx. But when I run the app with gunicorn or python3 my app runs and shows all images with the css and styles. But whenever I try to serve my django app with nginx by proxy_pass the image or style or anything on static folder could not be accessed. my error log shows permission issue. But I have set the app with user and group both nginx. but nothing is showing. nginx conf on nginx.conf http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 4096; include /etc/nginx/mime.types; default_type application/octet-stream; include /etc/nginx/conf.d/*.conf; server { listen 80; server_name dev.softopark.com; root /home/ec2-user/sites/softopark-django-cms; access_log /var/log/nginx/dev.softopark.com.access.log; error_log /var/log/nginx/dev.softopark.com.error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /usr/share/nginx/html/softopark-django-cms/static/; } location /media/ { root /usr/share/nginx/html/softopark-django-cms/media/; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://0.0.0.0:8000/; } } my gunicorn service file [Unit] Description=Softopark gunicorn service by: Softopark.com After=network.target [Service] User=nginx Group=nginx WorkingDirectory=/usr/share/nginx/html/softopark-django-cms Environment="/home/ec2-user/Env/cms5-XkwMz5k7/bin" ExecStart=/home/ec2-user/Env/cms5-XkwMz5k7/bin/gunicorn --workers 3 --bind 0.0.0.0:8000 … -
Annotate the union queryset not support in djagno
how calculate summery from union queryset: after union queryset sometime needed to calculate or summery data but annotate not work in django how calculate this a simple scenario for my case from django.db import models from django.db.models import Sum, F class Person(models.Model): name = models.CharField() class InvoiceRemain(models.Model): person = models.ForeignKey(Person, models.PROTECT) currency = models.CharField() currency_rate = models.DecimalField(max_digits=20, decimal_places=5) amount = models.DecimalField(max_digits=20, decimal_places=5) class PersonPayReceive(models.Model): person = models.ForeignKey(Person, models.PROTECT) currency = models.CharField() currency_rate = models.DecimalField(max_digits=20, decimal_places=5) amount = models.DecimalField(max_digits=20, decimal_places=5) class OpenBalance(models.Model): person = models.ForeignKey(Person, models.PROTECT) currency = models.CharField() currency_rate = models.DecimalField(max_digits=20, decimal_places=5) amount = models.DecimalField(max_digits=20, decimal_places=5) invoice = InvoiceRemain.objects.all().values('person', 'amount', 'currency_rate') pay_rec = PersonPayReceive.objects.all().values('person', 'amount', 'currency_rate') open_balance = OpenBalance.objects.all().values('person', 'amount', 'currency_rate') result = invoice.union(pay_rec, open_balance).values('person').annotate( result=Sum(F('amount') * F('currency_rate'))).values('person', 'amount') -
filter outpout of process with potentially unlimted output, detect exit code and timeout after X
This is question is related to select.select issues with subprocess.Popen (process doesn't stop, no data to read) and I still don't have any idea how to nicely solve the problem. I have some existing django code running under uwsgi (under Linux) with threading disabled, that executes for some requests a subprocess, that I don't have any control over. The normal operation is following: the subprocess runs for a rather short time and returns either an exit code of 0 or something different. The code will write some messages to stdout / stderr. The return code (exit ode) will tell me whether the work was done correctly. if execution failed it would be good to gather stdout/stderr and log it to understand why things failed. On rare occasions however the subprocess can encounter a so far not understood race condition and will do following. it will write repeatedly a specific message to stdout and stderr and loop and hang forever. As I don't know whether there are any other race conditions, that could freeze the process with or without any output. Id' also like to add a timeout. (Though a solution, that adresses getting the return code and detecting the repeated … -
Django REST Framework API : How to save/upload images with the name given by user(e.g. username.jpg) at Django server
I want to upload image with the name (which is given by user) at Django server through rest API,but i am not be able to find out the solution for this.Please tell me how to upload image with given name. here is my code(mainly): IN API TASK ->URLS: from django.conf.urls import include, url from django.contrib import admin from rest_framework import routers from django.conf import settings from myapi import views from django.conf.urls.static import static #Define API Routes router = routers.DefaultRouter() router.register(r'myimage', views.myimageViewSet) #we have only on viewset urlpatterns = [ url(r'^',include(router.urls)), url(r'^admin/',admin.site.urls), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) IN My API 1. MODEL from django.db import models # Create your models here. class myimage(models.Model): my_name=models.CharField(max_length=50) my_image=models.ImageField(upload_to='Images/',default='Images/None/No-img.jpg') def __str__(self): return self.my_name 2.SERIALIZERS from rest_framework import serializers from .models import myimage class myimageserializer(serializers.ModelSerializer): class Meta: model =myimage fields=('id','my_name','my_image') 3. VIEWS from django.shortcuts import render from .models import myimage from rest_framework import viewsets from .serializers import myimageserializer from rest_framework import filters import django_filters.rest_framework class myimageViewSet(viewsets.ModelViewSet): queryset = myimage.objects.all() #We use Filters for Ordering so remove order_by part serializer_class = myimageserializer filter_backends = (django_filters.rest_framework.DjangoFilterBackend,filters.OrderingFilter,) ordering = ('id','my_name',) 4.ADMIN from django.contrib import admin from .models import myimage admin.site.register(myimage) -
Password not changing of user
So I'm trying to change the password of the user via a form but it never changes, It says password changed but it always stays the same. views.py @login_required def userchange(request): if request.method == 'POST': user = request.user old_password = request.POST['Old password'] new_password1 = request.POST['New password1'] new_password2 = request.POST['New password2'] print(new_password1) print(new_password2) if user.check_password(old_password): if new_password1 == new_password2: if new_password1 == "" or new_password2 == "": return render(request, 'main/change.html', {'error':'Your new passwords are empty!'}) else: User.objects.get(username=request.user.username).set_password(new_password1) logout(request) return render(request, 'main/change.html', {'error':'Your password has been changed succesfully!'}) else: return render(request, 'main/change.html', {'error':'Your new passwords do not match'}) else: return render(request, 'main/change.html', {'error':'Your old password is incorrect'}) elif request.method == "GET": return render(request, 'main/change.html') change.html <h1>Note: You will be logged out</h1> <h2>{{ error }}</h2> <form method="POST"> {% csrf_token %} <input type="password" placeholder="Old password" name="Old password"> <input type="password" placeholder="New password" name="New password1"> <input type="password" placeholder="Confirm password" name="New password2"> <button type="submit">Change password</button> </form>