Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Missing "dnspython" error for django + gninx + gunicorn app, even after installing it to the correct virtual environment
Getting the following Error: The "dnspython" module must be installed to use mongodb+srv:// URIs Exception location: ../python3.7/site-packages/pymongo/uri_parser.py, line 428, in parse_uri When trying to use pymongo with django app. I tried to install dnspython with pip3 to the correct virtual environment but still got the error. I also tried to re-start gninx. -
how to create django form from dictionary
I have dictionary like this p_dic = { 'Frequency': ['8kHz', '9kHz', '3.6kHz', '2.8kHz', '1.2kHz', ], 'Voltage - Input (Max)': ['-', '15V p-p', '80V p-p', '30V p-p'], 'Type': ['Feedback', 'Standard'], 'Impedance': ['500 Ohms', '400 Ohms', '350 Ohms', ], 'Capacitance @ Frequency': [ '25000pF @ 1kHz', '93000pF @ 1kHz'], } I want to create form where name will be key and options will be values as given in the list, how to do so. -
django: Auto populate m2m field of a model
I have a category kind of model (called Tag): class Tag(models.Model): name = models.CharField(...) slug = models.SlugField(unique=True) #... Used as m2m field in another model: class Order(models.Model): user = models.ForeignKey(...) type = models.CharField(...) tag = models.ManyToManyField(Tag, blank=True) Now, suppose an order is created and program wants to assign some tags to it automatically. Say, program wants to add Order.type to itsOrder.tag list. (Suppose Order.type happens to be same as a valid Tag.name) I tried Order's post_save to no luck: def order_post_save_reciever(sender, instance, *args, **kwargs): #... instance.tag.add(Tag.objects.filter(name=instance.type)) instance.save() Apparently, I have to use signals, but I don't know how. Your help is much appreciated. -
How to load django installed apps staticfiles in production?
This is probably a really simple adjustment that I've lost enough time searching for a solution. I built a project using Django + React and deployed it on Heroku. Everything works perfectly excepts for the static files from the INSTALLED_APPS: /admin and de Django Rest Framework views. In these urls, django throws a 500 server error. django.contrib.staticfiles is in my INSTALLED_APPS. I'm using whitenoise. My allowed hosts are correct. My STATIC_ROOT path is also correct. STATIC_URL = "/static/" STATIC_ROOT = os.path.join(FRONTEND_DIR, "build", "static") I've tried to add an empty directory in the STATICFILES_DIRS but it didn't work. What am I missing? Why django isn't collecting the static files from the INSTALLED_APPS? -
502 Bad Gateway nginx/1.18.0 django
var/log/nginx/error.log 2020/12/04 12:46:29 [error] 3938#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.14.128, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "uma-env.eba-hi5j8ufq.ap-south-1.elasticbeanstalk.com" 2020/12/04 12:46:30 [error] 3938#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.14.128, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8000/favicon.ico", host: "uma-env.eba-hi5j8ufq.ap-south-1.elasticbeanstalk.com", referrer: "http://uma-env.eba-hi5j8ufq.ap-south-1.elasticbeanstalk.com/" 2020/12/04 12:46:36 [error] 3938#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.14.128, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "uma-env.eba-hi5j8ufq.ap-south-1.elasticbeanstalk.com" 2020/12/04 12:46:36 [error] 3938#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.14.128, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8000/favicon.ico", host: "uma-env.eba-hi5j8ufq.ap-south-1.elasticbeanstalk.com", referrer: "http://uma-env.eba-hi5j8ufq.ap-south-1.elasticbeanstalk.com/" 2020/12/04 12:48:11 [error] 3938#0: *27 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.47.53, server: , request: "GET /TP/public/index.php HTTP/1.1", upstream: "http://127.0.0.1:8000/TP/public/index.php", host: "15.207.142.142" 2020/12/04 12:48:12 [error] 3938#0: *27 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.47.53, server: , request: "GET /TP/index.php HTTP/1.1", upstream: "http://127.0.0.1:8000/TP/index.php", host: "15.207.142.142" 2020/12/04 12:48:13 [error] 3938#0: *27 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.47.53, server: , request: "GET /thinkphp/html/public/index.php HTTP/1.1", upstream: "http://127.0.0.1:8000/thinkphp/html/public/index.php", host: "15.207.142.142" 2020/12/04 12:48:15 [error] 3938#0: *27 connect() failed (111: Connection refused) while connecting to β¦ -
Why can't Django via nginx find static files although manage.py findstatic is successful?
I deployed a Django app via nginx and this worked without any problem for the last few months. However now without any change that I know of Django can't find any static files anymore, so no images are displayed and the django admin page has no stylesheet. In my settings.py I have used the following setting: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... STATIC_ROOT = os.path.join(BASE_DIR,'static/') STATIC_URL = 'http://[ip.of.hosting.server]/[name_of_app]/static/' When I run e.g. manage.py findstatic --verbosity 2 img/logo.png Django is able to find the image file however in the deployed website the logo is not displayed and I get a 404 file not found error for the image. I also tried to run manage.py collectstatic however that added no new static files and the files are still not found. How can this suddenly happen. I have no idea what I might have touched to break -
ImportError: cannot import name 'APIView' from 'rest_framework.views'
ImportError pycharm I am trying to make a simple REST API using Django. I installed djangorestframework using pip and I am using Pycharm IDE for my work. When I try to import APIView from rest_framework using:from rest_framework.views import APIView I get this ImportError: ImportError: cannot import name 'APIView' from 'rest_framework.views' I am unable to solve this issue and need help -
slash ('/') is being automatically added to path ,even i havn't included it to my URLs and this is why it is giving PAGE NOT FOUND error
I have created a small project, and if i go to registration section. slash (/) gets added to URL automatically and says page not found. I have not included '/' in my code though This is my urls.py from django.urls import path from . import views urlpatterns = [ path('register',views.register, name = 'register'), # no slash over here path('login',views.login,name = 'login'), path('logout',views.logout,name='logout'), path('checkPincode',views.check,name `enter code here`= 'check'), ] this is navigation section of index.html <div class="topnav"> <a href="/" style="background-color:black; color:#54dfd8;">VIVER FOODS</a> <a href="#menu">Food Menu</a> <a href="cart/your-cart">Cart</a> <a href="help/questions">Help</a> {% if user.is_authenticated %} <a href="/" style="float: right;">Hello, {{ user.first_name }}</a> <a href="accounts/logout" style="float:right;">LogOut</a> {% else %} <a href="accounts/register" style="float:right;">SignUp</a> <a href="accounts/login" style="float:right;">logIn</a> {% endif %} </div> The thing is LOGIN working fine π€·ββοΈ. -
Django3: dynamically generating js which I can use in HTML page
As we know in Django framework we can generate the HTML page based on some predefined template files. Inside those templates we can use and some specific django keywords/operators/functions. Like: {% block stylesheets %} <link href="{% static 'js/jquery/jquery-ui.css' %}" rel="stylesheet"> <link href="{% static 'vendor/chosen/chosen.css' %}" rel="stylesheet"> {% endblock stylesheets %} But most important things which I want to touch in this question are related to tag 'translate' "{% trans 'List of all available masters' %}" So I can be sure that the final content of my page will use some predefined language. And the places where I am using such tags are different: "simple" html content with / and etc tags AND inline javascripts blocks. Like: <script type="text/javascript"> $('#datepicker_value').on('change', function(){ .... var dialog = BootstrapModalWrapperFactory.createModal({ title: '{% trans 'Extended information about the event' %}', message: '<pre>'+JSON.stringify(info.event.extendedProps.description, null, 4)+'</pre>', buttons: [ { label: '{% trans 'Close' %}', cssClass: "btn btn-secondary", action: function (button, buttonData, originalEvent) { return this.hide(); } } ] }); .... </script> So my main question here is such: HOW correctly I can move ALL <script>...</script> blocks from html template into the external JS file? To keep all the functionality of the django framework working! And my 1 variant β¦ -
Docker and Django: how to render templates in a right way
Hi guys how are you? I started with Docker and Django a little while ago and I already ran into a problem. Scenario: I want to create an application in Django using docker. I found this guide on the Docker website itself and followed the steps. My Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ Here is the docker-compose.yml version: "3.8" services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - .:/app web: build: . command: python manage.py runserver 0.0.0.0:5000 volumes: - .:/app ports: - "5000:5000" depends_on: - db The problem occurs when I want to start using Django templates. Currently, my file structure looks like this . βββ docker-compose.yml βββ Dockerfile βββ manage.py βββ requirements.txt βββ sao_app β βββ admin.py β βββ apps.py β βββ __init__.py β βββ migrations β β βββ __init__.py β βββ models.py β βββ __pycache__ β β βββ __init__.cpython-39.pyc β β βββ urls.cpython-39.pyc β β βββ views.cpython-39.pyc β βββ templates β β βββ sao_app β β βββ index.html β βββ tests.py β βββ urls.py β βββ views.py βββ sao_project βββ asgi.py βββ __init__.py βββ __pycache__ β βββ __init__.cpython-39.pyc β βββ settings.cpython-39.pyc β β¦ -
how to normalize this below json using panda in django
here is my json {"pages":[{"name":"page1","title":"SurveyWindow Pvt. Ltd. Customer Feedback","description":"Question marked * are compulsory.", "elements":[{"type":"radiogroup","name":"question1","title":"Do you like our product? *","isRequired":true, "choices":[{"value":"Yes","text":"Yes"},{"value":"No","text":"No"}]},{"type":"checkbox","name":"question2","title":"Please Rate Our PM Skill","isRequired":false,"choices":[{"value":"High","text":"High"},{"value":"Low","text":"Low"},{"value":"Medium","text":"Medium"}]},{"type":"radiogroup","name":"question3","title":"Do you like our services? *","isRequired":true,"choices":[{"value":"Yes","text":"Yes"},{"value":"No","text":"No"}]}]}]} this is my view.py jsondata=SurveyMaster.objects.all().filter(survey_id='1H2711202014572740') q = jsondata.values('survey_json_design') qs_json = pd.DataFrame.from_records(q) datatotable = pd.json_normalize(qs_json['survey_json_design'], record_path=['pages','elements']) qs_json = datatotable.to_html() -
ElasticSearch DSL DRF - Field Collapsing and Pagination
I am currently doing field collapsing using ElasticSearch DSL DRF - although that breaks the pagination completely; for example: Originally 19 items are matched After collapsing 18 items are left Pagination is set for 18 items per page Pagination still recognizes 19 items Is there anyone who knows a clean way of actually doing this? - making the count take into consideration the field collapsing? -
The wrapper over the database does not "fitβ on the MVC schema in Django
I am writing a mini project on Django that performs certain manipulations with the database. There was a need to write a small wrapper for clickhouse, which will give me the result of the request, and give a report in json format to GUI. The scheme of work is as follows: Ajax sends a request to a specific url, python calls this wrapper and returns the result in the form of json-a, then some magic happens. Question: What is the wrapper in this case? It does not fit on the model-view-controller scheme. How do I correctly add it to the Django app? (perhaps this is a separate application or a global singleton?) -
JSON problems ajax
me.addEventListener('change', (e) => { if (me.checked) { fetch("/demande/transporter/", { body: JSON.stringify({ cin_mle: cin_mle }), method: "POST" }).then(res => res.json()).then(data => { tn.value = data['email']; tn.disabled = true }); } }); code js class ReturnCredentilasView(View): def post(self, request): data = json.loads(request.body) cin_mle=data["cin_mle"] print(cin_mle) user=get_object_or_404(User, cin_mle=cin_mle) if not user: return JsonResponse({"User_status": "inexistant"}) return JsonResponse({"email":user.email}) the view The error : moi.js:10 POST http://127.0.0.1:8000/demande/transporter/ 404 (Not Found) (anonymous) @ moi.js:10 127.0.0.1/:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 I need to retrieve some data from the serer using ajax, but the errors above appears. the view is working good on postman me is checkbox element -
Passing in date string to Django management argument
I have a Django management command, which I pass like this: python manage.py tenant_command generate_weekly_invoice --start_date 2020-11-30 00:00:00 --end_date 2020-12-06 23:59:00 --schema=schema_name This doesn't work and I get an error saying that: argument 1 must be str, not None I suspect this is to do with the way the actual string of the date 2020-11-30 00:00:00 is being formatted. My management command code is below generate_weekly_invoice.py class Command(BaseCommand): help = 'Generates weekly invoice' def add_arguments(self, parser): parser.add_argument('--start_date', nargs='+') parser.add_argument('--end_date', nargs='+') def handle(self, *args, **options): start_str = options.get('--start_date') end_str = options.get('--end_date') start_date = datetime.datetime.strptime(start_str, '%Y-%m-%d %H:%M:%S') end_date = datetime.datetime.strptime(end_str, '%Y-%m-%d %H:%M:%S') ___Logic goes here___ -
Keep getting "FOREIGN KEY constraint failed" in Django
I am new to django and i am making a multivendor ecommerce website for my final year project. for the past three hours i keep having the foreingnkey constraints error when i want to add products. please i need smeone to help me and solve the problem. views.py def AddProduct(request): """this page will be used for adding products""" if request.method =='POST': form=ProductForm(request.POST) if form.is_valid(): model=User user=form.save() return HttpResponseRedirect('/becomeaseller/DashBoard') else: form=ProductForm() context={'form':form} return render(request, 'app/addproduct.html',context) return HttpResponse("enter the details and description of your products") models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): is_customer = models.BooleanField(default=False) is_seller = models.BooleanField(default=False) class Category(models.Model): category_name=models.CharField(max_length=100) def __str__(self): return self.category_name class Product_Details(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) product_name=models.CharField(max_length=100) category=models.ForeignKey(Category, on_delete=models.CASCADE) product_image=models.ImageField(null=True) product_description=models.CharField(max_length=100) product_price=models.IntegerField() product_quantity=models.IntegerField(default=1) shop_name=models.CharField(max_length=100) shop_location=models.CharField(max_length=100) shop_description=models.CharField(max_length=100) def __str__(self): return self.product_name -
icons are not visible for django, how to fix that?
I am trying to convert a bootstrap template to django project. I places all the css and other files to static and replaced with static tags. But, fontawesome icons are not showing. But with django: The html code: <div class="social-icons"> <a class="social-icon" href="#"><i class="fab fa-linkedin-in"></i></a> <a class="social-icon" href="#"><i class="fab fa-github"></i></a> <a class="social-icon" href="#"><i class="fab fa-twitter"></i></a> <a class="social-icon" href="#"><i class="fab fa-facebook-f"></i></a> </div> -
Django Admin - Disable the 'Add' action for a specific model Ask
hello there i want to add images in form from my admin panel with django when I created my class I do: photo = models.ImageField(null=True, blank=True, upload_to='images/') but I have an error: no such column: blog_post.company Request Method: GET error: 500 151197 -
WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/hi%20hi/' failed: WebSocket is closed before the connection is established
I am making a chat application in Django. I am following a YouTube tutorial and for most part the application is working fine, but there is some problem with my routings. When the name of the room is a single word like "room1", the Websocket is connected and I can send and receive messages. But when name of room is made or two or more words like "habiba room", the connection is not establishing. in console I get this error WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/habiba%20room/' failed: WebSocket is closed before the connection is established. and on server I get this error WebSocket DISCONNECT /ws/chat/habiba%20room/ [127.0.0.1:62063] [Failure instance: Traceback: <class 'ValueError'>: No route found for path 'ws/chat/habiba room/'. E:\New folder\env\lib\site-packages\autobahn\websocket\protocol.py:2839:processHandshake E:\New folder\env\lib\site-packages\txaio\tx.py:366:as_future E:\New folder\env\lib\site-packages\twisted\internet\defer.py:151:maybeDeferred E:\New folder\env\lib\site-packages\daphne\ws_protocol.py:72:onConnect --- <exception caught here> --- E:\New folder\env\lib\site-packages\twisted\internet\defer.py:151:maybeDeferred E:\New folder\env\lib\site-packages\daphne\server.py:200:create_application E:\New folder\env\lib\site-packages\channels\staticfiles.py:41:__call__ E:\New folder\env\lib\site-packages\channels\routing.py:54:__call__ E:\New folder\env\lib\site-packages\channels\sessions.py:47:__call__ E:\New folder\env\lib\site-packages\channels\sessions.py:145:__call__ E:\New folder\env\lib\site-packages\channels\sessions.py:169:__init__ E:\New folder\env\lib\site-packages\channels\middleware.py:31:__call__ E:\New folder\env\lib\site-packages\channels\routing.py:150:__call__ ] in project/routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) in chat/routing.py # chat/routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'^ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer), ] in my index.js var β¦ -
I only want the data of the table row whose checkbox is checked. my table row is in for loop how can i9 access them by jinja
I only want the data of the table row whose checkbox is checked. my table row is in for loop how can i9 access them by jinja. i tried with ajax but i am not able to redirect page with data please help me. this is my search.html : <form name="form" method="POST" id="form"> {% csrf_token %} <table class="table table-bordered table-responsive" id="flip-scroll"> <thead> <tr> <th scope="col">Visa Option</th> <th scope="col">Processing Type</th> <th height="60" scope="col">Travel Date</th> <th scope="col">Price</th> </tr> </thead> <tbody> {% for j in package %} <tr class="valid-container" data-id="{{ j.id }}"> <td style="cursor:pointer;" width="200"><input type="checkbox" name="c1" class="checkbox">&nbsp; <output class="visa_type" style="font-size:14.5px !important;">{{ j.visa_type }}</output></td> <td height="52" width="158"> <select class="custom-select processing_type" name="processing_type" required> <option value="{{ j.price }}" selected>Normal</option> <option value="{{ j.express_price }}">Express</option> </select> </td> <td width="190" height="60"> <div class="input-group date" data-date-format="dd.mm.yyyy"> <div class="input-group mb-2"> <input type="text" class="form-control travel_date" name="travel_date" value="dd.mm.yyyy" placeholder="dd.mm.yyyy"> <div class="input-group-text"><i class="ti-calendar"></i></div> <div class="input-group-addon"> </div> <div class="input-group-prepend"> </div> </div> </div> </td> <td width="166">{{ j.currency_type }}&nbsp;&nbsp; <output name="result" class="package_price">{{ j.price }}</output>.00</td> </tr> {% endfor %} </tbody> </table> <button type="submit" class="btn btn-primary col-md-4 offset-md-4 mb-3" id="check">Next</button> </form> please help I am stuck in it since yesterday -
Modify simpleJWT response
I'm using the simpleJWT authentication in Django. By default the response is like this: { "refresh"="" "access"= "" } I want to customize the response not to have a header and to contain some user details eg { username: ' ', detail1: ' ', detail2: ' ', accessToken: ' ', refreshToken: ' ' } How can I implement a response like this using simpleJWT? -
Django HTML Email Message Automatically pick receiver's email from form
Please can anyone help me with this issue. I am trying to allow the users of my website to send out review request to customers by filling out a form on their profile page. They only have to provide the email address of the recipient then the backend would use this to configure a HTML message then send to the recipient. Currently, the whole system works just fine if I hard code the recipient email address. But once I try to get the email from request.POST['receiver'] it seems not to be passing the argument to the function. Here is the view function: def request_review_api(request): receiver_email = request.POST['receiver'] print(receiver_email) request_review(request, receiver_email) return redirect('profile_company') @login_required(login_url='loginpage_company') @allowed_users_company(allowed_roles=['company']) def request_review(request, receiver_email): company = get_object_or_404(Company, user=request.user) company_id = company.pk print(company) html_tpl_path = 'companyusers/request_review.html' context_data = {'company': company, 'company_id': company_id,} email_html_template = get_template(html_tpl_path).render(context_data) receiver = receiver_email email_msg = EmailMessage('Review Request', email_html_template, settings.EMAIL_HOST_USER, [receiver], reply_to=['no-reply@bbb.com'], ) # this part allows the message to be send as html instead of plain text email_msg.content_subtype = 'html' email_msg.send(fail_silently=False) This is what I have in my Template: <p class="tm-request-review-display card-text"> <form class="tm-request-review-display" action="{%url 'request_review' %}" method="POST"> {% csrf_token %} <div class="form-group"> <div class="col-md"> <input type="email" class="form-control" name="receiver" id="receiver" placeholder="Enter Reviewer's Email"> β¦ -
User deactivation in Django
I am trying to allow users to deactivate their accounts on my django website. Here is what I have tried: views.py from django.contrib.auth.models import User @login_required def deactivate_user(request, username): context = {} try: user = User.objects.get(username=username) user.is_active = False user.save() context['msg'] = 'Profile successfully disabled.' except User.DoesNotExist: context['msg'] = 'User does not exist.' except Exception as e: context['msg'] = e.message return render(request, 'index.html', context=context) urls.py path('deactivate-user/<slug:username>', deactivate_user, name='deactivate_user'), base.html <form action="{% url 'users:deactivate_user' slug=username.slug %}" method="post"> {% csrf_token %} <button type="submit" class="active">Yes, Deactivate</button> <button type="button" data-dismiss="modal">Cancel</button> </form> I am getting a NoReverseMatch error Reverse for 'deactivate_user' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['users/deactivate\\-user/(?P<username>[-a-zA-Z0-9_]+)$'] Have tried a few different parameters in the template but can't get anything to work. -
add a pop up dropdown list when choose a radio button in django
I use Django 2.2.16 in windows 10. In my frontend page, I have to achieve this function, after choosing a radio button, a dropdown list will pop up. I have finished the radio button editing and know how to do dropdown list, but I do not know how I could achieve such kind of popup function after choosing the radio button. HTML: {% extends 'base.html' %} {% load static %} {% load humanize %} {% block content %} <div class="row"> <form> <label class="radio-inline"> <input type="radio" name="optradio" checked>&nbsp;Latest Available Semester </label> <label class="radio-inline"> <input type="radio" name="optradio">&nbsp;Specific Semester </label> </form> </div> -
my signup data are not saving in database table auth_user
I have created a signup form using django default django.contrib.auth signup form but it's not saving any data from sign up form.i watched many tutorial but couldn't reslove it tried deleting all my previous migrations as well but still facing this is issue , i am using mysql as my database kindly help if one can my form.py class SignUpForm(UserCreationForm): class Meta: model = User fields = ['username', 'email',] views.py from django.shortcuts import render from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from django.forms.utils import ErrorList from django.http import HttpResponse from .forms import LoginForm, SignUpForm def login_view(request): form = LoginForm(request.POST or None) msg = None if request.method == "POST": if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("/") else: msg = 'Invalid credentials' else: msg = 'Error validating the form' return render(request, "accounts/login.html", {"form": form, "msg" : msg}) def signup(request): if request.method == "POST": form = SignUpForm(request.POST) if form.is_valid(): form.save() return redirect('admin') else: form = SignUpForm() else: form = SignUpForm() return render(request, "accounts/register.html", {"form": form}) signup template {% extends "layouts/base-fullscreen.html" %} {% load static %} {% block title %} Login {% endblock β¦