Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Customizing Django login template
I'm new to Django and I want to use my custom login page instead of the ugly looking django login template. How could I make it work? I think I need to edit the urls.py file and override the login template but I don't know how to do it. Thanks -
Django Inline formsets always invalid
I am struck with inline formsets in Django. Each time I submit the formset it is considered invalid and hence the data doesn't get saved. I am a newbie in full-stack development and am learning Django. I am following Dennis Ivy's playlist on youtube and coding along with him. It is kind of an E-commerce portal where people can order stuff. Here is a link to the video where he implements inline formsets Video. It was working fine when I accepted orders through normal form i.e. one order at a time. I have done exactly as he did in his video. I also tried consulting my friends who are learning with me and also asked my mentor about it but no one could figure out what is wrong here. I browsed through the documentation but that too didn't help. Please help me out in fixing this. Github Repo link views.py from django.forms import inlineformset_factory def createOrder(request, pkCrteOrder): OrderFormSet = inlineformset_factory(customer, order, fields=('product','status'), extra=7) CustomerOrderOwner = customer.objects.get(id=pkCrteOrder) formSet = OrderFormSet(queryset = order.objects.none(), instance=CustomerOrderOwner) if(request.method == 'POST'): print("post request detected") formSet = OrderFormSet(request.POST, instance=CustomerOrderOwner) if formSet.is_valid(): formSet.save() return(redirect('/')) else: print("formset was invalid") context = {'formSet': formSet} return(render(request, 'accounts/orderForm.html', context)) Brief explaination: From … -
Edited form not getting saved in django
I've fixed almost everything, the form opens and I can make the edits but as soon as I make the edits and click on save, this shows up: I don't understand what's wrong. I did the same thing for my edit profile page and it worked perfectly there so I don't understand why it's not working here. views.py: class EditComplaint(UserPassesTestMixin, UpdateView): model = Complaint fields = ('reportnumber', 'eventdate', 'event_type', 'device_problem', 'manufacturer', 'product_code', 'brand_name', 'exemption', 'patient_problem', 'event_text', 'document') template_name = 'newcomplaint.html' def form_valid(self, request): complaint = request.user.complaint form = ComplaintForm(instance=complaint) if request.method == 'POST': form = ComplaintForm(request.POST, request.FILES, instance=complaint) if form.is_valid(): form.save() context = {'form': form} return render(request, 'newcomplaint.html', context) def test_func(self): complain = self.get_object() if self.request.user == complain.user: return True raise Http404(_('This complain does not exist')) What seems to be wrong? I think I need to change something in my views because everything else seems to work well so I'm not including anything else. But i don't understand what needs to be changed -
How to add a custom download path to downloaded files in django admin?
I have written some snippet to download datas from a model from default django admin. It works and csv file with name "some.csv" is downloaded to root project foler in my local machine. But what i want is customise the dir to new specific folder for eg ( C:\downloads). Also I am hosting it to heroku and I want the clients to see the downloads in their download folder. How to do that in both production and my local?? My model: class Booking(models.Model): name = models.CharField(max_length=100,blank=True) email = models.EmailField(blank=True) phone = models.CharField(max_length=50, blank=True) model = models.CharField(max_length=100, choices=Model,blank=True) # message = RichTextField(blank=True, null=True) location = models.CharField(max_length=50, blank=True) sent_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Meta: ordering = ('sent_at',) My admin.py: def download_csv(modeladmin, request, queryset): f = open('some.csv', 'w') abc = csv.writer(f) abc.writerow(["name", "email", "phone", "model"]) for s in queryset: abc.writerow([s.name, s.email, s.phone, s.model]) class BookingAdmin(admin.ModelAdmin): def delete(self, obj): return format_html('<a class="btn-btn" href="/admin/core/booking/{}/delete/">Delete</a>', obj.id) def edit(self, obj): return format_html('<a class="btn-btn" href="/admin/core/booking/{}/edit/">Change</a>', obj.id) list_display = ('name', 'email', 'phone', 'model','edit','delete') list_display_links = ('name',) icon_name = 'folder_open' actions = [download_csv] admin.site.register(Booking,BookingAdmin) -
how to implement test case for logout in Django?
I am trying to test the logout bypassing the username and password, but it is getting failed. Can anyone help from django.contrib.auth import logout from django.test import TestCase class BasicTest(Testcase): def test_logout(self): request = { 'data' : { 'username': 'admin', 'password': 'admin' } } logout(request) Error: request.session.flush() AttributeError: 'Session' object has no attribute 'flush' Thanks! -
View is getting rendered in the Network Preview tab Django
I have created the logon form in Django which working properly. However in the Network tab I am able to view the Form and for other views like GET request the form is getting rendered with prepopulated data. Am I missing something or doing something wrong. Below is the screenshot and login form code. {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section col-md-6"> <form method="POST" autocomplete="off"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Log In</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="Submit">Login</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> </small> </div> </div> {% endblock content %} logon_form_in_network_tab -
What is the best and stable ODM for mongodb and django?
I want to connect django to mongodb but what is the best ODM for this issue? Djongo or mongoengine ? -
CSS is only applying on few html files and not rest
So i am building a personal website and am using Materialize for web designing. At first it was good and my pages look good, but then I added some new pages and i found that the css is not applied in these new pages, can anybody help me in solving this. Actually both are same pages(categories.html) but the path are different. header.html (main html file, have not changed the name yet) <<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--Import materialize.css--> <link type="text/css" rel="stylesheet" href="static/main/materialize.css" media="screen,projection"/> </head> <body> {% load static %} {% include "main/includes/navbar.html" %} {% include "main/includes/messages.html" %} <main> <div style="background-image: url('https://www.google.com/url?sa=i&url=https%3A%2F%2Fwallpapersafari.com%2Fw%2FcU6JWo&psig=AOvVaw1eBAulQvnXOrIK1yQueVX5&ust=1623841457736000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCPje9_--mfECFQAAAAAdAAAAABAD')"> <div class = "container"> <br> {% block content %} {% endblock %} </div> </div> </main> {% include "main/includes/footer.html" %} <script type="text/javascript" src="static/main/materialize.js"></script> </body> </html> views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Item, ItemSeries, ItemCategory from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login, logout, authenticate from django.contrib import messages from .forms import NewUserForm def single_slug(request, single_slug): categories = [c.category_slug for c in ItemCategory.objects.all()] if single_slug in categories: matching_series = ItemSeries.objects.filter(item_category__category_slug=single_slug) series_urls = {} for m in matching_series.all(): part_one = Item.objects.filter(item_series__item_series=m.item_series).earliest("item_update") series_urls[m] = part_one.item_slug return render(request, "main/category.html", … -
Saving HTML form data all at once
I want to save HTML data using request.POST method all at once instead of column by column. But it is giving me error because of crsf token. I am using templates so I can't use Django Forms views.py @require_http_methods(["POST"]) def save_add_user(request): error="" message="" data=request.POST first_name=data.get('first_name') last_name=data.get('last_name') username=data.get('username') email=data.get('email') password=data.get('password') phone=data.get('phone') address=data.get('address') user_type=data.get('usertype') try: user=CustomUser.objects.create_user(username=username, email=email,password=password,user_type=user_type) #user=CustomUser.objects.create(**data) #gives me error unexpected argument 'csrfmiddlewaretoken' #user=CustomUser.objects.create_user(**data) #gives me error username not defined user.save() CustomUserDetails.objects.create(user=user, phone=phone,address=address,first_name=first_name,last_name=last_name) message='User Added Succesfully' except: error='Failed to add user' return render(request,'internal/add_user.html',{'messages':message,'error':error,}) -
Forum button only works when I am authenticated but returns NoReverseMatch at /forum/ Reverse for '' not found. '' when i'm not logged in
I'm having a lot of trouble with this. I don't understand why the same "Forum" button works when I'm logged in and redirects me to the forum page. However, it returns this when I'm not authenticated: NoReverseMatch at /forum/ Reverse for '' not found. '' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/forum/ Django Version: 3.1.11 Exception Type: NoReverseMatch Exception Value: Reverse for '' not found. '' is not a valid view function or pattern name. Here is my layout.html which home.html extends from: <body> <nav class="nav d-flex flex-row justify-content-between nav-fill navbar-expand-lg navbar-dark bg-dark sticky-top container-fluid" style=""> <div class="first"> <a class="navbar-brand mr-4 ml-4" href="#"><b>My Site</b></a> <a class="nav-item nav-link text-light" href="{% url 'home' %}">Home</a> <a class="nav-item nav-link text-light" href="{% url 'forum:index' %}">Forum</a> {% if user.is_authenticated %} <a class="nav-item nav-link text-light" href="{% url 'users_list' %}">Find New Buddies</a> </div> {% block searchform %}{% endblock searchform %} <div class="second"> <a class="nav-item nav-link text-light" href="{% url 'post-create' %}">Create Post</a> <a class="nav-item nav-link text-light" href="{% url 'my_profile' %}">Profile</a> <a class="nav-link dropdown-toggle text-light" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Messaging</a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <a class="dropdown-item" href="{% url 'postman:inbox' %}">Inbox{% if unread_count %} <strong>({{ unread_count }})</strong> {% endif %}</a> <a class="dropdown-item" href="{% … -
Is there any module in python for web development?
I want to do web development in python and in a very simple language. Kindly suggest me some modules for web development in python. -
django 404 when loading admin but not local pages when deployed to heroku
I have just deployed my Django application to Heroku, All my locally saved apps load fine but not the django admin page # mysite/urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('', include('home.urls')), path('api/', include('api.urls')), path('admin/', admin.site.urls), # ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) When I go to the home page it loads and the same for all other URLs, except for the admin page at https://myapp.herokuapp.com/admin and you get the following error. -
Django query to fetch top performers for each month
I need to fetch the top performer for each month, here is the below MySql query which gives me the correct output. select id,Name,totalPoints, createdDateTime from userdetail where app=4 and totalPoints in ( select max(totalPoints) FROM userdetail where app=4 group by month(createdDateTime), year(createdDateTime)) order by totalPoints desc I am new to Django ORM. I am not able to write an equivalent Django query which does the task. I have been struggling with this logic for 2 days. Any help would be highly appreciated. -
Can't seem to understand where I'm going wrong
I am working on a django project that accepts complains from users: models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber views.py: def History(request): complaint_data = Complaint.objects.filter(user=request.user) context = { 'complaint':complaint_data } return render(request, 'myHistory.html', context) class EditComplaint(UserPassesTestMixin, UpdateView): model = Complaint fields = ('reportnumber', 'eventdate', 'event_type', 'device_problem', 'manufacturer', 'product_code', 'brand_name', 'exemption', 'patient_problem', 'event_text', 'document') template = 'newcomplaint.html' def form_valid(self, request): complaint = request.user.complaint form = ComplaintForm(instance=complaint) if request.method == 'POST': form = ComplaintForm(request.POST, request.FILES, instance=complaint) if form.is_valid(): form.save() context = {'form': form} return render(request, 'newcomplaint.html', context) def test_func(self): complain = self.get_object() if self.request.user == complain.user: return True raise Http404(_('This complain does not exist')) template for my-history: <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">My Complaints</h1> <p class="all-comp-txt">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do … -
In my Django Models How can I create an Auto field which stores an id with format 'AAA BBB CCCC' (I also want to make this field as primary key)
In my Django Models, I want to create a custom field called 'facility_id' which will be storing in my database table column a unique facility_id for every registered facility using a format 'AAA BBB CCCC', where AAA,BBB, and CCCC are just mere random numbers. I intend to format this field because it will be used by people in a form, so I want it to look better and formatted, otherwise I would have simply used the default AutoField shown below. (Am too new in django & python, so pardon my simple question) Below is my autofield which I want to format, kindly help: class Facilities(models.Model): ... facility_id = models.AutoField(primary_key=True) # I want store this in form 'AAA BBB CCCC' ... -
What seems to be wrong with my code in django?
urls.py: urlpatterns = [ .... path('My-History/', accounts.views.History, name='MyHistory'), path('Complaint/<int:id>/edit', accounts.views.EditComplaint.as_view(), name='Complaint') ] views.py: def History(request): complaint_data = Complaint.objects.filter(user=request.user) context = { 'complaint':complaint_data } return render(request, 'myHistory.html', context) class EditComplaint(UserPassesTestMixin, UpdateView): model = Complaint fields = ('info', 'reportnumber', 'eventdate', 'event_type', 'device_problem', 'manufacturer', 'product_code', 'brand_name', 'exemption', 'patient_problem', 'event_text', 'document') def form_valid(self, request): complaint = request.user.complaint form = ComplaintForm(instance=complaint) if request.method == 'POST': form = ComplaintForm(request.POST, request.FILES, instance=complaint) if form.is_valid(): form.save() context = {'form': form} return render(request, 'newcomplaint.html', context) def test_func(self): complain = self.get_object() if self.request.user == complain.user: return True raise Http404(_('This complain does not exist')) models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber template for my-history: <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">My Complaints</h1> <p class="all-comp-txt">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor … -
Serializing Django simple history items the same way as the main model
I am trying to work with Django rest framework in conjunction with Django simple history. This answer has gotten me pretty far with understanding how to serialize the history items of a model. This works well for simple cases, but my model has a calculated field ("store" in the example below). The problem is that the the serialization of the history field doesn't seem to capture these. How to I serialize the history in the same way as the main model? Is it possible to do this in the to_representation method of the HistoricalRecordField? class MyModel(models.Model): ... history = HistoricalRecords() @property def store(self): return {} class HistoricalRecordField(serializers.ListField): child = serializers.DictField() def to_representation(self, data): return super().to_representation(data.values()) class MySerializer(serializers.ModelSerializer): ... store = serializers.DictField(child=serializers.CharField(), read_only=True) history = HistoricalRecordField(read_only=True) class Meta: model = MyModel -
You're accessing the development server over HTTPS, but it only supports
enter image description here enter image description here -
AttributeError: 'WSGIRequest' object has no attribute 'app'
I'm building a dashboard with these commands on a local machine and then copy it to the remote server: cd ~/repos/fork/saleor-dashboard git checkout 2.11.1 npm14 --verbose install export API_URI="https://api.mydomain.com/graphql/" export GTM_ID="GTM-K9ZZ3R8" npm14 run build ls build/dashboard/ scp -i ~/Documents/webserver-key-pair.pem -r build/dashboard ec2-user@3.1.16.71:/srv/www/mydomain/ The dashboard is available online. But when I log in with a valid user/pass, the Saleor API throws these errors, visible by sudo journalctl -xe: File "/home/ec2-user/repos/fork/saleor/saleor/graphql/utils/__init__.py", line 128, in get_user_or_app_from_context return context.app or context.user graphql.error.located_error.GraphQLLocatedError: 'WSGIRequest' object has no attribute 'app' ERROR saleor.graphql.errors.unhandled A query failed unexpectedly [PID:8388:Thread-108] ... File "/home/ec2-user/repos/fork/saleor/saleor/graphql/utils/__init__.py", line 128, in get_user_or_app_from_context return context.app or context.user AttributeError: 'WSGIRequest' object has no attribute 'app' ... File "/home/ec2-user/repos/fork/saleor/saleor/graphql/utils/__init__.py", line 128, in get_user_or_app_from_context return context.app or context.user AttributeError: 'WSGIRequest' object has no attribute 'app' What could be the cause? Thanks! =) -
Nginx problem when i enabled the file by linking to the sites-enabled dir
my gorgeous friends on the internet. I was doing something about Nginx for deploying my app made by Django, Postgresql, Gunicorn, Nginx, and DigitalOcean. First of all, The project name in the Github gist is btre_project, but my app's project name is pfc_calc. Considering the name dif, I created project folder by coping and pasting the line on the gist. sudo nano /etc/nginx/sites-available/pfc_calc And, copy the code and paste it into the file I just made. server { listen 80; server_name 104.248.152.6; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/djangoadmin/pyapps/pfc_calc; } location /media/ { root /home/djangoadmin/pyapps/pfc_calc; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } BUT, here is where I made a mistake and got an error I was so foolish that I forgot to change btre_project to pfc_calc sudo ln -s /etc/nginx/sites-available/btre_project /etc/nginx/sites-enabled Because I noticed that mistake, I typed this line again. sudo ln -s /etc/nginx/sites-available/pfc_calc /etc/nginx/sites-enabled I thought it would be ok and my mistake was under the bridge, but it wouldn't. When I typed this line sudo nginx -t this error below showed up. nginx: [emerg] open() "/etc/nginx/sites-enabled/btre_project" failed (2: No such file or directory) in /etc/nginx/nginx.conf:62 nginx: configuration … -
How to improve tests for models with multiple foreign keys (Django)
I have a MVP for my testing suite, but my current style will be a beast to maintain. I am running into trouble efficiently writing tests for my model which has two Foreign Keys. I include my model.py file and my test.py file below: models.py class Category(models.Model): name = models.CharField(max_length=100) class Product(models.Model): name = models.CharField(max_length=100) class ProductCategoryValue(models.Model): value = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="categories") product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="products") class Meta: unique_together = [['category', 'product']] (The idea behind this model structure is that there can be a list of products and a list of categories, with the ProductCategoryValue to serve as the glue between the two lists. The list of categories may change later on in the project and I would like to easily modify the values of each product text with respect to that category. I am open to suggestions to improve this model structure as well!) test.py #... def setUp(self): p = Product(name="Touchscreen") p.save() Product.objects.create(name="Dancer") c = Category(name="Use Case", selection_type="bullets") c.save() Category.objects.create(name="Video Conferencincg", selection_type="text") Category.objects.create(name="Multisite", selection_type="Boolean") ProductCategoryValue.objects.create(value="foobar", product=p, category=c) Is this the canonical way of writing tests for models which have multiple foreign keys? I'm hoping that there is a more efficient way so that my testing … -
Django rest framework large file upload
Is there an easy way to upload large files from the client side to a django rest framework endpoint. In my application, users will be uploading very large files (>4gb). Browsers have a upload limit, here's the chart. My current idea is to upload the file in chunks from the client side and receive the chunks from the rest endpoint. But how will I do that? I saw some libraries like - resumable.js, tus.js, flow.js etc. But how will I handle the chunks in the backend? Is there any library that is actively maintained for a problem like this? Please help me. -
How to use detailview pk in createview
# models.py class NewBlank(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=50) description = models.CharField(max_length=100, blank=True) blank_on_off = models.BooleanField(default=False) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) class BlankContent(models.Model): refer = models.TextField() memo = models.TextField() new_blank = models.ForeignKey('NewBlank', on_delete=models.CASCADE, related_name='blankcontent') # views.py class BlankDetail(LoginRequiredMixin, DetailView): model = NewBlank template_name = 'blank_app/blank_detail.html' context_object_name = 'blank' class BlankContentCreate(CreateView): model = BlankContent fields = "__all__" template_name = 'blank_app/new_blank_content_create.html' def get_success_url(self): return reverse_lazy('blank_detail', kwargs={'pk': self.object.new_blank.pk}) # urls.py urlpatterns = [ path('blank/<int:pk>/', BlankDetail.as_view(), name='blank_detail'), path('new-blank-content/', BlankContentCreate.as_view(), name='blank_content_create'), ] There is a creativeview in the detail view and I want to create a model in the detailview when I press it. So even if I don't specify the new_blank part, I want it to be filled automatically according to the pk in the detailview, what should I do? -
Django request + variable issues when Debug = True
I am getting a 500 error on all my pages except admin when I set debug to False in Django. (When Debug is True, everything works just fine.) When I look at my error log, I get a huge litany of errors, starting with the following: [20/Jul/2021 00:10:22] DEBUG [django.template:869] Exception while resolving variable 'self' in template '404.html'. I also get a number of "VariableDoesNotExist" errors for variables that are not even associated with the template in question. -
Django form is not valid in class based view
I'm currently working on a blog project where I have created a custom user model in which I intend on creating a Registration Form from this custom user model. I have my registration form that inherits from the UserCreationForm in Django. The form rendered properly in my template as it should but whenever I try registering a user the form is not valid. I'm not sure what I'm doing wrong. I'm looking forward to get some help from you brilliant people! :-) See the related usages below: models.py from django.contrib.auth import get_user_model from django.db import models from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from .managers import CustomUserManager class CustomUser(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=255, null=True, blank=True) last_name = models.CharField(max_length=255, null=True, blank=True) username = models.CharField(max_length=200, unique=True) email = models.EmailField(_('email address'), max_length=150, unique=True) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', ] class Meta: ordering = ['-date_joined', 'username', 'email'] verbose_name = 'User' verbose_name_plural = 'Users' def __str__(self): return self.username.title() forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import get_user_model class RegistrationForm(UserCreationForm): # confirm_password = forms.CharField(widget=forms.PasswordInput(attrs=registration_form_fields['confirm_password'])) class Meta: model = get_user_model() fields = ['first_name', …