Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I set a ForeignKey on a specific attribute from another table?
This is my first class Klant wich means customer. It has an id, a customer-name and users from the customer wich is a ManyToManyField referring to users from the the User-table django gives me. class Klant(models.Model): id = models.AutoField(primary_key=True) klant_naam = models.CharField(max_length=100, default='-') klant_gebruiker = models.ManyToManyField(User) def __str__(self): return str(self.id) + " - " + self.klant_naam This is the class Actie (Action or the action the user determines) wich has an id, an action-name, an action-publish-date, an ending-date (the deadline), a customer-id wich refers to Klant and actie_gebruiker that I want to refer to klant_gebruiker from the table Klant. class Actie(models.Model): id = models.AutoField(primary_key=True) actie_naam = models.CharField(max_length=150, default='-') actie_aanmaakdatum = models.DateTimeField(default=datetime.now()) actie_einddatum = models.DateTimeField(default=datetime.now() + timedelta(days=1)) actie_klant = models.ForeignKey(Klant, default=1) actie_gebruiker = models.ForeignKey(Klant.klant_gebruiker, default=1) def __str__(self): return str(self.id) + " - " + self.actie_naam So my question now is what do I have to do to set the value of actie_gebruiker to the attribute klant_gebruiker from the table Klant? -
Django fields editable in create but not in edit
I am creating a small application where I am able to add / modify / delete / view a member. def member_edit(request,member_id): MemberForm = modelform_factory(Member, fields=('employee_id', 'employee_name')) if request.method == 'POST': member = MemberForm(request.POST) if member.is_valid(): member.save() return HttpResponseRedirect(reverse("members:member_view")) else: member = get_object_or_404(Member, pk=member_id) return render(request, 'members/member_edit.html', {'member': member}) I notice that instead of being able to edit all the fields become in display mode. <form action="" method="post"> {% csrf_token %} {{ form.non_field_errors }} <table> <tr> <th> <label for="{{ member.employee_id.id_for_label }}">Employee id:</label> </th> <td> <input type="text" value = {{ member.employee_id }} /> </td> <td> {{ member.employee_id.errors }} </td> </tr> <tr> <th> <label for="{{ member.employee_name.id_for_label }}">Employee Name:</label> </th> <td> <input type="text" value = {{member.employee_name }} /></td> <td> {{ member.employee_name.errors }} </td> </tr> </table> <input type="submit" value="Update"> If I change the member_edit function to this, it works but I don't have any data to change(obviously) : def member_edit(request,member_id): MemberForm = modelform_factory(Member, fields=('employee_id', 'employee_name')) if request.method == 'POST': member = MemberForm(request.POST) if member.is_valid(): member.save() return HttpResponseRedirect(reverse("members:member_view")) else: member = MemberForm() # change made only here return render(request, 'members/member_edit.html', {'member': member}) What am I missing here ? -
Django: form validation for a form with tabular inline
Hello i have registered models like that # models.py class Property(models.Model): address = models.TextField() ... class PropertyImage(models.Model): property = models.ForeignKey(Property, related_name='images') image = models.ImageField() is_front = models.BooleanField(default=False) and: # admin.py class PropertyImageInline(admin.TabularInline): model = PropertyImage extra = 3 class PropertyAdmin(admin.ModelAdmin): inlines = [ PropertyImageInline, ] admin.site.register(Property, PropertyAdmin) The is front picture is boolean so I know which will be the picture to be shown on the announces Problem I don't know how to make validation so I can throw an eror If 0 or more that 1 picture were chosen as is_front can you please help me with the admin form validation? Thank you! -
django redirects : how to make exact redirect
I need return redirect(url) in django, and force template to do to this url. It returns me template html-code instead when EXACTLY redirect is required. Any ideas? Now i have to write redirect in templates window.location='url' , it works, but make code tangled. django.__version__ == '2.0.1' -
Transform data with django ORM
I have the following model: class Entry(models.Model): name = models.CharField(max_length=100) date = models.DateTimeField(default=timezone.now) material = models.CharField(max_length=20]) price = models.FloatField(null=True) With data as follows: john, 2011-01-21, GOLD, 10.00 blair, 2011-01-21, GOLD, 20.00 peter, 2011-01-21, SILVER, 21.00 peter, 2011-01-22, GOLD, 11.00 john, 2011-01-22, SILVER, 12.00 I would like to: aggregate (addition) by material per date produce an entry per day, with all the available materials (not known in advance) As follows: DATE GOLD SILVER 2011-01-21 30.00 21.00 2011-01-22 11.00 12.00 (dates not present in the input data will not get an output row) How can this be achieved in SQL? With Django ORM? Note: my database backend is Postgres -
django custom management command to add files into a client's app
I need to write a custom command for those users who use my package so they are able to add some python files into their apps from my package (later on they can use these added files as a template for further use). So what I have in mind now is to add a 'management' folder into my package so the users who install the package can type: django my_command_name THEIR_APP_NAME which will result that a file from my package will be added to the THEIR_APP_NAME folder. I know that it can be done just by writing a custom management command 'from scratch' as it is described here (https://docs.djangoproject.com/en/2.1/howto/custom-management-commands/) But on the other hand the AppCommand (a subclass of BaseCommand) seems to do a very similar job: it takes a template from within Django and moves it into a project (not app!) folder. How (if at all) I can subclass AppCommand to do the trick? -
Make a django query with a list of parameter
i have a list of id like : ids = [1,2,3] Is there a quicker way to do a query for all of them than a for ? Like: users = [] for id in ids : users.append(User.objects.get(id=id)) thanks -
Django 2.1 - ManyToMany on_delete
Im having a problem with Django 2.1 and on_delete mandatory field. I have an ORM like this: class Slideshow(models.Model): bla bla dashboards = models.ManyToManyField( Dashboard, through='SlideshowDashboard', through_fields=('slideshow','dashboard') ) class SlideshowDashboard(models.Model): dashboard = models.ForeignKey(Dashboard, on_delete = CASCADE) slideshow = models.ForeignKey(Slideshow, on_delete = CASCADE) slide_time_dashboard = models.DurationField(null = True, blank = True) slide_order = models.IntegerField(null = True, blank = True) Dashboard is another Model. When updating the information about Slideshow, I need to TRUNCATE al previous Dashboard associated to Slideshow to save the new list. So I use: slideshow_to_save.dashboards.all().delete() Unfortunally, and I don't know why, this command delete the Dashboard related entry in Dashboard table. By specific, on_delete should delete SlideshowDashboard if I delete a Dashboard, not the opposite. -
How to link two models, each with its own template using foreignKey in Django
I want to link two models using foreignKey, The problem is when i try to do that, one model does not get foreignKey value for the next model in the database table. The aim is for user to fill information on the first page (have its own model and template) then click next (fill more info in the next page having its own model and template) then click next for the same logic. then when other users view this post it must show all content from different models in one page. here is my code. 1st model class Map(models.Model): user = models.ForeignKey(User, default=None, blank=True, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100) position = GeopositionField() HAVING ITS OWN TEMPLATE 2nd Model class Post(models.Model): parent = models.ForeignKey("self", default=None, blank=True, null=True, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, default=None, on_delete=models.CASCADE) title = models.CharField(max_length=50) content = models.TextField() map = models.ForeignKey(Map, related_name='mapkey', default=None, blank=True, null=True, on_delete=models.CASCADE) HAVING ITS OWN TEMPLATE BUT also has serializer method(API) below: class PostModelSerializer(serializers.ModelSerializer): user = UserDisplaySerializer(read_only=True) parent = ParentPostModelSerializer() map = serializers.SerializerMethodField() class Meta: start_date = forms.DateField(widget = forms.SelectDateWidget()) end_date = forms.DateField(widget = forms.SelectDateWidget()) model = Post fields = [ 'id', 'user', 'title', 'content' 'image', 'map', ] Please focus only on the map field as … -
Get count of Related Objects DRF Django
I've a massive database where we've large tables I used DRF to get the count i used SerializerMethodField. But It's taking too long to get the count. I need an efficient way to get counts. Here's the Database structure of Relations Products id, Attributes, Categories, Sizes All Fields expect id are many to many relation Sizes id, Title Sizes Through (Table Joining the Sizes) id, size_id, product_id, stock Categories id, Title Categories Through (Table Joining the Products) id, category_id, product_id This table is created by django it self Now i'm listing sizes as filters in my site but i want to make sure i only put those sizes which have some products and i also want to put counts of the products and with each filter that should change as well let's say i selected a category now i only need those sizes which have products from specific categories . I hope anyone can help me with this situation. -
Django form auto adding same fields
I have a html form, with auto adding form elements by pressing + button. It browser it looks like this. If i press + form will auto add same elements, and i can adding elements as long as i want. Question is how to store date from every form as a new objects in database. I made a working form, but without adding same elements by button. Here is my code: model: class FtpPath(models.Model): period = ( ('Раз в сутки','Раз в сутки'), ('Раз в неделю','Раз в неделю'), ('Раз в 2 недели','Раз в 2 недели') ) ftp = models.ForeignKey(FTP, on_delete=models.CASCADE) path = models.CharField(max_length=200, blank=True) period = models.CharField(choices=period, max_length=20, null=True, blank=True) find = models.BooleanField(null=True, default=False) recursive = models.BooleanField(null=True, default=False) class Meta: verbose_name = 'FTP path' verbose_name_plural = 'FTP paths' Form: class FtpPathForm(forms.ModelForm): path = forms.CharField(widget=forms.TextInput(attrs={'type':'text','class':'effect-16'}), required=True) recursive = forms.BooleanField(widget=forms.CheckboxInput(attrs={'id':'check'}), required=False) period = forms.CharField(widget=forms.TextInput(attrs={'type':'text','style':'display:none'}), required=True) class Meta: model = FtpPath fields = ('path', 'recursive','period') View: if request.method == 'POST': ftppath = FtpPathForm(request.POST) if ftppath.is_valid: path = request.POST['path'] recursive = request.POST.get('recursive') if recursive == 'on': recursive = True else: recursive = False period = request.POST['period'] site = MySites.objects.filter(user=request.user).last() ftp = FTP.objects.filter(site=site).last() FtpPath.objects.create( ftp = ftp, path = path, recursive = recursive, period = period … -
which one is better?? Django vs Spring
I’m a beginner developer I’m learnning Spring and studying in django which one is better?? If possible, tell me two features and usable frontend language -
DRF show different fields on 'list' and 'get_object'
I am using viewsets like this: class UserViewSet(viewsets.ModelViewSet): """Viewset for model User.""" queryset = User.objects.all() serializer_class = UserSerializer and my serializer has following fields: fields = ('id', 'url', 'username', 'first_name', 'middle_name', 'last_name', 'role', 'get_role_display', 'is_authenticated', 'is_staff', 'is_superuser', ) When I access the api to list all users with this url /api/user/, it returns this json_data: [ { "id": 1, "url": "http://127.0.0.1:8000/api/user/1/", "username": "admin", "first_name": "", "middle_name": null, "last_name": "", "role": "A", "get_role_display": "Admin", "is_authenticated": true, "is_staff": true, "is_superuser": true }, { "id": 2, "url": "http://127.0.0.1:8000/api/user/2/", "username": "7004104463", "first_name": "Vaibhav", "middle_name": "Bold", "last_name": "Vishal", "role": "S", "get_role_display": "Student", "is_authenticated": true, "is_staff": false, "is_superuser": false } ] But what I am trying to do is returns only a few fields on list, say only 'id', 'username', 'url', but on requests where a single object is requested like this /api/user/1/ I want to return all fields. I want to avoid using two different rest_framework views. I want a single viewset and serializer to achieve this. Is there any way to make it happen? I am using React on frontend and I want to avoid fetching unnecessary data. -
Auto Discover tasks not working in Celery4
I have been using Celery previously in this project, I have tasks.py file in my app directory where some tasks are defined and scheduled in the Celery.py file but when i run celery -A project worker -l info the tasks in app/tasks.py file are not getting discovered due to a reason not able to figure out. Here is my tasks.py file @shared_task def fetch_interface_logs(*products): """ Function responsible for fetching the interface logs """ # print(products) for product in products: print(product[0]) headers = {'X-Auth-Token': ACCESS_TOKEN, "Content-Type": 'application/json'} log_URL = BASE_URL_PROD + ACTION_URLS.get('logs').format(product[0]) interface_resp = requests.get(log_URL, headers=headers).json() if Cloud.objects.filter(product_uid=product[0]): base_obj = Cloud.objects.get(product_uid=product[0]) elif Cloudx.objects.filter(product_uid=product[0]): base_obj = Cloudx.objects.get(product_uid=product[0]) interface_json = interface_resp['data'] for log in interface_json: if log['event']: interface = InterfaceLogs() interface.event_name = log['event'] interface.message = log['message'] interface.resource_type = log['resource_type'] interface.log_time = arrow.get(int(log['time']) / 1000).datetime interface.save() # print(interface.log_time) base_obj.interface_logs.add(interface) base_obj.save() return and here is the code for the Celery.py file from __future__ import absolute_import import os from celery import Celery from celery import shared_task from django.conf import settings from celery.schedules import crontab import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cloud_sdn.settings') django.setup() app = Celery('cloud_sdn') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all … -
Django Rest Framework - PermissionDenied raises 500 status code
i am working with django rest framework and want to raise a PermissionDenied exception and return a 403 response to user: raise PermissionDenied("Custom exception message") But it returns a 500 status code... Can anybody explain? thanks! -
How can I email a saved blob as attachment?
I'm sending a pdf as a blob via javascript to django, and then trying to send it as an email attachment. My code is: def SendPrescriptionbyMail(request, cliniclabel, patient_id): from django.core.files.storage import default_storage print(request.FILES) print(request.FILES['file']) myform = forms.Form(request.POST, request.FILES) file = myform.files['file'] print(file) file_name = default_storage.save(file.name, file) file = default_storage.open(file_name) print(f'file_name is {file_name}') file_url = default_storage.url(file_name) print(f'Or maybe {file_url}') recipient = 'joel@domain' import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart msg = MIMEMultipart() msg['Subject'] = "Your prescription" msg['From'] = "admin@me" msg['To'] = recipient msg.preamble = 'Your prescription is attached' msg.attach(MIMEText(file(file_name).read())) s = smtplib.SMTP('smtp.mailgun.org', 587) s.login('myid@somewhere', 'apikey') s.sendmail(msg['From'], msg['To'], msg.as_string()) s.quit() return HttpResponse('Successfully sent email') Output: <MultiValueDict: {'file': [<TemporaryUploadedFile: blob (application/pdf)>]}> blob blob file_name is blob_4VZxpHY Or maybe /data/blob_4VZxpHY 2018-11-14 19:02:36,554 django.request ERROR Internal Server Error: /clinic/madhav/prescription/sendemail/patient/18 Traceback (most recent call last): File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/joel/myappointments/clinic/views.py", line 4953, in SendPrescriptionbyMail msg.attach(MIMEText(file(file_name).read())) TypeError: 'File' object is not callable -
Django template fragment caching - is it possible to prerender?
I am looking into Django caching mechanism, namely template fragment caching. I am planning to cache list of books for every institute, because it takes too long to fetch it and render on every request. I plan to use it like this: {% load cache %} {% cache 600 sidebar student.institute %} <List of books for the institute> {% endcache %} If I understand correctly, it will work like this: For the first request from a student from the institute the list of books will be fetched and rendered, but for all subsequent requests it will be just taken from cache, till the cache invalidates. So the first request after invalidation is always slow. Is it possible to automatically pre-fetch and pre-render this template fragment for all possible institutes, so that even the first request would just hit the cache? -
Abstract or generic django class inheritance?
I want to be able to get the list of all wallets in my app - but every wallet needs to be specified as UserWallet, TeamWallet, CarWallet, and so on. There should be no generic wallet instances. I still want to be able to set foreign keys in other models (eg payment model) to the generic wallet model or link in a way to the wallet without having one foreign key for each child model. I see these advantages for generic class inheritance: I can get a list of all wallets I can set foreign keys to the parent wallet model Disadvantages for the generic class inheritance: I can't make prohibit creating a generic wallet inheritance. Slower cause of JOIN in database Confusing DB structure I see these advantages of using abstract class inheritance: No generic wallet instances possible. Easy database table structure. Disadvantages for the abstract class inheritance: I need to use itertools or other hacks to get a list of all wallets. I need to set up one foreign key for each child model in outside models, or use slow contenttype keys. As I am pretty new to Python and Django development, I think I'm misssing quite some … -
Django rest framework return model queryset based on user
We are building middleware and have the following situation: we have different users, each has their own database (not managed by us), all have some sort of 'Order' table. We built an API endpoint where users can create an Order, a buffer is linked to the Order and based on the user who created the Order we send it to the correct database. This basically means we have a 'middleware' model Order, and during processing the Order is parsed to match the structure of the user's database and create it in their database. Now we want to retrieve the orders from their database and display them at our API endpoint. We have non-managed models for the users to retrieve the orders, one is called AppOrder. But since our endpoint uses the middleware Order model we cannot simply return AppOrder.objects.all() when user is X, since the serializer is built for Order not for AppOrder. class OrderViewSet(viewsets.ModelViewSet): queryset = Order.objects.all() # <-- Simply returns all middleware Order objects, not what we want serializer_class = OrderSerializer The response should be the same, e.g. it should not be different if another user with a different db makes the call. How can I, based on … -
Building Web via Django connect with request,json and beautiful soup
My code python3 are working via jupyter but now im working to develop interface that is using django as web application.. im know basic django and the website is already run but how do i connect my code that is use request json beautiful soup with django.. what should i put at views.py , templates, models.py? Any suggestion website to follow or tips? -
Filtering searches with Elasticsearch
My project is a search tool which searches by questions and/or responses. I want it to also be able to filter the searches by e.g. topics, clients. Each response is mapped to a question, topic and client with a foreign key. I am able to search by questions and responses but when I add in the filter topics, it returns 0 results. models.py: class Topic(models.Model): Definition = models.TextField(default='Definition') Name = models.TextField(default='Name') class Meta: ordering = ['Name'] def __str__(self): return self.Name class Question(models.Model): Statement = models.TextField() def __str__(self): return self.Statement class Response(models.Model): Question = models.ForeignKey(Question, on_delete=models.CASCADE) Topic = models.ForeignKey(Topic, default=13, on_delete=models.CASCADE) Response = models.TextField() Client = models.ForeignKey(ClientDetail, default=8, on_delete=models.CASCADE) Planit_location = models.ForeignKey(Planit_location, default=1, on_delete=models.CASCADE) Date_added = models.DateField(default=datetime.date.today) def __str__(self): return self.Response documents.py: class ResponseDocument20(DocType): Question = fields.NestedField(properties={ 'Statement': fields.TextField(), 'pk': fields.IntegerField(), }, include_in_root=True) class Meta: model = Response fields = [ 'Response' ] related_models = [Question] def get_instances_from_related(self, related_instance): if isinstance(related_instance, Question): return related_instance.response_set.all() views.py: if q:#ES cleanQ = stopwords.strip_stopwords(q) if (queryR == "questions"): if (queryT != "empty"): responses = ResponseDocument20.search().filter(Q_ES("match", Question__Statement=cleanQ.lower())&Q_ES("match", Topic__Name=queryT)).extra(size=10000) else: responses = ResponseDocument20.search().query("match", Question__Statement=cleanQ.lower()).extra(size=10000) #ES I assumed all I had to add was Topic__Name=queryT to filter the search by topic and it would give me results that … -
Django - Direct assignment to the forward side of a many-to-many set is prohibited
I have this class in my project: class ManejoEventoSanitario(models.Model): id_evento_sanitario = models.AutoField(primary_key=True) id_tipo_evento = models.ForeignKey(TipoEvento, on_delete=models.PROTECT) descricao = models.CharField(max_length=90, blank=True, null=True) dt_evento_sanitario = models.DateField(blank=True, null=True) dt_prox_evento = models.DateField(blank=True, null=True) responsavel = models.ForeignKey(Pessoa, on_delete=models.PROTECT) animais = models.ManyToManyField(Animal) produtos = models.ManyToManyField(DoseProduto) objects = models.Manager() And I have this post endpoint in my ._views : class ApiEventoSanitarioAnimal(APIView): def post(self, request, format=None): data_evento = request.POST['data_evento'] tipo_evento = request.POST['tipo_evento'] responsavel = request.POST['responsavel'] descricao = request.POST['descricao'] data_proximo_evento = request.POST['data_proximo_evento'] animais_json = jsonpickle.decode(request.POST['animais']) produtos_json = jsonpickle.decode(request.POST['produtos']) tipo_evento = get_object_or_404(TipoEvento, id_tipo_evento=tipo_evento) responsavel = get_object_or_404(Pessoa, id_pessoa=responsavel) animais = set() for animal_json_id in animais_json: animal = get_object_or_404(Animal, id_animal=animal_json_id) animais.add(animal) dose_quantidade_produtos = set() for produto_json in produtos_json: produto = get_object_or_404(Produto, id_produto=produto_json['id']) unidade_medida = Unidade.objects.filter(descricao=produto_json['unidade']).first() dose_quantidade = produto_json['dose'] dose_produto = DoseProduto() dose_produto.id_produto = produto dose_produto.id_unidade_medida = unidade_medida dose_produto.quantidade = dose_quantidade dose_produto.save() dose_quantidade_produtos.add(dose_produto) m_evento_sanitario = ManejoEventoSanitario() m_evento_sanitario.dt_evento_sanitario = data_evento m_evento_sanitario.id_tipo_evento = tipo_evento m_evento_sanitario.responsavel = responsavel m_evento_sanitario.descricao = descricao m_evento_sanitario.save() #Adiciono os animais e produtos ao evento sanitario cadastro m_evento_sanitario.animais = animais m_evento_sanitario.produtos = dose_quantidade_produtos m_evento_sanitario.save() return Response(status=status.HTTP_200_OK) What I'm trying to do is: Create a ManejoEventoSanitario (this is an event in Real life) Put the animals that will be in this event Put the products that will be used in this event But … -
Mobile Apps: React Native with Django REST
I'm looking to build a mobile application for app stores with React Native (for frontend) and a Django REST framework (for backend). I find that I learn quicker by following a start to end video/videos on how to integrate these parts together. I would appreciate any resources that could show me how to do this. Going through the web, I found resources on how to build individual parts of frontend and backend but very little on a complete integration. It doesn't need to be a complex app. It could be a simple example on how to retrieve GET and POST, JSON data from Django and showing that in React Native mobile app. Thank you. -
How do I make a CLI with Django for a database
I'm a student and I got assigned for a project where I'm using Django + PostgreSQL and I'm supposed to make a CLI (Command Line Interface) possibly with Django showing my database modules. What's the easiest way to do that? I only have some knowledge in C++ programming so I was thinking like a switch statement where a user has an option to choose from different queries, but I don't know how to do that in Django. Thank you :) -
Django custom user model: IntegrityError: null value in column "is_superuser" violates not-null constraint
I am trying to create a custom user model in Django and thereafter create RESTAPI as per django-rest-auth provides. CustomUserModel and CustomUSerManager are defined as- from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, email, name, phone_no, user_android_id, user_fcm_token, user_social_flag, user_fb_id, user_android_app_version, password=None): user = self.model( email = self.normalize_email(email), phone_no = phone_no, password=password, user_android_id = user_android_id, user_fcm_token = user_fcm_token, user_social_flag = user_social_flag, user_fb_id = user_fb_id, user_android_app_version = user_android_app_version, name = name, ) # user.is_staff = False # user.is_superuser = True user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, name, phone_no, user_android_id, user_fcm_token, user_social_flag, user_fb_id, user_android_app_version, password): user = self.create_user( email, password=password, phone_no=phone_no, user_android_id=user_android_id, user_fcm_token=user_fcm_token, user_social_flag=user_social_flag, user_fb_id=user_fb_id, user_android_app_version=user_android_app_version, name=name, ) user.is_staff = True user.is_admin = False user.is_superuser = True user.save(using=self._db) return user def create_superuser(self, email, name, phone_no, user_android_id, user_fcm_token, user_social_flag, user_fb_id, user_android_app_version, password): user = self.create_user( email, password=password, phone_no=phone_no, user_android_id=user_android_id, user_fcm_token=user_fcm_token, user_social_flag=user_social_flag, user_fb_id=user_fb_id, user_android_app_version=user_android_app_version, name=name, ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): objects = UserManager() name = models.CharField(max_length=100, blank=True, null=True) email = models.EmailField(unique=True) created_at = models.DateField(blank=True, null=True) phone_no = models.BigIntegerField(blank=True, null=True) user_android_id = models.CharField(max_length=255, blank=True, null=True) user_fcm_token = models.CharField(max_length=255, blank=True, null=True) user_social_flag = models.IntegerField(blank=True, null=True) user_fb_id = models.CharField(max_length=255, blank=True, null=True) user_android_app_version = models.CharField(max_length=25, blank=True, null=True) …