Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting ModuleNotFoundError in Django
Project Structure urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.homepage, name='homepage'), path('login_user', views.login_user, name='login_user'), path('logout_user', views.logout_user, name='logout_user'), path('register_user', views.register_view, name='register_user'), path('dashboard', views.dashboard, name='dashboard'), ] chat_app2/views.py from django.contrib.auth import logout, authenticate, login from django.http import HttpResponse from django.shortcuts import render, redirect from chat_app2.account.forms import RegistrationForm def register_view(request, *args, **kwargs): user = request.user if user.is_authenticated: return HttpResponse("You are already authenticated as " + str(user.email)) context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email').lower() raw_password = form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) destination = kwargs.get("next") if destination: return redirect(destination) return redirect('homepage') else: context['registration_form'] = form else: form = RegistrationForm() context['registration_form'] = form return render(request, 'register_user.html', context) settings.py AUTH_USER_MODEL = 'account.Account' # Application definition INSTALLED_APPS = [ 'account', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Error File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Manish Gusain\Documents\Python_Projects\chat_app2\chat_app2\urls.py", line 3, in <module> from . import views File "C:\Users\Manish Gusain\Documents\Python_Projects\chat_app2\chat_app2\views.py", line 4, in <module> from chat_app2.account.forms import RegistrationForm ModuleNotFoundError: No module named 'chat_app2.account' I'm trying to add new user to the database using a user … -
React and Django - Connect the Note model with the specific User
I am creating a notes saving app using react and django_rest_framework. My Note model - from django.db import models from django.contrib.auth.models import User class Note(models.Model): title = models.CharField(max_length=100) content = models.TextField() def __str__(self): return self.title Note Serializer - from rest_framework import serializers from .models import Note class NoteSerializer(serializers.ModelSerializer): class Meta: model = Note fields = ("id", "title", "content") For register and logging in I am following the answer here - Answer Now, how do I connect my note object to the specific logged in user so a particular note is only visible to that user? This can be done with ForeignKey in django but how to do it in django_rest_framework? Please help. Thanks! -
Fast Search With Django + PostgreSQL
I am newbie working on Django with PostgreSQL database. I want to know that, what are the most efficient approaches for fast search on large data (millions of records). because I ran query on 300K records, it took too much time. Please kindly guide me that how can I do fast search in Django? Thank you so much. -
unable to get CSS to load on a Django html page
My css is not rendering on any of my HTML pages in a dJango project. I have followed a few Stack solutions to no avail, including adding <link rel="stylesheet" href="{% static "styles.css" %}" type="text/css" media="screen" /> as described here: Django static files (css) not working and also changing that to <link rel="stylesheet" href="{% static 'style.css' %}" />, suggested here: Unable to Apply CSS on my HTML file Django currently my HTML looks like: {% extends "mail/layout.html" %} {% load static %} <link rel="stylesheet" href="{% static 'styles.css' %}" /> {% block body %} <div id="inbox-view"> <h3>Inbox</h3> <button id="show-email-row" class="btn default"> email row </button> <button class="btn default">Default</button> </div> {% endblock %} {% block script %} <script src="{% static 'mail/inbox.js' %}"></script> {% endblock %} And my css file called styles.css, which is in a folder called '''static''' looks like this: textarea { min-height: 400px; } .btn { border: 2px solid black; background-color: white; color: black; padding: 14px 28px; font-size: 16px; cursor: pointer; } /* Gray */ .default { border-color: #e7e7e7; color: black; } .default:hover { background: #e7e7e7; } Ideally, the button will change color on hover, and have a dark background. Thank you -
Django.db.utils.DataError: value too long for type character varying(300) In django Models
I'm not sure what limit is this error django.db.utils.DataError: value too long for type character varying(300) is referring to, Can you tell me what I'm doing wrong and how to fix that problem. #models.py class Meetings(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, verbose_name = "Appointment Made By") reasonOfAppointment = models.TextField(null=True, blank=True, verbose_name = "Reason of Appointment") dateOfBirth = models.CharField(max_length=200, null=True, blank=True, verbose_name = "Patient Date Of Birth") gender = models.CharField(max_length=200, null=True, blank=True, verbose_name = "Gender") maritalStatus= models.CharField(max_length=200, null=True, blank=True, verbose_name = "Merital Status") phoneNumber=models.CharField(max_length=200, null=True, blank=True, verbose_name = "Phone Number") emergencyContactNo=models.CharField(max_length=200, null=True, blank=True, verbose_name = "Emergency Contact Number") medicalHistory= models.TextField(null=True, blank=True, verbose_name="Patient Medical History") previousTreatmentDetails=models.TextField(null=True, blank=True, verbose_name="Prevous Treatment Details") allergicTo= models.CharField(max_length=200, null=True, blank=True, verbose_name="Allergies") taxPrice = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) consultancyServiceFee = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) totalFee = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) isPaid = models.BooleanField(default=False, verbose_name= "Is Payment Recieved ") paidAt = models.DateTimeField(auto_now_add=False, null=True, blank=True, verbose_name= "Paid At") meetingWillBeConductedOn = models.CharField(max_length=200, null=True, blank=True, verbose_name ="Meeting Venue Zoom or etc") meetingSchedual = models.CharField(max_length=200, null=True, blank=True, verbose_name ="Give Tentative Time Of when Meeting will be conducted") meetingLink = models.CharField(max_length=2000, null=True, blank=True, verbose_name ="Enter Meeting Link") isMeetingConducted = models.BooleanField(default=False, verbose_name="Is Meeting Has been Held") meetingConductedAt = models.DateTimeField( auto_now_add=False, null=True, blank=True, verbose_name="Meeting … -
how can i deal with this problem "i want a button which shows when i click on radio button after that it will display "
enter image description here I want this button whenever i clicked on perfect address so please can any one help me -
How to serve dynamic sitemap.xml through nginx?
How to serve dynamic sitemap.xml file (generated from a CMS) through nginx? Is there any rules that have to be configured? Thanks -
send user to a link with data in that link
The main idea is I want to generate a Qrcode that going to have a URL, I want the URL to contain data {object}, and I want to collect that object in the other page(URL). I hope the Idea is clear, and can someone please help me with methodologies to achieve that result. -
__str__ returned non-string (type NoneType) ERROR when adding DATA
Right now I'm trying to get user-specific data in a website I'm using but I'm getting what seems to be a pretty basic error when I click submit on one of my forms. The error is: str returned non-string (type NoneType) my view looks like this: def adddata_asbestos(request): if not request.user.is_staff or not request.user.is_superuser: raise Http404 form = SheetForm_Asbestos(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() messages.success(request, "Successfully Created") return HttpResponseRedirect("/front_page/sheets/list_data_asbestos/") context = {"form": form,} return render(request, 'sheets/add_data/add_data_asbestos.html', context) And importantly this is the form that adds data: {% load static %} <!DOCTYPE html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static "css/add_data.css" %}"> <link rel="stylesheet" href="{% static "css/materialize2.css" %}"> <title>Ladder - Asbestos Add Data</title> </head> <div class="back_button_sheet"> <a style="background-color: #2f3d50; border-radius: 18px;" href="{% url 'list_asbestos' %}" class="btn btn-primary">< Back</a> </div> <div class="table_position_add container my-4"> <div class="card my-3"> <div class="card-body"> <h4 style="font-size: 30px; text-align: center;">Asbestos Testing</h4> <form class="table_add" method="POST" action=""> {% csrf_token %} <table class="table table-bordered"> <tr> <td style="font-weight: bold;">Date</td> <td> <input placeholder="MM/DD/YYYY"{{ form.date }} <div style="font-size: 15px;">{{ form.date.errors }}</div> </td> </tr> <tr> <td style="font-weight: bold;">Time</td> <td> <input placeholder="HH:MM am/pm"{{ form.time }} <div style="font-size: … -
Modify objects before making query in Django
I have a model like this: name price N1 950 $ N2 930 € N3 1200 $ N4 800 € I want to get objects that their price is lower than or equal 1000 $. But before that, I want to first convert the unit of all prices to dollars and secondly convert their data type to int. Some thing like this: for i in range(0, len(price)): if '€' in price[i]: price[i] = int([int(s) for s in price[i].split() if s.isdigit()][0] * 1.18) else: price[i] = int([int(s) for s in price[i].split() if s.isdigit()][0]) print(price) ############ Output ############ # [950, 1097, 1200, 967] and then make this query:(Entry.objects.price__lte=1000). (N1, N4 must be results) -
Remove text without tags
I am trying to do a manual rendering of Django forms and it generates the code below, is there a way to get rid of the texts that do not have any HTML tags, a good example is the texts "Currently: " and "Change:" it is really difficult to style with CSS. <div class="row align-center mb-0 text-center"> <div class="col-md-12"> <div class="fuzone mb-2"> <div class="fu-text"> <span><i class="mdi mdi-image-area"></i> Click here or drop files to upload</span> </div> Currently: <a href="/media/realtor/download.jpeg">realtor/download.jpeg</a> <input type="checkbox" name="image-clear" id="image-clear_id"> <label for="image-clear_id">Clear</label><br> Change: <input type="file" name="image" accept="image/*" class="clearablefileinput form-control-file" id="id_image"> </div> </div> -
SQL statement INNER JOIN to Django ORM
I'm new with Django but my sql is working fine. I wonder how i can make such query in Django I have SQL statement with join select a.id, b.id from model.a join model.b on model.b.a_id=model.a.id where 'need to find'=Any(a.info); Models: class A(models.Model): name = models.CharField(max_length=200) info = models.ArrayField() class B(models.Model): name = models.CharField(max_length=200) a = models.ForeignKey('A', related_name='a', on_delete=models.CASCADE) -
Django No Such Table exception after three simple commands
I am following this Django tutorial, and tried to do copy the code from the video. I have created a class which is a to-do-list, and I want to show it in the shell by running ToDoList.objects.all(). my models.py: from django.db import models from django.forms import model_to_dict from django.utils.timezone import now class Item(models.Model): title = models.CharField(max_length=200) # Short description of the item datetime_found = models.DateTimeField(default=now, blank=True) # Date and time of when the item was found def items(): res = [] for i in Item.objects.all(): res.append(model_to_dict(i)) return res # I ADDED THESE TWO CLASSES BELOW class ToDoList(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class ListItem(models.Model): todolist = models.ForeignKey(ToDoList, on_delete=models.CASCADE) # from ToDoList class text = models.CharField(max_length=300) complete = models.BooleanField() # Boolean says if we're completed list item def __str__(self): return self.text Then I ran py manage.py makemigrations and got this prompt: Migrations for 'myapp': myapp\migrations\0005_listitem_todolist.py - Create model ToDoList - Create model ListItem In the shell I wrote >>> from myapp.models import ToDoList, ListItem >>> t = ToDoList(name="My list") >>> t.save And I got this prompt: <bound method Model.save of <ToDoList: My List>> But now, that I try to see my list object by writing ToDoList.objects.all() I get an … -
Page Not found 404 when i try to create a new comment to Post object?
I am trying to let users create comment from listview on the social app am working on currently but am having a hard time working out the pattern. I keep getting the Error 404 when i try to load the listview. Here is Formlist view which my Post list view inherent from. class FormListView(FormMixin, ListView): def get(self, request, *args, **kwargs): if request.method == 'GET': post_id = request.GET.get('post_id') comment = request.GET.get('comment', False) post_obj = get_object_or_404(Post, pk=post_id) session_obj = User.objects.get(username=request.user.username) create_comment = Comment.objects.create( post=post_obj, user=session_obj, comment=comment) create_comment.save() # From ProcessFormMixin form_class = self.get_form_class() self.form = self.get_form(form_class) # From BaseListView self.object_list = self.get_queryset() allow_empty = self.get_allow_empty() if not allow_empty and len(self.object_list) == 0: raise Http404(_(u"Empty list and '%(class_name)s.allow_empty' is False.") % {'class_name': self.__class__.__name__}) context = self.get_context_data(object_list=self.object_list, form=self.form) return self.render_to_response(context) def post(self, request, *args, **kwargs): if request.method == "POST": description = request.POST['description'] pic = request.FILES.get('pic', False) #tag = request.FILES['tag'] user_obj = User.objects.get(username=request.user.username) post_data = Post(username=user_obj,pic=pic,description=description,) post_data.save() messages.success(request, f'Posted Successfully') return redirect('feed:feed') return self.get(request, *args, **kwargs) For one strange thing am able to create New Post from the PostListview but, Comment has been a challenge for me, for the past two weeks now and i have look on here but can't seem to find a … -
Django - can't download file (showed as text instead)
I have a pdf in my static files, I need to add it some text and let the user download it, but the download part gives me some problems, here is part of my code: views.py import io from werkzeug.wsgi import FileWrapper from pathlib import Path from PyPDF2 import PdfFileWriter, PdfFileReader from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter from django.http import HttpResponse, FileResponse def downloadpdf(request): pdf_path = (Path.home()/"bot"/"mysite"/"static"/"images"/"tesseragenerica.pdf") # 1 pdf_reader = PdfFileReader(str(pdf_path)) packet = io.BytesIO() # create a new PDF with Reportlab can = canvas.Canvas(packet, pagesize=letter) testo = "text to add" #in future "text to add" will be the username can.drawString(5, 5, testo) can.save() #move to the beginning of the StringIO buffer packet.seek(0) new_pdf = PdfFileReader(packet) # read your existing PDF existing_pdf = PdfFileReader(open("/home/myusername/bot/mysite/static/images/tesseragenerica.pdf", "rb")) output = PdfFileWriter() # add the "watermark" (which is the new pdf) on the existing page page = existing_pdf.getPage(0) page.mergePage(new_pdf.getPage(0)) output.addPage(page) # finally, write "output" to a real file outputStream = open("destination3.pdf", "wb") output.write(outputStream) outputStream.close() return FileResponse(FileWrapper(packet), as_attachment=True, filename='hello.pdf') The code for adding text to pdf is correct because in local it works so i think the problem is what i'm putting as the first argument of FileResponse, if I put FileWrapper(packet) for … -
Django searching for user with url
I have a problem with django. I try to search for users by getting an inputvalue and append this value to my url, so that one can basically search by typing a name in the url too (like it is by Instagram). For example: "localhost/name", it gives me all information to the User. Although the value is in the url and I have a dynamic url function, it doesn´t work. I read a lot of questions here but none worked for me. Thanks in advance. urls.py path("<str:name>/", views.search, name="search"), views.py @login_required(login_url="login") def search(response, name=None): if response.method == "POST": searched = response.POST['searchinput'] users = User.objects.filter(username=name) return render(response, "main/search.html", {"searched":searched, "user":users}) else: return redirect("home") base.html (for the input) <form id="searchform" class="form-inline my-2 my-lg-0" name="searchinputform" method="POST" action=" {% url 'search' name=None %}"> {% csrf_token %} <input class="form-control mr-sm-2" type="search" name="searchinput" id="searchinput" placeholder="Suche" > <script> $( "#searchform" ).submit( function( e ) { e.preventDefault(); document.location = $( "#searchinput" ).val(); } ); </script> -
How to add data from a Postgres View to an existing Django View?
I’m new to Django and still trying to get my head around some of its concepts. So far I have been able to get everything I want working, except for this thing where I clearly don’t fully grasp some of its concepts. If only I knew where the gap in my understanding is. I have a Postgres database with a number of tables. All tables are in models.py and I can read from the main table tbl_items using a Django model and template. So far so good. There is one more complex bit of data that needs to be combined from three tables in two JOINS. I have created a Postgres View that does the heavy lifting with all the JOINS and it works fine. I can query the View from the PSQL command line as if it was a real table and everything works as expected. I then added the Postgres View tbl_combi to models.py, migrated it, and figured that from now on, every part of Django should be oblivious to the fact that tbl_combi is actually a Postgres View instead of a real table. This is the relevant part from models.py: from django.db import models class TblItems(models.Model): item_id … -
Django Formset: how to get the current user? (using django-extra-views)
I'm used to collecting the current logged in user in a CreateView and passing it to the form like so: class MakeFantasyTeam(CreateView): form_class = MakeFantasyTeamForm [...] def form_valid(self, form): form.instance.tourney = Tournament.objects.filter(id=tourney_id).get() form.save() return super(MakeFantasyTeam, self).form_valid(form) However, this doesn't seem to work when using an InlineFormSetView as provided by django-extra-views. I get an error NOT NULL constraint failed: tournament_invite.invited_by_id and I'm not sure how to get the user.id passed on to the form. My View: class InvitePlayersView(InlineFormSetView): template_name = 'invite_players.html' model = Tournament inline_model = Invite form_class = InvitePlayerForm pk_url_kwarg = 'tourney_id' factory_kwargs = {'can_delete': False, 'extra': 1} def formset_valid(self, formset): tourney_id = self.kwargs['tourney_id'] formset.instance.invited_for = Tournament.objects.filter(id=tourney_id).get() formset.instance.invited_by = self.request.user formset.save() return super(InvitePlayersView, self).formset_valid(formset) def get_success_url(self): return reverse('make_team', kwargs={'tourney_id': self.object.invited_for.id}) My Model: class Invite(models.Model): name = models.CharField(max_length=200, blank=True, null=True) email = models.CharField(max_length=320, null=False, blank=False, validators=[EmailValidator],) invited_by = models.ForeignKey(get_user_model(), on_delete=models.DO_NOTHING) invited_for = models.ForeignKey(Tournament, on_delete=models.DO_NOTHING) created_dt = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email def get_absolute_url(self): return reverse('home') My Form: class InvitePlayerForm(forms.ModelForm): class Meta: model = Invite fields = ('name', 'email',) Any tips or hints much appreciated! Thank you, Jon -
my add to cart form throwing me to the register form
i created a add to cart form in my section.html but when i click add to cart button it redirect me to register page what i want to achieve is load the same page and open the same spot where i click add to cart but it not happening here is my section.html <ul class="sec"> {% for section in section_list %} <div class="card col-11" id="{{ section.id }}"> <div class="card-header"> {{ section.title }} </div> <div class="card-body"> <h5 class="card-about">{{ section.about_section }}</h5> <br> <i class="price fas fa-rupee-sign"> {{ section.price }}</i> <br> <br> <i class="icon text-white fas fa-chalkboard-teacher"> {{ section.teacher }}</i> <i class="icon text-white fas fa-clock"> {{ section.content_duration}}</i> <i class="icon text-white fas fa-tags"> {{ section.subject.name }}</i> <form action="/{{section.id}}" method="POST"> {% csrf_token %} <input hidden type="text" name="section" value="{{section.id}}"> <input type="submit" class="btn btn-outline-primary" value="Add To Cart"> </form> </div> </div> {% endfor %} </ul> and here is my views.py for section.html @method_decorator(login_required, name='dispatch') class Sections(View): def post(self, request, subject_id): sections =request.POST.get('section') cart = request.session.get('cart') if cart: cart[sections] = 1 else: cart = {} cart[sections] = 1 request.session['cart'] = cart print(request.session['cart']) return redirect('subjects:section', subject_id=subject_id) def get(self, request, subject_id): subject = get_object_or_404(Subject, pk=subject_id) # retrieve the subject sections = subject.section.all() # get the sections related to the subject return … -
Virtualenv and django not working in bash on windows 10
I have a problem with using virtualenv and django in bash. If I type python -m venv env in cmd, then env\Scripts\activate, and then virtualenv - I get 'virtualenv' is not recognized as an internal or external command, operable program or batch file.. If I do the same in bash I get bash: virtualenv: command not found. How do I fix this? -
How to get total sum based on the date__year?
Here in the template I am iterating MyModel objects. Now in the template I want to get the total sum of integer fields for the particular year. I don't know how I can I use these three functions in order to get the total sum of field? Or there might be any better approach ? model class MyModel(models.Model): date = models.DateField() field1 = models.DecimalField(default=0.0) field2 = models.DecimalField(default=0.0) views def get_total_field1(year): return MyModel.objects.filter(date__year=year).annotate(total=Sum('field1'))['total'] def get_total_field2(year): return MyModel.objects.filter(date__year=year).annotate(total=Sum('field2'))['total'] def get_total(year): return get_total_field1() + get_total_field2() class MyView(ListView): model = MyModel template_name = 'my_template.html' template {% for obj in objs %} <tr> <td>{{obj.date|date:'Y'}}</td> <td>Field 1 total sum for obj.date </td> <td>Field 2 total sum for obj.date</td> <td>Field 1 total + field2 total </td> {% endfor %} -
Update two tables simultaneous when using POST method Django
So, I need your help again. I'm struggling with a little problem and I didn't find any solution for it. I'm having two tables in my models.py and what I want to do is to update both tables status from my models using post method. Can you help me with any ideas? Thank you in advance. My models.py: class Chat(models.Model): chat_id = models.IntegerField(primary_key=True, unique=True, blank=True) payload = models.CharField(max_length=299, validators=[validate]) user_id = models.IntegerField() utc_date = models.DateTimeField(auto_now_add=True, blank=True) status = models.CharField(max_length=10) class ScheduleTable(models.Model): status = models.CharField(max_length=10) views.py: @api_view(['GET', 'POST']) def get_chat(request): if request.method == 'GET': chat_objects = Chat.objects.all() chat_serialize = ChatSerializer(chat_objects, many=True) return JsonResponse(chat_serialize.data, safe=False) elif request.method == 'POST': chat_data = JSONParser().parse(request) chat_data['status'] = 'new' chat_data['chat_id'] += 1 chat_serializer = ChatSerializer(data=chat_data) if chat_serializer.is_valid(): chat_serializer.save() return JsonResponse(chat_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(chat_serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django how to add incline css from a deep rooted folder
I've checked all the similar questions and it doesn't exactly target deeper rooted folders and I've also tried their solutions and it hasn't worked. In my HTML i have this: <div class="c-bg-img-center" style="height:800px;background-image: url({% "index/img/content/shop3/21.jpg" %})"> The image I am searching to add to my HTML page is found here: Project\index\static\index\img\content\shop3\21.jpg I've tried different variations of methods that I've found online and no luck - please don't thumbs me down on the verge of being banned from asking anymore questions sigh -
how to get access to the django class object
i have created a model class in django class metaTag(models.Model): page_choice=[ ('index','index'), ('about','about'), ('carrer','carrer'), ('base','base'), ('checkup','checkup'), ('contact','contact'), ('faq','faq'), ('checkup','checkup'), ('app','app'), ('googleads','googleads'), ('graphics','graphics'), ('seo','seo'), ('socialmedia','socialmedia'), ('web','web'), ] page=models.CharField(max_length=15,choices=page_choice,default='index') title=models.CharField(max_length=50,default="AdsOptimiser") description=models.CharField(max_length=160,default="AdsOptimiser") keywords=models.CharField(max_length=200,default="AdsOptimiser") def __str__(self): return self.page what i want to achive by this i want my client have an option to change the title keywords and description meta tags from its admin panel to achive this i created this class so the client can fill the data now i am confused how to plug in the data and what will be the optimal way to do it -
How do i properly show a flash message in django
I have this view function that needs to send a flash message to a user when they sign up. Now that is running well but the problem is that I set an error message to show when the username or password is incorrect and its always showing there by default. Here is my code views.py def signup(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'An account was created for ' + user) return redirect('login') def login_user(request): username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.info(request, 'Incorrect Username or Password') And when I go to the login page its just showing me incorrect username or password even though I just got there How can I make it to show only when the username or password is incorrect Thanks for your contribution