Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django / admin.py how to add multi models
How add to admin.py admin.register for 3 model: Page/PageAdmin/PageListing? Below screenshot from my code: screenshot from vscode. -
Apache Index Of / Whenever a domain tries to point to my Server IP address
I have a server that has hosts multiple domain. I'm running Django + Apache for my websites. I was having an issue when a fresh domain tries to point to my server ip address, it always shows "Index /" This poses a really big problem as it was able to view my server files I know i can setup redirect beforehand, but only if i know the domain and configured to do so. I have even tried to point my IP itself to redirect whenever it was pointed. <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName XXX.XXX.XXX.XXX ServerAlias XXX.XXX.XXX.XXX DocumentRoot /var/www/TestServer/ ErrorLog ${APACHE_LOG_DIR}/defaulterror.log CustomLog ${APACHE_LOG_DIR}/access.log combined RewriteEngine on RewriteCond %{HTTP_HOST} ^XXX\.XXX\.XXX\.XX$ RewriteRule ^(.*)$ https://www.google.com$1 [R=permanent,L] </VirtualHost> -
TypeError: create_user() missing 1 required positional argument: 'group'
Everything worked fine, until I dropped the database and run the migrations again. Now, I'm not able to create superuser again. The error I got is: TypeError: create_user() missing 1 required positional argument: 'group' Anyone faced the same problem and is there any solutions to fix the error? models.py class CustomUserManager(BaseUserManager): def create_user(self, email: str, password: str, group: Group, **extra_fields): if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() if group is not None: group.user_set.add(user) return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email username = models.CharField(max_length=30, blank=True, default='') is_superuser = models.BooleanField(default=True) is_admin = models.BooleanField(default=True) is_employee = models.BooleanField(default=True) is_headofdepartment = models.BooleanField(default=True) is_reception = models.BooleanField(default=True) is_patient = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) forms.py class UserForm(ModelForm): group = forms.ModelChoiceField(queryset=Group.objects.all()) #temp['group']=request.POST.get('group') #role = forms.ChoiceField(choices=ROLE_CHOICES, label='', widget=forms.RadioSelect(attrs={})) class Meta: … -
Error message in Django when I try to runserver - does not appear to have any patterns in it. If you s ee valid patterns in the
Every time I write python manage.py runserver i get the error message The included URLconf '<module 'strana.views' from 'D:\novi projekat\strana\views.py'>' does not appear to have any patterns in it. If you s ee valid patterns in the file then the issue is probably caused by a circular import. mysite urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('strana/', include('strana.views')), ] myapp(named strana) from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] views.py from django.http import HttpResponse def index(request): return HttpResponse('Kita u Bila') -
I want to display data using ORM in django but only a query is being generated on my html webpage
I want to display data from the database using ORM in django but only a sqlquery is being generated on my html webpage instead of the data. can anyone please help me resolve this? My codes: views.py def home(request): Values = Major.objects.raw('SELECT p.major_cd, m.description FROM percentages as p, major as m WHERE p.major_cd = m.major_cd;') context = { "Values": Values } return render(request, "website/index.html" , context ) index.html {{ Values }} -
attribute error in django NoneType object has no attribute group
I kept writing the code in android but I get this error in the log, I tried coding in more than one way. The API works on Postman but the API keeps bringing this error when I use the HttpLoggingInterceptor.Where is the error in the code? The images are uploaded to Cloudinary in Django rest Framework. package com. iconic.enrollment_app; import androidx.appcompat.app.AppCompatActivity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.util.Base64; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.iconic.services.EnrollClient; import com.iconic.services.EnrollService; import com.iconic.services.models.Member; import org.jetbrains.annotations.NotNull; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Calendar; import java.util.Objects; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class NewMemberActivity extends AppCompatActivity implements View.OnClickListener { private static final int BUFFER_SIZE = 1024 * 2; @BindView(R.id.search_member) Button mSearchButton; @BindView(R.id.profile_photo) ImageView mProfilePhoto; @BindView(R.id.front_id) ImageView mFrontId; @BindView(R.id.back_id) ImageView mBackId; @BindView(R.id.title_member) EditText mTitleMember; @BindView(R.id.id_number) EditText mIdNumber; @BindView(R.id.first_name) EditText mFirstName; @BindView(R.id.middle_name) EditText mMiddleName; @BindView(R.id.surname) EditText mSurname; @BindView(R.id.birth_day) EditText mBirthDay; @BindView(R.id.phone_number) EditText mPhone; @BindView(R.id.email_address) EditText mEmail; @BindView(R.id.gender) EditText mGender; @BindView(R.id.postal_address) EditText mPostalAddress; … -
Search on NestedField with django-elasticsearch-dsl
I don't understand how to search with a NestedField. I first want to filter the results using a PK and then make a search on several fields from one or more words. I created a nestedfield because the relationship is "manytomany". My Model: class Club(models.Model): """ Sport club Model, related to :model:`auth.User` and :model:`clubs.CategoryClub` """ name = models.CharField(max_length=50, verbose_name="nom") category = models.ForeignKey('CategoryClub', on_delete=models.CASCADE) clubs_members = models.ManyToManyField(User, related_name="clubs_members", blank=True) token = models.CharField(max_length=8, unique=True, blank=True, null=True) class Meta: verbose_name = "Club" verbose_name_plural = "Clubs" def __str__(self): return self.name def get_absolute_url(self): return reverse("detailClub", kwargs={"pk": self.pk}) My document: @registry.register_document class UserDocument(Document): clubs_members = fields.NestedField(properties={ 'pk': fields.IntegerField(), 'name': fields.TextField(), }) class Index: # Name of the Elasticsearch index name = 'user' # See Elasticsearch Indices API reference for available settings settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = User # The model associated with this Document # The fields of the model you want to be indexed in Elasticsearch fields = [ 'id', 'first_name', 'last_name', 'email', ] My view: search = UserDocument.search() search = search.query( 'nested', path='clubs_members', query=Q('match', clubs_members__pk=request.user.profil.club_administrator.pk) # request.user.profil.club_administrator.pk == 1 in my example ) if form.cleaned_data['search'] != "": search = search.query( Qelastic('bool', should=[ Qelastic('multi_match', query=form.cleaned_data['search'], fields=['last_name^2', 'first_name^2', 'email^1'], fuzziness="auto" ), … -
How do I show the likes & my post in my template?
I have a created two models in my models.py file. I have also created a view and that view renders a template named index.html. I want to show the post and it's likes count in my index webpage/template. but the below code doesn't work. models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=42) author = models.ForiegnKey(User, on_delete=models.CASCADE, related_name='author_user') create_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.author.first_name} {self.author.last_name}' class Like(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='liked_post') user = models.Foreignkey(User, on_delete=models.CASCADE, related_name='post_liked_by') def __str__(self): return f'{self.user.username}@{self.post.title}' views.py from django.shortcuts import render from .models import * def index(request): posts = Post.objects.all() likes = Like.objects.all() context = { 'posts': posts, 'likes': likes, } return render(request, 'index.html', context) index.html <html> <head> <title> Home </title> </head> <body> {% for post in posts %} <h1> {{ post.title }} </h1> <p> Author: {{ post.author.first_name }} {{ post.author.last_name }} </p> <p> Date Created: {{ post.create_date }} </p> <p> <i class="fa fa-heart"></i> {{len(likes)}} </p> {% endfor %} </body> </html> thank you in advance. -
Does TemplateView supports pagination?
How can I implement pagination with Templateview? The below view is class-based view where I am using Templateview for listing out networks ( which I am calling from api from another application). Here I am not using models so I cant use Listview because I don't have queryset. class classView(TemplateView): template_name = 'view_network.html' # paginate_by = 5 context_object_name = 'networks' paginator = Paginator('networks', 5) def get_context_data(self, **kwargs): ... ... return context in html page i have added this: <span class="step-links" style="margin-left: 30%; margin-bottom: 0px; margin-top: 0px; width: 100%;"> <div style="text-align: justify"></div> <table style="width: 50%"> <tr> {% if page_obj.has_previous %} <td><a href="?page=1">&laquo; First</a></td> <td> <a href="?page={{ page_obj.previous_page_number }}">Previous</a></td> {% endif %} <td> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.</td> {% if page_obj.has_next %} <td><a href="?page={{ page_obj.next_page_number }}">Next</a></td> <td><a href="?page={{ page_obj.paginator.num_pages }}">Last &raquo;</a></td> {% endif %} </tr> </table> </div> </span> </div> -
Adding django_prometheus middlewares cause 500 (server error)
I wanted to monitor my django app with prometheus and I added the django-exporter and it worked well. Then I decided to change my dependency from django-exporter to django-prometheus and then all my requests, except /metrics causes 500, which surprisingly don't cause any errors on my server's logs. I tested different things, and by commenting the two django-prometheus middlewares, the 500 response code is gone. # 'django_prometheus.middleware.PrometheusBeforeMiddleware', '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', # 'django_prometheus.middleware.PrometheusAfterMiddleware', Is there anything wrong about my middlewares? Another problem which I have is that without commenting these two middlwares, my local docker-compose (Only django and memchache with dbengine of sqlite) is working, but my deploy-test docker-compose, consisting of postgres, django, memcache, autoheal is not working. I can't understand how these middlewares are related to my deploy-test set-up. -
Django-Rest-framework private API
I am building a Django application which has a REST API. I want this API to be private, only allowing petitions from users who have an auth token. But I have my frontend, which is made with React and inserted into the Django template. I want that, when making requests from the frontend to the API, no token is necessary to get a valid response. The site is not going to have a user registration/login system, so it cannot be done with user params. Thank you! -
Send message to RabbitMQ using Django and Docker
I have no idea how to use RabbitMQ. Any tutorial on how to use rabbitmq and django in docker to send messages would be helpful. -
heroku django showing stacktrace error 500 on logs?
I have heroku/django app. When i got error 500, i would like to get stacktrace in logs. So i do this: heroku logs -t --app myapp Then when i got error 500 i see this: The problem is i don't get stacktrace ... So to debug i have to put DEBUG to True, and i don't think that the right way to do it on production. How can i display error in logs please ? PS : I tried to set ADMINS email in settings.py to receive an email with stacktrace, but i don't :/ ADMINS= [('support@******.com', 'admin@******.com'),] So how can i see my stacktrace error 500 without setting debug = True please :3 ? Thank you ! -
django import export app error: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
I'm upgrading a Django site to 3.1.2 and noticed one backend app wasn't working, in the process of asking the community help in fixing this I found out the app wasn't a custom made code by a single coder for the site but a community project called django-import-export. Since it's up to date and supports django 3.1 i deleted the manual way it was setup as a folder and pip installed it. i then tried to do a makemigrations threw an error and after reading the setup docs assumed possibly you need to do collectstatic first, it also threw the same error (kpsga) sammy@kpsga:~/webapps/kpsga$ python manage.py collectstatic Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in … -
We can not request API service after build project
We develop the backend side of our project with the Django Rest Framework. We develop the frontend side of our project with the VueJs. The project will run on the apahce We had a problem after building Vuejs. We did not any problem with the Django Rest Framework. We can connect with Postman and we can do transactions. No problem. We finish our development in the frontend and write localhost or 127.0.0.1 to axios.default.baseURL; const ApiService = { init() { Vue.use(VueAxios, axios); Vue.axios.defaults.baseURL = "http://localhost:8000/"; //Vue.axios.defaults.baseURL = "http://127.0.0.1:8000/"; } } After build we move the files in dist to /var/www/htdocs We cannot send any request to the API service. The users can't login, can not perform any transactions. Even though both sides working on same device If i wrote endpoint IP address the axios.default.baseURL. The project will working inside in network. There is no domain name or endpoint IP address. Maybe There will be no internet connection on the this server. I think we should be able to write localhost or 127.0.0.1 on the VueJS. And by opening backend to a port we don't feel it's safe, because we are building security focused projects we want to have a close … -
Is this the right way to open object from DB for editing in the same form, and then saving the updated value for the same object using django?
This is my code: To create the new issue object, use form def raise_issue_view(request, *args, **kwargs): form = RaiseIssueForm(request.POST or None) if form.is_valid(): form.save() obj = RaiseIssueModel.objects.latest('id') return redirect("/raise_issue/" + str(obj.id)) context = { "form" : form } return render(request,"raise_issue.html", context) To edit the previously created issue, by link 127...8000/edit_issue/<issue_id> def edit_issue_view(request, id): obj = RaiseIssueModel.objects.get(id=id) form = RaiseIssueForm(instance=obj) new_form = RaiseIssueForm(request.POST, instance=obj) if new_form.is_valid(): new_form.save() return redirect("/raise_issue/" + str(obj.id)) context = { "form" : form } return render(request,"raise_issue.html", context) Here, in Edit issue view, first i'm loading the DB data into 'form', then I'm creating a new form (new_form) to save the updated data. Is this OK, or is there a better way to do this? Thanks, -
How to connect docker to oracle external database outside docker container?
i have create database on oracle. How to connect oracle external database with docker? -
How to get request user id in Django Serializers?
I'm getting KeyError: 'request' while i want to get the current user id through user request. I tried something like this: validated_data['user_id'] = CarOwnerCarDetails.objects.get(user_id=self.context['request'].user.id) but it's throwing me KeyError. How to get the current user id through request in serializers? if any help would be much appreciated. Thank you so much in advance my friends. models : class CarOwnerCarDetails(models.Model): user_id = models.OneToOneField(User, on_delete=models.CASCADE) car_plate_number = models.CharField(max_length=20, null=True, blank=True) class GetQuotes(models.Model): user = models.ForeignKey(CarOwnerCarDetails, on_delete=models.CASCADE, blank=True, null=True) subject = models.CharField(max_length=240, blank=False, null=True) serializers : class ShopGarageGetQuoteSerializer(ModelSerializer): subject = CharField(error_messages={'required':'subject key is required', 'blank':'subject is required'}) user_id = serializers.CharField(read_only=True) class Meta: model = GetQuotes fields= ['user_id', 'subject'] def create(self,validated_data): subject = validated_data['subject'] validated_data['user_id'] = CarOwnerCarDetails.objects.get(user_id=self.context['request'].user.id) quotes_obj = GetQuotes.objects.create( subject=subject, user_id=validated_data['user_id'] ) return validated_data views.py : class ShopGarageGetQuoteAPIView(APIView): permission_classes = (IsAuthenticated,) def post(self,request,*args,**kwargs): data = request.data serializer = ShopGarageGetQuoteSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({'success' :'True','message' : 'Quotes send successfully','data' : serializer.data},status=200) return Response(serializer.errors,status=400) -
Wagtailadmin allow group only to view in CMS admin
Hello everyone I've been working with wagtail for a while I faced and interesting thing when I create a group with only view permissions and access to wagtail all its fancy tabs like pages and images begone. I might assume that it is due to permissions of add/edit missing. But the question is is it possible in a fast easy way make something like that? display_what_needed and still be with this menu which disappear -
How to implement Agora into a Django project?
I would like to implement Agora voice and video SDK into a Django project. I have found some articles on this issue such as https://medium.com/@rayanuthalas/build-a-video-call-website-using-django-agora-a20ba6b8e7d5 Which might be helpful for someone with a previous experience but for so first time implementer it is too little, also they omit chunks of code here and there which makes it impossible to follow. I have found some package for Django - https://pypi.org/project/django-agora/ but it seems inactive and it hasn't even reached version 1. I would appreciate any tips on what to follow or any advice on how to implement it with Django. Or if you have an experience with another such SDK with Django and you know it is fairly straight forward to implement, I am open to suggestions too. Any material will be appreciated. -
Django Filter Default Date
Unfortunately I can't wrap my head around how to set a default value for a Date Filter, as described in some other posts it should be possible to set it in the init function, but to no avail: filters.py: class LoaderErrorFilter(django_filters.FilterSet): product = django_filters.ModelChoiceFilter(queryset=Product.objects.all(), label='Product*') operator = django_filters.CharFilter(field_name="operator", lookup_expr='contains', label='Operator') load_from = django_filters.DateFilter(label='From*') load_to = django_filters.DateFilter(label='To*') error = django_filters.CharFilter(field_name="error", lookup_expr='contains', label='Error') def __init__(self, *args, **kwargs): super(LoaderErrorFilter, self).__init__(*args, **kwargs) self.form.initial['load_from'] = datetime.datetime.today().replace(day=1) self.form.initial['load_to'] = datetime.datetime.today() if self.data == {}: self.queryset = self.queryset.none() The queryset will be filled after the user makes a selection since there are different models affected depending on the choices. Any ideas would be highly appreciated! -
Django cache framework not working with django-cms
I am using django 3.1 and the database caching and it is working properly, but when I included the django-cms in the project the cache table started giving an error that psycopg2.errors.UndefinedTable: relation "abc_cache_table" does not exist is there any config that I am missing to add? any help and suggestion will appriated. Thank you. -
SystemError: <built-in function uwsgi_sendfile> returned a result with an error set
I habe deploy my django app on pythonanywhere but have an error with export in excel my code works except on pythonanywhere I try to use from werkzeug.wsgi import FileWrapper but module werkzeug is not found... how to fix this issue? views.py from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django.db.models import Q from django.utils.translation import ugettext as _ import time from django.utils import timezone from datetime import datetime # http://www.learningaboutelectronics.com/Articles/How-to-create-an-update-view-with-a-Django-form-in-Django.php from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import permission_required from randomization.models import Medicament, Randomisation, is_randomizable, categorie_medicament from parameters.models import Profile, Pays, Region, Site, Thesaurus from pharmacy.models import Entree, Sortie, Parametrage, Alerte, Stock, alerte_existe, alerte_activation, mise_a_jour_alerte, stock_site_existe, liste_medicaments_a_envoyer_site,liste_medicaments_a_envoyer_pays, quantite_medicament_a_expedier, liste_medicaments_a_expedier import os import xlwt import csv @login_required def export(request): response = HttpResponse(content_type='application/ms-excel') export_date = str(timezone.now())[0:10] sites = [s.sit_abr for s in request.session.get('user_authorized_sites')] pays = Pays.objects.get(pay_ide = request.session.get('user_pays')).pay_abr filename = str(export_date) + "_intensetbm_export.xls" response['Content-Disposition'] = 'attachment; filename= "{}"'.format(filename) # response['Content-Disposition'] = 'attachment; filename="intensetbm_export.xls"' wb = xlwt.Workbook(encoding='utf-8') # styles normal_style = xlwt.XFStyle() ... if request.user.has_perm('randomization.can_export_data_randomization'): ws = wb.add_sheet('crf_ran') row_num = 0 columns = ... wb.save(response) return response -
Need help in adding Foreign key using django models
Okay so I don't know how to frame this. I have two models Employee and Customer. I am storing the Employee as foreign key in Customer model under emp_id. The epm_id stores the primary key of the employee who admits the customer. I am not sure how to do this in django. Here are my models: class Customer(models.Model): firstname = models.CharField(max_length=15) lastname = models.CharField(max_length=15) age = models.IntegerField() sex = models.CharField(max_length=10) phoneno = models.IntegerField() emailid = models.CharField(max_length=25) address = models.CharField(max_length=50) children = models.IntegerField() adults = models.IntegerField() roomtype = models.CharField(max_length=10) aadharno = models.CharField(max_length=15) daysstayed = models.IntegerField() date_visited = models.DateTimeField(default=timezone.now) emp_id = models.ForeignKey(Employee,on_delete=models.SET_NULL,blank=True,null=True) class Employee(models.Model): firstname = models.CharField(max_length=15) lastname = models.CharField(max_length=15) age = models.IntegerField() sex = models.CharField(max_length=10) phoneno = models.IntegerField() emailid = models.CharField(max_length=25) address = models.CharField(max_length=50) salary = models.IntegerField() designation = models.CharField(max_length=10) password = models.CharField(max_length=10) aadharno = models.CharField(max_length=15) datejoined = models.DateField(default=timezone.now) I need some help here. -
How to display the user groups because they didn't show in django view?
I have CRUD operations for users which can be done only from admin and he can assign users to 6 different groups. It saved in the database and everything works well. The problem I faced now is that the groups are not visualize in my views (in the UI) I attached picture to show what I mean: model.py class CustomUserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email username = models.CharField(max_length=30, blank=True, default='') is_superuser = models.BooleanField(default=True) is_admin = models.BooleanField(default=True) is_employee = models.BooleanField(default=True) is_headofdepartment = models.BooleanField(default=True) is_reception = models.BooleanField(default=True) is_patient = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) forms.py class UserForm(ModelForm): class Meta: model = CustomUser fields = ['email', 'password',] useradd.html <h1 class="display-4">Add new user</h1> <form action="" method="post" autocomplete="off"> {% csrf_token %} {{ form.as_p }} <button …