Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JQuery - Changing calendar dates based on model data
As a part of a task, I created an "apartment listings" website. I managed to get that done, but now I need to make a "reservation system" for it. The basic idea is that a logged in user can select an apartment from the listed apartments, pick a "start_date" and an "end_date" (if the apartment already isn't booked ) and book the apartment. When the user clicks on the date input field, a jquery datepicker pops up and he can then pick the date via the calendar, same for end date. Once he goes through with the booking, I want the dates to be "disabled" in the calendar so no one else can pick them. This is the datepicker that I'm using: https://jqueryui.com/datepicker/ and the code: <script> $(function () { $("#datepicker").datepicker(); }); </script> Im a total Django / web development newbie, and need some pointers in order to start somewhere with this task, I know some JS but jquery is new to me, that's why I'd like some help. I have an Apartment model which contains all of the Apartments info that I use to print everything out with the template. I have an Reservation model which saves the start … -
Doubts how to design data with Django and PostgreSQL when having a value for every hour of the year
I am running a django app with PostgreSQL as my database. I have a building model called building. From this model I create many building instances. I have another model which is called forests from which I create many forests instances. (Let's assume I have even more models for which the same applies) Now I want to add data (let's call it x) for every building and for every forest for every hour of the year. That means I will have 8760 values for every building and forest instance. For instance: Hour1 : 234 Hour2 : 667 ... HourX : x ... Hour8760: 34 These 8760 values will be added, roughly estimated, 10-15 times a day, so that could lead to 131400 values a day. Now, I have doubts on how to design that. I thought I could go with a model like so: class Hour(models.Model): building = models.ForeignKey(Building, on_delete=models.CASCADE) forest = models.ForeignKey(Forest, on_delete=models.CASCADE) hour = models.IntegerField(...) value = models.FloatField(...) timestamp = models.CharField(max_length=200, null=True, blank=True) My second thought is to design it with a JSONField inside of an ArrayField like discussed here: Django JSONField inside ArrayField. So maybe I could save a dictionary for every building and every forest OR … -
problem with get_absolute_url django python
I used get_absolute_url in my app but it works only on admin site (by button view on site). On my website, the hyperlink is not responding. I've checked every line of code a couple of times and it seems like everything's fine. Does anyone know why it doesn't works? models.py class CrashReport(models.Model): number_id = models.AutoField(primary_key=True) date_notice = models.DateField(auto_now=False, auto_now_add=False) SHIFT_NUMBER = ( ('I', 'Zmiana I (6:00 - 14:00)'), ('II', 'Zmiana II (14:00 - 22:00)'), ('III', 'Zmiana III (22:00 - 06:00)'), ) which_shift = models.CharField( max_length=3, choices=SHIFT_NUMBER, blank=True, default='I', help_text='Zmiana.' ) who_notice = models.ManyToManyField(Author, help_text='Select a occupation for this employee') description = models.TextField(max_length=1000, help_text='Please type what happened') which_stuff = models.ManyToManyField(Device, help_text='Select a exactly devices') PROCESSING_STATUS = ( ('o', 'Otwarty'), ('p', 'Przetwarzanie'), ('z', 'Zakonczony'), ) status_notice = models.CharField( max_length=1, choices=PROCESSING_STATUS, blank=True, default='o', help_text='Status dokumentu.' ) def __str__(self): return f'ZGL /{self.number_id} / {self.which_stuff.all()} / {self.date_notice}' def get_absolute_url(self): return reverse('crashreport-detail', args=[str(self.number_id)]) views.py from django.shortcuts import render from django.views import generic from .models import CrashReport def index(request): """View function for home page of site.""" # Generate counts of some of the main objects num_crashreports = CrashReport.objects.all().count() # num_instances = BookInstance.objects.all().count() # Opens Crashreports (status = 'o') # num_crashreport_open = CrashReport.objects.filter(status__exact='o').count() context = { 'num_crashreports': num_crashreports, … -
Python Django render an html code from a db field
In my django project i have a model with a field that contain html code as text: html_test = models.TextField() for example in this field could be: <html> <header><title>This is title</title></header> <body> Hello world </body> </html> i would ti retrive this code and render dinamically showing the correspondenting html page without create a file or save it on disk. Someone know how can i render an html code in memory for display page and then destroy it? So many thanks in advance -
My swiper-pagination is overlapping with the text and my Hamburger appears behind the slider when open
i have a simple problem that i can't wrap my head around. My swiper-pagination that is supposed to appear at the bottom of the text overlaps with the text at the bottom of the page hence it cannot be seen clearly. I would like for it to appear like 10px below the text to clearly be seen by anyone visiting my site. Another problem is when you view it in mobile platform when you click on the hamburger the contents appear behind the slider and i would like then to come in-front of the slider and be clickable for clients to view the other pages. My project is on django and i have linked the swiper.min.js and swiper.min.css to my static root folder.My code is as follow below. If you seek more clarification please tell me and i will upload the additional details. Thanks in advance guys. Html {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <meta name='viewport' content='width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1'> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'buyer/main.css' %}"> <link rel="stylesheet" href="{% static 'buyer/swiper.min.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <script … -
python manage.py migrate freezes
I'm trying to add forum to my website and I found saleor. So I want to test it on virtualenv first and I'm stuck following the installation. Whenever I run python manage.py migrate ... It just stucks showing no additional error I've created a new virtualenv then installed django, installed requirements via pip install -r requirements.txt in /saleor. I've set the database and user with superuser privileges set to all "saleor". I've changed my secret_key and port number in databases from settings.py. -
Can you reference only one from image gallery for Wagtail/Django?
{% for item in page.architecture_images.all %} {% image item.image fill-800x800-c100 %} <p>{{ item.caption }}</p> {% endfor %} Is there a way to call only one image from this gallery that has 2+ images in it? -
How to fix 'TypeError: join() ' When displaying DB Images in Django Templates
I am trying to display some images uploaded to my DB via the admin page using the image.url attribute. When the page loads, the image.url is correct, but the terminal shows an internal server error with the traceback ending with "TypeError: join() argument must be str or bytes, not 'list'" I can't find where specifically the join method is called as the traceback seems to only talk about internal files. I thought it might be related to an override save function, but commenting the function out yields the same results. settings.py STATIC and MEDIA and MEDIA_URL are all set. Template: <img class='project-details-image' src="{{ project.image.url }} Model: image=models.ImageField(upload_to='project-covers/', default='/Default.png', null=True) settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, '/my_portfolio/my_portfolio/static/') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'my_portfolio/static'), ] MEDIA_ROOT = [ os.path.join(BASE_DIR, 'my_portfolio/img'), ] MEDIA_URL = '/img/' Traceback: File "/home/user/django-portfolio/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/user/django-portfolio/lib/python3.5/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/user/django-portfolio/lib/python3.5/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/django-portfolio/lib/python3.5/site-packages/django/views/static.py", line 36, in serve fullpath = Path(safe_join(document_root, path)) File "/home/user/django-portfolio/lib/python3.5/site-packages/django/utils/_os.py", line 32, in safe_join final_path = abspath(join(base, *paths)) File "/usr/lib/python3.5/posixpath.py", line 89, in join genericpath._check_arg_types('join', a, *p) File "/usr/lib/python3.5/genericpath.py", line 143, in _check_arg_types (funcname, s.__class__.__name__)) … -
Django APIClient test case returns 400 but postman works
I have these test cases in my tests.py """Unit tests for client application.""" from django.test import TestCase from rest_framework.test import APIClient # Create your tests here. class ClientTestCase(TestCase): api_client = APIClient() def test_get_clients(self): response = self.api_client.get('http://127.0.0.1:8000/client/clients/') self.assertEqual(int(response.status_code), 200) def test_add_client(self): response = self.api_client.post( path='http://127.0.0.1:8000/client/clients/', data={ 'name': 'Jon Snow', 'age': 18, 'gender': 'M', 'address': 'night watch wall', 'phone_number': '+9290078601', 'email': 'jon@nightwatch.com', }, content_type='application/json' ) self.assertEqual(response.status_code, 201) When I run these tests through command python manage.py test --debug-mode client/ -v 3 test_get_clients succeeds and test_add_client fails as the API returns 400. When I hit the same API I am hitting in test_add_client through postman, it returns the expected result. The body of postman API is { "name": "Bruce Wayne", "age" : 23, "gender" : "M", "address" : "abc asdasd asdasd asdada", "phone_number" : "+92 3242225259", "email" : "abc@xyz.com" } and in header there is Conent-Type:'application/json as I am already specifying in my test case. What might I be missing here? The output of running test case is not giving any insight at all. -
Django docker image only starts python shell
I have the following docker-compose file version: '3' services: web: build: . command: bash -c "python manage.py collectstatic --no-input && gunicorn -w 2 --bind 0.0.0.0:8000 api.wsgi:application" volumes: - .:/code - static_volume:/code/api/static expose: - 8000 environment: - DJANGO_SETTINGS_MODULE=api.settings.production depends_on: - redis redis: image: "redis:alpine" celery: build: . command: celery -A api worker -l warning volumes: - .:/code environment: - DJANGO_SETTINGS_MODULE=api.settings.production depends_on: - redis nginx: build: ./nginx ports: - 80:80 volumes: - static_volume:/code/api/static depends_on: - web volumes: static_volume: which I use to build a docker image and push it to our gitlab docker registry with the following commands: docker build -t foo/api-django . docker push foo/api-django This works without a problem. But as soon as I pull the image and run it using the following command docker run -p 8000:80 -i -t foo/api-django it just shows me the python shell of the image: any advice? when i just run the docker-compose up it starts nginx, gunicorn etc. normally. -
django print all record in the cmd but display the last one on template
i have a function that retrieve data from sql server database where i am using fetchall() then for loop the retrieved data are all printed on the cmd console but when i tried to display these result on the template it only display the last record. views.py def search(request): query = cursor.execute('Select id, fullname from person') result = query.fetchall() for row in result: print("ID==>",id) IPD=row[0] return render(request,"test.html",{"IPD":IPD}) test.html {{ IPD }} -
The script django-admin is installed in '/tmp/somedir/deps/0/python/bin' which is not on PATH. Consider adding this directory to PATH
I am trying to host my Django application on Cloud Foundry, After installing the packages mentioned in requirement.txt file, I m getting error saying the package is installed in path "/tmp/somedir/deps/0/python/bin" which is not on Path. So I want to know how can I add this directory to the Path. I am using CF CLI's CF push manifest.yml cmd to push the django application. -
how to get get fix this error "The QuerySet value for an exact lookup must be limited to one result using slicing."
filtering 2 models id = request.GET.get('StudentID') studentenroll = StudentsEnrollmentRecord.objects.filter(Student_Users=id) payment=StudentsPaymentSchedule.objects.filter(Students_Enrollment_Records=studentenroll) return render(request, 'Homepage/enrollmentrecords.html',{"studentenroll":studentenroll,"payment":payment}) my models class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='+', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE,null=True) Remarks = models.TextField(max_length=500,null=True) def __str__(self): suser = '{0.Student_Users} {0.Education_Levels}' return suser.format(self) class StudentsPaymentSchedule(models.Model): Students_Enrollment_Records=models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,null=True) Payment_Schedule = models.DateField(null=True,blank=True) Amount = models.FloatField() Remarks=models.TextField(max_length=500) def __str__(self): suser = '{0.Students_Enrollment_Records}' return suser.format(self) can you guys help me for my assignment, cause i dont know how to connect this 2 models in views and i am little confuse in filtering . thank you in advance. -
how to check if two timestamps partially comes between given two timestamps in python
given startTime is 3:00 AM given endTime is 5:00 AM // 3am |----------------------------| 5am /// these four condition should be not match, these four comes partially in given range, // 3:30am |-------------| 4:30am // 2am|---------------|4am // 3:45am|----------------------|6am // 1am|-------------------------------------------------|7am previously what i have done is, "starttime": {"$gte": starttime, "$lte": endtime}, "endtime": {"$gte": starttime, "$lte": endtime}, in mongo query. -
how to resolve error in Django models.py?
I am new to django and was trying to make a Django project inside the virtualenv to learn but getting following error on python manage.py makemigrations: File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/suraj/Documents/my_projects/django_project/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/suraj/Documents/my_projects/django_project/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/suraj/Documents/my_projects/django_project/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/suraj/Documents/my_projects/django_project/venv/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/suraj/Documents/my_projects/django_project/venv/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/home/suraj/Documents/my_projects/django_project/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/suraj/Documents/my_projects/django_project/web_board/boards/models.py", line 11, in <module> class Topic(models.Model): File "/home/suraj/Documents/my_projects/django_project/web_board/boards/models.py", line 14, in Topic board = models.ForeignKey(Board, related_name='topics') TypeError: __init__() missing 1 required positional argument: 'on_delete' -
Django / JQuery - Changing JQuery calendar based on DB data
As a part of a task, I created an "apartment listings" website. I managed to get that done, but now I need to make a "reservation system" for it. The basic idea is that a logged in user can select an apartment from the listed apartments, pick a "start_date" and an "end_date" (if the apartment already isn't booked ) and book the apartment. When the user clicks on the date input field, a jquery datepicker pops up and he can then pick the date via the calendar, same for end date. Once he goes through with the booking, I want the dates to be "disabled" in the calendar so no one else can pick them. This is the datepicker that I'm using: https://jqueryui.com/datepicker/ and the code: <script> $(function () { $("#datepicker").datepicker(); }); </script> Im a total Django / web development newbie, and need some pointers in order to start somewhere with this task, I know some JS but jquery is new to me, that's why I'd like some help. I have an Apartment model which contains all of the Apartments info that I use to print everything out with the template. I have an Reservation model which saves the start … -
I want the sign up button to disappear when I sign up (in django templates)
Model class TeamMember(models.Model): team = models.ForeignKey(TeamInfo, on_delete=models.CASCADE) member = models.ForeignKey(User, on_delete=models.CASCADE) position = models.CharField(max_length=50,default="member") class TeamInfo(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) team_name = models.CharField(max_length=50, unique=True) team_description = models.TextField(blank=True) member_count = models.IntegerField(default=1) def __str__(self): return self.team_name View class TeamInfoListView(LoginRequiredMixin,ListView): model = TeamInfo paginate_by = 20 template (https://github.com/hyunsokstar/django_inflearn2/blob/master/todo/templates/todo/teaminfo_list.html) {% for tm in p.teammember_set.all %} {% if tm.member.username == request.user.username %} <a class="btn btn-outline-info btn-sm team_register_button" data-id = {{p.id}} data-user={{request.user.id}} >탈퇴</a> {% endif %} {% endfor %} I have two questions. 1.How can I make the sign up button disappear when a user is registered? 2.For logic seems to be inefficient at present~! Is there a way to improve it? Thank you for letting me know about this. -
Fresh mysql database getting "mydb.background_task doesn't exist" - Django
I have a fresh install of a django app that uses background_tasks. If I remove the models that use background_task then I am able to do python manage.py makemigrations However, if I keep them, I get a table missing exception: "mydb.background_task doesn't exist" I have seen other people with this issue but I have tried every single suggestion: - delete all migrations files - delete sqlite3 dump file - uninstall django and django-background-tasks - make sure my machine does not have those two packages installed even outside of the virtualenv - I tried deleting my virtualenv and reinstalling everything. I have tried all of these things and python manage.py makemigrations is still giving me that exception. But nothing else does that. Django==2.1.5 django-background-tasks==1.2.0 django-compat==1.0.15 django-mysql==3.2.0 p.s: I am using Cloud SQL, I don't know if that affects anything, I don't think so. -
Formset data is not submitted via request.POST
I am using django formset to update multiple existing model objects, but after clicking the submit button nothing is received, but only non-formset data (csrf and others) Formset contains data about multiple products (forms) which may have multiple tickets (attributes) <form method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div id="{{ form.prefix }}"> {{ form }} </div> <a class="btn-floating btn-large waves-effect waves-light red" id="add_ticket" onclick="addTicketingBlock('{{ form.prefix }}')"><i class="material-icons">add</i></a> {% endfor %} <input type="submit" name="apply" class="waves-effect waves-light btn center-align"/> <input type="hidden" name="action" value="{{ action }}"/> </form> #addTicket button adds additional field to the specific form, not whole formset Here is what I get in request.POST in the action processing method <QueryDict: {'csrfmiddlewaretoken': ['long_hash'], '_selected_action': ['long_uuid'], 'select_across': ['0'], 'action': ['set_order_ticketing'], 'index': ['0']}> -
How to integrate a function based view into a class based view in Django?
In my site I have 2 sections for users. The user posts page and the profile page. The profile page has all their info on it, so username, description, first/last name, etc. And the user posts page has all their posts on it. However, I want to integrate them together somehow. Here is some of the code. Here is the view for the User Posts class UserPostListView(ListView): model = Post template_name = 'mainapp/user_posts.html' context_object_name = 'posts' def get_queryset(self): user = get_object_or_404(User,username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-published_date') As you can see, I am returning the specific users posts. And now here is my profile view def view_profile(request,pk=None): if pk: user_profile = User.objects.get(pk=pk) else: user_profile = request.user context = {'user':user_profile} return render(request,'mainapp/profile.html',context) It returns all the user's info. Here is the HTML code for both the profile and user posts page {% block content %} <div class="profile-page-container"> <div class="profile-page-info"> <div class="profile-page-banner"> <div class="profile-page-banner-background"> <!-- <img src="https://cdn.pixabay.com/photo/2017/08/30/01/05/milky-way-2695569_960_720.jpg" alt="{{ user }}'s Background Image" > --> </div> <div class="profile-page-banner-text"> <h2 title="{{ user }}" id="username-profile-page">{{ user|safe|linebreaksbr|truncatechars_html:25 }} {% if user.userprofileinfo.verified %} <span class="image-profile-verified"><img draggable="false" title="Verified User" class="verifed" src="{% static 'images\verified.png' %}" alt="verified" width="25" height="25" srcset=""></span> {% endif %}</h2> <p>{{ user.first_name }} {{ user.last_name }}</p><br> </div> </div> <div class="profile-page-user-desc-box"> <p>{{ … -
How to Connect Django with Python based Crawler machine?
Good day folks Recently, I made a python based web crawler machine that scrap some news ariticles and django web page that collects search title and url from users. But I do not know how to connect the python based crawler machine and django web page together, so I am looking for the any good resources that I can reference. If anyone knows the resource that I can reference, Could you guys share those? Thanks -
Integrate django model with legacy db
I understand that Django Model is pretty fussy when it comes to the absence of a primary key. I have a legacy database (SQL Server) that I am connecting too (it is not the default one), and in that I have a database.view which I am supposed access. However, the issue is that the view does not have any primary key. How do i enable django to query from that table without being able to modify the schema? Here is what I did: I created a ReadOnlyModel and got my other django model to subclass it. This was done because I wanted to bypass the django's need for PK (evidently it did work, but threw another error - see below) class ReadOnlyModel(models.Model): def save(self, *args, **kwargs): pass def delete(self, *args, **kwargs): pass I created an ActiveObjectManager for Django to know which database to point too. The reason i used this over a router is because the router would work best if I was creating two seperate applications in the same repo. However, I am using one application: class Db2ActiveObjectManager(models.Manager): def get_queryset(self): qs = super(Db2ActiveObjectManager, self).get_queryset() if hasattr(self.model, 'use_db'): qs = qs.using(self.model.use_db) return qs Below is a sample model from the … -
How to follow HINT: Use a callable instead, e.g., use `dict` instead of `{}`?
How to follow the warnings? models.py from django.contrib.postgres.fields import JSONField from django.db import models from django_extensions.db.models import TimeStampedModel class UnderwritingValidator(TimeStampedModel): plan = models.PositiveIntegerField(null=True, blank=True, unique=True) logic = JSONField(default=dict( accept_list=[], reject_list=[] )) Then makemigrations WARNINGS: uw_validators.UnderwritingValidator.logic: (postgres.E003) JSONField default should be a callable instead of an instance so that it's not shared between all field instances. HINT: Use a callable instead, e.g., use `dict` instead of `{}`. Migrations for 'uw_validators': uw_validators/migrations/0002_auto_20191011_0321.py - Remove field accept_list from underwritingvalidator - Remove field reject_list from underwritingvalidator - Add field logic to underwritingvalidator Software: postgres: 10.9 Django==2.2.5 Questions: Am I safe from error? If it safe I will ignore this warning and erase my short warning note How to fully follow the warning? -
How to see what rows were added with Django connection.cursor.execute()?
I have this python code ... sql = "INSERT INTO ... long complicated query ...;" try: with connection.cursor() as cursor: cursor.execute(sql) log.info( '%s rows inserted.' % cursor.rowcount) for row in cursor.fetchall(): print(row) except Exception as ex: err = ex log.error("sql: %s" % sql) raise err ... it prints the row count and then throws the exception: django.db.utils.InterfaceError: not a query I guess because I wasn't doing a select. But the Django documentation (https://docs.djangoproject.com/en/2.2/topics/db/sql/) says to get the affected rows call cursor.fetchall(). So how do I get the affected/rows inserted? -
How are User objects with is_active=False tested?
Here a User object is instantiated with a is_active=False attribute. I'm testing a login in conjunction with an AuthenticationForm with those same user credentials, but I'm not getting the expected response. When passing data to the form: form.is_valid() is returning False. https://docs.djangoproject.com/en/2.2/topics/auth/default/#django.contrib.auth.forms.AuthenticationForm In the docs it says: By default, AuthenticationForm rejects users whose is_active flag is set to False. How can I set User.is_active to False, but also enter the conditional blocks subsequently so that the appropriate flash message is returned dependent on the aformentioned attribute status? def sign_in(request): import pdb; pdb.set_trace() form = AuthenticationForm() if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): if form.user_cache is not None: user = form.user_cache if user.is_active: login(request, user) return HttpResponseRedirect( reverse('home') # TODO: go to profile ) else: messages.error( request, "That user account has been disabled." ) else: messages.error( request, "Username or password is incorrect." ) return render(request, 'accounts/sign_in.html', {'form': form}) class UserAccountSignIn(TestCase): @classmethod def setUpTestData(cls): cls.inactive_user = { 'username': 'non_user', 'password': 'secret', 'is_active': False } User.objects.create_user(**cls.inactive_user) def test_inactive_user_login_fail(self): self.client.login(**self.inactive_user) response = self.client.post(reverse('accounts:sign_in'), self.inactive_user) self.assertContains(response, "That user account has been disabled.") https://github.com/django/django/blob/master/django/contrib/auth/forms.py#L213 Actual results:ValidationError("This account is inactive.") Expected results: A flashed messaged of: "That user account has been disabled."