Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NameError: name 'Class' is not defined, How to access in a class it same name in Django?
models.py file that contain the Category model with name, description parent_category fields class Category(models.Model): """ Categories representation model """ name = models.CharField(max_length=50) description = models.TextField() parent_category = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) serializers.py file, that container the Category model serializer with all it fields class CategorySerializer(serializers.ModelSerializer): """ product categories model serializer """ parent_category = CategorySerializer() class Meta: """ profile model serializer Meta class """ model = Category fields = ( 'id', 'name', 'description', 'parent_category' ) views.py file, API view to get all available categories with required user authentication class GetCategoriesView(APIView): """ product categories getting view """ permission_classes = (IsAuthenticated,) def get(self, request, *args, **kwargs): """ get request method """ categories = Category.objects.all() serializer = CategorySerializer(categories, many=True, context={'request':request}) return Response(data=serializer.data, status=HTTP_200_OK) Expectected result, Json result with a recursive data from the parent_category field { name:'boy shoes', description:'boy shoes category description' parent_category:{ name:'shoes', description:'shoes category description', parent_category:{ name:'clothes', description:'clothes category description', parent_category: null } } } Error i get, i noticed that i can't access directly the Class inside the same class NameError: name 'CategorySerializer' is not defined How can i solve that?, i think you can help solve that issue Thank you for your attention :) -
How can I display a tuple field from a model to a template in Django?
I'm pretty new to Django here guys so go easy on me please... Let me elaborate on what the title question says. Basically I have this model.... class Meta: verbose_name_plural = 'Digital Media' CATEGORY_CHOICES = ( ('icon_sets', 'Icon Sets'), ('brand_logos', 'Brand Logos'), ('web_banners', 'Web Banners') ) name = models.CharField(max_length=20, choices=CATEGORY_CHOICES) SIZE_CHOICES = ( ('1616', '16 x 16 pixels'), ('3232', '32 x 32 pixels'), ('6464', '64 x 64 pixels'), ('128128', '128 x 128 pixels'), ('256256', '256 x 256 pixels') ) sizes = models.CharField(max_length=20, choices=SIZE_CHOICES) def __str__(self): return self.name and this view ... def product_detail(request, product_id): """ A view to show individual product details """ print_media = Print_Media.objects.all() digital_media = Digital_Media.objects.all() product = get_object_or_404(Product, pk=product_id) print(product, print_media, digital_media) context = { 'product': product, 'print_media': print_media, 'digital_media': digital_media, } return render(request, 'products/product_detail.html', context) So "IF" all is ok with the above code, can someone help me to get the field "sizes" from the model onto a template as I'm having trouble doing this on my own - here is what I have tried so far... {% with product.is_print_media as p %} {% if p %} <div class="col-12"> {{ p.sizes }} <p><strong>Size:</strong></p> <select class="form-control rounded-0 w-50" name="product_size" id="id_product_size"> <option value="{{ p.sizes }}"></option> <option value=""></option> … -
How to take user selected longitude and latitude coordinates as form input in Django?
I am making a Django project where I need the user location coordinates as input for my django form . Just to make it more clear , here is roughly how I want my django form to look : //Form First name [input field] last name [input field] username [input field] location : {a google map like map is shown here where user can search the map and pin a location} [the cordinates of the location pinned by the user on the map are stored in the in the input field] password [input field] How can I achieve this ? I tried the GeoDjango library but it requires installation of too many additional softwares ? is there a simple way to achieve what I want ? -
Django dramatiq, dramatiq abort issue with Elasticache Redis
I use dramatiq and django_dramatiq to setup scheduled delayed jobs. In Django, on a model I added on save() the functions needed to schedule a job. I also use dramatiq-abort in order to be able to cancel jobs. My implementation looks like so: models.py class TestModelA() task_id = models.CharField(max_length=50, blank=True, editable=False) def save(self, *args, **kwargs): """ Creates a dramatiq job on save() """ super(Event, self).save(*args, **kwargs) # if the task id exists, it means a scheduled job has been previously set if self.task_id: # dramatiq abort previous job by the task id abort(self.task_id) # create a new job set_task_id = self.setup_dramatiq_job() # save new task_id on db if set_task_id: self.task_id = set_task_id super(Event, self).save(*args, **kwargs) def setup_dramatiq_job(self): now = timezone.now() # schedule a job to run in 1 minute from now eta = now + timedelta(minutes=1) if eta: milli_to_wait = int((eta - now).total_seconds()) * 1000 result = custom_dramatiq_job.send_with_options( args=('some message',), delay=milli_to_wait, ) return result.message_id return None tasks.py @dramatiq.actor def custom_dramatiq_job(message): return message Now all of the above works and if I hit save multiple times on my local environment I can see jobs being "skipped" / aborted. Let's say it has been saved 5 times; 4 jobs will be skipped … -
jquery get not activating view function
I have this jquery funtcion in my django project that returns pk values to my view function in order to print a pdf with the database values. However, it seems that the view funtction is not saving my pdf when using the get function in jquery. why? my template: <script> let getValues2 = () => $("input[name='checkb']:checked").map((i,el) => el.id.trim()).get(); console.log('getValues2 ',getValues2()) $(document).ready(function() { $('.print').on('click', () => { $.get('eprint/ticked/', { marked: getValues2() }); console.log('print: ',getValues2()) }); $('.delete').on('click', () => { $.get('edelete/ticked/', { marked: getValues2() }); console.log('delete: ',getValues2()) }); }); </script> <td id='row1'><button class='print'><i class="bi bi-sim"></i></button> <form> <label><input type="checkbox" id={{l.pk}} name="checkb"></label> <form> urls.py: path('eprint/ticked/',views.eprint,name='eprint'), views.py: def eprint(request): print('eprint') g=request.GET checked=g.getlist('marked[]') print(checked) res=[Concert.objects.get(pk=l) for l in checked] buffer=io.BytesIO() pdf=canvas.Canvas(buffer) pdf.setFont("Helvetica",14) for l in res: pdf.drawString(1,100,l.cname) pdf.drawString(1,100,"test") pdf.showPage() pdf.save() buffer.seek(0) return FileResponse(buffer,as_attachment=True,filename='test.pdf') -
pass any amount to stripe payment
I am trying out stripe payment method. So have created a test account in stripe. Have also created a web app in pythonanywhere where a user can select an amount from. http://singhaidotnish.pythonanywhere.com/products/dennis/ ( WIP ) Need to pass this selected amount to stripe checkout. If you click on button "Next step to supporting barefoot" it will go to stripe checkout. This should show the selected amount. Not Rs 99 as it now shows. For reference have used https://github.com/PrettyPrinted/youtube_video_code, which is helpful. Next step is to pass selected amount. How is it possible ? -
Django - How to manage many messages?
I'm currently searching for a way to properly manage messages I show the user, as a have a lot of them, for example at my views.py: messages.error(request, 'You cannot do this bla bla') I also have in mind to make the site multi-language. So how do you guys solve this? Do you simply setup a messages.py and reference stuff at views.py or is there maybe a more elegeant way that also has multi-langauge implementation in mind? Thanks in advance :) -
the user who have post should only able to edit blog below code correct but is this professional approach
below is my code inside views.py. Here i don't required that also staff should able to edit but what we should do i needed @method_decorator(login_required(login_url='login'), name='dispatch') class PostUpdate(UpdateView): model = Post form_class = PostForm template_name = 'blog/post_form.html' def get_queryset(self): return super(PostUpdate, self).get_queryset().filter(user=self.request.user) def get_success_url(self): return reverse('dashboard') -
Using specified db in Django connection
I'm using Django to do some db query: from django.db import connection def my_custom_sql(self): with connection.cursor() as cursor: cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz]) cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz]) row = cursor.fetchone() return row And below is my db settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'ka_a', 'USER': 'ka_a', 'PASSWORD': 'ka_a', 'HOST': 'xxx', 'PORT': '3306', 'STORAGE_ENGINE': 'INNODB', 'OPTIONS': { 'init_command': "set sql_mode='traditional'", 'charset': 'utf8mb4' } }, 'ka_b': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'ka_b', 'USER': 'ka_b', 'PASSWORD': 'ka_b', 'HOST': 'xxxxx', 'PORT': '3306', 'STORAGE_ENGINE': 'INNODB', }, } KA_B = 'ka_b' How can I select to KA_B in connection? Thanks -
Redirect another url for first time users in django
I am trying to redirect the url for first time users only using django. I can achive this method using DefaultAccountAdapter for below method. In this method I have used last_login - date_joined so I am facing issue while the users delay to login on same date. So I have tried a method while last_login having blank data but I don't know how to set blank of null for the field. Request you to please give your suggestion for this. Note : first time login users redirect tutuorial-page otherwise all users redirect to welcome page. ## adapter.py using time method class AccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): threshold = 300 #seconds assert request.user.is_authenticated if (request.user.last_login - request.user.date_joined).seconds < threshold: url = 'tutorial-page/' else: url = settings.LOGIN_REDIRECT_URL return resolve_url(url) ## adapter.py using last_login field empty class AccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): assert request.user.is_authenticated if (request.user.last_login == null): url = 'tutorial-page/' else: url = settings.LOGIN_REDIRECT_URL return resolve_url(url) -
signals post_save called twice after updating data in class base view django
So i've been stack on this problem that everytime I update my stock in orders it called twice for updating I use the class base view built in Django but in models I have a post signal which it removing the stock of the product. I already use the dispatch_uid but it's not working or any solution that I found on internet not working on my problem. here is my class base view for updating: class ItemQtyUpdateClassBaseView(UpdateView): template_name = 'components/update/item.html' form_class = ItemForm def get_context_data(self, **kwargs): kwargs['context_title'] = 'Update Order Qty' return super(ItemQtyUpdateClassBaseView, self).get_context_data(**kwargs) def form_valid(self, form): try: order_item = OrderModel.objects.get(pk = self.kwargs[self.pk_url_kwarg]) fetch_product = ProductsModel.objects.get(product_name = order_item.product_name) print(fetch_product.qty) if fetch_product.dough != None: if int(fetch_product.dough.qty) <= 0: messages.error(self.request, 'Not enough qty to order.') return self.form_invalid(form) if int(fetch_product.qty) <= 0: messages.error(self.request, 'Not enough qty to order.') return self.form_invalid(form) else: self.object = form.save() messages.success(self.request, 'Successfully update qty.') except Exception as e: messages.error(self.request, e) return self.form_invalid(form) return super(ItemQtyUpdateClassBaseView, self).form_valid(form) def form_invalid(self, form): return super().form_invalid(form) def get_queryset(self): return OrderModel.objects.filter(pk = self.kwargs[self.pk_url_kwarg]) def get_success_url(self): return reverse_lazy('core:createorder', kwargs = { 'typeoforder': self.kwargs['typeoforder'] }) and here is my model with signal post_save: class OrderModel(models.Model): date = models.DateField(auto_now = True) invoice_no = models.ForeignKey(InvoiceModel, on_delete = models.CASCADE) product_name = … -
auth_token table created field is showing different time in pgAdmin and my admin module
I have done TokenAuthentication successfully. When I tried to set token expiring I'm wondering that the field "created" in the auth_token table is showing different time in pgAdmin and my admin module. In pgAdmin it is showing correct time and in my admin module date is correct but time is different . Anyone pls help me out . Anyway thanks in advanve -
How to return all values in serializer from a for loop
hello am quite new to python and Django am stuck in a point. i have number of user_id in the list and against of these user_id's am getting some data from the table named My_story_1 now i want to display the whole data that are related to the user_id in the list. but am just getting the last id data when i put the things in the for loop. here is my code ```for i in (list): print("here i am getting the ids from the list",i) story=My_story_1.objects.filter(user_id=i) serializer = Storiesserializer(story,many=True) return JsonResponse(serializer.data,safe=False)``` and the response am getting is "id": 41, "text": "testa", "time": "2021-04-22T09:12:49.040296+02:00", "user_id": "11" }, { "id": 42, "text": "testing", "time": "2021-04-22T09:13:01.337255+02:00", "user_id": "11" }, { "id": 43, "text": "testing", "time": "2021-04-22T10:18:05.886045+02:00", "user_id": "11" } ]``` here its all the response from the lastly looped user_id: 11 so its showing its data. i want to get the data from the loop complete and store somewhere and in last i can return it. please help me in this.! thanks in advance -
Django - How to allow registration only for predefined list of e-mails/usernames
I have a following simple view in my views.py for registration on my django site: def register_user(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) messages.succes(request, ('You have registered')) return redirect('home') else: form = UserCreationForm() context = {'form': form} return render(request, 'register.html', context) That approach would allow anyone to register but I want to allow only selected people to be able to register. I have a simple model for my database class EmailList(models.Model): email_addres = models.CharField(max_length=300, blank=True) def __str__(self): return self.email_addres with some e-mail addreses (my site doesn't have usernames, your username is an email addres) and I want to allow registration only for email addresses that are in that database. How would I perform such check? -
Djanggo sass module not found
im getting this error but a few hours ago this was working just fine, when i run the local server im getting this error enter image description here and when i try to python manage.py makemigrations im getting this error enter image description here i tried pip install django_sass but same thing is happening i read somewhere to try migrations and i did but no, nothing im really confused right now any help will really be appreciated thanks in advance -
Two ManyToMany fields are not working in if statement in template
I am building a BlogApp and I am stuck on a Problem. What i am trying to do :- I am trying to use if statement in template of two many fields BUT if statement is not working correctly. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) friends = models.ManyToManyField("Profile",blank=True) class Post(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) viewers = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='viewed_posts',editable=False) template.html {% if request.user.profile.friends.all in post.viewers.all %} "SHOWING SOME TEXT" {% endif %} I am trying to show if request.user friends are in post viewers then show some text. When i print {{ request.user.profile.friends.all }} it show friends of request.user, It works correctly. AND when i print {{ post.viewers.all }} then it correctly shows the post viewers (users). When i try to print some text after combine both in if statement then it doesn't showing anything. I have no idea where is the Mistake. Any help would be Appreciated. Thank You in Advance. -
Ajax call in Django to see if user already exists
I am verifying if a user already exists when he puts his email address in the field on an onblur event. I am also using an external JS file which sends an ajax request to the specified url. However, it is not working. When I start typing in the field, it is telling me email address already exists. Am I doing it the right way? Here is the code: views.py def validate_stud_username(request): if request.is_ajax(): username = request.GET.get('stud_email', None) if User.objects.filter(username__iexact=username): response = { 'is_taken': User.objects.filter(username__iexact=username).exists() } return JsonResponse(response) urls.py urlpatterns = [ path('', views.home, name="home"), path('login/', views.login, name="login"), path('signup/', views.signup, name="signup"), path('validate_stud_username', views.validate_stud_username, name='validate_stud_username'), ] signup.html <form action="{% url 'signup' %}" id="stud_registration_form" method="POST" data-url="{% url 'validate_stud_username' %}"> {% csrf_token %} <input type="email" id="stud_email" style="color: black;" name="stud_email" value="" placeholder=" Email" autocapitalize="none" required> <span style="color: red;" class="error_form" id="stud_email_err"> </span> <button class="btn btn-primary btn-block login_btn" type="submit" style="padding: 2% 0;"> Sign Up </button> </form> form_validations.js $("#stud_email").blur(function () { $.ajax({ data: $(this).serialize(), url: $("form#stud_registration_form").data("url"), success: function (response) { if (response.is_taken == true) { $("#stud_email").addClass("taken"); } else { $("#stud_email").addClass("valid"); } }, error: function (response) { console.log(response.responseJSON.errors); }, }); check_stud_email(); }); function check_stud_email() { var pattern = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; var email = $("#stud_email").val(); if (pattern.test(email)) { $("#stud_email_err").hide(); $("#stud_email").css("border-bottom", … -
Django makemigrations getting keyerror
migration file 0001 under service class Migration(migrations.Migration): initial = True dependencies = [ ('subscription', '0001_initial'), ] operations = [ migrations.CreateModel( name='Service', fields=[ ('id', models.CharField(default=account.utils.hex_uuid, editable=False, max_length=32, primary_key=True, serialize=False)), ('subscription', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='subscription.subscription')), ], migration file 0001 under subscription class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Subscription', fields=[ ('id', models.CharField(default=account.utils.hex_uuid, editable=False, max_length=32, primary_key=True, serialize=False)), ('discount', models.FloatField(blank=True, null=True)), ], ), ] I tried to run makemigrations, but I got the error, old_field = model_state.fields.pop(self.name) KeyError: 'discount' Wondering why I'm getting this error, I did some update on the subscription table before, which dropped the discount field, and already migrated that change in the database. Is it because service 0001 is referencing an old migration file that I'm getting the key error? -
how to tag posts by country efficient way in django
how can i create tag in django to tag post by country but dont create every single post id by country how it is england as tag country 1 post_id content England 2 post_id content England 3 post_id content England i think it will create milions of them in postgresql for every post and cannt find way to tag them like create tags 1 usa 2 russia 3 china 4 england and eg maybe in redis or casandra? i just want to select country and save one tag in post maybe put tag in just post scheme i adk weird but wish u all understand what i am saying thanks -
How to pass a variable from template to views in django?
index.html {% if request.session.visitor_language == 'en' %} {% with current_page=request.resolver_match.url_name %} {{current_page}} {% endwith %} My name is Khan <a style="color: blue;" href="{% url 'change_language' %}?current_page={{current_page}}">BN</a> {% endif %} Here I am trying to send the value of current_page to views through urls urls.py path('home/change_lang/$', views.change_visitor_language, name='change_language'), views.py def change_visitor_language(request,current_page): print(current_page) The Error I am getting from Screen TypeError at /home/change_lang/$ The Error I am getting in command line TypeError: change_visitor_language() missing 1 required positional argument: 'current_page' -
Django - How to check if the user has uploaded an excel file or input text and validate the form
def search_variant(request): context = { 'current_tab': '1' } if request.method == 'POST': form = SearchVariantForm(request.POST, request.FILES) if form.is_valid(): input_file = request.FILES['input_file'] if 'input_file' in request.FILES else None input_file_copy = save_input_file(input_file) context['current_file_name'] = path.basename(input_file.name) #db input hardcoded data db_input_data = [{'Chr': 'HARDCODEDchrX', 'Start': 107844640}] # run interpretation and display the result interpretations = run_intervar(input_file_copy.name, db_input_data) context['search_variant_form'] = SearchVariantForm() context['evidence_formset'] = PathogenicInterpretationFormSet(initial=interpretations) else: # display the search variant form with the errors context['search_variant_form'] = form else: context['search_variant_form'] = SearchVariantForm() return render(request, 'geneticvariants/index.html', context) The specifications of my project have changed, and now apart from an xlsx file, it is also possible that the user through the html form send strings (in a text input, with basically the same content as the xlsx file). The desired logic would be the following (semi pseudo-code): def search_variant(request): gene = request.POST.get('gene') variant = request.POST.get('variant') specimen = request.POST.get('specimen') if gene or variant or specimen: #same logic as per xlsx but with data from db_input_data (hardcoded) if request.method == 'POST': form = SearchVariantForm(request.POST, request.FILES) if form.is_valid(): input_file = request.FILES['input_file'] if 'input_file' in request.FILES else None input_file_copy = save_input_file(input_file) context['current_file_name'] = path.basename(input_file.name) #db input hardcoded data db_input_data = [{'Chr': 'HARDCODEDchrX', 'Start': 107844640}] # run interpretation and display the result … -
Check if user had filled questionnaire before with Django
I'm working on a questionnaire and I made a page where user have a list of which questionnaires to fill and which did he filled before but I have stucked. I like to check if the user filled a form/questionnaire before and if he didn't show him the questionnaire link. My solutions doesn't work because it checks the db just if the user filled the questionnaire but if he did not (no row for him in the db) it shows a blank cell in my table. (I don't know if exists query could be a solution but I can't made it work) main.html {% for i in oke_vezetoi %} {% if i.vezetoi_ok == True %} <td><button class="btn btn-sm btn-outline-info"> <a href="{% url 'stressz:vezetoi_item' %}">Kitöltöm</a></button> <td><i class="fas fa-running fa-2x text-dark"></i></td> {% else %} <td class="text-success text-uppercase">Kitöltötted</button> <td><i class="fas fa-check fa-2x text-success"></i></td> {% endif %} {% endfor %} views.py def main(request): oke_vezetoi = Vezetoi.objects.filter(user_name=request.user) oke_stressz = Stressz_teszt.objects.filter(user_name=request.user) context = { 'oke_vezetoi': oke_vezetoi, 'oke_stressz': oke_stressz, } return render(request, 'stressz/main.html', context) models.py class Vezetoi(models.Model): def __str__(self): return str(self.user_name) user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) vezetoi_v01 = models.IntegerField( null=True) vezetoi_v02 = models.IntegerField( null=True) vezetoi_v03 = models.IntegerField( null=True) vezetoi_v04 = models.IntegerField( null=True) vezetoi_v05 = models.IntegerField( null=True) vezetoi_v06 … -
How to save boolean value in to database while pressing html button using django
How to save the boolean value as true to database also route to another page. While we press continue button to save True value to db using django model also route to another page as welcome page. #models.py class Tutorial(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) is_tutorial = models.BooleanField(verbose_name=_('tutorial'), default=False) #views.py def tutorial_page(request): return render(request, "home/tutorial_page.html") #urls.py from . import views as homeview path('tutorial-page/', homeview.tutorial_page) #tutorialpage.html <article> <h2>demo</h2> <p>press <a href="https://localhost:8000/welcomepage/">continue</a> to skip the tutorial on next time </p> </article> -
Django redirect user upon login failure at /complete/auth0/
I'm using Django with Auth0 for authentication. Sometimes the login fails on Auth0 and redirected to my Django server with /complete/auth0/ with a token indicating error. This reaches my backend at the AUTHENTICATION_BACKENDS class, calling the function auth_complete, which calls process_error. This throws an exception and reaches the http500 page. The question is how should I handle that within these functions? How can I redirect the user to some page (e.g /login_failed.html) to show the client and them decide what to do -
Why can't I enter the admin interface in django after costumizing the user model?
So I have been trying to customize the user model of my django program, my model.py looks like this from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.core.validators import MaxValueValidator, MinValueValidator from django.utils.translation import gettext_lazy as _ from django.utils import timezone # Create your models here. class costumer_base_manager(BaseUserManager): def create_user(self, email, username,firstname, lastname, password, contact, **other_fields): if not email: raise ValueError("Please provide email") email = self.normalize_email(email) user = self.model(email=email, username=username, firstname=firstname, lastname=lastname, password=password,contact=contact, **other_fields) print(password) user.set_password(password) print(password) user.save() return user def create_superuser(self, email, username,firstname, lastname, password, contact, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', False) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must assign is_staff = True') return self.create_user(email, username, firstname, lastname, password, contact, **other_fields) class costumer(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_("email"),unique=True, blank=False) username = models.CharField(max_length=100, unique=True) firstname = models.CharField(max_length=100, blank=False) lastname = models.CharField(max_length=120, blank=False) start_date = models.DateTimeField(default=timezone.now) about = models.TextField(_("about me"), max_length=500, blank=True) investing_style = models.PositiveIntegerField(default=0,validators=[MinValueValidator(0), MaxValueValidator(3)]) contact = models.PositiveIntegerField(default=0,validators=[MinValueValidator(9000000001), MaxValueValidator(9999999999)]) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) objects = costumer_base_manager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'firstname', 'lastname', 'contact'] def __str__(self): return self.username and it worked after makemigrations and migrate I am also able to create super user here after createsuperuser As you can see I actually printed …