Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Starting docker with powershell dev script
I am doing a docker project from scratch, and following a tutorial (I am following the Django2 WebDevelopment Cookbook). I came upon a section, that I don't know how to convert to Powershell from Bash. I have the following script in my /bin/dev.ps1 #!/usr/bin/env bash # bin/dev # environment variables to be defined externally for security # - MYSQL_USER # - MYSQL_PASSWORD # - MYSQL_ROOT_PASSWORD DOMAIN=myproject.local DJANGO_USE_DEBUG=1 \ DJANGO_USE_DEBUG_TOOLBAR=1 \ SITE_HOST="$DOMAIN" \ MEDIA_HOST="media.$DOMAIN" \ STATIC_HOST="static.$DOMAIN" \ MYSQL_HOST="localhost" \ MYSQL_DATABASE="myproject_db" \ docker-compose $* I have edited the file to such, since the above wasn't working for Windows: #!/usr/bin/env bash # bin/dev # environment variables to be defined externally for security # - MYSQL_USER # - MYSQL_PASSWORD # - MYSQL_ROOT_PASSWORD $DOMAIN="myproject.local" $DJANGO_USE_DEBUG=1 $DJANGO_USE_DEBUG_TOOLBAR=1 $SITE_HOST="$DOMAIN" $MEDIA_HOST="media.$DOMAIN" $STATIC_HOST="static.$DOMAIN" $MYSQL_HOST="localhost" $MYSQL_DATABASE="myproject_db" docker-compose And now it gives me the standard output when you run docker-compose without any arguments. I am trying to also run the following from my terminal: MYSQL_USER=myproject_user \ > MYSQL_PASSWORD=pass1234 \ > ./bin/dev up -d Obviously this won't work in Windows, it even gives me an error that it can't find the MYSQL_USER command or anything. How do I edit the PS file so that I can use it for Windows? And how … -
How to map a Single User Model with multiple roles (student and teacher) to another model when relationship with the model varies based on user role?
So, I have a User model in Django which can have three roles - teacher, student or both. I have another Model, say Course which can have only one teacher but can have multiple students mapped to it. How do I relate these models with another? -
Django (or sqlite3) change(s) the sequence of attributes of a model
I'm using django with sqlite3, and here is my models.py: from django.db import models from django.conf import settings from django.utils import timezone class VoterDetails(models.Model): number = models.CharField(max_length=200,null=True) voter_id = models.CharField(null=True,max_length=200) elector_name = models.CharField(max_length=200,null=True) father_or_husband_name = models.CharField(max_length=200,null=True) has_husband = models.CharField(max_length=200,null=True) house_no = models.CharField(max_length=200,null=True) age = models.CharField(max_length=200,null=True) sex = models.CharField(max_length=6,null=True) ac_name = models.CharField(max_length=200,null=True) parl_constituency = models.CharField(max_length=200,null=True) part_no = models.CharField(max_length=200,null=True) year = models.CharField(max_length=200,null=True) state = models.CharField(max_length=200,null=True) filename = models.CharField(max_length=200,null=True) main_town = models.CharField(max_length=200,null=True) police_station = models.CharField(max_length=200,null=True) mandal = models.CharField(max_length=200,null=True) revenue_division = models.CharField(max_length=200,null=True) district = models.CharField(max_length=200,null=True) pin_code = models.CharField(max_length=200,null=True) polling_station_name = models.CharField(max_length=200,null=True) polling_station_address = models.CharField(max_length=200,null=True) net_electors_male = models.CharField(max_length=200,null=True) net_electors_female = models.CharField(max_length=200,null=True) net_electors_third_gender = models.CharField(max_length=200,null=True) net_electors_total = models.CharField(max_length=200,null=True) change = models.CharField(default="",max_length=200,null=True) def __str__(self): return self.elector_name As one can see, there is no attribute, which would claim to be the primary key. In this case, django generates an attribute id, which is an auto incrementing Auto field, which is chosen as the primary key. I did the migrations, and then checked the schema of the table temp_voterdetails thus generated.(temp is the name of my app.) sqlite> .schema temp_voterdetails CREATE TABLE IF NOT EXISTS "temp_voterdetails" ( "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "age" varchar(200) NULL, "ac_name" varchar(200) NULL, "change" varchar(200) NULL, "district" varchar(200) NULL, "elector_name" varchar(200) NULL, … -
Specify related string field in Django Rest Framework
Django 1.11, Django Rest Framework 3.6. I have 2 models, Foo and Bar: class Foo(models.Model): name=models.CharField() sex=models.CharField() class Bar(models.Model): type=models.CharField() foo=models.ForeignKey(Foo) In my serializers.py I have: class FooSerializer(serializers.ModelSerializer): class Meta: model = Foo fields = ('sex',) class BarSerializer(serializers.ModelSerializer): foo = FooSerializer(many=False) class Meta: model = Bar fields = ('type', 'foo',) This produces JSON like this: { "type": "abcdefg", "foo": { "sex": "male" } } What I really want is for the "foo" field to be flat, i.e.: { "type": "abcdefg", "foo": "male" } One possible solution would be to use the StringRelatedField, but this would entail setting the __str__ method of the Foo model to return the sex field, which I do not want. -
Django: Avoid duplicated
The following for loop is shown to me as 3x duplicate. Do you have any idea how to avoid that? @cached_property def social_ticketing_coin_allocation_formset(self): initial = [] for ticket in self.tickets_as_list: coin_allocation = Coins.objects.filter(ticket=ticket['ticket']) if not coin_allocation.exists(): initial.append({'ticket': ticket['ticket']}) extra = len(initial) -
How give custom permission in middleware - Django
I am creating Custom Access Control List. For that i have created a model class AclRoleAccess(models.Model): acl_role = models.ForeignKey(ACLRoles, on_delete=models.CASCADE) acl_company = models.ForeignKey(Company, on_delete=models.CASCADE) acl_functionality = models.ForeignKey(AclFunctionality, on_delete=models.CASCADE) acl_has_access = models.BooleanField() class Meta: db_table = "acl_role_accesses" Can i use has_perm for this model. How can i restrict user can any give me suggesstion. What is actual codename in permission table -
post an array of data to database
I have this model: name = models.CharField(max_length=50, unique=True) readable_name = models.CharField(max_length=50, unique=True) permissions = models.ManyToManyField(Permission, related_name='permissions_group', db_table='role_permissions', blank=False,null=False) and this serializer: class Meta: model = models.Role fields = '__all__' and I have this post class: serializer = serializers.RolePostSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({"message": _("Added Successfully")}, status=status.HTTP_201_CREATED) Front end give me this kind of data: "name": "test role", "permissions": { "0": 5, "1": 2, "2": 6, "3": 7 }, "readable_name": "test" } I dont know how I can give my permission an array of data like this. In my postman I can give just one permission id and its ok but I cannot give more than one -
Formset is not filtering
Anyone who understands, why my queryset is not working? The filter doesn't apply and it's showing all: CoinAllocationFormset = modelformset_factory( Coins, fields=('ticket', 'coins'), # form=SocialTicketingCoinAllocationForm, extra=0, ) return CoinAllocationFormset( data=self.request.POST or None, initial=initial, queryset=Coins.objects.filter(ticket__event=self.request.event), ) -
Django tables2 sorting
I have a django model that I am rendering with django tables2. I am trying to make the columns sortable. It appears by default clicking on the headers should sort them already looking at the browser address localhost:10000/gui/?sort=max_val But it doesn't do anything. I added a method following https://django-tables2.readthedocs.io/en/latest/pages/ordering.html But this still does not order anything. class Strategy(models.Model): ... max_val = models.DecimalField(max_digits=32, decimal_places=0) class DfTable(tables.Table): max_val = tables.Column() def order_max_val(self, QuerySet, is_descending): QuerySet = QuerySet.order_by(('-' if is_descending else '') + 'max_val') return (QuerySet, True) Any idea what I am missing here? -
What should be the data type to store Currency Symbol in Django Models
I have a Django model that relates to the currency with fields like currency name, currency code and currency symbol. class Currency(models.Model): currency_name = models.CharField(max_length=100) currency_code = models.CharField(max_length=3) currency_symbol = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True,null=True) updated_at = models.DateTimeField(auto_now=True) The currency_symbol field will hold a symbol for a particular currency, for example "€". However when I'm trying to save the model, I'm getting the following exception, django.db.utils.DataError: (1406, "Data too long for column 'currency_symbol' at row 1") So what should be the correct datatype? -
Django rest API deploy on apache
I have created a django application and deployed it on the server.I have run the application through python manage.py runserver 8000 & and handle the requests on the apache server through proxy ProxyPass "/" "http://www.example.com/" ProxyPassReverse "/" "http://www.example.com/". But there is a issue that I am facing while testing the api through JMeter, when i am running a test case for 10 users my python service over the server gets killed automatically. What i am doing wrong or what i have to do more to resolve the above test scenario,please suggest? -
Datatables with Django can not fetch data from MySQL Database
I am trying to fetch data by searching in the default search bar provides by the datatables using Django. The default view shows up but when I search in the search box, It shows nothing. The view it shows like this: My View is this: def searchProductTable(request): xh = ProductLaptop.objects.all() context = { "xh": xh } return render(request, "searchTableView.html", context) for the model below: class ProductLaptop(models.Model): laptops_name = models.CharField(max_length=500, null=True, blank=True) laptops_url = models.CharField(max_length=500, null=True, blank=True) laptops_price = models.IntegerField(null=True, blank=True) laptops_image = models.CharField(max_length=400, null=True, blank=True) brand_name = models.CharField(max_length=20, null=True, blank=True) def __str__(self): return self.laptops_name I know the model is not correct and at the same time I do not know how will I implement the model cause I do not have that much experience with Django. The code of my .html file is: <!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>Search Table</title> <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"> <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> </head> <body> <table id="example" class="display" style="width:100%"> <thead> <tr> <th>Name</th> <th>Seller</th> <th>Price</th> </tr> </thead> <tbody> {% for foo in xh %} <tr> <td>{{ foo.laptops_name}}</td> <td>{{ foo.brand_name}}</td> <td>{{ foo.laptops_price}}</td> {% endfor %} </tr> </tbody> </table> <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> … -
Unable to collectstatic
I tried to run python manage.py collectstatic, but recieved the following error. I'm not sure where to even begin troubleshooting. There doesn't seem to be much helpful information within the error information below. Traceback (most recent call last): File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\module_loading.py", line 13, in import_string module_path, class_name = dotted_path.rsplit('.', 1) ValueError: not enough values to unpack (expected 2, got 1) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 189, in handle collected = self.collect() File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 104, in collect for finder in get_finders(): File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\staticfiles\finders.py", line 277, in get_finders yield get_finder(finder_path) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\staticfiles\finders.py", line 286, in get_finder Finder = import_string(import_path) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\module_loading.py", line 15, in import_string raise ImportError("%s doesn't look like a module path" % dotted_path) from err ImportError: d doesn't look like a module path Any ideas would be appreciated! Thanks! -
Bower not installed
I'm attempting to install django-scheduler, which requires bower. I've followed the Installation instructions here. https://github.com/llazzaro/django-scheduler I ran pip freeze and can see that I have django-bower==5.2.0 installed. Last step within the github instructions is as follows: install bower dependencies with: ./manage.py bower install I went into my project directory and ran the following command: manage.py bower install I get the following error: BowerNotInstalled: Bower not installed, read instruction here - http://bower.io/ I've gone to the site and can't see anything about the python install. Any help would be appreciated. Thanks! -
Static method returning empty list in Django
I am trying to run a Django app on local server. It works fine on mu Ubuntu machine but in mac, I can't get the CSS for localhost:8000/admin and localhost:8000/docs to load. On digging further, I found out that the static URL in main "urls.py" file return an empty list instead of a URL pattern. Does anyone have an idea why it is like that on the new mac system? -
password reset implementation with djoser
I wanted to use djoser for the reset password functionality and as per the documentation " PASSWORD_RESET_CONFIRM_URL URL to your frontend password reset page. It should contain {uid} and {token} placeholders, e.g. #/password-reset/{uid}/{token}. You should pass uid and token to reset password confirmation endpoint. I have done the following: PASSWORD_RESET_CONFIRM_URL': 'reset/password/reset/confirm/{uid}/{token}', url url(r'^reset/password/reset/confirm/(?P<uid>[\w-]+)/(?P<token>[\w-]+)/$', PasswordResetView.as_view(),), View : class PasswordResetView(APIView): def get (self, request, uid, token): post_data = {'uid': uid, 'token': token} return Response(post_data) In my mail I get this link : http://127.0.0.1:8000/reset/password/reset/confirm/Mjk/538-954dccbc1b06171eff4d This is obvious that I will get : { "uid": "Mjk", "token": "538-954dccbc1b06171eff4d" } as my output but I wanted to go to auth/password/reset/confirm when the user clicks the link in the mail. -
Get title from object closest to date, django model
I have to models: Week: class Week(models.Model): week_id = models.Charfield(unique=True, null=False, primary_key=True) year = models.PositiveSmallInteger() weeknumber = models.PositiveSmallInteger() ... and Deadline class Deadline(models.Model): deadline_type = models.CharField() end_at = models.DateTimeField(blank=False) week_id = models.ForeignKey(Week, related_name='deadlines', on_delete=models.CASCADE) ... Which gives me an output like: { "weeknumber": 1, "leaflet_year": 2019, "week_id": "01_2019", "deadlines": [ { "deadline_type": "Some Deadline type", "end_at": "2019-10-23T14:00:00Z", }, ... ] } What I want to achieve, is to annotate the Week object with the deadline_typeof the deadline object which have the end_atclosest to today. I can annotate the end date, but I simply have no idea on how to get the type. -
Analysing and improving the performance of a query generated by Django's ORM (SORT)
I have a not-so-complex (imho) filtering logic based on several conditions in my Django models. There is one particular query which takes an inusual amount of time to finish. The query is built based on those two querysets: queryset = self.serializer_class.Meta.model.valid_pricelist_objects.filter( Q(drug_prices__pricelist__price_destination__to_all_insurances=True ) | # pylint: disable=line-too-long Q( drug_prices__pricelist__price_destination__to_organization_data__organization__uuid =self.kwargs.get('i_uuid'))) return queryset and return super().get_queryset().filter( Q(active=True), Q(drug_prices__pricelist__active=True), # Lista de precios activa # Q(drug_pictures__is_main=True), # Que tenga una imagen # TODO: Hacer filtros por pais PriceListCountries Q( Q(drug_prices__pricelist__expires=False) | # Que tenga precios que no caducan o Q( Q(drug_prices__pricelist__expires=True), # Que tenga precios que si caducan Y Q(drug_prices__pricelist__datestart__date__lte=timezone.now()), # Fecha de inicio menor que hoy Y Q(drug_prices__pricelist__dateend__date__gte=timezone.now()) # Fecha final mayor que hoy ) ) ).distinct().prefetch_related( 'categories__contexts', 'brands', 'drug_prices__pricelist', 'drug_pictures', 'drug_prices__pricelist__price_destination', ) The second querysets wraps the first one (via the super() call). The resulting query looks like this: SELECT DISTINCT "phdrug_phdrug"."id", "phdrug_phdrug"."uuid", "phdrug_phdrug"."default_description", "phdrug_phdrug"."ean", "phdrug_phdrug"."parent_ean", "phdrug_phdrug"."reg_num", "phdrug_phdrug"."atc_iv", "phdrug_phdrug"."product_type", "phdrug_phdrug"."fraction", "phdrug_phdrug"."active", "phdrug_phdrug"."loyal", "phdrug_phdrug"."patent", "phdrug_phdrug"."chronics", "phdrug_phdrug"."recipe", "phdrug_phdrug"."deal", "phdrug_phdrug"."specialized", "phdrug_phdrug"."armored", "phdrug_phdrug"."hight_speciality", "phdrug_phdrug"."temp_8_15", "phdrug_phdrug"."temp_15_25", "phdrug_phdrug"."temp_2_8", "phdrug_phdrug"."temp_less_15", "phdrug_phdrug"."new", "phdrug_phdrug"."mdk_internal_code", "phdrug_phdrug"."mdk_single_id", "phdrug_phdrug"."is_from_mdk_db", "phdrug_phdrug"."top", "phdrug_phdrug"."laboratory_id", "phdrug_phdrug"."specialty_id" FROM "phdrug_phdrug" INNER JOIN "monetary_drugprice" ON ( "phdrug_phdrug"."id" = "monetary_drugprice"."drug_id" ) INNER JOIN "monetary_pricelist" ON ( "monetary_drugprice"."pricelist_id" = "monetary_pricelist"."id" ) INNER JOIN "monetary_drugprice" T4 ON ( "phdrug_phdrug"."id" = T4."drug_id" ) … -
Django- update() and get_or_create() check entry count before uploading
Is there any way to check how many objects would be updated or created before committing to the DB? Something like this: <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" onclick="return confirm('Upload File? {{created_objects}} Objects will be created. {{updated_objects}} Objects will be updated')">Upload</button> </form> And then in the view with open(str(csv_file)) as file: number_of_lines = len(file.readlines()) reader = csv.reader(file) for row in reader: id += 1 try: _, p = CSV3.objects.get_or_create(id = id, defaults = {'gebaeudebereich' : row[0], 'gebaeudenummer' : row[1], 'ebene' : row[2], 'raum' : row[3], 'dose' : row[4], 'switch_ip' : row[5], 'switch_port' : row[6], 'datum' : row[7], 'akteur' : row[8]}) created_objects += 1 except IntegrityError: _, p = CSV3.objects.filter(id = id).update(gebaeudebereich=row[0], gebaeudenummer=row[1], ebene=row[2], raum=row[3], dose=row[4], switch_ip=row[5], switch_port = row[6], datum = row[7], akteur = row[8]) updated_objects += 1 #messages.INFO("Objects Created: %(created_objects)s") #messages.INFO("Objects Updated: %(updated_objects)s") return redirect('appp:index') form = UploadFileForm() return render( request, "appp/file_upload.html", {"form": form} ) Thanks in advance -
How to iterate over a json object in Python?
I have a json object contaning currencies as listed below which I need to convert it into my model and save it into the DB. Also is there a way to save the list of models in one go? { "results": { "ALL": { "currencyName": "Albanian Lek", "currencySymbol": "Lek", "id": "ALL" }, "KWD": { "currencyName": "Kuwaiti Dinar", "id": "KWD" }, "LSL": { "currencyName": "Lesotho Loti", "id": "LSL" }, "MYR": { "currencyName": "Malaysian Ringgit", "currencySymbol": "RM", "id": "MYR" }, "MUR": { "currencyName": "Mauritian Rupee", "currencySymbol": "₨", "id": "MUR" } } } I tried this : for key,value in currencies.results : #print(currency) #print(value) However, I get the following error : "Too many attribures to unpack, expected 2 Can someone help me with this? -
How to create Django DRF API to Upload file and pass it to function in Views.py?
I'm trying to create an API using DRF where PDF documents are uploaded and stored in separate Directory "/media/documents". Once during it's uploading I want it to pass it through an function where I will need it to convert into a new format and then save it to the "/media/documents". The function as follows. Function for processing Uploaded File -
Gunicorn throws error 403 when accessing static files
python==2.7.5, django==1.11.10, gunicorn==19.7.1, RHEL 7.4 I have a django project at my job written not by me. It was in eventcat user's home directory and with time we ran out of available space on the disk. I was to move the project to /data/. After I moved the project directory and set up a new environment I faced the problem that static files are not loaded and throwing 403 forbidden error. Well, I know that gunicorn is not supposed to serve static files on production, but this is an internal project with low load. I have to deal with it as is. The server is started with a selfwritten script (I changed the environment line to new path): #!/bin/sh . ~/.bash_profile . /data/eventcat/env/bin/activate exec gunicorn -c gunicorn.conf.py eventcat.wsgi:application The gunicorn.conf.py consists of: bind = '127.0.0.1:8000' backlog = 2048 workers = 1 worker_class = 'sync' worker_connections = 1000 timeout = 120 keepalive = 2 spew = False daemon = True pidfile = 'eventcat.pid' umask = 0 user = None group = None tmp_upload_dir = None errorlog = 'er.log' loglevel = 'debug' accesslog = 'ac.log' access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"' proc_name = None def post_fork(server, worker): … -
ModuleNotFoundError: No module named 'acl.validators.login_validator'; 'acl.validators' is not a package
I try to write a custom validator under validators folder I have login_validator.py file and I defined it here: def validate_field(username, password): if username == "": raise ValidationError(_('Username may not be blank'),params={'username': username},) then I called this validator in my login view like this: def login(request): try: username = request.data.get('username', validators=[validate_field]) but when I run the project I get this error: ModuleNotFoundError: No module named 'acl.validators.login_validator'; 'acl.validators' is not a package I am not sure how I should use my validator to check if a user in login page entered any data or other things. -
Django (DRF) & React - Forbidden (CSRF cookie not set)
There are tens of questions that are essentially identical to the one I'm asking. However, none of their answers seem to be working for me. I have a React front-end where I am using axios to send requests to the back-end. Example const request = await axios.post('${BASE_URL}/logout/') Most of the Django Rest Framework endpoints are made with ViewSets. However, I have a few that are custom and mostly made for authentication. path('createaccount/', views.create_account), path('me/', views.current_user), path('logout/', views.logout), path('login/', views.login), path('resetpassword', views.reset_password), For the development of this project I've included @csrf_exempt above these views because I didn't want to deal with it at the time. Now I'm nearing deployment and it's time to figure it out. Some answers say I need to get a CSRF Token from Django which is stored in cookies and I need to pass that in the header of each request. Some answers say all I need to do is configure axios like axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios.defaults.xsrfCookieName = "XCSRF-TOKEN"; And it will "just work". I've tried adjusting my CSRF_COOKIE_NAME to various values to get this to work too. Some answers even say to keep @csrf_exempt but that sounds like a very, very bad idea. Do I actually … -
Django new user with email confirm
I am super new to Django and currently working on a training project. Question 1 - I want new registered user can receive a confirm email. Referring to https://docs.djangoproject.com/en/2.1/topics/auth/customizing/, I create my User model as below and I hope create_user() in UserManager been called on new user creation but it turns out it never been called. Is my implementation wrong? from authtools.models import AbstractEmailUser from django.db import models from authtools.models import UserManager as BaseUserManager from mysite.models import UserType from mysite.models import Organisation class UserManager(BaseUserManager): def create_superuser(self, **kwargs): user = self.create_user(**kwargs) user.is_superuser = True user.is_staff = True user.user_type = UserType.objects.get(name='ADMIN') user.save(using=self._db) return user def create_user(self, email, password=None, **kwargs): user = super().create_user(email, password, kwargs) user.email_user("Register Confirm", "welcome", "admin@mysite.com") class User(AbstractEmailUser): first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) user_type = models.ForeignKey(UserType, on_delete=models.CASCADE) organisation = models.ForeignKey(Organisation, null=True, blank=True, on_delete=models.CASCADE) modified = models.DateTimeField(auto_now=True) objects = UserManager() REQUIRED_FIELDS = ['first_name', 'last_name'] class Meta: db_table = 'users' Question 2 - Can anybody explains how Django framework works on triggering to create a new user? Say receiving api call /users/add, how create_user() been called?