Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to connect to the Django database via a widget encoded in pure Javascript?
I'm creating an external widget to an existing application that is coded in Django/Angular. The widget that i'm coding is in HTML, CSS and pure Javascript. There is a REST Django API. I want to retrieve the data via a fetch. const url = 'http://localhost:8000/api/services'; const csrftoken = getCookie('csrftoken'); const headers = new Headers(); headers.append('X-CSRFToken', csrftoken); const myInit = { method: 'GET', headers: headers, mode:'no-cors', cache: 'default', credentials: 'include' }; fetch(url, myInit) .then(res => { res.json(); }) .then(data => { console.log(JSON.stringify(data)); }); function getCookie(name) { var value = "; " + document.cookie; var parts = value.split("; " + name + "="); if (parts.length == 2) return parts.pop().split(";").shift(); } My problem: I can't connect to the API, I get a 403 error. I tried to recover the data via Insomnia but it's the same thing, error 403 I also tested in the terminal via http but still the same thing. http http://localhost:8000/api/services/ 'Authorization: Token MyToken' HTTP/1.1 403 Forbidden Content-Length: 22 Content-Type: text/html Vary: Origin, Cookie X-Frame-Options: SAMEORIGIN <h1>403 Forbidden</h1> -
Rendering HTML to PDF with images included Django
I have a django app where users would print some pages which include images as a part of Data processing. I tried jsPDF but it didn't render my images and I ended up with just text $(document).ready(function() { $("#pdfDownloader").click(function() { var doc = new jsPDF('p', 'pt', 'a4', true); doc.fromHTML($('#renderMe').get(0), 15, 15, { 'width': 500 }, function (dispose) { doc.save('thisMotion.pdf'); }); }); }) This was my code and it didn't render the images so do I need to change anything? is using a Django view would solve this and is there any alternatives to xhtml2pdf as with this I need to include my CSS in the HTML file ? -
Catching some values in django signals
I'm using django signals to catching some values. My example: @receiver(post_save, sender=Profile) def my_example(sender, instance, created, **kwargs): if created: user_id = instance.user.id level = instance.is_admin company = instance.company I need to catch user_id, level and company. But only user_id contains value. company value is always None and level is always False. This is my basic model for profile: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_supervisor = models.BooleanField("Supervisor", default=False) is_admin = models.BooleanField("Admin", default=False) company = models.ForeignKey( "core.company", related_name="users", on_delete=models.CASCADE, blank=True, null=True, ) def __str__(self): """Unicode representation of MyUser.""" return self.user @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() -
Incorrect password can access database in django
I create posgresql db user named 'user'. Password: django1234. And I type the database info in settings.py. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test', 'USER': 'user', 'PASSWORD': '1q2w3e', 'HOST': 'localhost', 'PORT': '5432', } } The password does not match definitely. However, it can access the 'test DB' when I run the server, which means, I guess, that anyone can access my DB. What is the problem? Thank you in advance. -
NameError: name 'api' is not defined for Django Rest Framework
I am trying to learn the Django Rest Framework. I create a project called djangorest. Then I created an app called api In djangorest/urls.py I have: from django.contrib import admin from django.urls import path, include from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(api.urls)), ] In djangorest/settings.py I included the new app api: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api.apps.ApiConfig', ] However, when I run the server I get the error: NameError: name 'api' is not defined -
Wrote a command that creates a Django-CMS plugin from an existing one
I have a plugin (PodcastPlugin) that contains two ManyToManyField (podcasts and custom_podcasts). I want to create a Django command that creates a new plugin on the same page and placeholder with the old instances. I can create a new plugin but it does not copy the old instances of podcasts and custom_podcasts into the newly created PodcastPlugin. Here is my code: from cms.models.pagemodel import Page from cms.api import add_plugin for page in Page.objects.all(): for placeholder in page.placeholders.filter(page=263): for plugin in placeholder.get_plugins_list(): if plugin.plugin_type == 'PodcastPlugin': for custom_ids in plugin.get_plugin_instance()[0].custom_podcasts.values_list('id'): for podcasts_ids in plugin.get_plugin_instance()[0].podcasts.values_list('id'): add_plugin( placeholder=placeholder, plugin_type='PodcastPlugin', podcasts=[podcasts_ids[0]], cmsplugin_ptr_id=plugin.id, custom_podcasts=[custom_ids[0]], title='New Podcast', language='de' ) -
Django RF: POST geometry from Leaflet Draw to PostGIS
I'm trying to store some geometry in a PostGIS DB which is created using Leaflet Draw. The following answer only covers the first part: how to transform the drawn shape into GeoJSON, i.e.: map.on(L.Draw.Event.CREATED, function (e) { var type = e.layerType var layer = e.layer; // Do whatever else you need to. (save to db, add to map etc) drawnItems.addLayer(layer); //Export to DB (source: https://stackoverflow.com/a/24019108/3976696) var shape = layer.toGeoJSON() shape_for_db = JSON.stringify(shape); For example, shape_for_db contains: { "type": "Feature", "properties": {}, "geometry": { "type":"Polygon", "coordinates":[[[-0.217073,51.918784],[-0.361362,51.101904],[-0.96918,53.4925],[-0.217073,51.018784]]] } } However, I can't find any solution to successfully insert the geometry in the DB. So far, based on this, I've tried the following: $.ajax({ type: "POST", dataType: "json", contentType: "application/json", beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, url: "/en/api/geomtable/", data: JSON.stringify({"description":"this is a test", "geom":shape_for_db}), success : function(result) { console.log(result); } }); This returns a 400 Bad Request with the following error: Unable to convert to python object: Invalid geometry pointer returned from "OGR_G_CreateGeometryFromJson"." What should I make of this error? Should I parse the GeoJSON first or something? -
Django, get sum of amount for the last day?
class Point(models.Model): user = models.ForeignKey(User) expire_date = models.DateField() amount = models.IntegerField() I want to know sum of amount for the last expire_date for a given user There could be multiple points for a user and with same expire_date I could do two query to get first last expire_date and aggregate on those. but wanna know if there's better way. -
I have errors with Django is.authenticated() built in function, showing "inconsistent use of tabs and spaces in indentation"
I have been woking in django 2.2.4 in vscode. Whenever I try to run the code, error in powershell says that, "inconsistent use of tabs and spaces in indentation"(into the is_authenticated() line. I have this code: def login_page(request): form = LoginForm(request.POST or None) print(request.user.is_authenticated) if form.is_valid(): print(form.cleaned_data) return render(request, "auth/login.html", {}) For LoginForm() is imported by my file forms.py from django import forms class ContactForm(forms.Form): fullname = forms.CharField( widget=forms.TextInput( attrs={ "class": "form-control", "placeholder": "Your Full Name" } ) ) email = forms.EmailField( widget=forms.EmailInput( attrs={ 'class': 'form-control', "placeholder": "Your email" } ) ) content = forms.CharField( widget=forms.Textarea( attrs={ 'class': 'form-control', "placeholder": "Your message" } ) ) def clean_email(self): email = self.cleaned_data.get("email") if not "gmail.com" in email: raise forms.ValidationError("email has to be gmail.com") return email class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField() -
The session variable is lost, in Django
In a system that should be multi-company, I use context_processors.py to load company options, by selecting from the sidebar. The user can change companies at any time. When the user selects a company, the option is recorded in a session variable. It happens that when the user changes pages, the information of the session variable is lost. What am I doing wrong or failing to do? Is there a better way to do this? Relevant code snippets follow: context_processors.py from apps.client.models import Client def units (request): # Dictionary with business options clients = Client.objects.values ( "client_id", "company_id__name", ) clients_list = [] for client in clients: clients_list.append ( { 'client_id': client ['client_id'], 'name': client ['company_id__name'] } ) return {'clients_list': clients_list} base.html # System base page. # Displays the list of business options. <select class = "form-control select2"> <option value = "{{request.session.unit_id}}"> {{request.session.unit_id}} </option> {% for client in clients_list%} <option value = "{{client.client_id}}" {% if request.session.unit_id == client.client_id%} selected {% endif%}> {{client.client_id}} </option> {% endfor%} </select> ... # Whenever a company is selected ... <script> $ ("# select_unit"). click (function () { var option_id = $ (this) .val (); var url = "{% url 'home: set_unit'%}"; $ .ajax ({ type: "GET", url: … -
How to pass data in a GET request in django-rest-framework?
I need to send data in a GET request. I don't like passing the parameters in the URL, so this way I need to modify the URL every time I want to insert a new parameter I need in the view. To do this I send an object with the parameters. This is my URL: path(r'acounts_api/', views.AcountsAPI.as_view(), name='accounts_api') This is my view: class AccountsAPI(APIView): def get(self, request): id_account = request.GET.get('id_account', None) if (id_account): try: account = Accounts.objects.get(id=id_account) account_serializer = AccountsSerializer(account) except Accounts.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) else: account = Accounts.objects.all() account_serializer = AccountsSerializer(account, many=True) return Response(account_serializer.data, status=200) And this is my javascript: function get_conta_receita(id_to_get) { var myData = { "id_account": id_to_get, }; const defaults = { 'method': 'GET', 'credentials': 'include', 'headers': new Headers({ 'X-CSRFToken': csrf_token, 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }), }; merged = {defaults, myData}; fetch(accounts_api, merged) .then(function(response) { return response; }).then(function(data) { console.log("Data is ok", data); }).catch(function(ex) { console.log("parsing failed", ex); }); }; With jquery ajax this worked: $.ajax({ type: "get", headers: { "X-CSRFToken": csrf_token, }, data: { "id_account": id_to_get, }, url: acounts_api, dataType: 'json', success: function (dados) { return dados; } }) How can I use the same process with the fetch method? -
Profile data are not saved for custom user model
I'm new to python and I'm trying to make user registration that is extend from user creation model, I created profile model with the fields I want and saved the profile object with signal when user is saved, the profile is created successfully and linked with the user but profile data is not saved (in this example: jobtitle, company, phone)are empty in model.py class profile (models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) company = models.CharField(max_length=100) jobTitle = models.CharField(max_length = 100,default ='') phonenumber = PhoneNumberField(null=False, blank=False, unique=True, help_text='Contact phone number', default ='') @receiver(post_save, sender = User) def create_user_profile( sender, instance, created, **kwargs): if created: profile.objects.create(user = instance) instance.profile.save() @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() in forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required= True) company = forms.CharField(required = True) phonenumber = PhoneNumberField(widget=forms.TextInput(attrs={'placeholder': ('Phone')}), label=("Phone number"), required=True) first_name = forms.CharField(required = True) jobTitle = forms.CharField(required = True) class Meta: model = User fields = [ 'username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'company', 'jobTitle' ] def save(self, commit=True): user = super(UserRegisterForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user in views.py #User register def signup(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save() … -
Processing a file while its being uploaded in django
My Application requires client to upload a Huge file through a Form . Currently , django stores the file in temp folder and my view function gets hit only after the whole file is uploaded where i can access the file. My requirement is to be able to get uploaded chunks as soon as they arrive at the server so that i can start the processing . I checked , there is streaming HTTP response but nothing for HTTP request (POST from client) Thanks -
Render a form that shows list values as the checkbox values. [each entry in the list represent a checkbox field]
Is it possible to render a form from a list data? For example let Cont = ['Brazil' ,'India', 'USA', 'Aus', 'UAE', 'Russia', 'China'] I want to present a form to user that shows the entries in the form as checkbox which I can save into a result list called Result= []. How is it possible? -
Django ORM group by a custom Func
I'm working with Django and I need to group a model by a custom function. Okay so the query I want is: SELECT date_trunc('week',"model_table"."date") AS "date" FROM "model_table" GROUP BY "date" Then what I've tried is the following: class DateTrunc(Aggregate): function = 'date_trunc' template = "%(function)s('%(date_type)s',%(expressions)s)" date_types = ['microsecond', 'millisecond', 'second', 'minute', 'hour', 'day', 'week', 'month', 'quarter', 'year', 'decade', 'century', 'millenium'] def __init__(self, date_type, expression, group_by=False, **extra): self.must_group_by = group_by # Name "group_by" is already used. if date_type not in self.date_types: raise AttributeError('The specified "date_type" is not correct.') super().__init__(expression, date_type=date_type, **extra) def get_group_by_cols(self): if self.must_group_by: return [self] return super().get_group_by_cols() In [3]: HotelRating.objects.annotate(date=DateTrunc('week','crawled_at',True)).values('date').query.__str__() Out[3]: 'SELECT date_trunc(\'week\',"metrics_hotelrating"."crawled_at") AS "date" FROM "metrics_hotelrating" GROUP BY "metrics_hotelrating"."id", date_trunc(\'week\',"metrics_hotelrating"."crawled_at")' Which works find except for the fact that the GROUP BY clause also inserts the table unique id. This implies the final result is not grouped at all. I've been checking the Django code and in the Query class there's a function set_group_by that is the one that mess it all but i don't really know how to hack it. Anyway I think the correct way to proceed would be to inherit from Func class instead of Aggregate but then I can't get Djangot to insert the … -
how to automate connecting to SSH using python in ubuntu?
What I normally do is that I open a terminal in ubuntu and type this: ssh -p 2200 mydomain@ssd4.rackset.com then I enter the password I then activate my virtual environment: source /home/myproject/virtualenv/myproject/3.5/bin/activate then I change the working directory: cd myproject I then go to django shell and do some stuff python manage.py shell I then exit from django shell exit() and exit from ssh exit What I want to do is automate all of these. How can I do all these using Python? I see that there some libraries to connect to ssh but I did not see entering password in non of them -
How to put the problem of html code in database
I was trying to include a hyperlink between the text which loads dynamically from database, similar to the one in wikipedia. The text somehow looks like this - "Some Text some text <a href="#">Hyperlink</a>Remaining text" But is doesn't gives me a hyperlink, instead it shows the same text as i have written in the database. When i checked the source code it look like this: "Some Text &lt;a href="#"&gt;Hyperlink&lt;/a&gt; Remaining Text" I expect the ouput as as - "Some Text Hyperlink Remaining Text" Please help me to solve the problem. -
How to keep urlpatterns neat
Django==2.2.3 I have a rather big list in urlpatterns. I use namespaces, but urlpatterns are all the same big. Example: urlpatterns = [ path('semantics', SemanticsList.as_view(), name="semantics"), path('common_negative_phrases', CommonNegativePhrasesList.as_view(), name="common_negative_phrases"), path('semantics_level3_minus_phrases/<int:level>/', SemanticsLevel3MinusPhrasesList.as_view(), name="semantics_level3_minus_phrases"), path('semantics_level2_minus_phrases/<int:level>/', SemanticsLevel2MinusPhrasesList.as_view(), name="semantics_level2_minus_phrases"), path('comparative_phrases_list', ComparativePhrasesList.as_view(), name="comparative_phrases_list"), path('transactional_phrases_list', TransactionalPhrasesList.as_view(), name="transactional_phrases_list"), path('info_phrases_list', InfoPhrasesList.as_view(), name="info_phrases_list"), ] I'd like to keep them more neat. Maybe sort them alphabetically. Any other ideas? As for alphabetic sorting. I wouldn't like to sort them by myself. Maybe there is an online service or something for this purpose? -
Is there any solution on using id as url in django?
I was doing some blog related site and wished for a blog to appear when its id is provided in the URL. Overall the code seems fine but it keeps on saying page not found. Can anyone help me with the problem? I tried searching in the internet but couldn't get any specific solution. It works when id is not given but says page not found when id is given. url script for blog: urlpatterns = [ path('', views.allblogs, name ='allblogs'), path('<int:blog_id>/',views.details, name='detail') ] views script for blog: def details(request,blog_id): detailblog = get_object_or_404(Blog, pk = blog_id) return render(request, 'blog/details.html', {'blog': detailblog}) -
Django Template: Use translation in default_if_none
How can I use a translated string inside a template for default_if_none? Usually you would use something like this: {% trans 'TRANSLATED STRING' %} Example {{ value|default_if_none:'TRANSLATED STRING' }} -
cannot link ondrop div element to ajax
I m working on a project to create drag and drop quiz using django framework , I m able to drag and drop but the ondrop div element is not responsive to ajax i tried using ajax and to link it up to django views and urls, but it doesnt work Drop Here function allowDrop(ev){ ev.preventDefault();} function drag(ev){ ev.dataTransfer.setData("text",ev.target.id);} function drop(id,ev){ev.preventDefault();var ans=ev.dataTransfer.getData("text");ev.target.appendChild(document.getElementById(ans));alert(ans);$.ajax({url:"{% url 'test_dd' %}",type:"POST",data:{ans:ans},success:function(){alert("ajax works");return true}});return false;} im unable to type the indentation for the code part as this site is not allowing me to do so.. so this is one more question. I worked for about oneday to ask this question in this site. https://imgur.com/LZU9YjZ alert is working for function but not in ajax -
JSON Response output is not updated on single click event
I am trying to build a java online compiler web app using django. but every time i submit my code through AJAX call the new code is posted successfully to view.py but the Jsenter code hereon response object is still the previous one. def code1(request): response_data={} **codet=request.POST.get("code","")** # getting the code text from Ajax req **output=code(codet)** #sending code for execution response_data['result']="Successful" #storing in response response_data['message']=output **return HttpResponse(json.dumps(response_data), content_type="application/json")** def code(code_text): return execute(code_text) def execute(code_text): filename_code=open('Main.java','w+') #creating file filename_code.flush() f1 = code_text.split("\n") # splitting code line by line for i in f1: filename_code.write(i+"\n") #writing code line by line filename_code.close() #closing file time.sleep(2) #giving wait **compile_java(filename_code)** #compiling file (Note: I am not using the file passed in compile_java) **return execute_java(filename_code,input**) #running java file def compile_java(java_file): proc = subprocess.Popen('javac Main.java', shell=True) def execute_java(java_file, stdin): #java_class,ext = os.path.splitext(java_file) cmd = ['java ', 'Main'] proc = subprocess.Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT) stdout,stderr = proc.communicate(stdin) stdoutstr= str(stdout,'utf-8') ** 1. return stdoutstr ** Actually the previous json response is being sent for current code(codet) -
How to implement class methods with attributes of another class?
I have three models, BoletoConfig(BilletConfig),Tickets and CategoryTicket, one ticket has a CategoryTicket and CategoryTicket has a BilletConfig, BilletConfig has an attribute with the days for the billet due, I want to create a method in the tickets class to calculate the due date. I have doubts if I use the decorator @property or @classmethod, which would be the best choice and why? and how would i get the value of days_to_become_due from my BoletoConfig class in tickets? This my /billets/models.BoletoConfig class BoletoConfig(models.Model): base_amount = models.DecimalField( db_column='valor_base', max_digits=10, decimal_places=2, verbose_name='valor base do boleto', ) check_specialization_for_amount = models.BooleanField( default=False, db_column='especializacao_protocolo', verbose_name='especialização do protocolo', ) days_to_become_due = models.IntegerField( db_column='dias_vencimento', verbose_name='dias até vencimento', ) class Meta: db_table = 'boletos_boleto_configuracao' verbose_name = 'boletos_configuração' def __str__(self): return self.base_amount This my /tickets/models.tickets class Ticket(TimestampedModel, permissions.TicketPermission): """A ticket requested by someone to address a situation""" requested_by = models.ForeignKey( settings.AUTH_USER_MODEL, models.PROTECT, db_column='requerido_por', related_name='+', ) show_ticket_for_request_user = models.BooleanField( default=True, db_column='mostrar_ticket_para_requerente', ) message = models.CharField( max_length=4000, blank=True, null=True, db_column='mensagem', ) status = models.ForeignKey( Status, models.PROTECT, ) category = models.ForeignKey( Category, models.PROTECT, ) files = models.CharField(max_length=4000, blank=True, null=True) boleto_id = models.UUIDField( db_column='boleto_id', verbose_name='Uuid Boleto', null=True, blank=True, ) @property def get_boleto_duo_date(self): return self.ticket.created_at + timedelta(days=days_to_become_due) This my /tickets/models.CategoryTicket class Category(TimestampedModel): """ Represents what … -
Using docker for Celery Task +Rabbitmq not working on python 3.7
I am using Docker to setup periodic task with Celery+RabbitMQ in DJANGO Project. Using new versions of packages: Python: 3.7 Celery: 4.4.0rc1 Django: 2.2.5 Getting below error: Traceback (most recent call last): worker_1 | File "/usr/local/lib/python3.7/site-packages/celery/app/utils.py", line 241, in find_app worker_1 | found = sym.app worker_1 | AttributeError: module 'modulename' has no attribute 'app' worker_1 | worker_1 | During handling of the above exception, another exception occurred: worker_1 | worker_1 | Traceback (most recent call last): worker_1 | File "/usr/local/bin/celery", line 10, in <module> worker_1 | sys.exit(main()) worker_1 | File "/usr/local/lib/python3.7/site-packages/celery/__main__.py", line 30, in main worker_1 | main() worker_1 | File "/usr/local/lib/python3.7/site-packages/celery/bin/celery.py", line 81, in main worker_1 | cmd.execute_from_commandline(argv) worker_1 | File "/usr/local/lib/python3.7/site-packages/celery/bin/celery.py", line 793, in execute_from_commandline worker_1 | super(CeleryCommand, self).execute_from_commandline(argv))) worker_1 | File "/usr/local/lib/python3.7/site-packages/celery/bin/base.py", line 309, in execute_from_commandline worker_1 | argv = self.setup_app_from_commandline(argv) worker_1 | File "/usr/local/lib/python3.7/site-packages/celery/bin/base.py", line 469, in setup_app_from_commandline worker_1 | self.app = self.find_app(app) worker_1 | File "/usr/local/lib/python3.7/site-packages/celery/bin/base.py", line 489, in find_app worker_1 | return find_app(app, symbol_by_name=self.symbol_by_name) worker_1 | File "/usr/local/lib/python3.7/site-packages/celery/app/utils.py", line 246, in find_app worker_1 | found = sym.celery worker_1 | AttributeError: module 'modulename' has no attribute 'celery' I am stuck how to use Celery, celery-beat, RabbitMQ, Docker along with Django Project for my asynchronous task … -
django.db.utils.IntegrityError: duplicate key value violates unique constraint "core_user_pkey" DETAIL: Key (id)=(23) already exists
i'm working on project using python 3.7 , django 2.2.4 , docker and postgresql and when i want to create super user i get this error i do it for 23 times(that's why the id equal to 23). here is my model : class UserManager(BaseUserManager): def create_user(self, email, username, name, password=None): """ create and save new user""" if not email: raise ValueError('User must have an email address') user = self.model(email=self.normalize_email(email), name=name, username=username) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, name, password): """create and save new super user""" user = self.create_user(email, username, name, password) user.is_staff = True user.is_superuser = True user.save(self._db) return user class User(AbstractBaseUser, PermissionsMixin): """custom user model that using username in username field""" email = models.EmailField(max_length=70, unique=True) username = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=50) gender = models.PositiveIntegerField(validators= [MaxValueValidator(3)], null=True) # 1 for men 2 for woman 0 for not mention bio = models.TextField(null=True) lives_in = models.CharField(max_length=70, null=True) phone_number = models.PositiveIntegerField(validators= [MaxValueValidator(99999999999)], null=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'name'] here is my migration code: class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0011_update_proxy_permissions'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), …