Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DjangoRest- I'm not able to set permission for user model
As I started with the application I want to add permission for my User model but failed miserably. I've created User model ,the basic serializer and corresponding Views permissions. Scenario: I want to set these 2 permissions as mentioned below: (a) Admin can access all users view/edit. (b) object owner to view/edit. I've created these 2 endpoints path('customer/', UserListCreateAPIView.as_view()), path('customer_info/<int:pk>/', UserRetrtieveUpdateDestroyAPIView.as_view()), Any help would be appreciated. Thank you! **models.py** from pyexpat import model from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser) GENDER_CHOICES = ( (0, 'male'), (1, 'female'), (2, 'not specified'),) class UserManager(BaseUserManager): def create_user(self, email, name,contact_number,gender,address,state,city,country,pincode,dob ,password=None, password2=None): """ Creates and saves a User with the given email, name and password. """ if not email: raise ValueError('User must have an email address') user = self.model( email=self.normalize_email(email), name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, pincode=pincode, dob=dob, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name,contact_number,gender,address,state,city,country,pincode,dob , password=None): """ Creates and saves a superuser with the given email, name and password. """ user = self.create_user( email, name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, pincode=pincode, dob=dob, password=password, ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = … -
Django ModelForm Submit button does nothing
I have the following ModelForm, UpdateView and template but when I click on the 'Save' button and the 'Save and continue editing' button, nothing happens. I tried following the fix in this post but it didn't work. How do I post the data in these forms into their respective tables? forms.py: class ProductForm(SEOFormMixin, forms.ModelForm): FIELD_FACTORIES = { "text": _attr_text_field, "richtext": _attr_textarea_field, "integer": _attr_integer_field, "boolean": _attr_boolean_field, "float": _attr_float_field, "date": _attr_date_field, "datetime": _attr_datetime_field, "option": _attr_option_field, "multi_option": _attr_multi_option_field, "entity": _attr_entity_field, "numeric": _attr_numeric_field, "file": _attr_file_field, "image": _attr_image_field, } class Meta: model = Product fields = [ 'title', 'upc', 'description', 'is_public', 'is_discountable', 'structure', 'slug', 'meta_title', 'meta_description'] widgets = { 'structure': forms.HiddenInput(), 'meta_description': forms.Textarea(attrs={'class': 'no-widget-init'}) } def __init__(self, product_class, metal, data=None, parent=None, *args, **kwargs): self.set_initial(product_class, metal, parent, kwargs) super().__init__(data, *args, **kwargs) if parent: self.instance.parent = parent # We need to set the correct product structures explicitly to pass # attribute validation and child product validation. Note that # those changes are not persisted. self.instance.structure = Product.CHILD self.instance.parent.structure = Product.PARENT self.delete_non_child_fields() else: # Only set product class for non-child products self.instance.product_class = product_class self.instance.metal = metal self.add_attribute_fields(product_class, metal, self.instance.is_parent) if 'slug' in self.fields: self.fields['slug'].required = False self.fields['slug'].help_text = _('Leave blank to generate from product title') if 'title' … -
Django use custom method name in Django class view
I have Url like /foo/bar and Class based view has been defined as below. class FooBar(View): def handle_post_bar(self, request): pass def handle_get_bar(self, request): pass def handle_put_bar(self, request): pass In url i define as path('foo/bar/', FooBar.as_view()) Based on the http method and path i would like build view method names ex: handle_{0}_{1}'.format(method, path) Please suggest me how to achive this, this should be common to all the urls and views. i tried exploring the possibility of django middleware, but endedup in no luck. -
I have a tuple and i want to store it in database. how can i do it with django
here is my database image CATEGORY_CHOICES = (('M', 'Mobile'), ('L', 'Laptop'), ('TW', 'Top Wear'), ('BW', 'Bottom Wear'), ('W', 'Watch'), ('P', 'Printer'), ('F', 'Fan'), ('EB', 'Earbuds'), ('C', 'Camera'), ('O', 'Oil'), ('SH', 'Shower'), ('MU', 'Museli'), ('CL', 'Cleaner'), ('CA', 'Computer and Accessories')) models.py class Product(models.Model): title = models.CharField(max_length=200) selling_price = models.FloatField() discounted_price = models.FloatField() description = models.TextField() brand = models.CharField(max_length=100) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) product_image = models.ImageField(upload_to='productimg') def __str__(self): return str(self.id) views.py @login_required def upload_details(request): category = CATEGORY_CHOICES dict_category = dict(category) print("Category", type(category)) if request.method == "POST": product_name = request.POST.get('product-title') product_selling_price = request.POST.get('product-selling-price') product_discounted_price = request.POST.get('product-discounted-price') product_description = request.POST.get('product-description') product_brand = request.POST.get('product-brand') product_category = request.POST.get('product-category') product_main_image = request.FILES['product-main-image'] print("Product Category", type(product_category)) save_product = Product(title=product_name, selling_price=product_selling_price, discounted_price=product_discounted_price, description=product_description, brand=product_brand.upper(), category=product_category, product_image=product_main_image) save_product.save() return render(request, 'app/uploaddetails.html', {'dict_category': dict_category}) views.py class ProductView(View): def get(self, request): totalitem = 0 topwears = Product.objects.filter(category='TW') bottomwears = Product.objects.filter(category='BW') mobiles = Product.objects.filter(category='M') laptops = Product.objects.filter(category='L') watch = Product.objects.filter(category='W') computer_accessories = Product.objects.filter(category='CA') random_watch = list(watch) watch_shuffle = random.sample(random_watch, 14) random_mobile = list(mobiles) mobile_shuffle = random.sample(random_mobile, 9) mobile_shuffle_mob = random.sample(random_mobile, 4) random_item = list(Product.objects.all()) item_shuffle = random.sample(random_item, 20) if request.user.is_authenticated: totalitem = len(Cart.objects.filter(user=request.user)) return render(request, 'app/home.html', {'topwears': topwears, 'bottomwears': bottomwears, 'mobiles': mobiles, 'laptops': laptops, 'watch': watch, 'computer_accessories': computer_accessories, 'watch_shuffle': watch_shuffle, 'mobile_shuffle': mobile_shuffle, 'mobile_shuffle_mob': … -
Refreshing a Django view function/sending in new parameters
I have my default views function returning a loop of objects and status of each object in a nice little grid on my Django site. I was hoping to add some buttons that lets the user filter down to see a smaller group of this data. My idea was basically three radio buttons, one for the default to see everything, and the other two would refresh the loop in this div to just show the smaller group of data. My understanding is that when this button is clicked I would have to call the views function again and pass it this additional parameter which will refresh the data presented on my site or is that not correct? What would be the best way to do this? The default view function on the home page: def index(request): #Here is a bunch of code to get the status of different campuses and send it to the template via the return line below return render(request, 'home.html', {'campuses': sorted_sites, 'cc_campuses': cc_sorted_sites, 'update': update}) And here is how I display it: {% for campus, status in campuses %} <a class= "campusbutton"><div class= "item" id="{{ status }}" > {{ campus }}</div></a> {% endfor %} What would … -
Python DIsplay either Image or Video File, without empty player/icon
ive been working on a social media website where you can upload images and videos and follow other users. I managed to upload and display uploaded files to the website. I used FileField to load the image and video files, but when I implement it in my Template it shows both spaces, because there both using the same source url {{ source.file.url }} models.py class Post(models.Model): title = models.CharField(max_length=150) file = models.FileField(upload_to='uploads/%Y-%m-%d') models code works perfectly feeds.html {% if post.file.url %} <video class="video-context" width="500px" height="500px" controls> <source src="{{ post.file.url }}" type="video/mp4"> </video> {% endif %} {% if post.file.url %} <img class="image-context" src="{{ post.file.url }}" type="image/jpg" type="image/jpeg"> {% endif %} heres a sreenshot empty video player over img How is it possible to difference the upload types, but still using FileField? -
how to generate unique accountid in user model which should be auto generated after user registration
This is my models.py file from django.db import models from django.contrib.auth.models import AbstractUser from .manager import UserManager # Create your models here. class User(AbstractUser): account_id = models.IntegerField(unique=True, default=1111111) log_id = models.IntegerField(unique=True, default=0000000) username = None email = models.EmailField(unique=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] From this code, I am able to make an account id from the admin panel but I want to generate a unique account id automatically when users fill out the registration form it should generate a unique account id in the admin panel. This is my tools.py file from random import randint from .models import * from django.contrib.auth import get_user_model User = get_user_model() def User(): def account_id(): account_id = randint(1000000, 9999999) print(account_id) is_unique = User.objects.filter(account_id=account_id).exists() if not User.account_id: is_unique = False while not is_unique: account_id User.account_id = account_id User.save() else: account_id() User.save() ``` -
Django dumpdata from multiple databases
Running on Django 3.2 I use dumpdata -o db.json -a to export multiple databases to .json. Looking into dumpdata.py, it retrieves all objects from a model by calling queryset = objects.using(using).order_by(model._meta.pk.name) https://github.com/django/django/blob/main/django/core/management/commands/dumpdata.py, line 185 My problem is that in my case, using is set to 'default' by default, even though I use --all parameter. And later, when calling objects.using(using) it tries to retrieve all objects from default database, even though it's supposed to be 'MIFIR'. What did I do wrong? Have I misconfigured something in my database? I set the app_label in _meta and added my app_label to dbrouter.py, I can see it resolving database name correctly. Manager, Still tries to use default, Error -
Django chat working on project_ip:8000 but not on project_ip
My django chat is working if I run my project on port xx.xx.xx.xx:8000 but the moment I run iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8000 to map 8000 to 80, to run my project on ip xx.xx.xx.xx the chat doesn't work, why is this happening ? My project is running on ec2 ubuntu instance -
Initial Dropdown Menu Table Population
I was wondering if someone could help me solve this problem I have. I created a form that populates a table based on the selected name in a dropdown menu, however, when I initially load the page, since it is a for-loop and no option has been selected yet, the for loop runs through all the datapoints, populating the table with all the data for each name, but works fine once an option is chosen. I was wondering if someone could explain how I can get the initial page load to either show nothing or the values of one option, not everything at once until an option is chosen. Thanks for the help. <form method="GET" action="."> <div id="option-wrap"> <select name="option-menu" id="option-menu"> <option value="" hidden disabled selected value id="option-filler">Choose a Name</option> {% for l in options %} <option value="{{loans.company_name}}">{{l.names}}</option> {% endfor %} </select> <button type="submit" class="btn-filter">Filter</button> </div> <div class="card-items"> <table class="main-items-table"> <tr> <td class="menu-box-tab-items-identifiers">Name:</td> {% for l in queryset %} <td class="menu-box-tab-items" href=""><span>{{l.name}}</span></td> {% endfor %} <td class="menu-box-tab-items-identifiers">Sector:</td> {% for l in queryset %} <td class="menu-box-tab-items" href="#6"><span>{{l.sector}}</span></td> {% endfor %} </tr> </tbody> </table> </div> </form> -
django.db.utils.IntegrityError: NOT NULL constraint failed: new__blogapp_created_blog.user_id
I just created a simple childish model but it raise a unpredictable error that is django.db.utils.IntegrityError: NOT NULL constraint failed: new__blogapp_created_blog.user_id enter code here from django.db.models import * from django.db import models class created_blog(Model): user=CharField(max_length=100) blog_title=CharField(max_length=100) blog_subtitle=CharField(max_length=100000000) date=CharField(max_length=100) blog_content=CharField(max_length=1000000000000000) -
Django validate property
Is there any way to apply a Django validator to a property instead of a field? I have a field dob and a property age tied to that field. I'll like to guarantee that age cannot be smaller than 18. -
How to delete an object after 5 minutes? Celery
I am trying to create a periodic task with celery to delete an object after 24 hours of expiration, I have searched and tried several solutions but none of them work celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'arhi.settings') app = Celery('arhi') BASE_REDIS_URL = os.environ.get('REDIS_URL', 'redis://localhost:6379') CELERY_BROKER_URL = os.environ.get('REDIS_URL') app.conf.broker_url = BASE_REDIS_URL app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.beat_schedule = { 'every-1-minute':{ 'task':'tarea.tasks.delete_file', 'schedule':60, } } app.conf.timezone = 'America/Bogota' app.autodiscover_tasks() models.py import uuid from django.db import models from django.utils import timezone # Create your models here. class Archivo(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) file = models.CharField(max_length=60) fecha_subida = models.DateTimeField(default=timezone.now) class Meta: verbose_name = 'Archivos' Celery executes any other task that you assign to it, but this one to delete some object does not execute it tasks.py from datetime import datetime from django.utils import timezone from celery import shared_task from .models import Archivo @shared_task def delete_file(): files = Archivo.objects.filter(fecha_subida__lte=timezone.now()) if files: files.delete() return "files eliminados" return "no hay archivos" -
Django Nested Query
Here is my view.py class ItemFilter(filters.FilterSet): stk_no=filters.CharFilter(lookup_expr="icontains") itemtran__ledindi=filters.CharFilter(lookup_expr="iexact") part_no=filters.CharFilter(lookup_expr="icontains") brand_name=filters.CharFilter(lookup_expr="icontains") class Meta: model=Item fields=['stk_no','itemtran__ledindi','part_no','brand_name'] class ItemViewSet(viewsets.ModelViewSet): serializer_class = ItemSerializer queryset = Item.objects.all() filter_backends = [DjangoFilterBackend] filterset_class = ItemFilter pagination_class = PostPagination def get_queryset(self): return self.queryset.filter() Here is my serializer.py class ItemTranSerializer(serializers.ModelSerializer): id = serializers.IntegerField() class Meta: model = ItemTran read_only_fields = ( "stk_no_id", ), fields = ( "id", "stk_no", "qty", "trntype", "company", "department", ) class ItemSerializer(serializers.ModelSerializer): itemtran = ItemTranSerializer(many=True) class Meta: model = Item read_only_fields = ( "created_at", "created_by", ), fields = ( "id", "stk_no", "part_no", "brand_name", "itemtran", ) Im trying to filter all items with the "company" field in "ItemTran" filtered. but the api just returns all the transactions. "id": 7614, "stk_no": "NT1515", "part_no": "185/65 R 15", "brand_name": "Brand X", "itemtran": [ { "id": 620855, "stk_no": "NT1515", "qty": 4.0, "trntype": "INV", "company": "I", "department": "I" }, { "id": 632238, "stk_no": "NT1515", "qty": 2.0, "trntype": "ARR", "company": "A", "department": "F" }, where i only need the "itemtran" to show only company "I" rows. i pretty new at this so please any help is greatly appreciated. i have a similar module which works but cant figure out whats wrong here i tried rewriting the whole thing from scratch and still not … -
why i am getting NoReverseMatch error while i am practicing beginner projects from github in Django 4.0.6?
I am getting a NoReverseMatch error after adding the primary key to the URL links in the urls.py file. please solve it. I am a beginner in programming so I could not find a solution for this issue. Thank you for your time and effort. I got this exercise from Github. The code is written below. settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR=os.path.join(BASE_DIR,"templates") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-6mtsgnhk=-=5ka0-e4619v0_uq)s+t=dtybe8^ojwmg1gwoj**' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'g7app', ] 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', ] ROOT_URLCONF = 'g7.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'g7.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } urls.py from django.contrib import admin from django.urls import path from … -
Elegant way to handle invalid pages in Django with a generic class-based view
I found a partial solution in Django: How to catch InvalidPage exception in class-based views?, but the URL in the address bar still shows the original page request. Django has Paginator.get_page(number), but there doesn't seem to be a way to use it to redirect inside of the view. I originally thought I might be able to do it in get_context_data, but I don't seem to be able to force a redirect as it will only allow a dict as a response. def get_context_data(self, **kwargs): paginator = self.get_paginator(self.queryset,self.paginate_by,self.paginate_orphans) try: context = super().get_context_data(**kwargs) except Http404 as err: self.kwargs['page'] = paginator.get_page(self.request.GET['page']).number return redirect('my_list_view', kwargs=self.kwargs) context['page_list'] = context['paginator'].get_elided_page_range(context['page_obj'].number,on_each_side=2,on_ends=1) return context That fails outright. The following works (per the linked answer above), but does so in a non-optimal way. def get_context_data(self, **kwargs): paginator = self.get_paginator(self.queryset,self.paginate_by,self.paginate_orphans) try: context = super().get_context_data(**kwargs) except Http404 as err: self.kwargs['page'] = paginator.get_page(self.request.GET['page']).number context = super().get_context_data(**kwargs) context['page_list'] = context['paginator'].get_elided_page_range(context['page_obj'].number,on_each_side=2,on_ends=1) return context I feel like there should be a simple/elegant way to do this, but I just haven't found one. I could of course go for a function-based view, but I can't shake the feeling that there's got to be a way to do it this way. -
Django - how to make frontend-customizable sets / groups in models?
I am trying to create an app, that handles laboratory analyses - something like similar Laboraotory Information System (LIS) The issue is that i dont know which approach to take. I am plannin to make it as follows: "ANALYSES" table - consisting of "name", "ID" of analyses "PROBES" table - consisiting of "name", "ID", "reference", "VALUE", "measurement". Also the PROBES will have the field which links it to certain "ANALYSES" instance. SO it will be like "ANALYSES #1" -> "PROBE1", "PROBE2", "PROBE3" "ANALYSES #2" -> "PROBE1", "PROBE3" And so on. The operator should be capable of adding new analyses and adding probes to this analyses via frontend in one "view" - like "LAB settings" and in another view - to enter values to instances of this analyses (all analyses instances will be linked to some "VISIT" - the service case) What approach should i take planning the app and models? will it be some Meta classes or just multiple tables linked "manytoone" or "manytomany"? Will be gratefull for any advice! -
I can't start runserver in django. the error is cannot find python
I'm using a different computer. I have Windows 10 Pro, "py manage.py runserver" does not work for me. Creating a project works for me. I use py -m django startapp My error from the terminal: "I'm using a different computer. I have Windows 10 Pro, "py manage.py runserver" does not work for me. Creating a project works for me. I use py -m django startapp My error from the terminal: "python could not be found. start" please help with that -
Como fazer o deploy do Django + vue.js no heroku? [closed]
Eu estou querendo fazer o Deploy do Django rest + vue.js em apenas um servidor, mas não sei como fazer. -
Mongoengine conditonal query using fastapi
I want to get spacetypes where is_custom is false and where is_custom is true but user should be requested user I've written below code but this seems to give me empty qs spacetypes = SpaceType.objects.filter( Q(is_custom = False) & Q(is_custom = True, user=user) ) -
Annotate new field with the same name as existing one
We are facing a situation here that I would like to get more experienced user’s opinion. We are at Django 4, Python 3.9. The current scenario: We already have our system running in production for a reasonable time and we need to change on the Backend some returned data to our Frontend application (Web, mobile…) based on users choice. Something important is: Changes on the Frontend side are not an option for now. We need to override some attributes from one model, based on existing or not corresponding data on another table. The Tables (Django Models): AgentSearch (this data is replaced every single day by an ETL process) id identifier_number (unique) member_first_name member_last_name member_email some_other_attrbs Agent (Optional data that the agent can define) id agent_search_identifier_number (FK OneToOne) first_name last_name email For our requirement now, all the queryset will be made starting on AgentSearch. The idea is getting the Agent data instead of AgentSearch data every time there is an agent linked to it. Today we get like this: AgentSearch.objects.all() I know that would be easier to annotate new columns like this: # using a different attribute name NEW_member_first_name=Case( When( agent__id__isnull=True, then=F("member_first_name"), ), default=F("agent__first_name"), ), This would require us to make … -
Django Rest How I can Get all values from model Serializer each separately
I have model serializer in django rest frame work I would like to use values from my class serializer for example serializer.py profile = ProfileSerializer() class Meta: model = User fields = ['username', 'email', 'profile'] @api_view(['GET', 'POST']) def snippet_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = SnippetSerializer(data=request.data) if serializer.is_valid(): serializer.save() BUT INSTEAD OF USING Response I would like to make something like serializerd_sername = serializer.data['username'] serializerd_email = serializer.data['email'] serializerd_profile = serializer.data['profile'] and after few if else then some respond but how to get serialized data/values to use? return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
restrict signup with django-allauth
I'm thinking of using Django allauth for user athentication/authorization but am a bit puzzled about how you prevent or screen initial signup. I'm envisioning a small group of maybe 50 users (and I would have a list of these). I see nothing about allauth allowing you to check against my personal list of people who should be allowed access. Is allauth even a good solution in this scenario? Just to reiterate, my concern is not about using, say, Google to verify their email / identity, but rather pre-screening the people who can sign up in the first place. -
Problem with CSS styling in a html page in Django
So, i am literarily one week into learning web development and i'm following this Django tutorial, i got the index page that i swiped from online to compile properly with it's static elements also. Ran the "python3 manage.py collectstatic" command and everything. So now i'm linking a registration page which i setup up as a new app in the project and when i try and put the css styling file it doesn't work. i've tried just puting in the same directory as the html templates, then i've moved it to styles and rerun the earlier python command so it's also present in assets, also made use of the "{% static 'abcde.css' %}" as well as {% load static %} in the register.html (only did it in the index initially) and i'm still having no luck with styling the page, any help would be appreciated -
django: override admin/login with custom loginview and authenticationform but same template
I added an expiry date field to my User. Now I want to add a custom error message to a failed login if the account is expired, because if I only override the ModelBackend's can_authenticate method, the form throws the standard validation error which suggests that the problem resides with the credentials. I prefer clarity. So I extended AuthenticationForm and overwrote its confirm_login_allowed method to do an expiry check and raise a ValidationError with a newly added error message. However, I get complaints from Django that the template does not exist: TemplateDoesNotExist at /admin/login/ registration/login.html urls.py from django.contrib.auth import views as auth_views from my_app.auth.forms import AuthForm urlpatterns = [ # path("admin/", admin.site.urls), # Have to comment out or the next item will not match re_path(r"^admin/login/$", auth_views.LoginView.as_view(form_class=AuthForm), name="login"), re_path(r"^logout/$", auth_views.LogoutView, name="logout"), ... ] my_app/auth/forms.py from django.contrib.auth.forms import AuthenticationForm from django.core.exceptions import ValidationError class AuthForm(AuthenticationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.error_messages["account_expired"] = "This account has expired." def confirm_login_allowed(self, user): super().confirm_login_allowed(user) if user.expired: raise ValidationError(self.error_messages["account_expired"], code="inactive")