Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'django' is not recognized as an internal or external command, operable program or batch file.(module error)
I have freshly installed python version 3.9 and it shows up in my CMD (command prompt), but when I try to install django via command pip install django (also tried sudo doesn't work either) command line screenshot but when I try to check my version via django --version command line screenshot I have already tried to configure my environment path variable added every possible path in it. Environment path variable screenshot P.S : I don't want to create virtual environment please don't suggest me that the same thing happen's there too. I have been stuck for many days with this problem if anybody actually know how to solve it please help -
How can I GET external data and combine it with my current view?
I have a view that I want to use to pull Model data + get data from an external API. Using the same URL path to get database data + external API data, as they are both relatively connected in terms of business logic. This is how I tried implementing it: class BucketList(generics.ListAPIView): permission_classes = [IsAuthenticated] serializer_class = BucketListSerializer filter_backends = [OwnerOrUserFilterBackend] queryset = Bucket.objects.all() # I use a field in my model as part of my GET request def get(self, request, *args, **kwargs): bucket_symbols = Bucket.objects.only('stock_list') symbols_unicode = (','.join(map(str, bucket_symbols))) postgrest_urls = f"http://localhost:3000/rpc/bucketreturn?p_stocks=%7B{symbols_unicode}%7D" response = requests.get(postgrest_urls, headers={'Content-Type': 'application/json'}).json() return Response(response, status=status.HTTP_200_OK) The idea of def get(), is to extract every stock_list field in objects, and feed that into my other API on localhost. To clarify, I want every stock_list in object passed into my get requests and returned, for each object. However I keep getting undefined errors in my JSON response. How can I properly implement a two-in-one view solution for my view, I still want to keep my original queryset = Bucket.objects.all() in my view. -
Fresh installation of Django-CMS as instructed at the url latest
Good Day. I am using djangocms for the first time... using https://docs.django-cms.org/en/latest/introduction/01-install.html I did exactly as instructed above and logged in but, as soon as i log in the following error occurs... Request Method: GET Request URL: http://127.0.0.1:8000/en/admin/cms/page/3/change/?language=en Raised by: cms.admin.pageadmin.change_view page object with primary key '3' does not exist. any idea.. Thanks for help... -
ERROR: Failed building wheel for psycopg2 (Ubuntu 20.04 + Python 3.8.5 + venv)
Greetings wisdom from Stackoverflow! I'm having issues building wheel for psycopg2 thru pip install -r requirements.txt. I'm on ubuntu 20.04 + python 3.8.5 + venv. This is my requirements.txt: amqp==2.6.1 anyjson==0.3.3 asgiref==3.2.10 billiard==3.6.3.0 brotlipy==0.7.0 celery==4.4.7 celery-progress==0.0.12 certifi==2020.6.20 cffi==1.14.2 chardet==3.0.4 cryptography==3.1 Django==3.0.3 dj-database-url==0.5.0 django-celery-results==1.2.1 django-cors-headers==3.5.0 django-crispy-forms==1.9.2 django-heroku==0.3.1 django-rest-framework==0.1.0 django-templated-mail==1.1.1 djangorestframework==3.11.1 djoser==2.0.5 fake-useragent==0.1.11 future==0.18.2 gunicorn==20.0.4 httpie==2.2.0 idna==2.10 kombu==4.6.11 lxml==4.5.2 pika==1.1.0 psycopg2==2.8.5 pycparser==2.20 Pygments==2.7.0 pyOpenSSL==19.1.0 PySocks==1.7.1 python-dateutil==2.8.1 python-decouple==3.3 pytz==2020.1 requests==2.24.0 six==1.15.0 SQLAlchemy==1.3.19 sqlparse==0.3.1 urllib3==1.25.10 vine==1.3.0 whitenoise==5.2.0 This is the output when I pip install -r requirements.txt: [...] Collecting urllib3==1.25.10 Using cached urllib3-1.25.10-py2.py3-none-any.whl (127 kB) Collecting vine==1.3.0 Using cached vine-1.3.0-py2.py3-none-any.whl (14 kB) Collecting whitenoise==5.2.0 Using cached whitenoise-5.2.0-py2.py3-none-any.whl (19 kB) Requirement already satisfied: setuptools>=3.0 in ./venv/lib/python3.8/site-packages (from gunicorn==20.0.4->-r requirements.txt (line 24)) (44.0.0) Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/pierre/Workspace/campground_scavanger/venv/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-1xr9yjk0/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-1xr9yjk0/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-b8g9assp cwd: /tmp/pip-install-1xr9yjk0/psycopg2/ Complete output (6 lines): usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: invalid command 'bdist_wheel' ---------------------------------------- ERROR: Failed building wheel for psycopg2 Running setup.py clean for … -
Can I deploy Django to heroku that retrieve data from firebase?
my django is retrieve data in realtime from firebase can i deploy it to heroku. I don't know what Add-ons I should select -
How to return username instead of user object in DRF?
I want to set a username for each object. Here is my models.py from django.contrib.auth.models import User from django.conf import settings # Tweet Model class TweetModel(models.Model): text = models.TextField(max_length=300, blank=False) created_at = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True) username = models.CharField(max_length=100, blank=True) And viewset.py from .models import TweetModel from rest_framework import viewsets, permissions # TweetViewset class TweetViewset(viewsets.ModelViewSet): permission_classes = [ permissions.IsAuthenticated ] serializer_class = TweetSerializer def get_queryset(self): ordered = TweetModel.objects.order_by('-created_at') return ordered def perform_create(self, serializer): serializer.save(owner=self.request.user, username=self.request.user.username) But it is not working. Error is django.db.utils.ProgrammingError: column tweets_tweetmodel.username does not exist LINE 1: ...el"."created_at", "tweets_tweetmodel"."owner_id", "tweets_tw... Can you help, please? -
How to accept both csv or xlsx files as input files? (Pandas)
I have a Django application that converts CSV files to other delimiter files. Now I want to improve a feature that can accept and convert both CSV or XLSX files. views.py def submit(request): #form that uploads files csv_form = '' if request.method == 'POST': csv_form = CsvForm(request.POST, request.FILES) if csv_form.is_valid(): csv_file = TextIOWrapper(request.FILES['csv_file'].file, encoding='ascii', errors='replace') data = pd.read_csv(csvfile,delimiter=',') #converts I tried: try: data = pd.read_csv(csv_file, delimiter = ',') except: data = pd.read_excel(csv_file) It shows error: OSError: [Errno 22] Invalid argument: "<_io.TextIOWrapper name='C:\\\\Users\\\\admin\\\\AppData\\\\Local\\\\Temp\\\\wtsrfox8.upload.xlsx' encoding='cp1252'>" templates: <div class="form-row"> <div class="name">Upload CSV file</div> <div class="value"> <div class="input-group js-input-file"> <input class="input-file" type="file" name="csv_file" required="required" id ="file" accept=".csv"> <label class="label--file" for="file">Choose file</label> <span class="input-file__info">No file chosen</span> </div> <div class="label--desc">Upload your file</div> </div> </div> Is there any way to accept and convert both CSV or XLSX files in both views and templates? -
Django get returns ValueError: Field 'id' expected a number but got <string>
Here is my models.py class Car(models.Model): name = models.CharField(max_length = 100) country = models.CharField(max_length = 100) def __str__(self): return str(self.name) class Model(models.Model): name = models.CharField(max_length = 50) car = models.ForeignKey(Car, on_delete = models.CASCADE) def __str__(self): return f"{self.car}-{self.name}" Here is some code I tried in shell that is returning some unexpected results from models import Model print(Model.objects.all()) returns <QuerySet [<Model: Toyota-Previa>, <Model: Toyota-Supra>, `<Model: Toyota-Camery>, <Model: Ford-Torous>, <Model: Ford-Mustang>, <Model: Ford-GT>, <Model: Mercedes-SLR>,` <Model: Mercedes-AMG>, <Model: Mercedes-C-Class>]> but print(Model.objects.get(car = 'Toyota')) returns ValueError: Field 'id' expected a number but got 'Toyota'. I don't understand why this happens, I thought this would return a queryset that gives all of the cars made by Toyota in the database. -
"source code string cannot contain null bytes" in file that has no null bytes
I'm working on a disassembler that prints a series of Python dictionaries calculated from parsing a chunk of hex code from a certain SNES rom file. These dictionaries are written to individual .py files so that they can be imported in the main codebase of a randomizer. I'm using django's manage.py command to run this code, eventassembler: from django.core.management.base import BaseCommand from randomizer.logic.enscript import EventScript from randomizer.logic.osscript import ObjectSequenceScript as OSCommand from randomizer.data.eventscripts.events import scripts class Command(BaseCommand): def handle(self): e = EventScript() print (e.assemble_from_table(scripts)) (not complete, just trying to print to console to test my progress on the assemble_from_table method I'm in the middle of writing) Where scripts comes from an autogenerated file, events.py, that follows this format: from randomizer.data.eventscripts.script_0 import script as script_0 from randomizer.data.eventscripts.script_1 import script as script_1 from randomizer.data.eventscripts.script_2 import script as script_2 ... (all the way up to 4095) scripts[0] = script_0 scripts[1] = script_1 scripts[2] = script_2 ... (all the way up to 4095) Where each of the 4096 import files are also autogenerated files, with each one basically structured like this: from randomizer.data.eventtables import ControllerDirections, RadialDirections, Rooms, ... from randomizer.data.objectsequencetables import SequenceSpeeds, VramPriority, ... from randomizer.data import items script = [ { "identifier": 'EVENT_3_ret_0', … -
django-cacheops return None
Django==2.2.12 django-cacheops==4.2 python 3.7.5 cacheops return None turn Redis off, it works fine. but values exist in both mysql and redis. cacheops option CACHEOPS = { 'user.userinfo': {'ops': 'all', 'timeout': 60 * 60 * 24 * 30}, } CACHEOPS_DEGRADE_ON_FAILURE = True ErrorCode @staticmethod def getUserInfo(userUID): userInfo = userInfo.objects.filter( userUID=userUID, ).first() return userInfo userInfo = getUserInfo(userUID) if not userInfo: raise NameError('userInfo not exist') Restarting uwsgi solves the problem. But I can't keep monitoring the situation, so I need a fundamental solution. It doesn't seem to be a problem with redis as it gets resolved when uwsgi is restarted. It is expected that the connection between django and redis is broken or there is some other problem. Please tell me how to fix cacheops return none differently from the actual value, or how to use mysql value when cacheops return none. -
Django: active Home link
This is my first project with django, I wanted my static site html/css/js to turn it into a dynamic website. However, in navMenu I want to have 'home' link only if the user is not on the index page. Here is my attempt: <style> #hm{ display:none; } .activate{ display:block; } </style> <div id="navMenu" class='py px'> <ul> {% url 'home' as home_view %} <li id = 'hm' {% if request.get_full_path != home_view%} class = 'activate' {% endif%}>Home</li> <li class='brd'>Alumni</li> <li class='brd'>Staff</li> <li class='brd'>Services</li> <li class='brd'>About</li> <li><a id='btnSearch' href="#"><i class="fa fa-search searchUpdate"></i></a></li> </ul> </div> the urls: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from pages.views import home_view from events.views import events urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name = 'home'), path('events/', events, name = 'events') ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) Any help is appreciated! -
How to make user-adjustaple pagination in Django?
I have pagination, html: {% extends 'base.html' %} {% load pagination_tags %} {% block title %}NewsLine{% endblock title %} {% load humanize %} {% block content %} {% autopaginate news news_on_page %} {% paginate %} News on page: <input type="submit" value="10" /> <input type="submit" value="20" /> <input type="submit" value="50" /> <div class="container mt-3"> <div class="row my-5"> <div class="col-11"> <p>News overall {{ paginator.count }}</p> <p>Number of pages {{ paginator.num_pages }}</p> <p>Page range {{ paginator.page_range }}</p> {% for peace_of_news in news %} <div class="p-3"> <h2>{{ peace_of_news.title }}</h2> <p><small>{{ peace_of_news.date|naturaltime }}</small></p> <p>{{ peace_of_news.text }}</p> </div> {% endfor %} </div> </div> </div> {% endblock content %} views.py: {% extends 'base.html' %} {% load pagination_tags %} {% block title %}NewsLine{% endblock title %} {% load humanize %} {% block content %} {% autopaginate news news_on_page %} {% paginate %} News on page: <input type="submit" value="10" /> <input type="submit" value="20" /> <input type="submit" value="50" /> <div class="container mt-3"> <div class="row my-5"> <div class="col-11"> <p>News overall {{ paginator.count }}</p> <p>Number of pages {{ paginator.num_pages }}</p> <p>Page range {{ paginator.page_range }}</p> {% for peace_of_news in news %} <div class="p-3"> <h2>{{ peace_of_news.title }}</h2> <p><small>{{ peace_of_news.date|naturaltime }}</small></p> <p>{{ peace_of_news.text }}</p> </div> {% endfor %} </div> </div> </div> {% endblock content … -
Django Javascript: How To Use Class Name With Template Tag Inside As Identifier in Function
I am using a for loop to print out all of the posts on my site and each post will have a form that allows users to add that post to a list. I am trying to use ajax to do this so that there is no page refresh. The ajax function works on the first post but on all of the others there are issues. i think that the issues are due to each post having the same class name that is being used to identify it, so this is why i want to use the forloop counter in the class name so that each one has a unique identifier. Here is some relevant code: Javascript: #this is where i want the class to have a tag inside $('.collection_save_form').submit(function(e){ e.preventDefault() const url = $(this).attr('action') const post_id = $(this).attr('name') const collection_id = $(this).attr('id') const text = $(`.saved_text${collection_id}`).text() var saveElement = document.getElementById(`save_btn${collection_id}`); $.ajax({ type: 'POST', url: url, data: { 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), 'post_id': post_id, 'collection_id': collection_id, }, success: function(response){ if (saveElement.classList.contains("saved")){ saveElement.classList.remove("saved") $(`.saved_text${collection_id}`).text('Save') } else if (!$(this).hasClass("saved")) { saveElement.classList.add("saved") $(`.saved_text${collection_id}`).text('Saved') } }, error: function(response){ console.log('error', response) } }) }) Code with the form: {% for item in posts %} #irrelevant post data … -
In spite of the fact that I have created the django project in the same conda environment it is showing the ImportError: Couldn't import Django?
I haven't even restartted the system. But I do have other conda environments with django version=1.* and 2.. I am facing this issue in 3. version of django. Can switching between these versions of django through conda environments can cause this problem? Because I am facing this problem often. Whatever the case maybe, please help me fix this. File "C:\Users\vinniiee\Desktop\django_blog_project\django_blog_project\manage.py", line 13, in main raise ImportError( 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? -
Django duplicating block.super content
using in template inheritance as in the docs here I'm getting duplication as shown: In the above photo the commented Google Tag Manager text has been duplicated. Obviously I would like to put the actual tag manager in there, but it's a simpler example for SO this way. Anything I put in my child template tag is duplicated when I call {{ base.super }} I'm using Oscar, so here's my inheritance scheme. oscar/base.html #from oscar module #relevent sections only {% load i18n %} {% load static %} <!DOCTYPE html> <html lang="{{ LANGUAGE_CODE|default:"en-gb" }}" class="{% block html_class %}no-js{% endblock %}"> <head> {% block tracking %} {# Default to using Google analytics #} {% include "oscar/partials/google_analytics.html" %} {% endblock %} </head> my base override # located in my procject at 'oscar/base.html' {% extends 'oscar/base.html' %} {% block tracking %} {{ block.super }} <!-- Google Tag Manager --> <!-- End Google Tag Manager --> {% endblock %} Below is anything else I think could be involved. Any troubleshooting tips that would help me debug this would be welcome. my view from django.http import HttpResponse from django.views.generic.base import TemplateView class BaseTestView(TemplateView): template_name = "oscar/base.html" urls.py from myurls import BaseTestView urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), … -
How to transfer data from HTML button to Django?
I want to make adjustable pagination, three buttons created: 10, 20 and 50 news per page. My html Django template element that in charge of pagination is {% autopaginate news 10 %}, where 10 is number of news per page. Also i can set in in views and use any variable {% autopaginate news variable %}. How to transfer meaning of some button to this variable? Or how to do adjustable pagination in another way? -
Django - allow only one user user/visitor(IP) per view(page)
I would be so grateful if someone could point me in the right direction. Im making a webapp in django where you can move around a webcam. The problem is that maybe 2 or 3 people at once can connect to the website and they all control the camera simultaneously. How could i make the page(view) where you move the camera, accessible to only one user/visitor and limit their time to about 3minutes. After 3 minutes it would cancel the current users session and move on to the next user in the line and so on.. Ideally it would show other users the time they have to wait, till they can control the camera. So.. user1 would be moving the camera(for 3mins), user2 would wait for 3 minutes and user3 would have to wait 6 minutes till his turn. I have tried some stuff with django.contrib.auth but cant get it to work. Anybody? Thanks a lot! -
Getting error 'SMTPSenderRefused at /accounts/password_reset/' when using mailgun sandbox for django in python
I'm trying to send password reset email using mailgun sandbox for django with python (PyCharm app) and I get this error when I try resetting my password. in settings.py, EMAIL_HOST = "smtp.mailgun.org" EMAIL_PORT = 587 EMAIL_HOST_USER = os.environ.get("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_HOST_PASSWORD") EMAIL_USE_TLS = True Where I have user and password in as environmental variables. The error I am getting is SMTPSenderRefused at /accounts/password_reset/ (550, b'5.7.1 Relaying denied', 'webmaster@localhost') -
how do I change the date format on selectDate django widget?
I have a date field of a form and I want it to have a format like '21 jan 2020' but I can't find a way to pass it on the selectDate widget class MemoryForm(ModelForm): class Meta: model = Memory fields = ["date"] labels = {"date": ""} widgets = { 'date': SelectDateWidget(attrs={"class": "time", "date_format":'%m/%d/%Y'}), } I've tried others attrs instead of "date_format":'%m/%d/%Y' like "months":'%m' , or "months_field":'%m' but none seemed to work the output was always '21 january 2021' -
API Transition : From GraphQL to REST (with Django)
For my current project (stack = Django + API + Vuejs), up to now I used GraphQL for my API (over Django, with graphene-django). But this library and other linked one (such as the one that handles JWTs) are quite abandoned, with bugs and weird things so to be more confident in the future I decided to switch to the well-known Django DRF. The thing is, I'm now quite used to GraphQL system of queries and mutations, which is (maybe because I'm used to it) quite simple in its design and when it comes to start with DRF, I feel kinda lost. Indeed, I think I understood the easiest way is to use both ModelSerializer and ModelViewSet but... I feel it's hiding lots of things under the hood. Like it has default methods (list(), retrieve(),...). What if I want to controll all this by defining only the necessary ? Moreover, I have really specific needs. For instance, update is not just giving all the arguments, update the model and TADAAA. For specific fields I have to perform specific actions. (e.g.: if a particular field is modified, send a mail,...) Maybe the best way for my use case is to use … -
How do I point to Node in a dockerized Django project using django-pipeline?
I'm trying to add django-pipeline to a dockerized Django 3.1 project. However, when I run collectstatic I receive the following error: pipeline.exceptions.CompressorError: b'/usr/bin/env: \xe2\x80\x98node\xe2\x80\x99: No such file or directory\n' My settings.py file includes: PIPELINE = { 'CSS_COMPRESSOR': 'pipeline.compressors.yuglify.YuglifyCompressor', 'COMPILERS': ('pipeline.compilers.sass.SASSCompiler',), 'YUGLIFY_BINARY': str(BASE_DIR.joinpath('node_modules/.bin', 'yuglify')), 'SASS_BINARY': str(BASE_DIR.joinpath('node_modules/.bin', 'sass')), 'STYLESHEETS': { 'twirlmate': { 'source_filenames': ( 'pages/scss/styles.css', ), 'output_filename': 'css/styles.css', }, }, } And my package.json includes: { ..., "dependencies": { "sass": "^1.32.5", "yuglify": "^2.0.0" } } I have other local Django projects that use pipeline, but not Docker, and they work fine, so I'm wondering if it has to do with Node not being installed in the container? Any thoughts/help is appreciated. -
Uploading files impossible on Heroku with Python?
Heroku doesn't allow you to upload files, they rather you upload them to a cloud storage service such as Amazon s3. But, in order to upload a file to s3 using Python the file needs to be saved as you need the string path...? -
How can i make, flex or grid work with this template in django?
I want my website to display the videos on three columns, i've tried some answers i found online but none of them work. This is the template. this is the css. And this is the result. -
Django view sometimes routes to wrong URL
I have a Django project with this layout in the urls.py from django.contrib import admin from django.conf.urls import url as path from mapping import views urlpatterns = [ path('admin/', admin.site.urls), path('map/', views.Map, name='map'), path('address',views.Address_Search,name='address') ] views.py from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse,HttpResponse import geocoder import pdb bingkey='mykey' def Map(request): return render(request,'mapping.html') @csrf_exempt def Address_Search(request): try: address=request.POST.get('fname') print(address) g = geocoder.bing(address,key=bingkey) x,y= g.latlng[1],g.latlng[0] print(x,y) return JsonResponse({'id': 1,'x': x, 'y': y,'Address': address}) except Exception as e: print(e) return render(request,'mapping.html') and in templates I have a mapping.html which contains {% block content %} <html> {% load static %} {% load leaflet_tags %} {% load bootstrap4 %} <head> {% leaflet_js %} {% leaflet_css %} {% bootstrap_css %} <title>Sals Food</title> <style type="text/css"> #map {width: 100%;height:800px;} </style> <link rel="stylesheet" type="text/css" href="{% static 'search_bar.css' %}"> <link rel="stylesheet" href="{% static 'bootstrap-4.0.0-dist/css/bootstrap.css' %}" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet" /> <script type="text/javascript" src="{% static 'jquery/jquery-3.3.1.min.js' %}" > </script> <script type="text/javascript" src="{% static 'dist/leaflet.ajax.js' %}" > </script> <script type="text/javascript" src="{% static 'turf/turf.min.js' %}" > </script> <script type="text/javascript" src="{% static 'basemaps/leaflet-providers.js' %}" > </script> <script> function subForm() { var jsdata = {"fname": $('#fname').val()}; console.log(jsdata); var url = "/address/"; var jqHdr = $.ajax({ async: true, cache: false, type: … -
Why django custom user model giving error when inherited PermissionsMixin?
Whenever I want to inherit PermissionsMixin like UserAccount(BaseAbstractUser, PermissionsMixin) it gives an error, but if I don't inherit PermissionsMixin then my user model work but don't have some fields permissions, is_superuser. What is the right way? Error: ValueError: Invalid model reference 'app.auth.UserAccount_groups'. String model references must be of the form 'app_label.ModelName'. My Custom Model: # app/auth/models.py from django.contrib.auth.base_user import ( AbstractBaseUser, BaseUserManager ) from django.contrib.auth.models import PermissionsMixin from django.utils import timezone from django.utils.translation import gettext_lazy as _ class UserManager(BaseUserManager): def _create_user(self, email, password=None, **extra_fields): # altmost the same codes here... user.save() return user def create_user(self, email, password=None, is_active=True, **extra_fields): # altmost the same codes here... return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): # altmost the same codes here... return self._create_user(email, password, **extra_fields) class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=150, blank=True) last_name = models.CharField(_('last name'), max_length=150, blank=True) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_( 'Designates whether the user can log into this admin site.' ), ) date_joined = models.DateTimeField( _('date joined'), default=timezone.now, editable=False ) last_login = models.DateTimeField(null=True) objects = …