Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use OuterRef with _in filter
I've been trying to rework a query and I can't figure out the solution. Here is the setup (oversimplified): An object OrderLine with a quantity and a product, and the product itself with a stock class Product(models.Model): inventory_quantity = models.IntegerField() class OrderLine(models.Model): product_id = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() What I want to do is annotate Product to know the predicted inventory and use it later in the code. I had this code that was working in Django 2: subquery_projected_product = OrderLine.filter( product_id__in=OuterRef('id') ).annotate( qty=ExpressionWrapper( F('product__inventory_quantity') - OrderLine.sum_quantity_sql(), output_field=IntegerField() ) ).values('qty') products_queryset = Product.objects.all(). annotate( nb_projected=Subquery( subquery_projected_product, output_field=IntegerField() ) ) But after Django switch to version 3 I ran into this: https://code.djangoproject.com/ticket/31135. If I understand correctly, this is not the correct way to do the request and it`s not supported anymore. So to put it simple, how can I, for each product, annotate the sum of quantity of related orderlines ? Thanks and have a good day. -
vscode lint extensions problems caused by different extensions
I have a problem in vscode where I have a lot of extensions installed and a lot of problems are reported in the Problems view. I've created a new django python project - but I want to set things up in such a way that the linters I am interested in will output correct problems. So for html files I want to use monosans.djlint. The idea being that all developers working on the project have the recommended extensions installed and any obtrusive ones disabled - but only for the project/workspace. So given a basic html file, I see 14 problems reported - just to highlight the wider problem in my project. templates/test.html <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Test</title> </head> <body> <ul> {% for x in z %} <li>x</li> {% endfor %} </ul> <script type="text/javascript"> const x = {{ data | safe }}; const y = { foo: [{{ count_1 }}, {{ count_2 }}] }; </script> </body> </html> Problems The following screenshot is what I see in vsode: Is it possible to actually identify what extension the problem is from? I can see Microsoft Edge Tools - but not … -
How to provide request to unit tests
How to provide a context request in the serializer? Because i get this error: price = int(self.context.get('request').query_params.get('price', None)) AttributeError: 'NoneType' object has no attribute 'query_params' serializers.py class IpotekaSerializer(serializers.ModelSerializer): payment = serializers.SerializerMethodField() class Meta: model = Ipoteka fields = '__all__' def get_payment(self, obj) -> int: """ :return: Payment value. float | int :rtype: float | int :except ValueError, TypeError: Returns errors if URL parameters were incorrectly provided """ try: price = int(self.context.get('request').query_params.get('price', None)) deposit = int(self.context.get('request').query_params.get('deposit', None)) term = int(self.context.get('request').query_params.get('term', None)) if price == 0 or term == 0: return 0 return self._get_offer_result(price, deposit, term, obj) except (ValueError, TypeError): return 0 test_serializer.py class SerializerTestCase(TestCase): def test_ser(self): # some logic data = IpotekaSerializer([offer_1, offer_2], many=True).data self.assertEqual(data, expected_data) -
F expression conjunction with Sum() is not working as expected
class Order(): pass class OrderItems(): order = models.ForiegnKey(Parent, related_name="items") price = models.DecimalField() quantity = models.DecimalField() class OrderItemSalesTax(): order_item = models.ForiegnKey(OrderItems, related_name="sales_tax") name = models.CharField(max_length=255) percentage = models.DecimalField(max_digits=6, decimal_places=2) class OrderItemDiscount(): name = models.CharField(max_length=255) discount = models.DecimalField(max_digits=6, decimal_places=2) in_percentage = models.BooleanField() I am using this query to calculate the total amount, but also deducting discount and adding Sales tax. Sum(F('items__sales_tax__percentage')) value is 25, and I have verified it, querying the database. Right now I have only One order and two Items and Items and two Sales Taxes and One Discount I am trying to Sum the Sales taxes to apply on discounted price, but I am getting the wrong result results. If I manually write 25 by replacing Sum(F('items__sales_tax__percentage')) then results are correct, is there anything wrong with my query ? Order.objects.filter(customer__zone__distribution=get_user_distribution(request.user.id))\ .annotate( trade_price=Sum(F('items__trade_price') * F('items__quantity')), tax = Sum(F('items__sales_tax__percentage')), discounted_price = F('trade_price') * ExpressionWrapper(0.01 * (100 - Sum(F('items__discount__discount'))), output_field=DecimalField()), total = F('discounted_price') + F('discounted_price') * Sum(F('items__sales_tax__percentage')) / 100 ) -
Django ValueError invalid literal for int() with base 10: ''how i can solve the None type error
in Django forms when i am appending the values , from old_car field getting ValueError invalid literal for int() with base 10: '' the values of new_car and old_car are string and need to convert to integer for further conditions, i know if i remove int will solve the error :). how i can solve that django forms.py car = cleaned_data.get("user", ['AUTO']) if car[0] == 'AUTO': records = [] for i in range(count): new_car = int(self.data.get(f'cardefination_set-{i}-new_car', [])) old_car =int(self.data.get(f'cardefination_set-{i}-old_car', [])) records.append((new_car, old_car)) records = sorted(records, key=lambda record: record[1]) trcae back Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/wm_data_collection/scenario/345/change/ Django Version: 3.1.1 Python Version: 3.7.4 Installed Applications: ['whitenoise.runserver_nostatic', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', 'wm_data_collection', 'masterdata', 'django_admin_listfilter_dropdown', 'grappelli', 'nested_admin', 'django.contrib.admin', 'django_select2', 'users.apps.UsersConfig', 'rest_framework', 'rest_framework.authtoken', 'adminsortable2', 'more_admin_filters', 'debug_toolbar', 'django_extensions'] Installed Middleware: ['debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'wm_data_collection.middleware.DefaultCountryMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "D:\Users\hasanm2\.virtualenvs\wm3330-46yZ5NJh\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Users\hasanm2\.virtualenvs\wm3330-46yZ5NJh\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Users\hasanm2\.virtualenvs\wm3330-46yZ5NJh\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "D:\Users\hasanm2\.virtualenvs\wm3330-46yZ5NJh\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "D:\Users\hasanm2\.virtualenvs\wm3330-46yZ5NJh\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "D:\Users\hasanm2\.virtualenvs\wm3330-46yZ5NJh\lib\site-packages\django\contrib\admin\sites.py", line 233, in … -
Add page loading while scraping process
I created a view using django that displays a search engine to type in the name of the product to be scraped and starts the scraping process. Also, I created a view as a loading page that I want to be displayed when I start the scraping and disappear when the scraping finishes and display the datatable as mentioned in my code. Here is my view.py : def home_view(request): context = {} context ['form'] = Scraping() # if user inserted into form and validated the form if request.method =='POST': form= Scraping(request.POST) if form.is_valid(): # get variable (nom product) subject = form.cleaned_data['subject'] # remove space and replace it with a + sign sbjt = subject.replace(" ","+") # call scrapy command line with this variable os.chdir('C:/Users/aicha/Desktop/new_version/django_project/aliScrap/scraper/codes/aliscraper/') os.system("scrapy crawl aliproduct -a product=" + sbjt) # get results from database client = MongoClient("mongodb://localhost:27017/") db = client["aliexpress"] col = db["listproducts"] products = col.find() context = {'products' : products} return render(request,'datatable.html', context) # default page return render(request,'index.html', context) Page loading view : def loading_view(request): return render(request,'loading.html') Knowing that I have already prepared the html of my loading page. The issue is that I don't know how to integrate my loading page after starting the scraping. It … -
How to implement an Api made with Django on kivy app
Hi everyone I followed the tutorial on the official docs here (https://www.django-rest-framework.org/tutorial/quickstart/) to make my authentification (sign up) and now If i am right with my api, I want to implement it on my kivy app. Aand I don't know how to do. Thanks for answering ! -
Can I add charset from utf-8 to utf8mb4 in django databases
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '{{projectName}}', 'USER': 'root', 'PASSWORD': 'root', 'HOST'strong text: 'localhost', 'PORT': '3306', } } How i can add or update charset, For Options Key i kept charset key i am getting error like below conn = Database.connect(**conn_params) TypeError: 'charset' is an invalid keyword argument for this function For my sql database there is option like this -
Django Form specify table to use for field
For the field cast in the Movie object I want to use the table Cast_movie generated which is movies_cast_movie instead i get an error that movies_movie_cast doesn't exist movies/models.py from django.db import models from .models import * class Movie(models.Model): cast = models.ManyToManyField('Cast_movie', related_name='cast_movies') class Cast_movie(models.Model): movie = models.ForeignKey('movies.movie', on_delete = models.CASCADE, blank=True, null=True) cast = models.ForeignKey('casts.cast', on_delete = models.CASCADE, blank=True, null=True) role = models.ForeignKey('casts.role', on_delete = models.CASCADE, blank=True, null=True) def __str__(self): return self.cast How do i specify the table to use? -
accessing one domain causes logout another domain in load balanced mutliple domain system
I have a elastic beanstalk application which is load balanced. It's a django multitenant application. I am facing a weird problem. If i just access a domain(loading a login page),other domain is getting logging out. I tried different window, different browser even different network. It's logging of. It's working for non load balanced single instance. Need help. -
Css classes not taken into acount on crispy forms button
I use Bootstrap5 and I have a crispy form with two buttons. The first one is the usual "Submit" button while the other refreshes all the fields of the form. I have the following code for the two buttons : self.helper.add_input(Submit('submit', 'Submit')) self.helper.add_input(Submit('refresh', 'Refresh', css_class='btn btn-danger ms-2', formnovalidate='formnovalidate',)) That worked perfectly for days, until a few hours ago when I refreshed the page and my Refresh button wasn't red anymore, but blue like the other one. I checked the classes of the button using Chrome inspector, and found that my button had the classes btn and btn-primary before the others I set. <input type="submit" name="refresh" value="Refresh" class="btn btn-primary btn btn-danger ms-2" id="submit-id-refresh" formnovalidate="formnovalidate"> I don't know if I've changed something without paying attention or if it stopped working for another reason, but I can't seem to find how to remove those two classes. -
How to get read of django secret_key? is using get_random_secret_key() recommended?
I am wondering if I can generate secret key inside my django application and assign it to the SECRET_KEY variable instead of reading it from the env variables? # settings.py from django.core.management.utils import get_random_secret_key SECRET_KEY = get_random_secret_key() is it recommended or it is a bad practice? -
Django order_by alpha first then numeric on attribute with both
I've got a model that has an attribute grade that is a CharField and can be alpha or numeric (for example it may contain any of the following: "K", "A", "5", "2", "1", "4") I am trying to .order_by on my queryset, but would like the alpha to come first, then the numeric. So I would like to see the queryset ordered by "A", "K", "1", "2", "3", but I'm struggling to achieve this. I've seen some solutions that involve using .extra() but I'm trying to avoid that since it's being deprecated in Django. What is the best way to achieve this? my_things = ( Thing.objects.filter( location__in=locations, year=current_year, ) .annotate(first_letter_group=Substr("grade", 1, 1)) .values( "first_letter_group", ) .order_by("first_letter_group") .distinct() .order_by("grade") ) -
Command 'lualatex -interaction=batchmode texput.tex' returned non-zero exit status 127 after rendering a pdf using latex in Django
Hi i want to render a pdf using latex, but there was an error displayed during generate the pdf after pressing a button(for save and generate a pdf latex in same time): this is the error: Command 'lualatex -interaction=batchmode texput.tex' returned non-zero exit status 127. this my views.py: @login_required def forms_render_pdf_view(request, *args, **kwargs): if request.user.is_authenticated: if request.method == 'POST': form = ReportForm(request.POST, ) form.instance.user=request.user if form.is_valid(): form.save() obj_Formulaire = Loads.objects.filter(user=request.user).last() field_obj_load_between_posts = Loads._meta.get_field('load_between_posts') field_value_load_between_posts = field_obj_load_between_posts.value_from_object(obj_Formulaire) load_between_posts = field_value_load_between_posts if load_between_posts == True: field_obj_custom_load = Loads._meta.get_field('custom_load') field_value_custom_load = field_obj_custom_load.value_from_object(obj_Formulaire) qh = float(field_value_custom_load) else: qh = float(0) context = { 'qh': qh, } template_name = 'pages/test.tex' context = {'qh': qh} return render_to_pdf(request, template_name, context, filename='test.pdf') form = ReportForm() context = {'form': form} return render(request, 'pages/form_gelander_report.html', context) this is my settings.py: TEMPLATES = [ { 'NAME': 'tex', } INSTALLED_APPS = [ 'django_tex', ] -
How to set an if statement to True in a Django template?
I have a Django form that corresponds with a model and allows the user to add or remove an item from his watchlist. I want the submit button to say "Add to Watchlist" if the user has not added the item to his watchlist and "Remove from Watchlist" if the listing is already on the user's watchlist. Currently, the button says "Remove from Watchlist" (whether or not it has been added) and changes to "Add to Watchlist" once it has been clicked once. Then the button does not change. html <form action = "{% url 'listing' auction_listing.id %}" method = "POST"> {% csrf_token %} {{ watchlistForm }} {% if watchlist %} <input type = "submit" value = "{{ watchlist }}"> {% else %} <input type = "submit" value = "Remove from Watchlist"> {% endif %} </form> views.py @login_required(login_url='login') def listing(request, id): #gets listing listing = get_object_or_404(Listings.objects, pk=id) #code for comment and bid forms listing_price = listing.bid sellar = listing.user comment_obj = Comments.objects.filter(listing=listing) #types of forms comment_form = CommentForm() bid_form = BidsForm() watchlist_form = WatchListForm() closelisting_form = CloseListingForm() #comment_form = CommentForm(request.POST) #watchlist_form = WatchListForm(request.POST) #bid_form = BidsForm(request.POST) #code for the bid form bid_obj = Bids.objects.filter(listing=listing) other_bids = bid_obj.all() max_bid =0 for … -
Django, Nginx & Gunicorn - Download reset for large files
We are working on a Django website alongside with NginX and Gunicorn. We have to provide the possibility to download large tar.gz files (up to 30Go) which are permanently stored whithin the tree structure. Oddly, when we download one of these archives (~9Go) we get the 1-2 first Go, then the download resets and reinitialize from 0. The logs showed that the worker was timeout. I tried to serve the files in chunk sizes with Django : no change. I tried to set time_out values in NginX conf file: no change. The only way to have the download going to its end was to set an unlimited timeout (timeout 0) in gunicorn.service file. I don't understand very well why do I need to set this unlimited timeout on Gunicorn ... I though that NginX would be able to manage the file download. May you please enlight me about the reasons of this ? What are we doing wrong ? Thank you very much for your help gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=dev Group=www-data WorkingDirectory=/web ExecStart=/web/env/bin/gunicorn \ --access-logfile - \ --workers 4 \ --timeout 0 \ --bind unix:/run/gunicorn.sock \ amused_website.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-enabled/website server { listen 80; server_name myservername; … -
Get S3 presigned url for media in Django
we am using django rest framework for a project and here we are trying to avoid using serializers. We have our AWS S3 as private , hence we need to provide a presigned key for the user to be able to see the image . Initially , we had our S3 as public so we were using annotate function to convert the image path to image link like this : def getImageFormatter(key:str)->Func: """Function to Get Formatted URL""" return Case( When( **{f'{key}__exact':''}, then=Value(None) ), When( **{f'{key}__isnull':False}, then=Concat( Value(settings.MEDIA_ROOT), F(key),output_field=CharField() ) ), default=Value(None), output_field=CharField(null=True) ) The problem is , this only works for public S3 . For private how can we do so so that we can get image on annotate? like using a custom django db function or something else? Any leads will be appreciated . The database we are using is PostgreSQL. We are using boto3 and django-storages to connect to our s3 bucket. We are actually not trying to run it through a serializer , and we are getting the data directly by using annotate and values. -
CPanel configuration files
When upload django app i have problem when setup python app configuration files after add requirements.txt gives me an error these libraries are not accepted: matplotlib==3.5.1 pandas==1.3.5 Pillow==9.0.0 psycopg2==2.9.1 scipy==1.7.3 seaborn==0.11.2 Is there a solution? -
Django manage.py CLI within Pycharm no longer showing any output pertaining to API calls
I'm using Pycharm and you can open the manage.py CLI using ctrl+alt+R and it will usually show errors, status codes etc etc when you make API calls. Now for some reason it doesn't show anything after I run the server. API calls are definitely going through but it's not in the output here. I'm having another issue which is "PermissionError: [WinError 5] Access is denied" for certain API calls. Others work fine. I have switched to working on this project on my laptop so I had to install Pycharm etc fresh so maybe that has something to do with it. I've tried running pycharm as admin, restarting etc. Would appreciate any help. -
Transfer a Django project using Conda environment to a Docker container
I am new to Django and am trying to follow the book Django for Professionals 3.1 by William S. Vincent. In this context, I am trying to move a simple Django project currently on my system (Mac OS) using conda environment on the PyCharm IDE to a Docker container. The Problem The book uses pipenv for the project and suggests to enter the following code in the Dockerfile: However, since I am using a Conda environment for the project, I cannot use the above code in Dockerfile. What I Tried Step 1 I started by entering the following code to create the environment.yml file containing all packages that the project uses. (django_for_professionals_31) My-MacBook-Pro:django_for_professionals_31_ch1 me$ conda env export --no-builds > environment.yml My environment.yml file looks like the following*: name: django_for_professionals_31 channels: - defaults dependencies: - asgiref=3.4.1 - bzip2=1.0.8 - ca-certificates=2022.4.26 - certifi=2022.5.18.1 - django=3.2.5 - krb5=1.19.2 - libedit=3.1.20210910 - libffi=3.3 - libpq=12.9 - ncurses=6.3 - openssl=1.1.1o - pip=21.2.4 - psycopg2=2.8.6 - python=3.10.4 - pytz=2021.3 - readline=8.1.2 - setuptools=61.2.0 - sqlite=3.38.3 - sqlparse=0.4.1 - tk=8.6.12 - typing_extensions=4.1.1 - tzdata=2022a - wheel=0.37.1 - xz=5.2.5 - zlib=1.2.12 prefix: /opt/anaconda3/envs/django_for_professionals_31 Step 2 Then, based on this tutorial, I tried to write my Dockerfile, as shown … -
как сделать пост-запрос с изображением с помощью axios?
to create a post, the user must go through the form for creating posts and upload an image, but I don’t know how to do this i tried to send file event.target.files[0] but I received "POST /api/tests/ HTTP/1.1" 400 91 it didn't help, i tried to send event.target.files[0].name but that didn't help either TestForm.jsx import React, {useState} from 'react'; import axios from "axios"; function TestForm() { const [testInputs, setTestInputs] = useState({title: '', title_image: '', test_type: ''}); console.log(testInputs); axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.xsrfHeaderName = "X-CSRFTOKEN" const handleClick = () => { axios({ method: 'POST', url: 'http://127.0.0.1:8000/api/tests/', data: { author: 1, title: 'sad', title_image: testInputs.title_image.name, test_type: 2, question: [1, 3, 4], result: [1, 2] } }) } return ( <div> <form> <input onChange={(event) => {setTestInputs({...testInputs, title_image: event.target.files[0]}); console.log(event.target)}} type="file" placeholder='upload'/> </form> <button onClick={handleClick}>asd</button> </div> ); } export default TestForm; models.py class Test(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=150) title_image = models.ImageField(default="images/IMG_1270.JPG/", null=True, blank=True, upload_to='titleImages/') test_type = models.ForeignKey(TestType, on_delete=models.CASCADE) question = models.ManyToManyField(TestQuestionBlok) result = models.ManyToManyField(TestResult, blank=True) def __str__(self): return self.title views.py class TestList(APIView): def post(self, request, format=None): serializer1 = TestSerializers(data=request.data) if serializer1.is_valid(): print(serializer1.data) return Response(serializer1.data, status=status.HTTP_200_OK) return Response(serializer1.errors, status=status.HTTP_400_BAD_REQUEST) -
How to return logs to Airflow container from remotely called, Dockerized celery workers
I am working on a Dockerized Python/Django project including a container for Celery workers, into which I have been integrating the off-the-shelf airflow docker containers. I have Airflow successfully running celery tasks in the pre-existing container, by instantiating a Celery app with the redis broker and back end specified, and making a remote call via send_task; however none of the logging carried out by the celery task makes it back to the Airflow logs. Initially, as a proof of concept as I am completely new to Airflow, I had set it up to run the same code by exposing it to the Airflow containers and creating airflow tasks to run it on the airflow celery worker container. This did result in all the logging being captured, but it's definitely not the way we want it architectured, as this makes the airflow containers very fat due to the repetition of dependencies from the django project. The documentation says "Most task handlers send logs upon completion of a task" but I wasn't able to find more detail that might give me a clue how to enable the same in my situation. Is there any way to get these logs back to airflow … -
how to redirect a django website from www to non www
How to redirect a django website from www to Non www. i have already tried library of django pip install django-redirect-to-non-www But No working. Please guide us how to perform the redirection in django website. Thank You -
Django ORM PostgreSQL DELETE query
I have 30 instances of the Room objects, i.e. 30 rows in the database table. In Python code I have Room.objects.all().delete(). I see that Django ORM translated it into the following PostgreSQL query: DELETE FROM "app_name_room" WHERE "app_name_room"."id" IN ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $30). Why doesn't the Django ORM use a more parsimonious DELETE FROM app_name_room query? Is there any way to switch to it and avoid listing all IDs? -
How to add permissions for "class UserRetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView)"?
I've created a model using an abstract user model class for Online flight ticket booking. I'm new to this so haven't added many functionalities to it. I'm sharing my model.py, admin.py, serializer.py, view.py. My question: In views.py -> "class UserRetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView)" I want to give access for GET PUT DELETE for only ADMIN and USER who created this profile(owner). I'm using postman to check endpoints. "Please do check my abstract user model if there is any mistake". permission for "BookViewSet" and "BookingRetrtieveUpdateDestroyAPIView" I only want ADMIN and USER owner who created this booking to view or modify it. #models.py import email from pyexpat import model from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) GENDER_CHOICES = ( (0, 'male'), (1, 'female'), (2, 'not specified'),) class UserManager(BaseUserManager): def create_user(self, email, name,contact_number,gender,address,state,city,country,pincode,dob ,password=None, password2=None): if not email: raise ValueError('User must have an email address') user = self.model( email=self.normalize_email(email), name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, pincode=pincode, dob=dob, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name,contact_number,gender,address,state,city,country,pincode,dob , password=None): user = self.create_user( email, name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, pincode=pincode, dob=dob, password=password, ) user.is_admin = True user.save(using=self._db) return user …