Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to add a ring on website using python django framework
I am creating a website using Django so the website shows stock prices and updates them every five seconds how and at a certain price some signals are on the website how can I add a bell if the signal appears so noise is there once we some signal generated -
How to import python functions from different file (in Ubuntu)
I have a python file called hero.py that refers to other python files located in views.py (Both these files exist in the same folder). hero.py code : #!/usr/bin/env python3 from .views import main, returnSum, most_frequent, find_mine_site_view_id, get_user_Activity, initialise_analytics_reporting list_of_mines = ['mine1', 'mine2', 'mine3'] start_date = 'yesterday' end_date = 'yesterday' main(list_of_mines, start_date, end_date) After making the file executable with chmod +x hero.py and adding #!/usr/bin/env python3 at the top of hero.py, I get this error when running ./hero.py: Traceback (most recent call last): File "./hero.py", line 2, in <module> from .views import main, returnSum, most_frequent, find_mine_site_view_id, get_user_Activity, initialise_analytics_reporting ModuleNotFoundError: No module named '__main__.views'; '__main__' is not a package I am aware that my views.py is not a package, I simply want to import the functions that exist within views.py Not sure if it is an Ubuntu thing. Please help When running ls -la in the folder where both files exist: total 72 drwxrwxr-x 8 llewellyn llewellyn 4096 May 13 06:39 . drwxrwxr-x 6 llewellyn llewellyn 4096 May 11 19:19 .. drwxrwxr-x 3 llewellyn llewellyn 4096 May 7 08:52 .idea -rw-rw-r-- 1 llewellyn llewellyn 0 May 7 07:21 __init__.py drwxrwxr-x 2 llewellyn llewellyn 4096 May 13 06:18 __pycache__ -rwxrwxr-x 1 llewellyn llewellyn … -
How to avoid an authentication error during testing drf?
During the development process, all classes were written with a variable permission_classes = [permissions.AllowAny, ]. In the file setting.py set 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', ], When writing the tests, it was not considered that user authentication is required to fulfill the request. Therefore, when the parameter [permissions.AllowAny, ] was removed the error 401 Unauthorized occurred. old_test.py from django.test import TestCase, Client from django.urls import reverse from django.db import IntegrityError from rest_framework.test import APITestCase from rest_framework import status class VendorProfileUpdateViewTest(APITestCase): def test_check_partial_update_api(self): data = {"vendor_name": "UN"} vendor = Vendors.objects.create(vendor_name="U4", country="US", nda="2020-12-12", ) VendorContacts.objects.create(contact_name="Mrk", phone="2373823", email="test@gmail.com", vendor=vendor) _id = vendor.vendorid url = reverse('vendor_update', kwargs={'vendorid': _id}) response = self.client.put(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) vendor = Vendors.objects.get(vendorid=_id) self.assertEqual(vendor.vendor_name, 'UN') I tried to add force_authenticate() configuration in the following way: class ContactsUpdateViewTest(APITestCase): def tearDown(self): self.client.force_authenticate(user=None) def test_contact_partial_update_api(self): .... But there have been no changes. -
Django: Call Python Function on Button Click and Display String
I found a couple of resources online, but none that worked for me. Here is what I currently have: In views.py: def button(request): return render(request, 'home.html') def display_text(request): return HttpResponse('TESTING', status=200) In urls.py: urlpatterns = [ url(r'^$', views.button), url(r'^display_text', views.display_text, name='script'), ] In home.html: <div class="row"> <input type="text" class="form-control js-text" id="input-box" placeholder="Type something to begin..."/> <div class="col-md-12" style="text-align:center;"> <button onclick="location.href='{% url 'script' %}'"></button> <hr> </div> </div> What happens right now is that it displays the string on a new web page. What I want to do is populate my text-box with that string returned by my Python function, and display it on the current page. How can I do so? Thanks! -
Relation does not exist, in PostgreSQL, Django
So I've created a new model in Django, then executed both python manage.py makemigrations and python manage.py migrate in the right order. But then for some reason I accidentally dropped the table(relation) in PgAdmin (I know it sounds silly). So I tried deleting all the files in migrations folder but the init.py file. Then I ran the two commands above again, but could see no table in the PgAdmin. What should I do, aside from creating a table myself in PgAdmin? Thanks in advance. -
Displaying comments using Ajax
i am working on a project using Django. There are lists of users posts in homepage and each post has a comment form. I was able to implement comment properly, but the issue now is how do i display comment on each post by user when a form is submitted. I attached an image to my questioin to clarify my question. home.html <!-- New Feeds comment Text --> {% if post.comments.all %} <div class="container newfeeds-comment" id="display-comment"> {% for comment in post.comments.all|slice:":1" %} <div class="row"> <div class="col-1 col-md-1 col-lg-1"> {% if comment.user.profile.profile_pic %} <img src="{{ comment.user.profile.profile_pic.url }}" class="d-flex rounded-circle" alt="image" height="28" width="28"> {% endif %} </div> <div class="col-10 col-md-10 col-lg-10 p-2 ml-1" id="user-commentpost"> <span class="comment-post truncate"> <span class="name text-lowercase">{{ comment.user }}</span> {{ comment.comment_post }}</span> </div> </div> {% endfor %} </div> {% endif %} Ajax: <script type="text/javascript"> //HomeFeeds Comment $(document).ready(function() { $('.feeds-form').on('submit', onSubmitFeedsForm); $('.feeds-form .textinput').on({ 'keyup': onKeyUpTextInput, 'change': onKeyUpTextInput }); function onKeyUpTextInput(event) { var textInput = $(event.target); textInput.parent().find('.submit').attr('disabled', textInput.val() == ''); } function onSubmitFeedsForm(event) { event.preventDefault(); console.log($(this).serialize()); var form = $(event.target); var textInput = form.find('.textinput'); var hiddenField = form.find('input[name="post_comment"]'); $.ajax({ type: 'POST', url: "{% url 'site:home' %}", data: form.serialize(), dataType: 'json', beforeSend: function() { form.find('.submit').attr('disabled', true); }, success: function(response) { $('#newfeeds-form' + … -
React x django Unhandled Rejection (TypeError): Cannot read property 'status' of undefined
im trying to implement a react as a front end to my django project. Right now im building the authentication system based off django-rest-framework-simplejwt and redux. I have just started learning react and i only understand the bare minimum to get an application working . Coming from a django background where most of these authentication is handled for me , authentication is really foreign to me. So far , i have been able to get the authentication to work , however im facing 2 issues: The error message : React x django Unhandled Rejection (TypeError): Cannot read property 'status' of undefined appears occasionally (Im not sure why) Upon logging in , in the component did mount method , the data i got from the API does not render in the console reads: xhr.js:178 GET http://127.0.0.1:8000/api/customer-information/ 401 (Unauthorized) even though in the console , it printed out the token comp did mount xxxxxxxx Heres some of my code to demonstrate the system: An example component class CustomerList extends Component { state = { customers: [], }; apiGet() { try { axiosInstance.get('/customer-information/') #<----- here i call the axios instance .then(response => { this.setState({ customers: response.data }); $('#customerlist').DataTable({ "scrollY": "70vh", "scrollCollapse": true, "paging": … -
How to configure axios to request to particluar <domain_name>/<path> just by writing path without having to hardcode domain name every time
Hey guys I am doing a project that uses Python as a backend and React as a frontend. Everything works fine. After deploying to heroku I changed all my axios request URL to my domain name. But I realize if I change my domain name I have to change the axios URL in my react app everytime. I have used redux to do perform axios request for CRUDL and all types of authentication. I know this sounds stupid but is there a way to configure all the axios request to particular domain name by only giving path name every time it makes request? Thanks -
The view accounts.decorators.wrapper_function didn't return an HttpResponse object. It returned None instead [closed]
sadly I am also having the same error. I am also followinf Mr. Dennis Ivy's lessons.Try to creating qith a new user. But it is also not working for me. please if someone can help me with this , I is great. from django.http import HttpResponse from django.shortcuts import redirect def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('home') else: return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorized to view this page') return wrapper_func return decorator def admin_only(view_func): def wrapper_function(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group == 'customer': return redirect("user-page") if group == 'admin': return view_func(request, *args, **kwargs) return wrapper_function from django.shortcuts import render, redirect from django.forms import inlineformset_factory from .models import * from .forms import OrderForm, CreateUserForm from .filters import OrderFilter from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from .decorators import unauthenticated_user,allowed_users,admin_only from django.contrib.auth.models import Group -
How to autoload DNS and server status on webpage using django and ajax?
we have 50 servers and 70 DNS. i have implemented web page using Django to display all the servers and DNS on web page with test button. when i click on test button , bakcend it will run sub-process command and shows the status. is there any way to load automatically and show the status of DNS and server with some colour on autoload (planning to skip test button and status column). can someone please help on this? Thanks in advance. -
how to render data on header and footer in django
If I have dynamic categories come from db and I want to render the same on header and footer. I know it's easy just pass it to the get_context_data(), but in this case I need to write the db query for all views of every app so I want to handle it just like Laravel, we put the code on BaseController once, and that it, the dynamic data is access on every page of header and footer. Does it possible on Django. If it's not which approach did you use to get this. -
Django return JsonResponse as a context?
I have a simple follow and un-follow button on my site. Each button it's own specific inline style and trans tags. When you click one of these buttons it would reload the entire page. I didn't really like this so I decided to use AJAX to not have the page reload. After struggling for some time, I finally got it working, but I have issues where it's replacing the entire text of my tag. This also includes any icons I had next to the text. I am wondering if there is a way I can return the JsonResponse as a context, such that I can accomplish something like this: {% if json follow_record is 'added' %} show a specific <a> {% else %} show a different <a> {% endif %} This is what I currently have: View: @login_required def follow(request, pk): #friend unfriend sidebar if request.is_ajax(): print("inside follow function") follow_user = User.objects.get(id=pk) print(follow_user) follow_record = Follower.objects.filter( user=request.user, follow_to_id=pk).first() if follow_record: follow_record.delete() follow_record = "deleted" else: if request.user.id != pk: Follower.objects.create(user=request.user, follow_to_id=pk) follow_record = "added" context = {'follow_record':follow_record} return JsonResponse({'friend_added':True, 'follow_record':follow_record}, context) and the JS code: $('#friend-button-ajax').on('click', function(){ var friend_id = $(this).attr("data-friend_user_id"); console.log(friend_id); friend_idd = parseInt(friend_id); $.ajax({ url: "/account/follow/" + friend_id, … -
How to populate my Django database using scraped data?
I am working on a project that is to develop a book site and I want to populate my project with books by writing a script instead of adding the books manually. I have Scrapped Data from https://www.amazon.in for books using bs4, but I want to use that data to populate my Django model with the same fields as scrapped data which I don't know how. if anyone could help me how to use this scarp data to store in Django models that would be great. PS: not using external CSV or Json Files would be great. I have tried these solutions but they did not work for me: How to populate a Django sqlite3 database populate Django model with scraped data This is the content which I scraped from amazon: Amazon books that I scraped This is my models.py: from django.db import models from django.contrib.auth.models import User class Product(models.Model): name = models.CharField(max_length = 200, null = True) price = models.DecimalField(max_digits=7, decimal_places=2) digital = models.BooleanField(default=False, null=True, blank=True) image = models.ImageField(null = True, blank = True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = "" return url This is my scrape.py: from urllib.request import urlopen … -
python for loop list comprehension - add function
I am trying to implement https://github.com/django-recurrence/django-recurrence into my Django application. Since, widget is not working for me I need to do it programmatically. I'd like to implement weekly recurrence. from datetime import datetime import recurrence my_week_day_dict = { 'P': 'recurrence.MONDAY', 'U': 'recurrence.TUESDAY', 'S': 'recurrence.WEDNESDAY', 'C': 'recurrence.THURSDAY', 'A': 'recurrence.FRIDAY', 'O': 'recurrence.SATURDAY', 'N': 'recurrence.SUNDAY' } for day in ['U', 'O', 'N']: mypattern = recurrence.Recurrence( dtstart=datetime.datetime.now(), dtend=datetime.datetime.now() + datetime.timedelta(days=19), rrules=[ recurrence.Rule(recurrence.WEEKLY, byday=exec(my_week_day_dict[day])) for day in day ], include_dtstart=False ) In the database I can see: DTSTART:20200512T000000Z DTEND:20200531T000000Z RRULE:FREQ=WEEKLY RRULE:FREQ=WEEKLY RRULE:FREQ=WEEKLY And output is: >>> date_obj = Availability.objects.first().recurrences.occurrences() >>> for i in date_obj: ... print(i) ... 2020-05-12 00:00:00+00:00 2020-05-19 00:00:00+00:00 2020-05-26 00:00:00+00:00 2020-05-31 00:00:00+00:00 My problem is in: [ recurrence.Rule(recurrence.WEEKLY, byday=exec(my_week_day_dict[day])) for day in days_in_week ], I think. The byday is missing. Does anyone has an idea how to get it works? Thank you for you time and help! -
Contents of folder to be displayed as a list in Django
I've uploaded a few files to the location /media/myfolder/file1.xml /file2.html /file3.txt I know I can access the individual files by giving the full path (http://127.0.0.1:8000/media/myfolder/file1.xml). But I need to get a list of all these files when I access http://127.0.0.1:8000/media/myfolder/ and then be able to view each of them by simply clicking on them. So, in general I need to access the contents of a folder. Is there an easy way to do this? -
Is there a way to call a django function without refreshing the page
I'm trying to create a function that generates a random value in django so that it can be recorded, and then is passed into a javascript file where it spins a wheel to show the animation, and then after the animation is over puts 10 coins into the profiles account. The problem is when I use a view function, the return type is a page redirect, so the animation gets cut off. Is there a type of django function that can parse in values without a redirect, similar to a C++ void function? Here's the code I have so far views.py @login_required def Red(request): profile = get_object_or_404(Profile, user=request.user) profile.coins += 10 profile.save(update_fields=['coins']) random = random.randrange(11) return render(request, "bets/bets.html", {'random' : random}) Profile model: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) coins = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) def __str__(self): # @ts-ignore return f'{self.user.username} Profile' and the html with the javascript in it <div class="Container"> <div class="inputContainer" blank="False"> {% csrf_token %} <span class="coinContainer2"><i class="fas fa-coins"></i></span> <input name="amount" class="amountInput" type="number" min="0.01" placeholder="Enter Amount"> <div class="sideContainer" id="buttonNav"> <span class="redButton"><button type="button" class="btn btn-danger" id="buttonRed" name = "redButton"> <a href="{% url 'redButton' %}" style="text-decoration: none; color: white;"> Red </a> </button></span> … -
Error with getting ForeignKey object from the object it is assigned under
I have two models in my models.py, Question and Choice. Since ForeignKey was used to link Choice as a child of Question, I assumed I could do the same for the built-in user object and the question object. I made a question object and linked it with the user I made, and all worked well until I tried to get the user using "question_object.author" (I named the ForeignKey "author" under the question object). So do I need to link the user and question object another way? or am I just trying to get the user object the wrong way? Thanks in advance for any help. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') author = models.ForeignKey(User, on_delete=models.CASCADE) -
django: Duplicate resolution on saving (insert)
I have a complex form with 2 inline formsets for entering a new record. When the form is submitted, a duplicate check needs to be made and if the entry, as defined by business rules, already exists, then the user needs to decide if he wants to add a child to the existing entry (this is one of the inline formsets) or if he wishes to proceed with entering the new record. What a user can do depends on his privileges. My question is how should I design this workflow? I'm coming from From A in View A and then I need to redirect to a different Form / webpage to show the resolution options but I obviously need to keep track of the already entered form data. How can I do that or what is the "django way" of doing this? -
docker stuck on pip install
I have lots of headaches while trying docker, but this one is killing me I am trying to install django on docker, but it got stuck on this line: Successfully installed asgiref-3.2.7 django-3.0.6 pytz-2020.1 sqlparse-0.3.1 Dockerfile: FROM python:3.6 COPY . /app WORKDIR /app CMD chmod +x entry.s # ENTRYPOINT ["./entry.sh"] # this will give me, ./entry.sh: Permission denied ENTRYPOINT ["sh", "./entry.sh"] entry.sh: echo entry point for django image cd code pip install -r requirements.txt # for keep container running, I couldn't find any other way touch app.log tail -f app.log docker run output: entry point for django image Collecting django Downloading Django-3.0.6-py3-none-any.whl (7.5 MB) Collecting sqlparse>=0.2.2 Downloading sqlparse-0.3.1-py2.py3-none-any.whl (40 kB) Collecting pytz Downloading pytz-2020.1-py2.py3-none-any.whl (510 kB) Collecting asgiref~=3.2 Downloading asgiref-3.2.7-py2.py3-none-any.whl (19 kB) Installing collected packages: sqlparse, pytz, asgiref, django Successfully installed asgiref-3.2.7 django-3.0.6 pytz-2020.1 sqlparse-0.3.1 --> stuck here -
New having problems with Update request
Hello i started Django recently and was looking guides and i encountered this problem, when i try to click on the bottom to update the database on the html page i dont see the form to update Note: I can create, delete , and view the things i create i just cant update them. This is the update function: def todo_update(request, id): todo = Todo.objects.get(id=id) form = TodoForm(request.POST or None, instance=todo) if form.is_valid(): form.save() return redirect('/') context = {'form ': form} return render(request, 'todo_update.html', context) And this is what the html page looks like: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name='viewport' content="width=device-width , initial-scale=1.0"> <title>Django Project</title> </head> <body> <h4>Update</h4> <form method="POST"> {% csrf_token %} {{ form.as_p}} <button type="submit">Submit</button> </form> </body> -
django.db.utils.OperationalError; filtering QuerySet with date lookup
I'm going through an example where a Model has a DateTimeField defined upon it. When trying to create a filtered QuerySet with a date lookup, the following error is returned. I'm confused as to why this error is being raised. It makes it sound like a function that I wrote is causing the error (which is not the case), but perhaps I'm reading that incorrectly. django.db.utils.OperationalError: user-defined function raised exception >>> a = Employee.objects.create( alias="User", age=0, hired=datetime(2020, 6, 12), experience=0 ) >>> result = Employee.objects.filter(hired__date__gt=datetime(2019, 1, 1)) from django.db import models class Employee(models.Model): alias = models.CharField(unique=True, max_length=11) age = models.IntegerField() hired = models.DateTimeField() experience = models.IntegerField() def __str__(self): return self.alias -
Django manytomany field filter problem(I can not get the result I want)
Hello, I want it to bring a single menu, but it brings all the menus in that database.Please help me how to solve my problem? Hello, I want it to bring a single menu, but it brings all the menus in that database.Please help me how to solve my problem? **views.py** -------------------------------------------------------------------------------------------------- def restoran_detail(request,id,slug): restoran = Restoran.objects.get(pk=id) category = Category.objects.all() menu = Menus.objects.get(id = restoran.menu_id) menu_tipleri = MenuT.objects.filter(id__in = menu.yiyecek.values_list('m_tipi_id' , flat=True)) context = { 'restoran': restoran, 'menu': menu, 'category': category, 'menu_tipleri': menu_tipleri } return render(request,'restoran_detail.html',context) ---------------------------------------------------------------------------------------------------- **models.py** ----------------------------------------------------------------------------------------------------- class MenuT(models.Model): title = models.CharField(max_length=30) keywords = models.CharField(max_length=255) description = models.CharField(max_length=255) def __str__(self): return self.title def get_yiyecekler(self): return Yiyecek.objects.filter(m_tipi=self) class Yiyecek(models.Model): STATUS = ( ('True', 'Var'), ('False', 'Yok'), ) m_tipi = models.ForeignKey(MenuT, on_delete=models.CASCADE) title = models.CharField(max_length=50) keywords = models.CharField(max_length=255) description = models.CharField(max_length=255) detail = RichTextUploadingField(blank=True) image = models.ImageField(blank=True, upload_to='images/') price = models.FloatField() status = models.CharField(max_length=10, choices=STATUS) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Menus(models.Model): title = models.CharField(max_length=30) keywords = models.CharField(max_length=255) description = models.CharField(max_length=255) yiyecek = models.ManyToManyField(Yiyecek) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title -
Solr returning way more values
Using Django 2.2.7, Python 3.6.9, PySolr 3.8.1, DJANGO Haystack 2.8.1 haystack_conn = {} search_engine = 'solr' if search_engine == 'whoosh': haystack_conn = { 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine', 'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'), } elif search_engine == 'solr': haystack_conn = { 'ENGINE': 'haystack.backends.solr_backend.SolrEngine', 'URL': 'http://127.0.0.1:8983/solr/bsd', } elif search_engine == 'elastic_search': haystack_conn = { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'artifacts', } HAYSTACK_CONNECTIONS = { 'default': haystack_conn, } HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' HAYSTACK_SEARCH_RESULTS_PER_PAGE = 10 When I search for ex. ios I get 250 results. When I search ios 10 i get 500 results, although I should get less .. around 90. -
Calling a Django Function upon an html button click
I'm trying to create a function where when an html button is clicked, the "coins" a profile has is incremented by 10. Here's my html <div class="sideContainer" id="buttonNav"> <span class="redButton"> <button type="button" class="btn btn-danger" id="buttonRed" name = "redButton"> <a href="{% url 'redButton' %}"> Red </a> </button> </span> </div> Here's my view @login_required def Red(request): Profile.coins += 10 return(request, "home/home.html") Here's my profile model from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) coins = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) def __str__(self): # @ts-ignore return f'{self.user.username} Profile' And Here is my urls.py from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('redButton/', views.Red, name='redButton'), ] Thanks! -
Custom user model can't login after creation
I'm trying to login with an account with my new custom user model. My superuser I created with my user model logs in just fine. However when I create non superuser account through the admin panel and try to login with exact credentials it fails. Here is my code: accounts/models.py from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) # Create your models here. class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name, company, phone, is_active=True, is_admin=False, is_staff=False, is_dealer=False, password=None): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") if not first_name: raise ValueError("Users must have a first name") if not last_name: raise ValueError("Users must have a last name") if not company: raise ValueError("Users must have a company") if not phone: raise ValueError("Users must have a phone number") user_obj = self.model( email = self.normalize_email(email) ) user_obj.set_password(password) user_obj.first_name = first_name user_obj.last_name = last_name user_obj.company = company user_obj.phone = phone user_obj.admin = is_admin user_obj.staff = is_staff user_obj.dealer = is_dealer user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_superuser(self, email, first_name, last_name, company, phone, password=None): user = self.create_user( email, first_name, last_name, company, phone, password=password, is_admin=True, is_staff=True ) return user def create_staff_user(self, email, first_name, …