Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Should authentication_classes and permission_classes in Django's APIView Be Defined with Lists or Tuples?
I'm trying to understand the best practice for setting authentication_classes and permission_classes in Django's APIView. Specifically, I’ve seen both tuples and lists being used to define these attributes: Using a tuple: class Home(APIView): authentication_classes = (JWTAuthentication,) permission_classes = (permissions.IsAuthenticated,) Using a list: class Home(APIView): authentication_classes = [JWTAuthentication] permission_classes = [permissions.IsAuthenticated] Both approaches seem to work correctly, but I'm unsure if there are any specific reasons to prefer one over the other. Should I use a list or a tuple in this scenario? Are there any implications for using one over the other in terms of performance, readability, or following Django's best practices? I tried using both tuples and lists for authentication_classes and permission_classes in Django’s APIView. Both work fine, but I’m unsure which one is better or recommended. I was expecting to find clear guidance on this. -
Whats the difference between asyncio and multithreading in python?
Multi-threading import threading def heavy_computation(): # A CPU-bound task result = sum(x * x for x in range(10**6)) threads = [] for _ in range(4): t = threading.Thread(target=heavy_computation) threads.append(t) t.start() for t in threads: t.join() Asynchronous python import asyncio # Define an asynchronous function (coroutine) async def async_task(name, duration): print(f"Task {name} started, will take {duration} seconds.") await asyncio.sleep(duration) # Simulate a long-running I/O-bound task print(f"Task {name} finished.") # Define the main coroutine async def main(): # Create multiple tasks using asyncio.create_task() task1 = asyncio.create_task(async_task("A", 2)) task2 = asyncio.create_task(async_task("B", 3)) task3 = asyncio.create_task(async_task("C", 1)) # Wait for all tasks to complete await task1 await task2 await task3 # Run the main coroutine asyncio.run(main()) What are the differences between using multi-threading in Python and Asynchronous Python since the global interpreter lock prevents parallelism of threads, only a single thread can execute at one time. Asynchronous Python is also also single threaded. I suppose, it could the resource management of multi-threads which could make asynchronous python more efficient. Which is preferred for backend applications like Django? Googled but no answers -
Python Django getting a TemplateDoesNotExist at / when deploying site to PythonAnywhere [closed]
enter image description here I keep getting this error message when trying to deploy my site on pythonanywhere's site. When I try it locally, it works without any issue. I am just wondering why the path is not working now. I have tried many different paths and they all seem to not work. Wondering if anyone has seen this before? Trying to deploy to site, and it did not go through. -
Django login_required redirect to login page even when user is authenticated
I setup login_required in my app to limit access to pages to logged users. It works fine locally, if user is authenticated, he has access to the page and if not, he will be asked to enter his credentials. The problem is, in production, even when the user is authenticated, he will be redirected to the login page. Any idea how can I resolve this issue ? Thanks! I removed login_required and tried the raw way which is using the if statement if not request.user.is_authenticated: return redirect(f"{settings.LOGIN_URL}?next={request.path}") But I still have the same issue. I need the user once logged into the app to be able to go to other pages without asking for login again as it works locally. -
How to Implement JWT Authentication with a Dynamic Database in Django? (User table is in each database its not central)
I'm working on a Django application where the user data is not stored in a central database. Instead, each client has their own separate database hosted on their own server. Here's the setup: JWT Authentication is used for the app. The central Django server handles authentication requests but must dynamically connect to a client's specific database based on information provided in the JWT token. The employee_id is stored in each client's database, not in the central Django database. The connection string to the client's database is included in the JWT token payload. My Implementation: I've created a custom JWTAuthentication class where: Token Validation: The JWT token is validated. Database Connection: Based on the token payload, I dynamically connect to the client's database using the connection string provided in the token. User Verification: I fetch the user from the client’s database using the employee_id in the token and check if the user is active. Here's a simplified version of my JWTAuthentication class: from rest_framework import authentication from rest_framework.request import Request from .models import TokenUser from .settings import api_settings from .tokens import Token from .exceptions import AuthenticationFailed, InvalidToken import pymssql class JWTAuthentication(authentication.BaseAuthentication): def authenticate(self, request: Request): header = self.get_header(request) if header is … -
React + Django full stack webdev
recently or maybe like year ago I started to learn everything that I need to know to be fullstack web developer (html,css,js,react..). Now I am trying to build a fullstack website as my first big project. I learned a lot of things about how to built it and now I´ve come to conclusion that I want to use react with django. **Little information about my website: it will consist of many pages like: ** HOME page, NEWS page where I want to display news about certain topics so I need to call API and Fetch data from websites, LEARN page where anyone can find information about certain topic that this website is based on, CHAT ROOM which is almost like mini Discord clone where anyone can talk to anyone in chat rooms they created and can modify them etc... FAQ and SUPPORT pages which are basically feedback from people to me, I might combine them to one page idk I am not sure right now, and of course PROFILE page for every user. My question is, is this a good combination for my website? I know that as a developer I should programm in language I want or I like … -
Django Admin Keeps Failing
I recently created a new Django project using cookie cutter with docker. I use this regularly to setup my Django projects but recently I've had an issue where any new project I start will boot up and load correctly but for some reason the admin says page not found. I can login with my created super user and stay on the root /admin dashboard but when I try to click on any of the table links it automatically goes to a page not found. Has anyone else experienced this and if so how have you fixed this? All of the normal django functions ie. migrate, makemigrations... are working fine. I just can't view anything in the admin. Could this be a docker issue? I've checked the logs in docker but haven't noticed anything important. -
Django Context getting lost in email
I am trying to send a forgot password email in Django. Although even after using print debug statements to make sure that the slug is available in my context, it's keeps throwing an error. My models.py: class Restaurant(models.Model): name = models.CharField(max_length=100) email = models.EmailField() description = models.TextField() landing_page_tagline = models.TextField() landing_page_image = models.ImageField(upload_to='restaurant_images/') address = models.CharField(max_length=255, null=True) phone = models.CharField(max_length=20, null=True) logo_image = models.ImageField(upload_to='restaurant_images/') primary_color = models.CharField(max_length=7) # Hex color code favicon = models.FileField(upload_to='restaurant_favicons/', null=True, blank=True) about_us_image1 = models.ImageField(upload_to='restaurant_images/') about_us_text1 = models.TextField(blank=True, null=True) about_us_image2 = models.ImageField(upload_to='restaurant_images/') about_us_text2 = models.TextField(blank=True, null=True) about_us_image3 = models.ImageField(upload_to='restaurant_images/') about_us_text3 = models.TextField(blank=True, null=True) contact_us_image = models.ImageField(upload_to='restaurant_images/') map_iframe_src = models.TextField(blank=True, null=True) footer_text = models.TextField() facebook_link = models.URLField(null=True, blank=True) instagram_link = models.URLField(null=True, blank=True) youtube_link = models.URLField(null=True, blank=True) twitter_link = models.URLField(null=True, blank=True) slug = models.SlugField(unique=True, max_length=100, null=True) stripe_subscription_id = models.CharField(max_length=255, blank=True, null=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) super().save(*args, **kwargs) def __str__(self): return self.name class RestaurantUser(AbstractUser): restaurant = models.OneToOneField('Restaurant', on_delete=models.CASCADE, null=True, blank=True) phone = models.CharField(max_length=20, blank=True, null=True) is_restaurant_admin = models.BooleanField(default=False) groups = models.ManyToManyField( Group, related_name='restaurantuser_set', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_query_name='restaurantuser', ) user_permissions = models.ManyToManyField( Permission, related_name='restaurantuser_set', blank=True, help_text='Specific permissions for … -
Django Admin: Custom bulk duplication action not processing form data correctly
Title: Django Admin: Custom bulk duplication action not processing form data correctly Description: I'm trying to implement a custom action in Django Admin to duplicate records in bulk for a model. The process should work as follows: Select multiple records in the Django Admin. Click on a custom action called "Duplicate selected records in bulk". A screen appears where the user can enter new effective dates (start and end). Upon clicking "Duplicate", new records are created, copying all fields from the original record except the effective dates, which are updated as entered by the user, and the liberado field, which should be set to False. The issue I'm facing is that when I submit the form with the new dates, the duplication view does not seem to process the submitted data. The POST method is not being triggered correctly, and the form data is not captured. When sending the created custom form, the request is not even falling into the view. The print which I placed is not being fired. Here is the relevant code structure: Model and Form: class OrcamentoOpicional(models.Model): nome = models.CharField(max_length=100) categoria = models.ForeignKey(CategoriaOpcionais, on_delete=models.DO_NOTHING, null=True, blank=True) sub_categoria = models.ForeignKey(SubcategoriaOpcionais, on_delete=models.DO_NOTHING, null=True, blank=True) descricao = models.TextField() valor … -
How do we unzip a zip file in the file's parent folder in python3.x
I have a requirement to unzip an archive by selecting it at runtime. I am passing the zip file using HTML input type file in my template and then using ZipFile's function extractall(). This rudimentary arrangement is working, however the unzipped contents are getting saved in the (Django) project's root folder. I can control where the extracted files get stored by using the path option, which I feel would be a little limiting in the sense that in that case, the folder path will have to be hardcoded. (There are other means of supplying the path information at runtime, but still user intervention would be required.) The file being an inmemory file, I know the path information will not be available, which otherwise would have been handy. Is there a way I may save the unzipped file to the same folder as the zipped file is selected from? Thanks a bucnh. -
How to ignore `ModuleNotFoundError` when using mypy for github actions?
I’m integrating mypy into my GitHub Actions workflow to check only the changed files in my django project: name: Pull Request Backend Lint and Format on: [push, pull_request] jobs: backend-lint-and-check: runs-on: ubuntu-latest defaults: run: working-directory: backend steps: - uses: actions/checkout@v3 with: fetch-depth: 0 - name: Set up Python uses: actions/setup-python@v4 with: python-version: '3.x' - name: Install dependencies run: | python -m pip install --upgrade pip pip install ruff mypy mypy-extensions django-stubs django-stubs-ext - name: Get changed files id: changed-files run: | if [ "${{ github.event_name }}" == "pull_request" ]; then BASE_SHA=${{ github.event.pull_request.base.sha }} else BASE_SHA=$(git rev-parse HEAD^) fi CHANGED_FILES=$(git diff --name-only --diff-filter=d $BASE_SHA...HEAD | grep '^backend/' | sed 's|^backend/||' | grep '\.py$' | tr '\n' ' ') echo "files<<EOF" >> $GITHUB_OUTPUT echo "$CHANGED_FILES" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT - name: Run Ruff check if: steps.changed-files.outputs.files run: | FILES="${{ steps.changed-files.outputs.files }}" if [ ! -z "$FILES" ]; then echo "Running Ruff check on files:" echo "$FILES" for file in $FILES; do ruff check "$file" || echo "Ruff check found issues in $file" done else echo "No Python files to check" fi - name: Run Ruff format check if: steps.changed-files.outputs.files run: | FILES="${{ steps.changed-files.outputs.files }}" if [ ! -z "$FILES" ]; … -
Windows 11 Home - Unable to run django-admin
I have looked through several post regarding either: django-admin : The term 'django-admin' is not recognized or [Errno 2] No such file or directory I am trying to run django-admin startproject...and again I have tried it several ways and keep getting one of the two above errors. I've used the full path to python, I have used variations of that command that I have seen in several post but none are working. I am able to run "python -m django --version" and I get 5.1. I can run a .py file in the terminal window fine. But can't use "django-admin". Here is one of the full errors: C:\Users\Famil\AppData\Local\Microsoft\WindowsApps\python.exe: can't open file 'C:\Alejandro\Django\django-admin.py': [Errno 2] No such file or directory Please advise, this is so crazy. Cheers -
Increase security when sharing images between two parties
I'm building a system that have two types of users: doctor and patient. Just to give context. A doctor is allowed to save medical records (images) for any patient, and this images are going to be saved as encrypted blobs on a MySQL DB. The doctor is also able to request a temporal access to a certain patient medical record (group of images) (here i'm using a magic link). The patient is just able to see their own records, and accept or deny access requests to see his own medical history from an specific doctor. After given all this context, the challenge i'm facing is that I'm trying to find a way to encrypt all the images for the same patient with certain "secret phrase" that the patient should be already entered before. But this phrase cannot be stored on the database for security reasons. So the thing is that this phrase it al should be available on the doctor session when its loading a record for a patient to encrypt the file, or maybe that could be done on another way that i'm not seeing. Any ideas? I'm using Django framework and I'm not working with Django Rest, just … -
Django: Use widgets in Form's init method?
Why the widget for the field defined as a class attribute is working, but it is not for the instance attribute inside the __init__ method? (I need the init method) class CropForm(forms.ModelForm): class Meta: model = CropModel fields = ['name', 'label'] label = forms.CharField(label='label', widget=forms.TextInput(attrs={'class': 'input'})) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.name = forms.CharField(label='name', widget=forms.TextInput(attrs={'class': 'input'})) How do I get the widget in the __init__ method to work? Thanks. -
How do i access my pysimplegui program online?
I made a program using Pysimplegui, but I want to access it over the internet. I found pysimpleguiweb which looked promising, except it looks like it is still version 0.39, so it isn't finished? I would like to know where instructions are for this. The below is a website which looks like someone is still working on it as of two weeks ago, but it also looks like they're asking for payment. https://github.com/PySimpleGUI/PySimpleGUI/issues/142 Below may be the answer, it looks like they're creating a pysimplgui and then using flask to show it over the internet. Will Django do the same thing? I can't find much on the internet about django and pysimplegui, or flask and pysimplegui. how to send data from separate computer to flask app Is there a way to access my pysimplegui program over the internet? -
How can I mark an email as verified in django-allauth?
I'm setting up a website from scrath that has been coded with Django and django-allauth. To create a new superuser from scratch, I need to run this command: python manage.py createsuperuser When I try to log in as this user on the website, I see this message: Verify Your Email Address We have sent an email to you for verification. Follow the link provided to finalize the signup process. If you do not see the verification email in your main inbox, check your spam folder. Please contact us if you do not receive the verification email within a few minutes. Let's say that I entered a fake email address or that the website doesn't have working SMTP yet. How do I mark the email address of this user as verified, either from the command-line, or in Python? -
"password authentication failed" for user after moving the credentials to .env file
I'm just trying to figure out this issue of "port 5432 failed: FATAL: password authentication failed for user "username" connection to server at "localhost"". The below code works fine in the dev environment but after I host it to Digital ocean it is not working. My setting.py code is config = environ.Env() # reading .env file environ.Env.read_env() DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": config("DB_NAME"), "USER": config("DB_USER"), "PASSWORD": config("DB_PASSWORD"), "HOST": config("DB_HOST"), "PORT": config("DB_PORT"), } } and the .env file is like SECRET_KEY=#$@#$@#$$##$%^%^&%^$#%#$%#$% DEBUG=True DB_NAME=polymath_core DB_USER=dc_user DB_PASSWORD=#$#$$%#$#%$###$ DB_HOST=localhost DB_PORT=5432 and the error django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: password authentication failed for user "dc_user" connection to server at "localhost" (::1), port 5432 failed: FATAL: password authentication failed for user "dc_user" The pg_hba.config Just cant figure this out. Any help would be appreciated. Thanks -
makemigrations is not identifying changes. Is there any solution to resolve this without touching my database migration logs?
I encounter this problem in every Django project whenever I do some complex work. I tried deleting all the migrations folders from each app and then changed the database. It worked, but I'm looking for a solution that doesn't involve touching migration files or the database. whenever i tried python manage.py makemigrations it always displays no changes dected. -
Django ignores static configuration for uploading to S3
I had the same problem with media files before, I did all the configuration but django kept saving the media files locally and not in S3, I think it was solved by implementing a custom class inheriting from S3Boto3Storage. Now I want to save my static files in the same S3 but I have the same problem, django completely ignores my configuration and keeps saving the files locally in the staticfiles directory. These are my installed apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'app', 'crispy_forms', 'crispy_bootstrap5', ] Media file setup currently working: AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_ENDPOINT_URL = config('AWS_S3_ENDPOINT_URL') AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_MEDIA_LOCATION = 'media' AWS_S3_REGION_NAME = config('AWS_S3_REGION_NAME') AWS_DEFAULT_ACL = 'public-read' AWS_QUERYSTRING_AUTH = False AWS_S3_CONNECTION_TIMEOUT = 60 MEDIA_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.{AWS_S3_REGION_NAME}.digitaloceanspaces.com/{AWS_MEDIA_LOCATION}/" PUBLIC_MEDIA_LOCATION = 'media' DEFAULT_FILE_STORAGE = 'cms.storage_backends.PublicMediaStorage' DEFAULT_PROFILE_PHOTO=config('DEFAULT_PROFILE_PHOTO') Static file configuration, the idea is to read CMS_STATIC_LOCAL_STORAGE from the environment variables, but for testing purposes the value is set constantly: CMS_STATIC_LOCAL_STORAGE = False print('Static Local Storage: ', CMS_STATIC_LOCAL_STORAGE) AWS_STATIC_LOCATION = 'static' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') if CMS_STATIC_LOCAL_STORAGE: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] else: STATIC_URL = f"https://{AWS_S3_REGION_NAME}.digitaloceanspaces.com/{AWS_STORAGE_BUCKET_NAME}/{AWS_STATIC_LOCATION}/" STATICFILES_STORAGE = 'cms.storage_backends.StaticStorage' Please note that I have also … -
Next JS doesn't send cookies to Django backend
I'm using NextJS on the front end and Django for the backend. I have authentication and authorization working by storing the tokens in local storage. I'm attempting to implement a more secure approach by using httonly cookies for authorization. The issue I'm stuck on is sending the httponly cookie back to Django on subsequent requests. Here is what I'm trying to do with some additional combinations I've attempted commented out. async function getData(url, errorMessage) { const response = await fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/json', // 'Access-Control-Allow-Credentials': true, // credentials: 'same-origin', credentials: 'include', // "Authorization": "Bearer " + localStorage.getItem(ACCESS_TOKEN_KEY) } }) if (!response.ok) { throw new Error(errorMessage); } return await response.json() } Here is what I have in my settings.py file in Django CORS_ALLOW_CREDENTIALS = True from corsheaders.defaults import default_headers CORS_ALLOW_HEADERS = default_headers + ( "credentials", 'access-control-allow-credentials', ) REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework_simplejwt.authentication.JWTAuthentication", 'dj_rest_auth.jwt_auth.JWTCookieAuthentication', ] } REST_AUTH = { "USE_JWT": True, "JWT_AUTH_HTTPONLY": True, 'JWT_AUTH_COOKIE': 'my-app-auth', } MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'allauth.account.middleware.AccountMiddleware', ] from datetime import timedelta SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(days=30), "REFRESH_TOKEN_LIFETIME": timedelta(days=30), "ROTATE_REFRESH_TOKENS": False, "UPDATE_LAST_LOGIN": True, "SIGNING_KEY": "complexsigningkey", # generate a key and replace me "ALGORITHM": "HS512", } When … -
Django Templates doesn't update
I have an application with Django 2.2. and IIS 8. It suddenly doesn't work when I made new changes. It changes appear in the Database but doesn't show on the webpage (templates or admin forms). I had tried start/stop the IIS server, I had modified the DEBUG option but still not working. The server Thanks. -
Preserve image metadata with Wagtail rendered images
I would like to find a way to preserve some or all of the image metadata when Wagtail generates renditions from the original. I have found the following reference in the Wagtail documentation about the function <generate_rendition_file>: NOTE: The responsibility of generating the new image from the original falls to the supplied filter object. If you want to do anything custom with rendition images (for example, to preserve metadata from the original image), you might want to consider swapping out filter for an instance of a custom Filter subclass of your design. It mentions the use of a filter, but as I am new to Django and Wagtail, I have not been able to determine how or where this would be used. This is an example of my code creating the renditions: {% image picture max-800x600 format-webp preserve-svg as picture_image %} {% image picture max-1600x1600 format-webp preserve-svg as original_image %} I would appreciate any help or guidance to figure this out. -
Django - call Form item by item with AJAX call
I'm new to Django and I'm trying to upload Form's items in my template with AJAX call to avoid refresh. Thanks to many Questions/answers here I have the following code which is working fine and renders the form as a table. I would like to do the same thing BUT instead of rendering it as a table, I would like to be able to choose which item to display and use it like this {{ form.item_name }} so I can organise my template like I want. What should I change ? view.py def test_company(request): if request.user.is_authenticated: company_num = request.GET.get('company_num') current_record8 = models_companies.objects.get(id_company=company_num) ser_template = forms_companies(instance=current_record8) return HttpResponse(ser_template.as_table()) else: messages.success(request, "You Must Be Logged In...") return redirect('home') template.html function load_company_test() { $.ajaxSetup({ data: { company_num: $('#id_id_company').val(), csrfmiddlewaretoken: '{{ csrf_token }}' }, }); $.ajax({ type: "GET", url: "../test_company/", success: function (data) { $("#div_company").empty(); $("#div_company").html(data); }, }); } // I want to populate the div like this <div id="div_company">{{ data.item_name }}</div> -
Dockerised Django project not serving files after trying to adjust static configuration
I'm running a dockerised web application using Django. I have had issues with getting static files to work (I couldn't get the application to find them), I thought I had this figured out that the files had the wrong permissions and added my current usergroup to it. After this the application won't run. What do I mean by won't run? I now get OOM messages from Gunicorn which I never got before. It's not a very intense application so far. My feeling is that changing permissions has caused some issues. This is the current permission setup: -rw-rw-r-- 1 ash ash 757 Aug 30 20:17 docker-compose.yml -rw-rw-r-- 1 ash ash 965 Aug 26 18:02 Dockerfile drwxrwxr-x 7 ash ash 4096 Aug 26 18:32 gs-python drwxr-xr-x 3 ash ash 4096 Aug 16 20:12 nginx -rw-rw-r-- 1 ash ash 6 Aug 15 17:16 README.md -rw-rw-r-- 1 ash ash 31 Aug 15 19:06 requirements.txt drwxrwxrwx 2 ash ash 4096 Aug 30 19:50 static docker-compose.yml version: '3.8' services: web: build: . command: gunicorn app-name.wsgi:application --bind 0.0.0.0:8000 volumes: - ./gs-python:/app - ./gs-python/static:/app/static # Directly mount local static folder expose: - "8000" depends_on: - db db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data environment: POSTGRES_DB: POSTGRES_USER: POSTGRES_PASSWORD: nginx: image: … -
make USERNAME_FIELD dynamic between phone and email
I have a Django rest framework app and I modified its User model with AbstractBaseUser. I deployed the project on a VPS and now the customer wants to make changes on authentication. I have to set BOTH phone and email as USERNAME_FIELD to let users send phone or their email and I have to make it dynamic. Here's my first approach : from django.db import models from django.core.validators import RegexValidator, MinValueValidator from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin class AllUser(BaseUserManager): def create_user(self, username, phone, email=None, password=None, first_name=None, last_name=None): if not email: raise ValueError('need Email') if not username: raise ValueError('need Email') if not phone: raise ValueError('need Phone Number') if not first_name: raise ValueError('First Name') if not last_name: raise ValueError('Last Name') user = self.model( email=self.normalize_email(email), phone=phone, username=username, first_name=first_name, last_name=last_name, ) user.is_active = True user.set_password(password) user.save(using=self._db) return user def create_staff(self, username, phone, email, password, first_name, last_name): user = self.create_user( email=email, phone=phone, username=username, password=password, first_name=first_name, last_name=last_name, ) user.is_active = True user.is_staff = True user.is_superuser = False user.save(using=self._db) return user def create_superuser(self, username, phone, email, password, first_name, last_name): user = self.create_user( email=email, phone=phone, username=username, password=password, first_name=first_name, last_name=last_name, ) user.is_staff = True user.is_active = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', …