Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django test case is showing errors because of moesif
I do not want to push actual api key. When I replaced the actual key on code base this error is generated E vcr.errors.CannotOverwriteExistingCassetteException: Can't overwrite existing cassette ('/app/armor_backend/users/tests/recordings/test_user_with_empty_code.yaml') in your current record mode ('once'). E No match for the request (<Request (GET) https://api.moesif.net/v1/config>) was found. E Found 1 similar requests with 0 different matcher(s) : E E 1 - (<Request (GET) https://api.moesif.net/v1/config>). E Matchers succeeded : ['uri', 'method'] E Matchers failed : /usr/local/lib/python3.10/site-packages/vcr/stubs/__init__.py:231: CannotOverwriteExistingCassetteException ----------------------------- Captured stdout call ----------------------------- Unauthorized access getting application configuration. Please check your Appplication Id. ------------------------------ Captured log call ------------------------------- ERROR moesifapi.controllers.base_controller:base_controller.py:41 HTTP Response not ok [response status: 401 | header: {'Connection': 'keep-alive', 'Content-Length': '153', 'Content-Type': 'application/json', 'Date': 'Wed, 09 Feb 2022 06:18:37 GMT', 'content-encoding': 'gzip', 'vary': 'Origin,Accept-Encoding'} | raw_body: {"moesif_error":{"code":"auth_error","msg":"X-Moesif-Application-Id request header is invalid. Please get a valid Moesif Collector Application Id from your Moesif account"}}] I skipped all outgoing and incoming calls from logging for testing. But still moesif is being called somehow. Here is my test case @vcr.use_cassette def test_user_with_invalid_code( self, client, use_invalid_code ): response = client.post( self.endpoint, content_type="application/json", data=json.dumps(use_invalid_code), ) assert response.status_code == status.HTTP_400_BAD_REQUEST I tried to skip logging all the incoming and outgoing calls but no luck -
Best way to share audio files on my website
I am developing a music-sharing app using Django and React. My problem is that on the home page, I could very well have up to 100 different songs, with each audio file being around 40 MB. This of course causes performance issues, and I don't know how to solve them. At the moment I am using Google Cloud storage for hosting audio files, should I switch to something else? Is the issue even in Google Cloud? I am new to handling a growing amount of data on the website so all suggestions are welcome. Thank you! -
Data not being saved to the Profile model
When attempting to register a new user through the registration form, the phone number (phone_number) and library ID (library_id) fields are not being saved to the database. Despite these fields being included in the registration form and rendered correctly, the submitted values are not written the database. views.py def user_register(request): userIsAuthenticated = False if request.user.is_authenticated: username1 = request.user.username userIsAuthenticated = True else: username1 = "N/A" userIsAuthenticated = False if request.method == 'GET': form = RegisterForm() return render(request, "register.html", {"form":form, "username": username1, "userIsAuthenticated": userIsAuthenticated}) if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.save() login(request, user) return render(request, "register-success.html") else: return render(request, 'register.html', {"form":form, "username": username1, "userIsAuthenticated": userIsAuthenticated}) forms.py class RegisterForm(UserCreationForm): first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) library_id = forms.CharField(max_length=100) phone_number = forms.CharField(max_length=100) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2'] def save(self, commit=True): user = super().save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: Profile.objects.create( user=user, phone_number=self.cleaned_data['phone_number'], library_id=self.cleaned_data['library_id'] ) user.save() return user models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(max_length=100) library_id = models.CharField(max_length=100) def __str__(self): return self.user.username signals.py @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() More details … -
How to Write a Code When Software are Close In One Year
kaise hum apne software ko diye gye time line me bnd kr skte hai kya coding hogi and kya process hoga ?? kaise coding and impliment krna hoga ki hum apna software one year me bnd kr ske python and django faremwork ko code likhna hai -
How to set image size in megabytes for "factroy.django.ImageField" ? e.g "my_img = ImageField(size=30)"
I have model Shop class Shop(models.Model): logo = models.ImageField("Logo", upload_to="logos/", blank=True, null=True) def save(self, *args, **kwargs): # condense logo if it's more than 30mb if self.logo: # instance = super().save(*args, **kwargs) logo_path = self.logo.path logo = Image.open(logo_path) logo_size = os.path.getsize(logo_path) # in bytes thirty_mb = 30 * 1024 * 1024 while logo_size > thirty_mb: logo = logo.convert("RGB") logo.save( logo_path, quality=60, optimize=True, format="JPEG", ) return instance And I have this factory for Shop model import factory from api.v1.apps.shops.models.shops import Shop from factory.django import DjangoModelFactory, ImageField class ShopModelFactory(DjangoModelFactory): class Meta: model = Shop logo = ImageField() # what I have logo = ImageField(size_in_megabytes=30) # what I want what I exactly want to do is tell to ImageField generate img with given size I looked at documentaino but find nothing https://factoryboy.readthedocs.io/en/stable/orms.html#factory.django.ImageField -
Django Multi-Tenant App shows site cannot be reached when using tenant
I am making a login system using django with multitenant. http://chatbot.com:8000/login/ points to the login page. I want http://google.chatbot.com:8000/login/ to point to a login page specific to google.chatbot.com users. Structure: app: app login Do i need to make changes in login views.py or login urls.py or app urls.py or all of them? i am new to django and mutli tenant. here is the github code: github code link I watched this video but couldn't figure it out -
Error while performing py manage.py runserver in Django
while executing the Django project it displays the below error message py .\manage.py runserver Traceback (most recent call last): File ".\manage.py", line 22, in <module> main() File ".\manage.py", line 14, in main "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? python version is 3.12 Django version is 5 the path of python is configured in the environment variables i tried uninstalling and reinstalling the django. -
Manytomanyfield mot saving data
I have an e-commerce store project on django which has an custom user model: from django.contrib.auth.models import AbstractUser from django.db import models from .managers import UserManager from upload.models import Product from django.conf import settings class CustomUser(AbstractUser): previous_orders = models.ManyToManyField(Product,related_name = 'previous_orders') cart = models.ManyToManyField(Product,related_name = 'cart') address = models.TextField(default='Address not provided') email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects=UserManager() I am trying to add a product in the cart field with following view def product_page(request,url): if request.method == 'POST': product=Product.objects.get(title=url) if request.user.is_authenticated: usr = CustomUser.objects.get(email=request.user.email) usr.save() usr.cart.add(product) usr.save() else: product=Product.objects.get(title=url) return render(request,'product_view.html',{'product':product}) But the field remains empty for some reason. -
Django 4.2: Apply sorting Child Table key based on foreignkey
pelase see bleow model defination class Product(models.Model): name = models.CharField(max_length=200, blank=True, null=True) prduct_type = models.CharField(max_length=30, blank=True, null=True) class ProductRateInfo(models.Model): product= models.ForeignKey(Product, on_delete=models.CASCADE, related_name='rate_info') season_start = models.DateField(blank=True, null=True) season_end = models.DateField(blank=True, null=True) sbr_rate = models.FloatField(default=0) While feteching the product we need apply sorting ProductRateInfo.sbr_rate column Tried below method but its not working product_qs = Product.object.fitler(prduct_type='demotest').prefetch_related('rate_info') Thanks in advance -
Django "<!DOCTYPE "... is not valid JSON quickview modal
I am trying to build an e-commerce website where I want users to be able to see a product quickview a product without going to the product_detail page. So I want to dynamically load all product details on a quickview modal. Can anyone help me with these errors? Thanks in advance! Okay so my models.py: class Business(models.Model): BUSINESS_TYPE_CHOICES = [ ('product', 'Product Business'), ('service', 'Service Business'), ] seller = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name='business') business_name = models.CharField(max_length=100) description = models.TextField() business_slug = models.SlugField(unique=True, blank=True) business_type = models.CharField(max_length=20, choices=BUSINESS_TYPE_CHOICES) countries = models.ManyToManyField(Country) states = models.ManyToManyField(State) # Add this line address = models.CharField(max_length=200) phone = models.CharField(max_length=20) website = models.URLField(blank=True, null=True) email = models.EmailField(blank=True, null=True) profile_picture = models.ImageField(upload_to='business_profiles/', blank=True, null=True) banner_image = models.ImageField(upload_to='business_banners/', blank=True, null=True) is_featured = models.BooleanField(default=False) def __str__(self): return self.business_name def save(self, *args, **kwargs): if not self.business_slug: self.business_slug = slugify(self.business_name) super().save(*args, **kwargs) class OpeningHour(models.Model): DAY_CHOICES = [ ('monday', 'Monday'), ('tuesday', 'Tuesday'), ('wednesday', 'Wednesday'), ('thursday', 'Thursday'), ('friday', 'Friday'), ('saturday', 'Saturday'), ('sunday', 'Sunday'), ('public_holiday', 'Public Holiday'), ] business = models.ForeignKey(Business, on_delete=models.CASCADE, related_name='opening_hours') day = models.CharField(max_length=20, choices=DAY_CHOICES) is_closed = models.BooleanField(default=False) opening_time = models.TimeField(null=True, blank=True) closing_time = models.TimeField(null=True, blank=True) def __str__(self): if self.is_closed: return f"{self.business.business_name} - {self.get_day_display()} (Closed)" else: return f"{self.business.business_name} - {self.get_day_display()} ({self.opening_time} - {self.closing_time})" class … -
ValueError: The view test_app.views.sse_stream didn't return an HttpResponse object. It returned an unawaited coroutine instead
I' ll post in this section the full error, since the "title" section has a characters size constraint. Here it is: ValueError: The view test_app.views.sse_stream didn't return an HttpResponse object. It returned an unawaited coroutine instead. You may need to add an 'await' into your view. I am trying to use SSE ( server sent event ) to make a real time update of some data from my database (i am using the Django framework ). It won't work as i get the prewies mentioned error. No matter what i have tried, i still get the same error. Here is my view, and the function that i use to fetch data from the database: ` @sync_to_async def retrievenotes(id_request): #logging.logger.debug(f"Retrieving notes for id_request: {id_request}") notes = Note.objects.filter(random_id=id_request).order_by('-created_at') return list(notes) @csrf_exempt async def sse_stream(request, username): """ Sends server-sent events to the client. """ #logging.logger.debug("Starting sse_stream") async def event_stream(): while True: # Call the sync function asynchronously notes = await retrievenote('wCgS8VVO0UY8fb4mAv0A') notes_str = "".join([f"Note created at: {note.created_at}, Note text: {note.text}<br>" for note in notes]) yield await f"data: {notes_str}\n\n" await asyncio.sleep(1) # Convert the async generator to an async iterator async def async_iterator_wrapper(async_gen): async for item in async_gen: yield await item return StreamingHttpResponse(async_iterator_wrapper(event_stream()), content_type='text/event-stream') … -
image reflection shadow positioning
I'm moving BG using rembg. Then I'm making the reflection of the car. But the problem is that I can't keep the four frames of reflection parallel with the four frames of the original car, I want to make picture number 2 like picture 1 below. image 1 image2 -
MiddlewareMixin.__init__() missing 1 required positional argument: 'get_response'
I have created a custom django middleware and decorator to authenticate the RESTful API that I am developing. Here is the code of the middleware that I have developed: # myproject/middleware.py import jwt from django.conf import settings from django.http import JsonResponse from users.models import User class JWTAuthenticationMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): excluded_paths = ['/auth/users/register/', '/auth/users/login/'] if any(request.path.startswith(path) for path in excluded_paths): return self.get_response(request) # Skip JWT validation for excluded paths token = request.COOKIES.get('jwt') if token: try: decoded = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"]) user = User.objects.get(id=decoded['id']) request.user = user except (jwt.ExpiredSignatureError, jwt.InvalidTokenError, User.DoesNotExist): return JsonResponse({'error': 'Invalid or expired token'}, status=401) else: request.user = None return self.get_response(request) This is the code for the decorator: # users/utils.py from functools import wraps from django.http import JsonResponse from django.middleware.csrf import CsrfViewMiddleware def token_required(view_func): @wraps(view_func) def _wrapped_view(view_class_instance, request, *args, **kwargs): csrf_middleware = CsrfViewMiddleware() # Check CSRF token csrf_error = csrf_middleware.process_view(request, None, (), {}) if csrf_error: return csrf_error if not request.user: return JsonResponse({'error': 'Token is missing or invalid'}, status=401) return view_func(view_class_instance, request, *args, **kwargs) return _wrapped_view Here is one of the views that are giving the error: from rest_framework.views import APIView from users.serializers import UserSerializer from rest_framework.response import Response from users.models import User … -
My Django project doesn't work: nothing beyond "Notebook started successfully!" appears on the page
I havea Django in Python like here, but I'm unable to run it; nothing beyond the 2nd snippet below occurs. -
ValidationError (Django)
hello am designing a system with feedback function that capture only user_id however am facing an error a validationerror as shown below enter image description here here is my model.py from django.db import models from django.conf import settings User = settings.AUTH_USER_MODEL class FeedbackMessage(models.Model): id = models.AutoField(primary_key=True) user_id = models.ForeignKey(User, on_delete=models.CASCADE) feedback = models.TextField() feedback_reply = models.TextField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() view.py # feedback/views.py from django.shortcuts import render, redirect from django.contrib import messages from accounts.models import User def feedback_view(request): user_obj = User.objects.get(is_superuser=request.user.id) feedback_data = FeedBackUser.objects.filter(user_id=user_obj) context = { "feedback_data": feedback_data } return render(request, "staff_template/staff_feedback_template.html", context) @property def feedback_save(request): if request.method != "POST": messages.error(request, "Invalid Method.") return redirect('feedback') else: feedback = request.POST.get('feedback_message') staff_obj = User.objects.get(is_superuser=request.user.id) try: add_feedback = FeedBack(user_id=user_obj, feedback=feedback, feedback_reply="") add_feedback.save() messages.success(request, "Feedback Sent.") return redirect('feedback') except: messages.error(request, "Failed to Send Feedback.") return redirect('feedback') i need to capture only the user id when they submit a feedback as well as i need to filter out foul words(cursing language) on each submitted feedback if any occurs -
ERR_TOO_MANY_REDIRECTS after setting up django with gunicorn and nginx
I am developing some website, until now I was using python manage.py runserver to access it, it was running fine. I decided to make it production-ready and set up gunicorn, and I am getting redirect loop. Considering that it works fine under runserver, I guess there is a problem with nginx configuration, but what am I doing wrong? server { listen 80; server_name example.com; location /static/ { alias /path/to/project; } location / { proxy_pass http://unix:/path/to/project/run/app.sock; proxy_redirect off; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_read_timeout 1000000; } } Tried few different nginx configuration but to no avail. Even disabled all views and urls in django and it does not make any difference, so it has to be nginx, right? Gunicorn is running fine without any errors too. And I am not running any redirects in my django project at all, not in views and not in urls. It's a simple website. -
Redirect/confirm not working for django web app registration
Working on the Corey Schafer django tutorials, and I've built a registration page that is supposed to redirect back to the home page (newsfeed) and display a confirmation message. However I don't know whether the issue is just in the redirection or where it is. def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('') else: form = UserCreationForm() return render(request, 'users/register.html', {'form': form}) {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %} {% extends "newsfeed/base.html" %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset> <legend class="border-bottom mb-4">Join Today</legend> {{ form.as_p }} </fieldset> <div class="form-group"> <buttom class="btn btn-outline-info" type="submit">Sign Up</buttom> </div> </form> <div class="border-top pt=3"> <small class="text-muted"> Already have an account? <a class="ml-2" href="#">Sign In</a> </small> </div> </div> {% endblock content %} I think that those are all of the relevant code snippets I've checked all of my paths and I believe that they are correct. My real issue is figuring out where the issue is as there is no syntax error. -
Why factory class creates more than one django model?
I created factory class "ShopModelFactory" vie factory-boy package which should return django model "Shop", additionally the model's fields feeling up via faker, than I write test via pytest, but I'm getting this error after running pytest in django project -> django.db.utils.IntegrityError: duplicate key value violates unique constraint "shops_shop_pkey" DETAIL: Key (id)=(cd84e095-7d1a-41fc-adb3-7f5db5e07d50) already exists. ========================================================================== short test summary info =========================================================================== FAILED tests/models/test_shop.py::test_shop_creation - django.db.utils.IntegrityError: duplicate key value violates unique constraint "shops_shop_pkey" BUT my db is empty and additionally I'm deleting all records before my model class Shop(TimedBaseModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) first_name = models.CharField("First Name", max_length=20) last_name = models.CharField("Last Name", max_length=20) email = models.EmailField("Email", unique=True) phone = PhoneNumberField( "Phone Number", unique=True, ) shop_name = models.CharField("Shop Name", max_length=50, unique=True) shop_url = models.URLField("Shop URL", unique=True) logo = models.ImageField("Logo", upload_to="logos/", blank=True, null=True) banner = models.ImageField( "Banner", upload_to="banners/", blank=True, null=True, ) street1 = models.CharField("Street 1", max_length=50) street2 = models.CharField("Street 2", max_length=50, blank=True) city = models.CharField("Town / City", max_length=100) zip_code = models.CharField("Zip Code", max_length=10) country = CountryField("Country", blank_label="(select country)") state = models.CharField("State", max_length=100, blank=True, default="") password = models.CharField("Password") confirm_password = models.CharField("Confirm Password") is_visible = models.BooleanField( verbose_name="Is the shop visible in the shops catalog", default=True, ) class Meta: verbose_name = "Խանութ" verbose_name_plural = "Խանութներ" app_label = … -
Getting AttributeError for a function that defined within the same file
I have a model below and I want to add a custom filesize validator for the file field. #../MOU.py def validate_file_size(value): limit = 1 * 1024 * 1024 # 1 MB if value.size > limit: raise ValidationError(_('...') % { 'limit': filesizeformat(limit), 'size': filesizeformat(value.size), }) class MOU(models.Model): file = models.FileField( upload_to='mou/', null=True, validators=[ FileExtensionValidator(allowed_extensions=['doc', 'docx', 'pdf']), validate_file_size ] ) On doing migrate I got AttributeError: type object 'MOU' has no attribute 'validate_file_size''. I'm confused as to why I received this error, any pointers is appreciated. I can remove the error by creating a separate file for the validator but I want to keep things tidy by having the validators in the same file as the model. -
How to implement Many to Many relationship between users and comments?
all i have a table user , post , comments in django Here i want to implement many to many relationship among them if possible please help me here class Post(models.Model): title = models.CharField(max_length=50) desc = models.TextField(max_length=200) views = models.IntegerField(default=0) answers = models.IntegerField(default=0) likes = models.IntegerField(default=0) view_status = models.BooleanField(default=False) like_status = models.BooleanField(default=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='users') post_image = models.ImageField(upload_to='upload/images') def __str__(self): return str(self.id) def genarate_comment_id(): last_comment_id = Comments.objects.all().order_by('cmnt_id').last().cmnt_id if last_comment_id: return last_comment_id + 1 return 1001 class Comments(models.Model): cmnt_id = models.IntegerField(primary_key=True,default=genarate_comment_id) comment = models.TextField(max_length=500) pid = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') def __str__(self): return str(self.cmnt_id) i want to maintain each user post and their comments postwise -
ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' in building docker
I'm new to learning docker and django. I've tried to dockerize an existing django project for adding MySQL database and command "runserver". After changing requirements.txt for dependecy conflict, my "runserver" container is running, but I can't see the app on my local. Here is my traceback: `runserver-1 | Exception in thread django-main-thread: runserver-1 | Traceback (most recent call last): runserver-1 | File "/usr/local/lib/python3.11/threading.py", line 1045, in _bootstrap_inner runserver-1 | self.run() runserver-1 | File "/usr/local/lib/python3.11/site-packages/sentry_sdk/integrations/threading.py", line 69, in run runserver-1 | reraise(*_capture_exception()) runserver-1 | File "/usr/local/lib/python3.11/site-packages/sentry_sdk/_compat.py", line 57, in reraise runserver-1 | raise value runserver-1 | File "/usr/local/lib/python3.11/site-packages/sentry_sdk/integrations/threading.py", line 67, in run runserver-1 | return old_run_func(self, *a, **kw) runserver-1 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ runserver-1 | File "/usr/local/lib/python3.11/threading.py", line 982, in run runserver-1 | self._target(*self._args, **self._kwargs) runserver-1 | File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper runserver-1 | fn(*args, **kwargs) runserver-1 | File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run runserver-1 | autoreload.raise_last_exception() runserver-1 | File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception runserver-1 | raise _exception[1] runserver-1 | File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 375, in execute runserver-1 | autoreload.check_errors(django.setup)() runserver-1 | File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper runserver-1 | fn(*args, **kwargs) runserver-1 | File "/usr/local/lib/python3.11/site-packages/django/__init__.py", line 24, in setup runserver-1 | apps.populate(settings.INSTALLED_APPS) runserver-1 | File "/usr/local/lib/python3.11/site-packages/django/apps/registry.py", line 114, in populate runserver-1 … -
Where should data validation happen? - Model or Serializer?
I am working on a project where data validation is crucial. I have noticed tutorials placing validation logic either on the data model itself or within a separate serializer class. This inconsistency is causing confusion. Can you clarify the pros and cons of each approach for data validation, and when it might be better to use one over the other? -
Access admin template [closed]
How to access the admin templates of 2 random projects project2 and project3 in project1. Project done in python django . Created 3 projects in python django and created database. Registered the models in admin of each project. -
Which cultural festivals take place in Abu Dhabi?
Abu Dhabi Festival Dates: Typically held in March and April. Events: Includes performances by international orchestras, ballet companies, and contemporary artists. Venues: Various locations across Abu Dhabi, including Emirates Palace and NYU Abu Dhabi. The Abu Dhabi Festival is one of the most prominent cultural events in the UAE, celebrating music, dance, theatre, and visual arts. It features performances by international and local artists, workshops, and art exhibitions. The festival aims to foster cultural dialogue and exchange, highlighting the city’s role as a cultural hub. -
How do I set a password for a Custom User model inside the Django admin page?
I have defined a custom user model using AbstractBaseUser class. Below is the implementation for your reference. #models.py class UserManager(BaseUserManager): def create_user(self, email, firstname, lastname, contact, password): if not email: raise ValueError('You must provide an email address') if not contact: raise ValueError('You must provide a contact number') email = self.normalize_email(email) user = self.model(email=email, firstname=firstname, lastname=lastname, contact=contact) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, firstname, lastname, contact, password): user = self.create_user(email, firstname, lastname, contact, password) user.is_admin = True user.save(using=self._db) return user class Users(AbstractBaseUser): id = models.AutoField(primary_key=True) firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) contact = models.CharField(max_length=10, unique=True) email = models.EmailField(unique=True) created_at = models.DateTimeField(auto_now_add=True) is_staff = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['firstname', 'lastname', 'contact'] objects = UserManager() def save(self, *args, **kwargs): if not self.firstname or not self.lastname or not self.contact or not self.email or not self.password: raise ValueError('All required fields must be provided') super().save(*args, **kwargs) def __str__(self): return str(self.id) + '. ' + self.firstname + ' ' + self.lastname def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True class Meta: db_table = 'users' verbose_name_plural = 'Users' Everything works well apart from setting password for a new user or updating same for an existing user in Django's native …