Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Subprocess command in Django working for localhost but not on openlitespeed vps server
I have the following function code in views.py of my django project: def word_to_pdf_logic(view_func): def wrapper_function(request, *args, **kwargs): if request.method == "POST" and request.FILES.get('word_file'): word_file = request.FILES['word_file'] # Generate unique temporary file name temp_filename = f"{uuid.uuid4()}.docx" temp_file_path = os.path.join(settings.MEDIA_ROOT, 'word_to_pdf', temp_filename) # Save uploaded Word file to temporary location fs = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'word_to_pdf')) temp_file = fs.save(temp_filename, word_file) word_filename = word_file.name print(f'word_filename : {word_filename}') print(f'temp_filename : {temp_filename}') out_path = os.path.join(settings.MEDIA_ROOT, 'word_to_pdf') # subprocess.call(['lowriter', '--headless', '--convert-to', 'pdf', '--outdir', out_path, temp_file_path]) subprocess.call(['libreoffice', '--headless', '--convert-to', 'pdf', '--outdir', out_path, temp_file_path]) output_pdf_filename = os.path.splitext(word_filename)[0] + '.pdf' output_pdf_path = os.path.join(settings.MEDIA_ROOT, 'word_to_pdf', temp_filename.replace(temp_filename.split('.')[1],'pdf')) print(f'output_pdf_filename : {output_pdf_filename}') print(f'output_pdf_path : {output_pdf_path}') if output_pdf_path: # Serve the PDF file for download with open(output_pdf_path, 'rb') as pdf_file: print(f'Pdf_file {pdf_file.name}') response = HttpResponse(pdf_file.read(), content_type='application/pdf') response['Content-Disposition'] = f'attachment; filename={os.path.basename(output_pdf_path)}' return response else: return HttpResponse("Error converting file to PDF") else: return view_func(request, *args, **kwargs) return wrapper_function Code is woking fine on localhost but the subprocess doesn't work in hosted VPS openlitespeed server on hostinger (os is Ubuntu 22.04). libreoffice and lowriter commands as working on vps if used with terminal to convert word (doc/docx) file into pdf, But if I use it through the django app it gives error. The same code is working on … -
Django React Communication Api
I have a confusion and it is killing be inside. When we work with website that uses react in frontend and Django in backend, what we do is create APIs in django, and then calls the APIs endpoints in our react app to get data. Then populate our frontend with the response data. But my question is, the api can be used by anybody, if he inspects the source code using dev tool. Because, the APIs are accessible by our react app without any authentication. And it should be so. Because, when someone first enters our website without any authentication credentials, we need to render our first webpage (homepage) and API should also be accessible there. But the same way, a hacker can make a lots of request on that server endpoint and thus effect our server, maybe make our server down. The First page of our site is authentication free. Homepage. Homepage is basically not logged in required. So New people try to access it. Its normal. The thing that is not normal is, if someone tries to access that endpoint outside of the browser. We should make sure the request is coming from client browser. Please help me … -
Cannot get Django ModelForm to display neither connect custom HTML form to database
I am currently creating a Django app that is a rental apartments homepage. It is supposed to have a booking form connected to a database. However I can't get the form from forms.py to be displayed on my bookings.html page. I'd appreciate help tons as I have no idea which detail I am missing. This is my code: models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Booking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_name") booking_date = models.DateField(auto_now=True) status = ( ('Requested', 'Requested'), ('Confirmed', 'Confirmed'), ('Cancelled', 'Cancelled'), ) booking_status = models.CharField(choices=status, blank=True, null=True, default='Requested') first_name = models.CharField(max_length=100, unique=True) last_name = models.CharField(max_length=100, unique=True) birth_date = models.DateField() email = models.EmailField(max_length=100, unique=True) phone_number = models.BigIntegerField() address = models.CharField(max_length=200) zip_code = models.CharField(max_length=100) city = models.CharField(max_length=100) country = models.CharField(max_length=100) booking_object = ( ('Upper Apartment', 'Upper Apartment'), ('Lower Apartment', 'Lower Apartment'), ('Whole House', 'Whole House'), ) booking_item = models.CharField(choices=booking_object) arrival_date = models.DateField() departure_date = models.DateField() guest_nationality = ( ('German', 'German'), ('Other', 'Other'), ) nationality = models.CharField(choices=guest_nationality) passport_number = models.CharField(max_length=100, blank=True, null=True) animals = models.BooleanField(blank=True, null=True) message = models.TextField(max_length=1000) class Meta: ordering=['last_name','first_name'] def __str__(self): return f'Booking: {self.last_name}, {self.first_name}' forms.py from django.forms import forms, ModelForm from .models import Booking class BookingForm(ModelForm): class Meta: model … -
Django add to cart not working with product variation
I am building an e-commerce website where both products with variations and products without variation can be sold. So I have a cart view which adds a product to a cart and creates a cart instance, but it is not working now that I have modified it for products with variation. So if a product has variations, eg colors and sizes, users can select the variations, eg red and XL, and the selected variations show up on this section of product_detail.html: <div id="selected-variations" class="mt-5"> <div class="text-title">Selected Variation:</div> <div class="mt-3"> <span id="selected-color">Color: None</span> / <span id="selected-size">Size: None</span> </div> </div> Now what I want is to take those selected variation values from there and then add the product to the cart with the selected values. But in doing so, the js is not working, I think my cart view logic is fine. It all seemed very easy in the beginning, since I am literally printing the selected variation values from the user above, just was supposed to take those values and create a cart instance with them. But now for some reason my main.js code won't accept it. Is there any way to fix this? My models.py: class Business(models.Model): BUSINESS_TYPE_CHOICES = [ … -
Django - Aggregate of an Aggregation
I am working with DRF and am having issues defining my queryset for use in my view class. Suppose I have three models like so: class ExchangeRate(...): date = models.DateField(...) rate = models.DecimalField(...) from_currency = models.CharField(...) to_currency = models.CharField(...) class Transaction(...): amount = models.DecimalField(...) currency = models.CharField(...) group = models.ForeignKey("TransactionGroup", ...) class TransactionGroup(...): ... I want to create a queryset on the TransactionGroup level with the following: for each Transaction in the transaction group, add an annotated field converted_amount that multiplies the amount by the rate on the ExchangeRate instance where the currency matches the to_currency respectively then sum up the converted_amount for each Transaction and set that on the TransactionGroup level as the annotated field converted_amount_sum An example json response for TransactionGroup using this desired queryset (assumes the exchange_rate.rate = 0.5: [ { "id": 1, "converted_amount_sum": 2000, "transactions": [ { "id": 1, "amount": 1000, "converted_amount": 500, "currency": "USD", }, { "id": 2, "amount": 3000, "converted_amount": 1500, "currency": "USD", }, }, ... ] I can get the annotations to work properly on the Transaction model - but trying to then sum them up again on the TransactionGroup level throws the error: FieldError: Cannot compute Sum('converted_amount'), `converted_amount` is an aggregate My … -
How can I E2E test celery task called in async function?
Although not recommended by the celery documentation CELERY_TASK_ALWAYS_EAGER = True option allows E2E testing where celery task is called inside a function with delay() method. async def wanna_test_function_e2e(): #.... logic dummy_task.delay() #<- modifies some db value The problem is when i mix sync function (for django transaction) in celery task: @celery_app.task # type: ignore[misc] def dummy_task() -> None: with tranaction.atomic(): User.object.get(id=1) <- note that this is sync operation The task runs fine locally, the issue is with the testing. With EAGER option, I am unable to run test: raise SynchronousOnlyOperation(message) kombu.exceptions.DecodeError: You cannot call this from an async context - use a thread or sync_to_async. As EAGER option forces celery to run in a main process but it was invoked in async context. If I follow Celery's guide and use pytest-celery without EAGER option: @pytest.fixture(scope='session') def celery_config(): return { 'broker_url': "memory://", 'result_backend': 'rpc', } @pytest.fixture(scope="session", autouse=True) def celery_register_tasks( celery_session_app, celery_session_worker, socket_enabled ) -> None: celery_session_app.register_task(dummy_task) Now there is huge problem: async def test_dummy_task( self, celery_session_worker, celery_register_tasks, ) -> None: ... import asyncio await asyncio.sleep(10) <- without this the remaining test can run before task runs user = await User.objects.aget(id=1) assert user.is_modified <- without sleep this fails! even worse if I … -
Django-MySQL remote connection trouble
I was trying to connect my app with a remote MySQL database (usually obtained from our hosting through cPanel) and encountered this error. Can anyone help me out? I'm stuck here. Does Django really allow remote MySQL connections? (https://i.sstatic.net/M6KXToRp.jpg) I tried the official documentation for the Django-MySQL connection, but it didn't work for me. I couldn't find any suitable tutorials on YouTube either. -
Adding frequently used context objects to a view in Django
I have several Django apps within a single project. What I am running into is that I often tend to add the same object(s) to the render call that renders a particular screen. In this example below, I have a view that displays a form with a dropdown of categories that you can choose from. Now I need to add these categories every time I display the create.html page. This is simplified, but imagine I have 6 more views that could potentially show the create.html page, all of them have to remember to add the categories array. def createmeeting(request): if request.method == "POST": categories = MeetingCategory.objects.all() // Some error checking, omitted for this example error_msg = "invalid content" if error_msg: return render(request, "meetings/create.html", { "categories": categories, "error_msg": error_msg, }) else: // Create the meeting here, omitted for this example return redirect("/meetings/profile/") else: categories = MeetingCategory.objects.all() return render(request, "meetings/create.html", { "categories": categories }) Is there a better way of handling cases like this? -
Deploying Wagtail on Ionos VPS
I have an Ionos VPS and have a Wagtail site installed on it. It is accessible when I use the command python manage.py runserver (ip address of VPS):8000 and it displays correctly. However, I tried to deploy it but I keep running in to issues. I used nginx and got a 502 error and the logs show that ModuleNotFound error: module 'wagtail' not found and couldn't get any further. I have now reinstalled wagtail on a freshly made image on my VPS and not sure what to do next. -
Why is DATA_UPLOAD_MAX_MEMORY_SIZE not working? Django, TinyMCE text field
I have a DATA_UPLOAD_MAX_MEMORY_SIZE = 209_715_200 FILE_UPLOAD_MAX_MEMORY_SIZE = 209_715_200 in settings. However, when im trying to add 5 images in a tinymce text field (the total weight of the images is > 2.5 mb) i'm getting error: Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. How could i fix it? settings.py Django settings for mainApp project. Generated by 'django-admin startproject' using Django 5.0.3. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from pathlib import Path from django.contrib import staticfiles from django.urls import reverse_lazy from dotenv import load_dotenv, find_dotenv import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ load_dotenv(find_dotenv()) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ["SECRET_KEY"] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["olimpiadnik.pythonanywhere.com", "127.0.0.1"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'tinymce', 'mainApp', 'portfolio', ] TINYMCE_DEFAULT_CONFIG = { 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'silver', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking … -
How to implement reload-on-rss is not available in mod_wsgi?
In uwsgi, reload-on-rss helps to prevent the Django server from running into OOM. How do you implement reload-on-rss on mod_wsgi in Django? I would like the Django server to reload after a certain memory limit. -
Django: models.Model.objects.filter(pk) return nothing [closed]
I started learn Django framework. Following the official tutorial I have model Question that is derived from django.db.models.Model After all migrations, In views.py I created function called detail that is supposed to show me question by quest_id here is the code def detail(request, quest_id): by_id = Question.objects.filter(id=quest_id).first() by_index = Question.objects.all()[quest_id] response = f"Via filter \"{by_id}\" Via index \"{by_index}\"" return HttpResponse(response) In urls.py I added corresponding path to urlpatterns Next I added two records of Question to my database, but when I tried to Question.objects.filter(quest_id).first(), I've always get None even if I have Question with id=quest_id Here Is result of detail for id quest_id -
Index file shown but not the live website
enter image description hereI have deployed my website in the cpanel of namecheap but it shows the following problem in the given image. How can i fix it? I tried to change the .htacces file but it still did not work, please help me because i cannot fix this porblem by myself. -
django modelForm : dynamically adjust field according to related field
I've been working on a hospital project exercice and am wondering how to render a given field (model "doctor") according to a speciality selection: user has to select first a medical speciality and according to that one, the doctor's list will be dynamically updated. How can I design my modelForm to achieve that goal? Do I need some javascript embedded in the template file? Here is the related code in my django project: # models.py class Speciality(models.Model): specialite_id = models.AutoField(primary_key=True) nom = models.CharField(max_length=50, unique=True, verbose_name="Spécialité") def __str__(self): return f"{self.nom}" class Doctor(CustomUser): medecin_id = models.AutoField(primary_key=True) matricule_medecin = models.CharField(max_length=50, unique=True) specialite = models.ForeignKey(Specialite, on_delete=models.CASCADE) admin = models.ForeignKey(Administrateur, on_delete=models.SET_NULL, null=Tru e, blank=True) def __str__(self): return f"Dr {self.nom} {self.prenom}, spécialité : {self.specialite}" # forms.py class CreateSejour(forms.ModelForm): class Meta: model = Sejour fields = '__all__' widgets = {'date_entree': forms.SelectDateWidget(years=range(2015, 2025)), 'date_sortie': forms.SelectDateWidget(years=range(2015, 2025)), 'motif': forms.Textarea()} I don't see how to tackle this situation : do I have to implement some logic inside the modelForm or in my view? Thanks for your help. De716 Actually i'm stuck to that stage, my django experience doesn't allow me to address this and I have no experience in javascript -
Why do I have a Flutter web CORS issue despite having set CORS in django backend
I'm developing a Flutter web application that needs to make requests to a Django backend. However, I'm encountering a CORS error when I try to make a request. The error message is: Access to XMLHttpRequest at '<API_URL>' from origin 'http://localhost:63730' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. I've already set up CORS in my Django settings as follows: INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL = True Despite this, I'm still getting the same CORS error. Interestingly, I have other applications built with React and Vue that are able to make requests to the same Django backend without encountering any CORS errors. I'm not sure why my Flutter web application is encountering CORS errors while my React and Vue applications are not. Any help would be greatly appreciated. -
my Django registration page redirect isn't working
i'm trying to make a registration page for my Django project. When i compile the registration form it gives me the error in the image because it tries to go to this path (he doubles users/register): localhost/users/register/users/register/. How can i fix it? this is my code: Error image: users/view.py: def register_view(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('homepage') else: form = UserCreationForm() return render(request, "users/register.html", {"form": form}) users/urls.py: urlpatterns = [ path('register/', views.register_view, name="register"), ] main/views.py: def homepage(request): return render(request, 'homepage.html') main/urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', views.homepage, name="homepage"), path('music/', include('music.urls')), path('users/', include('users.urls')), ] -
Kubernetes Persistent Volume not shared when uploading a file with Django and Nginx
I created 2 persistant volumes, one for static files and other for media files. The static files one works just fine, nginx serves the data. For media volume, nginx does not see the uploaded file and the volume content does not update. The nginx conf is fine. The location works but volume does not contain the uploaded file. This is my media pv and pvc: apiVersion: v1 kind: PersistentVolume metadata: name: mediafiles-pv spec: storageClassName: manual capacity: storage: 1Gi accessModes: - ReadWriteMany hostPath: path: "/usr/src/app/backend/media" apiVersion: v1 kind: PersistentVolumeClaim metadata: name: mediafiles-pvc namespace: default spec: storageClassName: manual accessModes: - ReadWriteMany resources: requests: storage: 1Gi volumeName: mediafiles-pv This is my deployment for backend (django): apiVersion: apps/v1 kind: Deployment metadata: name: backend labels: app: backend spec: replicas: 1 selector: matchLabels: app: backend template: metadata: labels: app: backend spec: volumes: - name: staticfiles persistentVolumeClaim: claimName: staticfiles-pvc - name: mediafiles persistentVolumeClaim: claimName: mediafiles-pvc containers: - name: backend image: loopedupl/backend:latest imagePullPolicy: Always ports: - containerPort: 8000 volumeMounts: - name: staticfiles mountPath: "/usr/src/app/backend/static" - name: mediafiles mountPath: "/usr/src/app/backend/media" and for nginx: apiVersion: apps/v1 kind: Deployment metadata: name: nginx labels: app: nginx spec: replicas: 1 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: volumes: - name: … -
Pass requests from host to container with domain socket
I have uwsgi running on a docker container. Nginx running on host. Current setup: ;uwsgi.ini http-socket=:8080 With docker, I've forwarded the host's 8080 port to containers 8080 port. Nginx is configured like server { listen 443 ssl http2; server_name domain.example.com; location / { proxy_pass http://127.0.0.1:8080; } } This works fine, only problem: my port 8080 is exposed and I can directly request the port on the public IP. I should be able to use domain sockets to mitigate this, but I don't know how the set up would look like. Here's my half attempt: ; uwsgi.ini in container socket=/path/uwsgi.sock # nginx on host upstream prod_server { server unix:///path/uwsgi.sock; } server { listen 443 ssl http2; server_name example.domain.com; location { uwsgi_pass pror_server; } } Since nginx is in host, it will look for the path on host server, is adding the socket as a volume the right way to go? Is there another best practice? How would you recommend the setup? Thank you. -
I can't upload a file
I am writing an application in django, drf, I use drf_spectacular for documentation, the problem is downloading the file through the documentation, I do not need to process the file or store it, I just want to upload it and send it to another service. class PFX_key(serializers.Serializer): file = serializers.FileField() pin = serializers.IntegerField(required=False) description = serializers.CharField(required=False) @extend_schema(request=serializers.PFX_key) @action(detail=False, methods=['post'], parser_classes=[MultiPartParser,], serializer_class=serializers.PFX_key) def load_pfx_key(self, request: Request) -> Response: serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) try: datatools.send_pfx_key(serializer.validated_data, self.request.user.username) except Exception as ex: raise ex return Response() The logic is fully working, all I need is the ability to upload files via drf_spectacular so that the fronts can work with it. I've tried adding different parameters, one of them even seems to fit the needs: OpenApiTypes.BINARY, but I get an error Please correct the following validation errors and try again. For 'file': Value must be a string. -
Django & React native, I can't login back after I logged out
const handleLogin = () => { axios.post('https://8d16-103-62-155-152.ngrok-free.app/api/auth/mobile-login/', { username, password }) .then(response => { // Clear existing user data AsyncStorage.removeItem('username'); // Assuming you stored the username in AsyncStorage // Set new username and navigate to Main screen setUsername(username); navigation.navigate('Main'); }) .catch(error => { Alert.alert('Login Failed', 'Invalid username or password'); }); }; THIS IS MY ERROR : Forbidden: /api/auth/mobile-login/ [29/May/2024 13:38:49] "POST /api/auth/mobile-login/ HTTP/1.1" 403 58 I can log in once but after I click logout I can't login again I think something is preventing it to access on my django after logging out. I just used navagation for my logout function -
What are the most common mistakes devs make? what can i learn from them? [closed]
I have joined a company as an intern. Recently, the manager told me to use best practices for coding etc.I wanna know what are professional best practices. I searched the net but couldn't find a satisfactory answer. ..... C'mon stack-overflow genies. -
How Do I Fix the errors in Django Models?
I am trying to create models in Django, but when I go to the admin page and click into the models, it gives me an error. Please see my code in python below. I also had problems when I was trying to make migrations, but it worked in the end, and in my admin panel. I could see the two models I created, but when I click into any of them, I got an error page. models.py from django.db import models from datetime import datetime import uuid # Create your models here. class ProductType(models.Model): Type_Name = models.CharField(max_length=200) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.Type_Name class ProductItem(models.Model): product_title = models.CharField(max_length=500, default="Product Name") product_type = models.ForeignKey('ProductType', on_delete=models.CASCADE) product_size = models.CharField(max_length=500, default="Product Size") product_finish = models.CharField(max_length=500, default="Product Finish") date = models.DateField(default=datetime.now, blank=False) quantity = models.IntegerField(default=0) unit_cost = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) unit_price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) reorder_quantity = models.IntegerField(default=0) reorder_date = models.DateField(default=datetime.now, blank=False) image = models.ImageField(null=True, blank=True, default='404-img.png') id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.product_title admin.py from django.contrib import admin from .models import ProductItem, ProductType # Register your models here. admin.site.register(ProductItem) admin.site.register(ProductType) models.py from django.db import models from datetime import datetime import uuid # Create your models here. … -
Extracting text from PDF after uploading (Django app on AWS)
@login_required(login_url="/login/") def upload_view(request): posts = Temp.objects.all() common_tags = Temp.tags.most_common() if request.method == "POST": form = TempForm(request.POST, request.FILES, initial={"user": request.user}) if form.is_valid(): newpost = form.save(commit=False) newpost.slug = slugify(newpost.title) unique_slug = newpost.slug num = 1 while Temp.objects.filter(slug=unique_slug).exists(): unique_slug = "{}-{}".format(newpost.slug, num) num += 1 newpost.slug = unique_slug newpost.user = request.user # Process the document before saving extracted_text = process_document( request.FILES["file_upload"], newpost.language ) # Save the post and the extracted text newpost.ocr_text = extracted_text newpost.save() # Save the file first form.save_m2m() notify_users_about_new_post(form) messages.success(request, "Your Post has been uploaded successfully.") else: messages.warning(request, "Upload unsuccessful. Please try again.") else: form = TempForm() context = { "posts": posts, "common_tags": common_tags, "form": form, } return render(request, "upload_file.html", context) Currently, users can upload files and it will be stored in S3. I want to extract the content from the file and store it in the mySQL database. I tried different ways and they all failed. I used the following code. It works when I am testing it locally, but fail to download in Production. urllib.request.urlretrieve( [link to S3 storage, where the document can be viewed publicly], "temp.pdf", ) I used boto3. It works when I am testing it locally, but fail to download in Production. import boto3 # … -
How to Write Tests for Password Recovery in Django?
Could you please recommend where to find tutorial examples on how to write tests for authentication in Django, especially for password recovery via email and ensuring that the password reset link is valid only once? I want to add testing to my project, but I lack experience with testing password resets. There are some bugs, and the status code in some places is not what is expected according to the unit tests. The link remains valid after setting a new password, although it stops being valid after setting a new password during manual testing. I would like to see examples of how password recovery is tested in a standard project. ChatGPT is not helping, absolutely useless idiot on this matter. -
Changing from abstractuser to abstractbaseuser mid project to remove username field
I created a project initially with abstractuser so I could add additional fields to users profiles as well as set session variables during user login. Ive realised that abstractuser still has a need for the username field even though I have set authentication field to be email. I have tried setting username = None in the model but it throws an error during makemigrations saying unknown field 'username' specified for CustomUser. If I change the base class from abstract user to abstractbaseuser I still get the error mentioned above when makemigrations. code below, help would be very appreciated. models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') user = self.model(email=self.normalize_email(email), **extra_fields,) user.set_password(password) user.save(using=self._db) print("user save from UserManager.create_user method") return user def create_superuser(self, email, password=None, **extra_fields): user = self.create_user(email, password=password, **extra_fields,) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(unique=True, db_index=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) phone = models.IntegerField(null=False, blank=False) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['phone'] def __str__(self): return self.email …