Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IntegrityError: null value in column "category_id" of relation "message" violates not-null constraint DETAIL: Failing row contains
I believe this error comes from this line that i might have written incorrectly. Anyone can share why this is written incorrectly in views.py? I understand that I have to specify the this field because it is a foreign key to the model Category: message.category_id = self.categories.id views.py class AddMessageView(DetailView, FormView): model = Room form_class = MessageForm template_name = 'add_message.html' def form_valid(self, form): message = form.save(commit=False) message.category_id = self.categories.id message.name = self.request.user message.room = self.get_object() message.save() models.py class Category(models.Model): categories = models.CharField(max_length=80, null=False, blank=False, unique=True) slug = models.SlugField(blank=True, unique=True) class Room(models.Model): categorical = models.ForeignKey(Category, related_name='categorical', on_delete=models.CASCADE) slug = models.SlugField(blank=True) class Message(models.Model): category = models.ForeignKey(Category, related_name='category', on_delete=models.CASCADE) room = models.ForeignKey(Room, related_name='messages', on_delete=models.CASCADE) name = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='naming', on_delete=models.CASCADE) -
Got AttributeError when attempting to get a value for field `members` on serializer `HealthQuotationSerializer`
Trying out serialising parent and child model.Here are my models: class HealthQuotation(models.Model): quotation_no = models.CharField(max_length=50) insuredpersons = models.IntegerField() mobile_no = models.CharField(max_length=10) def __str__(self): return self.quotation_no class HealthQuotationMember(models.Model): premium = models.FloatField(null=True) suminsured = models.FloatField() quotation = models.ForeignKey(HealthQuotation,on_delete=models.CASCADE) def __str__(self): return str(self.quotation) Here are my serializers: class HealthQuotationMemberSerializer(serializers.ModelSerializer): class Meta: model = HealthQuotationMember fields= "__all__" class HealthQuotationSerializer(serializers.ModelSerializer): members = HealthQuotationMemberSerializer(many=True) class Meta: model = HealthQuotation fields = ['id','members'] On Serialising parent model with parent serializer, Django throws error "Got AttributeError when attempting to get a value for field members on serializer HealthQuotationSerializer. The serializer field might be named incorrectly and not match any attribute or key on the HealthQuotation instance. Original exception text was: 'HealthQuotation' object has no attribute". -
NoReverseMatch at /blog Reverse for 'single_blog' with no arguments not found. 1 pattern(s) tried: ['single_blog/(?P<id>[0-9]+)/$']
I tried many times but the page not rendering , i am not understanding where i did wrong? could you please let me know , where i did wrong? models.py class Post(models.Model): head = models.CharField(blank=False, unique=True, max_length=250) date_time = models.DateTimeField(blank=True, null=True, default=None) description = models.TextField(blank=False, max_length=1000) by_name = models.CharField(blank=False, null=True, unique=True, max_length=250) by_img = models.ImageField(null=True, blank=True) def __str__(self): return self.head views.py def blog(request): blogs = Post.objects.all() return render(request, 'blog.html', {'blogs': blogs}) def blog(request): blogs = Post.objects.all() return render(request, 'blog.html', {'blogs': blogs}) def dynamicblog(request, id): obj = Post.objects.get(id=id) return render(request, 'single_blog.html', {'obj': obj}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('contact', views.contact, name='contact'), path('shop', views.shop, name='shop'), path('service', views.service, name='service'), path('blog', views.blog, name='blog'), path('single_blog/<int:id>/', views.dynamicblog, name='single_blog'), path('single_service', views.single_service, name='single_service'), blog.html {% for blog in blogs %} <div class="col-lg-4 col-md-6 col-sm-12 news-block"> <div class="news-block-two news-block-three wow fadeInLeft" data-wow-delay="300ms" data-wow-duration="1500ms"> <div class="inner-box"> <div class="image-holder"> <figure class="image-box"><img src="{{blog.by_img.url}}" alt=""></figure> </div> <div class="lower-content"> <h4><a href="{% url 'single_blog' %}">{{blog.head}}</a></h4> <div class="post-info">by {{blog.by_name}} on {{blog.date_time}}</div> <div class="text">{{blog.description}}</div> <div class="link-btn"><a href="{% url 'single_blog/{{blog.id}}' %}">Read More<i class="flaticon-slim-right"></i></a></div> </div> </div> </div> </div> {% endfor %} single_blog.html <div class="col-lg-4 col-md-12 col-sm-12 sidebar-side"> {% for blog in obj %} <div class="sidebar blog-sidebar"> <div class="contact-widget sidebar-widget … -
pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection:
I am trying to use MongoDB with Django Framework using the library Djongo. I am stuck in a particular problem right now where I can't store more than 1 document in MongoDB. After first data insert, Django Throws pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: Even though I only have one document. Also I am not setting '_id' field in my models. So its Djongo who does it for me. My Model.py from djongo import models # Create your models here. class Data(models.Model): company_name = models.CharField(max_length=200) company_url = models.CharField(max_length=200) company_logo = models.CharField(max_length=200) objects = models.DjongoManager() -
Django: Easy way how to handle if an objects exists already or not
I have on my website an inputfield only with an email, where customers can sign up for newsletters. At the moment I am handling by a function if this customer (email) exists already, if not then the object is created, if not, then the object is catched. There must be a simplier way to do that in Django? Any ideas? Thanks a lot This is the simplified function: def get_customer(email): # all only lowercase in order to avoid multiple entries email = email.lower() if Customer.objects.filter(email=email).exists(): # get customer object customer = Customer.objects.get(email=email) else: # save form input to database customer = Customer.create(email) customer.save() return customer This is the real function, where I also update optional parameters like name (which is an input in an other form): def get_customer(name, email): # all only lowercase in order to avoid multiple entries email = email.lower() if Customer.objects.filter(email=email).exists(): # get customer object customer = Customer.objects.get(email=email) # if no name available in customer object but name given here, then update customer object if len(customer.name) == 0 and len(name) > 0: Customer.objects.filter(id=customer.id).update(name=name) else: # save form input to database customer = Customer.create(name, email) customer.save() return customer P.S.: I know email = email.lower() is not 100% correct … -
i have create user model . how to change password using email password reset link without use built-in django user model
model.py from django.db import models class Customer(models.Model): firstname=models.CharField(max_length=50) lastname=models.CharField(max_length=50) phone=models.CharField(max_length=10) email=models.EmailField(max_length=100) password=models.CharField(max_length=30) address=models.CharField(max_length=200) is_activated = models.BooleanField(default=True) def str(self): return self.firstname @staticmethod def get_customer_by_email(email): try: return Customer.objects.get(email=email) except: return False -
The view message.views.message didn't return an HttpResponse object. It returned None instead
after submitting the form it shows this error that values error at /Contact/ and the error which i mentioned in title i want to load html file in httpresponse after submmiting the form views.py from django.shortcuts import render, redirect from .forms import Messageform from django.contrib import messages from django.http import HttpResponse, HttpResponseNotFound from django.template import Context, loader # Create your views here. def message(request): if request.method == 'POST': form = Messageform(request.POST) if form.is_valid(): form.save() messages.success(request, 'Message sent') template = loader.get_template("message/messagesent.html") return HttpResponse(template.render()) else: form = Messageform() return render(request, 'contact.html', {'form': form}) -
user_id does not exist in database in DJANGO
I'm trying to access the profile of the user using its id as the url. My problem is that it returns that the id does not exist. Here are some codes that is related to the problem. views.py: @login_required(login_url='login') def profile_view(request, *args, **kwargs): context = {} user_id = kwargs.get("user_id") try: profile = UserAccount.objects.get(pk=user_id) except UserAccount.DoesNotExist: return HttpResponse("User is not yet registered.") if profile: context['id'] = profile.id context['username'] = profile.username context['profile_image'] = profile.profile_image context['date_joined'] = profile.date_joined return render(request, 'chat/profile.html', context) models.py: class UserAccount(models.Model): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=60, unique=True) password = models.CharField(max_length=100) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_superuser = models.BooleanField(default=False) def __str__(self): return self.username urls.py: path('account/<user_id>/', views.profile_view, name='profile_view'), base.html: {% if user.is_authenticated %} <a class="nav-item" role="presentation" href="{% url 'profile_view' user_id=request.user.id %}">Profile</a> <span class="navbar-text actions"><a class="btn btn-light action-button" role="submit" href="{% url 'logout' %}">Logout</a></span> {% else %} <a class="btn btn-light action-button" role="button" href="{% url 'register' %}">Sign Up</a></span> {% endif %} Sample run CORRECT: Login (as the first created user) Clicked profile redirects to the localhost:8000/account/1/ Sample run Error: Login (as the 5th created user) Clicked profile redirects to localhost:8000/account/5/ --> gives HttpResponse() under the views.py changing the value to 1 localhost:8000/account/1/ --> gives correct information … -
Field 'id' expected a number but got 'test1'
So I'm trying to change user password. I have tried user.set_password but that just doesn't work, It does not change the password User.objects.get(user_permissions=request.user.username).set_password(new_password1) gives me an error. views.py @login_required def userchange(request): if request.method == 'POST': user = request.user old_password = request.POST['Old password'] new_password1 = request.POST['New password1'] new_password2 = request.POST['New password2'] if user.check_password(old_password): if new_password1 == new_password2: if new_password1 == "" or new_password2 == "": return render(request, 'main/change.html', {'error':'Your new passwords are empty!'}) else: User.objects.get(user_permissions=request.user.username).set_password(new_password1) logout(request) return render(request, 'main/change.html', {'error':'Your password has been changed succesfully!'}) else: return render(request, 'main/change.html', {'error':'Your new passwords do not match'}) else: return render(request, 'main/change.html', {'error':'Your old password is incorrect'}) elif request.method == "GET": return render(request, 'main/change.html') change.html <h1>Note: You will be logged out</h1> <h2>{{ error }}</h2> <form method="POST"> {% csrf_token %} <input type="password" placeholder="Old password" name="Old password"> <input type="password" placeholder="New password" name="New password1"> <input type="password" placeholder="Confirm password" name="New password2"> <button type="submit">Change password</button> </form> -
Deploying project to Heroku builds fine but is unable to release and generates the SECRET_KEY setting must not be empty error
I am new to Django and Heroku. I cloned t[his][1] project from Github and tried to push it to Heroku. The entire build process goes smoothly, but the project never gets released. Unfortunately as soon as I get to the release stage I keep running into this error and have no idea how to solve it. Any suggestions? remote: Traceback (most recent call last): remote: File "manage.py", line 15, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 224, in fetch_comman remote: klass = load_command_class(app_name, subcommand) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 36, in load_command_class remote: module = import_module('%s.management.commands.%s' % (app_name, name)) remote: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 994, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 971, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked remote: File "<frozen importlib._bootstrap>", line 665, in _load_unlocked remote: File "<frozen importlib._bootstrap_external>", line 678, in exec_module remote: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 14, in <module> remote: from django.db.migrations.autodetector import MigrationAutodetector remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/autodetector.py", line 11, in <module> remote: from django.db.migrations.questioner import … -
Stop Django from rendering JSON response
I'm using Django with rest_framework and in my views I'm using the rest_framework.viewsets, I stopped rest_framework to show it's fancy interface using: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer'), } But now Django is rendering the JSON response I want it always to return Raw Data How can I do that? -
How to access short_description of a property in Django
If I have a Django model with a property defined as def __task_state(self): if self.task_id is None: return None else: return # Calculate state somehow __task_state.short_description = _("Task State") # Task state task_state = property(__task_state) Now how do I access short_description for the property? I am trying to iterate over all properties and field for the model so I can get verbose_name equivalent to use in detailed view and for list view column header. I can't use __task_state.short_description directly and I can't figure out how to get this info using task_state doc() function says not defined, short_description is obviously not going to be an attribute of property. Can't seem to find anything on it anywhere. Everywhere all it says is use short_description for property text but no one mentions how to access it. This is how I am trying to find all properties for my model in case anyone feel its relevant # Get property (name, value) set for the object def get_properties(self): # Get all properties property_names = [ name for name in dir(Job) if isinstance(getattr(Job, name), property) ] # Return list result = [] # Let's prune out pk from the result as we don't want it for … -
Lightbox error when trying to find close.png next.png loading.png prev.png
Could someone point me in the direction where I am supposed to be saving the subjected files? The error I am getting is "Not Found: /images/close.png" when trying to add buttons to my lightbox images. It's obviously expecting an images folder but I cannot seem to place it in the correct location within my project. Anyone lend a hand on where exactly to place this images folder..? Using Pycharm enter image description here -
Serving Django Channel and Django Rest Framework from same Elastic Bean Server?
How to serve the Django Rest Framework and Django Channel from the same Elastic Bean Container? -
@user_passes_test not working as expected - Django Python
I have created a role based login in Django 3.1.2. And i have used @user_passes_test decorator to check the role of user according to his/her role he can access the views, or we can say views will execute but it is not working as expected. models.py class User(AbstractUser): GENDER = ( (True, 'Male'), (False, 'Female'), ) USER_TYPE = ( ('Admin', 'Admin'), ('Designer', 'Designer'), ('Customer', 'Customer'), ) user_id = models.AutoField("User ID", primary_key=True, auto_created=True) avatar = models.ImageField("User Avatar", null=True, blank=True) gender = models.BooleanField("Gender", choices=GENDER, default=True) role = models.CharField("User Type", max_length=10, choices=USER_TYPE, default='Customer') Here in user models I have a field, with help of that I can specify user role and default is Customer. views.py # view to check whether a user is Designer or Admin def check_role_admin_or_designer(user): if user.is_authenticated and (user.role == 'Admin' or user.role == 'Designer'): print(user.role) return True # view to check whether a user is Admin def check_role_admin(user): if user.is_authenticated and (user.role == 'Admin' or user.is_superuser): return True else: return HttpResponse("You are not Authorized to access this page") # my login view def loginPage(request): if request.user.is_authenticated and request.user.role == 'Customer': return redirect('user-home') if request.user.is_authenticated and ( request.user.role == 'Admin' or request.user.role == 'Designer' or request.user.is_superuser): return redirect('admin-home') else: if … -
How can I update page content without reloading the page on Modal close?
I am trying to edit a post on a page, clicking on edit link opens a Modal, clicking on save button, saves the edited post in the database but I have to refresh the page to see that edited post on the screen. I want the screen to be updated as soon as the modal is closed but I don't want the page to be reloaded. How can I achieve this without reloading the page? Views.py def editTweet(request, post_id): postData = Posts.objects.filter(id = post_id) if request.method == "PUT": data = json.loads(request.body) print("data value is ", data) #updating data in the database where id = post_id Posts.objects.filter(id = post_id).update(postContent = data.get('postContent', None)) print ("i'm inside PUT") return render(request, 'network/index.html') else: print("i'm inside else") return JsonResponse([post.serialize() for post in postData], safe=False) JavaScript function loadModal(id) { //load the modal var modal = document.getElementById("myModal"); var btn = document.getElementById("editLink"); var span = document.getElementsByClassName("close")[0]; var saveBtn = document.getElementById("saveButton"); //populate the modal with tweet content fetch(`/edit/${id}`) .then(response => response.json()) .then(postDetails => { modal.style.display = "block"; postDetails.forEach(element => { document.querySelector('#editPostBox').value = `${element.postContent}`; }) }) // When the user clicks on <span> (x), close the modal span.onclick = function () { modal.style.display = "none"; } saveBtn.onclick = function(){ fetch(`/edit/${id}`, … -
AttributeError: Generic detail view AddMessageView must be called with either an object pk or a slug in the URLconf
Generic detail view AddMessageView must be called with either an object pk or a slug in the URLconf. Basically I am trying to access a page for me to add post into a room through the link in room.html. However I received the error above. Why is this error happening?? It might be that i need to specify the 2 diff slugs in my classbased view but how do I do that if the slug belongs to 2 different models? url.py path('<slug:type1_slug>/<slug:type2_slug>/messages/', AddPostView.as_view(), name= "add_post"), room.html <a href="{% url 'add_post' type1_slug=room.slug type2_slug=category.slug %}"> views.py def room_view(request, type1_slug, room_slug): context = {} category = get_object_or_404(Category, slug=type1_slug) context['category'] = category room = get_object_or_404(Room, slug=room_slug, typeofcategories=category) context['room'] = room return render(request, "room.html", context) class AddPostView(DetailView, FormView): model = Room form_class = PostForm template_name = 'HomeFeed/add_post.html' models.py class Category(models.Model): category = models.CharField(max_length=80, null=False, blank=False, unique=True) slug = models.SlugField(blank=True, unique=True) class Room(models.Model): categories = models.ForeignKey(Category, related_name='typeofcategories', on_delete=models.CASCADE) description = models.TextField(max_length=300, null=True, blank=True) slug = models.SlugField(blank=True) -
django-static-precompiler throwing error with no message
I'm trying to use django-static-precompiler to compile scss but I'm getting an error StaticCompilationError that says No exception message supplied The version for django-static-precompiler is 2.0 and sass is installed and is the latest version (1.32.6). I have the precompiler configured to point to node modules in my settings.py. STATIC_PRECOMPILER_COMPILERS = ( ('static_precompiler.compilers.SCSS', { "executable": "node_modules/.bin/sass" }), ) Here is a snippet from the template it's used in: <link rel="stylesheet" href="{% static "/css/style.scss"|compile %}" /> The error message is not very helpful. Does anyone have any idea what the issue could be? -
request.post variable is always returning as empty
So I'm trying to see if user matches their old password, if they don't then it will give a message saying "Your old password in incorrect" but if they match their old password then it should check if user matched new and confirmed password correctly, if they did not then it should give a message saying "Your new passwords do not match" but if their password is empty it should say "Your new passwords are empty, But even if my passwords are not empty it always says my passwords are empty. I have also tried if new_password1 or new_password2 == '' but that also has the same result. views.py @login_required def userchange(request): if request.method == 'POST': user = request.user old_password = request.POST['Old password'] new_password1 = request.POST['New password1'] new_password2 = request.POST['New password2'] if user.check_password(old_password): if new_password1 == new_password2: if new_password1 or new_password2 is None: return render(request, 'main/change.html', {'error':'Your new passwords are empty!'}) else: user.set_password(new_password1) return render(request, 'main/change.html', {'error':'Your password has been changed succesfully!'}) else: return render(request, 'main/change.html', {'error':'Your new passwords do not match'}) else: return render(request, 'main/change.html', {'error':'Your old password is incorrect'}) elif request.method == "GET": return render(request, 'main/change.html') change.html <h1>Note: You will be logged out</h1> <h2>{{ error }}</h2> <form method="POST"> … -
I want my search function to be able to take multiple words rather than just one word, or exact sentence match in my database
Here is my search bar function: ` def searchbar(request): if request.method == "GET": search = request.GET["search"], deity = Deity.objects.filter(Q(name__contains=search[0])|Q(location__contains=search[0])|Q(alt_name__contains=search[0])|Q(culture__contains=search[0])|Q(religion__contains=search[0])|Q(description__contains=search[0])|Q(pop_culture__contains=search[0])), context = { "user": User.objects.get(id = request.session['user_id']), "deity": deity, "search": search[0], } return render(request, 'search_results.html', context) ` My Navbar has a search text box and button, and it searches my entire database for exactly what I put into the search bar (with the exception of capitalization, that doesn't seem to matter). However, if I put a sentence in, it takes whole sentence and searches for it exactly not recognizing the individual words in the search. How can I fix this? -
Annotate queryset with a boolean from ManyToMany relation
Lets say I have a Book model like this: class Book(models.Model) title = models.Charfield(...) likes = models.ManyToMany(User, related_name="books_liked") I need to annotate a queryset with a is_liked field for the current logged user. something in the view like this: qs = Book.objects.all().annotate(????) so I can use something like this in the template {% for book in books %} {% if book.is_liked %} ... {% endif %} {% endfor %} I'm checking this docs section, but I'm not too sure how to proceed or if is the correct way. https://docs.djangoproject.com/en/3.1/ref/models/expressions/#exists-subqueries How can I do this? Thanks. -
Django Channels: "No text section for incoming WebSocket frame!"
I'm using django-channels's AsyncJsonWebsocketConsumer [reference] and I keep getting the error "No text section for incoming WebSocket frame!" after sending a message on an established socket connection. AsyncJsonWebsocketConsumer throws this error when it can't find text_data. # django-channels source code async def receive(self, text_data=None, bytes_data=None, **kwargs): if text_data: await self.receive_json(await self.decode_json(text_data), **kwargs) else: raise ValueError("No text section for incoming WebSocket frame!") This is my code which causes this error to be thrown. async def send_message(self, txt): message = Message.objects.create(body=txt) data = serializers.MessageSerializer(message).data await self.send_json({ 'type': msg.get('type'), 'data': data, }) # await self.channel_layer.group_send(self.conversation_group_name, data) async def receive_json(self, content, close=False): message_type = content.get('type') if message_type == 'send.message': await self.send_json({ 'type': message_type, 'data': content.get['data'] }) -
Deploying Django to Production (Not on Heroku/PythonAnywhere)
i currently have completed my Django Project and am ready to launch it.Its my first time launching so I'm asking if anyone has a checklist of what is required to be changed before you launch it to production. `After launching it, do you need to keep your laptop switched on at all times to runserver? Or is there a way to someone else's server to run it, and if I use IAAS from someone else, would I be able to makechanges/ access the admin panel anytime i want? i need to change DEBUG from true to false -My static CDN and email login confirmations, how will they be stored and how will i be able to access them? -The settings secret key, will the settings.py file be widely available to the public for everyone to see? Or will it be hidden. If hidden, how can i hide it. Also same for the stripe key. -Requirements.txt, how do I "import" all the codes to the "server" to make sure that they all work? -What are all the files to be hidden from the public and how can I hide them? Is there anymore changes that I need to make? -
How do I turn Django Multislelect checkbox fields into clickable buttons?
Trying to create each of the fields/moods as clickable buttons. Not looking to make it a dropdown menu, as I want all the buttons to be visible at once. This is what I have so far... <b>What are you feeling?</b><br> Please choose at least one mood for best results. <br> {% for x in form.visible_fields.7%} <div> {{ x }} </div> {% endfor %}``` -
Django distinguish between add_fieldsets and get_fieldsets
I have a below fieldset in my model, fieldsets = [ (None, { "fields": ["email", "password", "name"] }), ("Account Profile", { "fields": [ "company", "profession", ] }), ("Account Settings", { "fields": [ "nsfw", "is_staff", "is_active", "is_dev", "detector_token", "detection_api_access" ] }), ] And I have added a get_fielsets method to display is_superuser field only when the logged in user is a superuser, def get_fieldsets(self, request, obj=None): fieldsets = super(AccountAdmin, self).get_fieldsets(request, obj) print(fieldsets) if request.user.is_superuser: fieldsets[2][1]['fields'].insert(1, 'is_superuser') return fieldsets Now the problem is that my code has add_fieldsets as below which gets called while creating new accounts and it gets failed at statement fieldsets[2][1]['fields'].insert(1, 'is_superuser') because it do not have those records, add_fieldsets = ((None, { 'classes': ('wide', ), 'fields': ("email", 'password', 'password2', "is_staff", "is_active") }), ) What is the best way to handle this scenario. I am getting error as tuple index out of range