Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fill nested dictionary with values of a Queryset in Django
I have a a dictionary like this: result = { 'year' : {} } and I have a queryset like this: <QuerySet [{'building_id': 1, 'year': 2019, 'demand': 123.34}, {'building_id': 1, 'year': 2019, 'demand': 345.0}, {'building_id': 1, 'year': 2019, 'demand': 12345.0}, {'building_id': 2, 'year': 2019, 'demand': 345.0}]> Now I would like to transform the values of the queryset into the nested dictionary so that it looks like so: result = { 'year' : {'1' : [123.34, 345.0, ...], 2 : [345, ...] } I get my queryset like this, so it is currently within a loop: for item in buildings: demand_cool_item = item.demandcool_set.filter(year=passed_year).values('building_id', 'year', 'demand') For starters I was trying to loop through the queryset push it to an array and then update the dict within the dict like so: demand_cool_list = [] for item in buildings: demand_cool_item = item.demandcool_set.filter(year=passed_year).values('building_id', 'year', 'demand') demand_cool_list.append(demand_cool_item) for item in demand_cool_list: result.update(item) tried also ``` result.update(item['building_id']['demand'])```` That said that dictionary update sequence element #0 has length 3; 2 is required or that I have a Type Error. ! Can someone land me a hand on this? Highly appreciated! Thanks in advance -
"No module named <module name>" Error on django
I'm working on a project and I'm facing this issue. i wanted to make an import from some folder but it always throws an exception. here is my files structure: \myWebsite \childWebsite \importedClass \myWebsite(same name as the parent) \classThatCallsTheImportedClass so my call is as following: from myWebsite.childWebsite.importedClass import someFunction However, it always throws an error: "No module named 'myWebsite.childWebsite'" I discovered that when executing the call line, django checks the files inside the child "myWebsite" folder and hence it can't find the "importedClass". So, how i make it checks the parent "myWebsite"? -
why is this code not working--django paginate
I'm trying to paginate a page in order to display 1 status per page...it fails to paginate and it doesn't display the link to the next pages views.py def post_list(request): posts= Post.objects.all() paginator = Paginator(post_list, 1) page = request.GET.get('page') return render(request, 'news.html', {'posts':posts}) templates {% for num in posts.paginator.page_range %} {% if posts.number == num %} <strong>{{ num }}</strong> {% else %} {{ num }} {% endif %} {% endfor %} -
Django ValueError "Cannot query "asd": Must be "OnlineGame" instance."
I got this error; "Cannot query "asd": Must be "OnlineGame" instance." (asd is gameslug) (OnlineGame is class which store online game name like; lol pubg) models.py class Game(models.Model): match=models.ManyToManyField(Match,related_name="gamematch") class Match(models.Model): teams = models.ManyToManyField(Team, through='MatchTeam') class MatchTeam(models.Model): match = models.ForeignKey('Match', on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) rank = models.IntegerField(default=20) point=models.IntegerField(default=0) views.py game=get_object_or_404(Game ,tournament__slug=tournamentslug ,slug=slug,game__slug=gameslug) teams = MatchTeam.objects.filter( match__game=game ).annotate( points=F('rank') ).order_by( '-broyale_match', 'rank' ) -
ImportError: cannot import name 'get_core_apps' from 'oscar' error while setting up django-oscar
I am building an e-commerce platform using Django-oscar. I've set up Django-oscar following the official documentation at available https://django-oscar.readthedocs.io/en/releases-1.6/internals/getting_started.html. But when I try to make migrations I get an error "ImportError: cannot import name 'get_core_apps' from 'oscar' (/home/imanoj997/anaconda3/envs/ecommerce/lib/python3.7/site-packages/oscar/init.py)" Here's my settings.py file import os from oscar.defaults import * BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ALLOWED_HOSTS = ['localhost','127.0.0.1'] # Application definition from oscar import get_core_apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.flatpages', 'compressor', 'widget_tweaks', 'apps' ] + get_core_apps() SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'oscar.apps.basket.middleware.BasketMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', ] and here's the init.py files inside oscar directory while the error is pointing to, Use 'alpha', 'beta', 'rc' or 'final' as the 4th element to indicate release type. VERSION = (2, 0, 0, 'final') def get_short_version(): return '%s.%s' % (VERSION[0], VERSION[1]) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) # Append 3rd digit if > 0 if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) elif VERSION[3] != 'final': mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'} version = '%s%s' % (version, mapping[VERSION[3]]) if len(VERSION) == 5: version = '%s%s' % (version, VERSION[4]) return version INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'oscar', … -
__init__() got an unexpected keyword argument 'failfast'
I've a problem with my Django App, this week I added some models and tests but when I'm about to test it with "python manage.py test", I have this error : TypeError: init() got an unexpected keyword argument 'failfast' I've tried to see if I have some bugs in my models (syntax error) or my serializers and even tried to go back to an ancient working commit, but it doesn't worked... Creating test database for alias 'default'... System check identified no issues (0 silenced). Destroying test database for alias 'default'... Traceback (most recent call last): File "manage.py", line 16, in <module> execute_from_command_line(sys.argv) File "C:\Users\Arh\.virtualenvs\mybacksentinhealth-gHbH4SRy\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Arh\.virtualenvs\mybacksentinhealth-gHbH4SRy\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Arh\.virtualenvs\mybacksentinhealth-gHbH4SRy\lib\site-packages\django\core\management\commands\test.py", line 23, in run_from_argv super().run_from_argv(argv) File "C:\Users\Arh\.virtualenvs\mybacksentinhealth-gHbH4SRy\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Arh\.virtualenvs\mybacksentinhealth-gHbH4SRy\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\Arh\.virtualenvs\mybacksentinhealth-gHbH4SRy\lib\site-packages\django\core\management\commands\test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File "C:\Users\Arh\.virtualenvs\mybacksentinhealth-gHbH4SRy\lib\site-packages\django\test\runner.py", line 633, in run_tests result = self.run_suite(suite) File "C:\Users\Arh\.virtualenvs\mybacksentinhealth-gHbH4SRy\lib\site-packages\xmlrunner\extra\djangotestrunner.py", line 57, in run_suite runner = self.test_runner(**runner_kwargs) TypeError: __init__() got an unexpected keyword argument 'failfast' I don't use the failfast argument in the command line so this error makes no sence for me. Thanks for your help ! -
How to use django and database?
I'm supposed to use Django, Rest API and some database management type. Can somebody explain me that how to use these tools together? -
How to change value of variable in django template?
I want to declare a flag variable in django template and the change it if some thing happened. But when I change value of variable by custom tag it is declared a new variable and doesn't change. for example my template tag and django template is: template tag: @register.simple_tag def update_variable(value): return value html: {% with True as flag %} <h1>1: {{ flag }}</h1> {% for e in events %} {% update_variable False as flag %} <h1>2: {{ flag }}</h1> {% endfor %} <h1>3: {{ flag }}</h1> {% endwith %} and result is: 1: True 2: False 2: False 2: False 3: True But the end result should be False! How to do this? -
ModuleNotFoundError when registering django app
I'm getting an error when I include my app in the settings.py file using <app>.apps.PagesConfig. I'm in a virtual environment, have the project and app installed, and the app has an __init__.py inside. If I just register it as <app>, it works, but not with the full <app>.apps.PagesConfig See code and error below. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app_test.apps.PagesConfig', ] Error: ModuleNotFoundError: No module named 'app_test.apps.PagesConfig'; 'app_test.apps' is not a package -
Django Server Just Stops
I just got done upgrading to Django 2.2.3 from version 2.0. For some reason the system will just stop working when going to a new page. I might go one or to pages and then the server stops. I am also using Cookiecutter. Below is a typical message that I am receiving. Though it changes. it was acting strange before this - why I upgraded. I checked all my migrations. Reinstalled Django. Using Pycharm. Thanks. [17/Jul/2019 06:21:45] "GET /case/index/4QUxNe8vSNkd/ HTTP/1.1" 200 1259481 [17/Jul/2019 06:21:45] "GET /static/CACHE/css/app.128af5d916e2.css HTTP/1.1" 200 356184 Traceback (most recent call last): File "/Users/benson/PycharmProjects/myanalysis/manage.py", line 29, in <module> execute_from_command_line(sys.argv) File "/Users/benson/PycharmProjects/myanalysis/v_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/benson/PycharmProjects/myanalysis/v_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/benson/PycharmProjects/myanalysis/v_env/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/benson/PycharmProjects/myanalysis/v_env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/Users/benson/PycharmProjects/myanalysis/v_env/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/benson/PycharmProjects/myanalysis/v_env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 95, in handle self.run(**options) File "/Users/benson/PycharmProjects/myanalysis/v_env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "/Users/benson/PycharmProjects/myanalysis/v_env/lib/python3.6/site-packages/django/utils/autoreload.py", line 587, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/Users/benson/PycharmProjects/myanalysis/v_env/lib/python3.6/site-packages/django/utils/autoreload.py", line 572, in start_django reloader.run(django_main_thread) File "/Users/benson/PycharmProjects/myanalysis/v_env/lib/python3.6/site-packages/django/utils/autoreload.py", line 290, in run self.run_loop() File "/Users/benson/PycharmProjects/myanalysis/v_env/lib/python3.6/site-packages/django/utils/autoreload.py", line 296, in run_loop next(ticker) File "/Users/benson/PycharmProjects/myanalysis/v_env/lib/python3.6/site-packages/django/utils/autoreload.py", line 336, in tick for filepath, mtime in self.snapshot_files(): File "/Users/benson/PycharmProjects/myanalysis/v_env/lib/python3.6/site-packages/django/utils/autoreload.py", … -
UniqueConstraint in django 2.2 don't raise ValidationError
Since django 2.2 docs recommend to use UniqueConstraint instead of unique_together, but this option didn't raise ValidationError in django admin without overriding clean or validate_unique methods. Is it possible to make UniqueConstraint raise ValidationError(in django admin) instead of IntegrityError without implementing validation logic by myself? -
Django template with html tag in jinja2
I use CKEditor in my django project to take bio details from user. When I display user data on front end, It show with html tag. How to I remove tag from front end & give display effect of that tag? {% for user in user_list %} <tr> <td>{{user.name}}</td> <td>{{user.gender}}</td> <td>{{user.dob}}</td> <td>{{user.hobbies}}</td> <td>{{user.message}}</td> <td>{{user.bio}}</td> its shows as this: <p><em><strong>Bio</strong></em></p> -
Export the groups that exist in Django (CMS) so they can be used as oauth2 scopes
I have three separate applications. One is a Django CMS application. The other two are CKAN and Superset apps. I am using Django Single Sign On(SSO) to automatically login to CKAN and Superset provided I am already logged in CMS. Now I am trying to export the groups that exist in Django (CMS) so they can be used as oauth2 scopes in CKAN and Superset When a user belongs to Group A in CMS, I expect the same user to belong to Group A in CKAN and Group A(ROle) in Superset. -
How do I display the deleted content from an existing form to a completely separate url, Where it displays the deleted items in django
How do I display the deleted content from an existing form to a completely separate URL, Where it displays the deleted items in django. I've been trying to figure out how to create a separate table where it displays all the items that I've deleted I can't figure out what I should put in my function key from django.shortcuts import render, redirect from employee.forms import EmployeeForm from employee.models import Employee # Create your views here. def emp(request): if request.method == "POST": form = EmployeeForm(request.POST) if form.is_valid(): try: form.save() return redirect('/show') except: pass else: form = EmployeeForm() return render(request,'index.html',{'form':form}) def show(request): employees = Employee.objects.all() return render(request,"show.html",{'employees':employees}) def edit(request, id): employee = Employee.objects.get(id=id) return render(request,'edit.html', {'employee':employee}) def update(request, id): employee = Employee.objects.get(id=id) form = EmployeeForm(request.POST, instance = employee) if form.is_valid(): form.save() return redirect("/show") enter code here return render(request, 'edit.html', {'employee': employee}) def destroy(request, id): employee = Employee.objects.get(id=id) employee.delete() return redirect("/show") -
Django view if statement
i have choices field. I want in views.py like this; How can i do? if gametype == 1: template='xxx.html' if gametype == 2: template='xxx1.html' models.py class Model(models.Model): type_tvt = 1 type_pvp = 2 type_royale=3 types = ( (type_tvt, 'T'), (type_pvp, 'P'), (type_royale,'R'), ) gametype=models.SmallIntegerField(choices=types) -
Redirect the users to their seprate pages on login
I am creating a django admin app in which there are two different types of users. One is the admin and another is the simple user. The problem is I have no idea on how to redirect these users to their own dashboards. For example, If a user who has created an admin account logs in then he/she should see a admin dashboard. and if a user who has a simple user account logs in then he/she must not be able to see the admin dashboard. -
DJANGO HEROKU :django.db.migrations.exceptions.InconsistentMigrationHistory:
i have pushed my django application to heroku and when i tried to fireup the url where my application is i just got this error ProgrammingError at / relation "accounts_user" does not exist LINE 1: ..."."is_active", "accounts_user"."date_joined" FROM "accounts_... so i have figured out that the issue is with migration so i tried to run the makemigrations command in heroku but unfortunately it returned as a failure with an error message django.db.migrations.exceptions.InconsistentMigrationHistory: Migration posts.0001_initial is applied before its dependency accounts.0001_initial on database 'default'. so what i have tried is i have completely removed the migrations and database and runnned makemigration and migrate command in my local server and then i pushed it back to heroku but still its of no use my local is running perfectly fine i'm not sure where exactly the migrations issue is , in my heroku django application i want to remove the previous migrations and have a clean database but i have no idea on how to do that -
How to run Django on Unix server (MobaXterm)?
While server (127.0.0.1) works just fine on PC using Pycharm which uses the Django framework, I've tried to execute the command on unix server (MobaXterm) but it just says that 10.1...1..69 (my own PC IP address) refused to connect. I've changed the ALLOWED_HOSTS = ['*']. But still, it doesn't work. By running [file leading to python directory]/python manage.py runserver 0.0.0.0:8000, there is a starting development server at http://0.0.0.0:8080/. However, when I tried to open this in Chrome (http://10.1...1..69:8080/), it just says it refused to connect. Can I check if I did everything correctly? Are there any additional steps that I need to make amendments to in order to run Django on Unix server (MobaXterm)? -
How to convert Generic Views to Class based Views for lists with modals
I'm trying to convert generic views to class based views, so that I can get some better readability in my code. From this I want to be able to create a function so that I can show a modal for individual items in a list. I'm new to django so I don't know what I can try, I've searched online and read the docs but not having any luck. View I'm currently using: """ def my_booking_list(request): booking_lab = Reservation.objects.filter(username=request.user.username).order_by('-id') key = settings.STRIPE_PUBLISHABLE_KEY print(booking_lab) return render(request, 'my_booking_list.html', {'booking_labs': booking_lab, 'key': key}) """ Class based view I have no idea what I'm doing with (am I at least on the right track?): """ class MyBookingsView(ListView): def get(self,request ,pk): booking_lab = Reservation.objects.filter(username=request.user.username).order_by('-id') key = settings.STRIPE_PUBLISHABLE_KEY print(booking_lab) return render(request, 'my_booking_list.html', {'booking_labs': booking_lab, 'key': key}) """ Template (partial): """ {% if booking_labs %} {% for lab in booking_labs %} <div class="tg-dashboardservices"> <div class="tg-dashboardservice"> <div class="tg-servicetitle"> <h2><a href="#" data-toggle="modal" data-target=".tg-categoryModal">{{lab.lab.name}}</a> {% if lab.status == 'Accepted' %} <span>({{lab.status}})</span> {% elif lab.status == 'Requested' %} <span>({{lab.status}})</span> {% elif lab.status == 'Denied' %} <span>({{lab.status}})</span> {% endif %}</h2> </div> <div class="tg-btntimeedit"> <span>{{lab.price}}</span> <button class="tg-btnedite"><a data-toggle="modal" data-target=".tg-categoryModal"> <i class="lnr lnr-pencil"></i></a> </button> <button class="tg-btndel"><a><i class="lnr lnr-trash"></i></a> </button> </div> </div> </div> </div> </fieldset> … -
Django set cookie using middleware fails on first page load
There's a cookie I need to be present from the start of the site so I set it using middleware like this #https://docs.djangoproject.com/en/2.2/topics/http/middleware/#writing-your-own-middleware def set_lang_cookie(get_response): def middleware(request): response = get_response(request) if not request.COOKIES.get('lang'): response.set_cookie('lang', 'en') return response return middleware it works but the first time loading a page for example after closing the browser and opening it again or using incognito it throws an error that the cookie doesn't exist because this is how I pipe it into a template filter {{ pg.title|translate:request.COOKIES.lang }} is there a work around this? -
want to protect views function from anonymous user using decorators
i have django website that require authentication and user login in order to use some functions and view templates. i used the decorator @login_required but nothing is change and anyone still able to view html page and use any function. what am i missing in my code ?? views.py from django.contrib.auth.decorators import login_required # Create your views here. @login_required(login_url="/login/") def create(request): ... return render(request,'blog/create.html') urls.py """ABdatabase URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path,include from blog.views import * from .views import * from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('',home), path("usr/logMeIn", logMeIn), path("usr/logMeOut", logMeOut), path('mainpage',mainpage,name="main"),# this is the main page where it redirect to the **blog/create.html** path('blog/', include('blog.urls')),# include ==> redirect the url into the **urls.py** file in … -
Create custom index on multiple columns in cassandra
I have a table in cassandra and I want to create index on multiple columns. Suppose I have a Table named Xyz with date, name, address, number, email, dob, is_active columns and my query is something like: Xyz.objects.filter(date__gte=date, date__lte=date, is_active=True) On every request this query executes approx. 365-400 times so it takes around 33 secs to complete a request. I want to minimize the response time and I was trying to create custom index on multiple columns in cassandra but I am getting error while creating index. I tried creating custom indexes using CREATE CUSTOM INDEX my_index on my_keyspace.xyz (date, is_active) USING 'org.apache.cassandra.index.sasi.SASIIndex' WITH OPTIONS = { 'mode': 'CONTAINS' }; I got this error: ConfigurationException: <Error from server: code=2300 [Query invalid because of configuration issue] message="Failed to validate custom indexer options: {mode=CONTAINS, class_name=org.apache.cassandra.index.sasi.SASIIndex, target=date, is_active}"> Is there any other to work around this? Thank you so much in Advance. -
ModuleNotFoundError: No module named 'Courses.wsgi'
When I try to check the status of my gunicorn.service - $ sudo systemctl status gunicorn - I get this error message: ModuleNotFoundError: No module named 'Courses.wsgi' I need to deploy my project to Digital-Ocean, but it something wrong. I hoping for your help, thank you in advance! Here file - $ sudo nano /etc/systemd/system/gunicorn.service: [Unit] Description=gunicorn daemon After=network.target [Service] User=don1k Group=www-data WorkingDirectory=/home/don1k/courses_api ExecStart=/home/don1k/courses_api/env/bin/gunicorn --access-logfile - --workers 3 bind unix:/home/don1k/courses_api/Courses/Courses.sock Courses.wsgi:application [Install] WantedBy=multi-user.target Here the structure of my working directories: courses_api env Courses ├── manage.py Courses ├── urls.py ├── settings.py ├── wsgi.py ├── init.py settings.py: WSGI_APPLICATION = 'Courses.wsgi.application' wsgi.py: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Courses.settings") Gunicorn bind worked successfully by this command: 1. $ cd /home/don1k/courses_api/Courses/ 2. $ gunicorn --pythonpath/home/don1k/courses_api/Courses --bind 0.0.0.0:8000 Courses.wsgi -
How to Create a dynamic Slider in Django?
I am New to django and I want to create a dynamic Slider in Django, I want this slider in Django Admin panel where I can Edit, update and Change Slider Images, Please let me know how I can make This functionality in Django Framework. -
how to allow only logged in user to post in the website
I am creating a site where user will be posting their stuff, in order to post to the site it requires to login, so for those who are not logged in when they want to post I want them to be redirected to the login page and a displaying pop up message "Post require login" This is for python 3.7.3 and django 2.2.3. For users who are not logged in, I have added @login_required which throw an error page not found, instead of that I want to redirect them to login form. Views.py for posting @login_required def PostNew(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('loststuffapp:IndexView') else: form = PostForm() return render(request, 'loststuffapp/form.html', {'form': form}) views.py for login def login_request(request): if request.method == "POST": user_form = AuthenticationForm(request, data=request.POST) if user_form.is_valid(): username = user_form.cleaned_data.get("username") password = user_form.cleaned_data.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect("loststuffapp:IndexView") else: messages.error(request, "Invalid username or password") user_form = AuthenticationForm() return render(request, "loststuffapp/login.html", {"user_form":user_form} ) login.html {% extends "loststuffapp/base.html" %} {% block content %} <form method="POST"> {% csrf_token %} {{user_form.as_p}} <p><button class="btn" type="submit" >Login</button></p> …