Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sjango - Saving updated information to existing user
I'm creating a multi-step user form for registration. The idea behind it, is when the user registers, it gets their registration information. Then, it saves the users information. In the registration form, if the user selected a certain option (rank = 'Anak'), they are redirected to a base form that obtains the tribe name. What I want it to do, is save the tribe name into that users account that was just created, but I am having trouble doing this since there is no save() function for base forms in Django. forms.py class RegisterForm(UserCreationForm): email = forms.EmailField( initial='', required=True, help_text='Please enter a valid email address' ) rank = forms.ChoiceField( label='Are you a PSMC member?', choices=SavBlock.models.User.rank, initial=False, required=True, help_text='Member accounts will be validated with your HC.', ) class Meta: model = User # username = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) fields = ['username', 'first_name', 'last_name', 'email', 'rank', 'password1', 'password2'] def save(self, commit=True): user = super(RegisterForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.ranking = self.cleaned_data['rank'] if commit: user.save() return user class AnakRegisterForm(Form): tribe = forms.ChoiceField( label='What tribe are you from, Uce?', choices=SavBlock.models.Anak.tribe, initial=False, required=True, help_text='Member accounts will be validated with your HC.' ) class Meta: model = Anak fields = ['tribe'] def save(self, commit=True): user = super(RegisterForm, … -
How should I do django admin becomes like this?
enter image description here What should I do django admin becomes like this? -
I get the error "SyntaxError: can't use starred expression here"
I get the error SyntaxError: can't use starred expression here in Python. At the same time, I also got the error SyntaxError: non-default argument follows default argument. Why is this? I would appreciate it if you could tell me more about this. -
Get all details from serializers.PrimaryKeyRelatedField in django
So I have my family serializer like below class FamilySerializer(serializers.ModelSerializer): members = serializers.PrimaryKeyRelatedField( many=True, queryset=Parishioner.objects.all(), allow_null=True ) class Meta: model = Family fields = ('id', 'name', 'address', 'monthly_contribution', 'members', 'enabled') read_only_fields = ('id',) depth = 1 Family can have multiple Parishioners so it's One to Many relationship. When I send a GET request to /api/family/1/ I get below response { "id": 1, "name": "Mendis Family test", "address": "No 48, Katukurunda, Moratuwa", "monthly_contribution": 50.0, "members": [ "1", "2" ], "enabled": true } as you can see in members array I can see only id of the members. How can I get all data of member within that array (NOT just the id. name, address, etc..) ? I tried changing depth = 1 to many numbers but it did NOT do the trick. -
Hi guys,Trying to get past the user registration as I assign groups to different users through giving different permisions. Kindly assist
Traceback (most recent call last): File "/home/alvin/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/alvin/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/alvin/.local/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) TypeError: 'NoneType' object is not callable [28/Apr/2021 10:17:24] "GET / HTTP/1.1" 500 70741 from django.http import HttpResponse from django.shortcuts import redirect def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('home') else: return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.users.groups.exists(): group = request.users.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse("You are not allowed to view this page!") return wrapper_func return decorator**strong text** -
django rest-auth login token use approach
I am using django rest-auth for handling user registration and login. whenever I try to login, it gives me token. so my question is now how to make use of that token to log in user to the home page. enter image description here what I want is to make use of that token to login the user in to home page. thank you -
Use dictionary value from if in statement
I have a need for an If/Else statement in my Django (3.1.5) template check if a value exists in a dictionary (very popular concept). My challenge here is now trying to use the value from the dictionary it matched on. I know i can use a for loop and then use another if to match again when that value exists but i am wondering if there is a shorter way to do what i am looking for. For example, in my template i have 2 query sets, config and user_settings that i pass to the template. What i do is check if the name from the config exists in the user_setting dictionary, then I use the config details in a form. What I want to do is take the "total" field from user_settings dictionary that matched on the if in statement. In the below code the, the piece i am talking about is on line 6 value='{{user_setting.total}}'. This clearly doesn't work but can i do something like that to reduce the amount of code? {% for c in config %} {% if c.location == 'Dashboard' %} {% if c.name in user_settings.all %} <div class="form-group col-md-6"> <label for="{{c.web_friendly_name}}">{{c.name}}</label> <input class="form-control" data-type="dashboard" … -
I cloned it from the collar, and the django admin goes like this. Why is that?
enter image description here I cloned it from the collar, and the django admin goes like this. Why is that? -
page will keep getting 404 error with {%endfor%} but if removed will render but now posts will show
Hi i'm hoping i make sense here i was hoping someone can point out for me why {% endfor % causes a 404 error for me but when i remove it the page renders but no posts show thank you in advance i've also attached screenshots code for Views from django.shortcuts import render from django.http import HttpResponse posts = [ { 'author': 'Joshua Harvey', 'title': 'blog post', 'content': 'first post test', 'date': 'may 1st 2021', }, { 'author': ' Deidre gibson', 'title': 'blog post 2', 'content': 'second post test', 'date': 'may 2st 2021', } ] def myView(request): context = { 'posts': posts } return render(request, 'hello/home.html', context) def about(request): return render(request, 'hello/about.html', {'title':about}) code for home.html {% extends "hello/base.html" %} {% block content %} <article class="media content-section"> <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted }}</small> </div> <h2><a class="article-title" href="#">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endblock content %} when i enter {%endfor} above {% endblock content%} i get 404 error for webpage but i need {%endfor%} to end the block but if i remove it i dont see any post's whatsoever -
Django Paginator - If there are more than ten posts, a “Next” button should appear
How can I detect in my JavaScript how many posts are there if my views method only sends 10 every time? basically, my all posts length is in the views.py method..But I need to know how many So I can add a next button if there are more than 10 posts. views.py def show_posts(request): all_posts = NewPost.objects.all() all_posts = all_posts.order_by("-date_added").all() paginator = Paginator(all_posts, 10) page_number = request.GET.get('page', 1) page_obj = paginator.get_page(page_number) return JsonResponse([website_post.serialize() for website_post in page_obj], safe=False) index.js function load_posts(){ document.querySelector('#page-view').style.display = 'none'; document.querySelector('#load-profile').style.display = 'none'; document.querySelector('#posts-view').style.display = 'block'; document.querySelector('#show-posts').style.display = 'block'; document.querySelector('#post-form').onsubmit = function() { compose_post(); } fetch('/posts/all_posts') // url with that API .then(response => response.json()) .then(all_posts => { // Loop and show all the posts. console.log(all_posts.length) all_posts.forEach(function(post) { // loop to loop over each object build_post(post) }); }); document.querySelector('#show-posts').innerHTML = "" } urls.py # API Routes path("posts/all_posts", views.show_posts, name="show_posts"), -
How to export information displayed in the template table to excel Django
I tried to export the information I display in the template under the table tag to excel, and the information was pulled from the SQL server. However, the exported csv only has headers in the file, I was wondering if anyone knows what might cause this? Here's my template: <body> <a href="{% url 'export_csv' %}">Export all PPs</a> <table class="myTable" id="myTable"> <center> <thead> <tr> <th>id</th> <th>Tracking Number</th> <th>Delivery Date</th> <th>Delivered</th> </tr> </thead> <tbody> {% for display in Project %} <tr> <td>{{display.id}}</td> <td>{{display.TrackingNumber}}</td> <td>{{display.EstimatedDeliveryDate}}</td> <td>{{display.Delivered}}</td> </tr> {% endfor %} </tbody> </center> </table> </body> Here's my model.py: id = models.CharField(max_length=1000) TrackingNumber = models.CharField(max_length=1000) EstimatedDeliveryDate = models.DateField(max_length=25) Delivered = models.CharField(max_length=1000) Here's my views.py: conn_Project = pyodbc.connect('driver={sql server};' 'server=test;' 'Database=test;' 'Trusted_Connection=yes;') cursor_Project = conn_Project.cursor() selectedpp_p = request.POST.get('selectedpp_p', None) query_Project = """select id,TrackingNumber,EstimatedDeliveryDate,Delivered from Test.Project where Project = ?""" cursor_Project.execute( query_Project, selectedpp_p ) result_Project = cursor_Project.fetchall() return render(request, 'introduction/project.html', {'Project': result_Project, 'selected_project': selected_project}) def export_csv_p(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=Exported Table' + \ str(datetime.datetime.now())+'.csv' writer = csv.writer(response) writer.writerow(['ID', 'TrackingNumber', 'DeliveryDate', 'Delivered']) for project in Project.objects.all().values_list('ID', 'TrackingNumber', 'DeliveryDate', 'Delivered'): writer.writerow(project) return response Here's my url.py: path('admin/', admin.site.urls), path('', introduction.views.project, name='project'), url(r'^export/csv/project/$', introduction.views.export_csv_p, name='export_csv_p'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Thank you in advance! -
Django unit test - patch multiple requests for external api
I need to write 'one' test code with external api, which requires requests 'twice'. first, I need to check if user is valid. So I handled this with decorator in ./users/utils.py import requests def login_decorator(func): def wrapper(self, request, *args, **kwargs): # this access token is issued by external api access_token = request.headers.get('Authorization', None) # first requests, which gives me an info about user. response = requests.get( 'https://kapi.kakao.com/v2/user/me', headers={'Authorization':f'Bearer {access_token}'} ) user_email = response.json()['kakao_account']['email'] request.user = User.objects.get(email=user_email) return func(self, request, *args, **kwargs) return wrapper and then, I need to send that user a message with the external api again. this code is in ./bids/views.py import requests class BiddingView(View): #it uses login_decorator above @login_decorator def post(self, request, art_id): try: user = request.user data = json.loads(request.body) with transaction.atomic(): #handle things with bidding system# #the external api requires its token to use a message api. token = request.headers.get('Authorization', None) #second requests, with post method response = requests.post( 'https://kapi.kakao.com/v2/api/talk/memo/default/send', headers = {'Authorization' : f'Bearer {token}'}, data = {"template_object" : json.dumps({'message':'contents'})} ) return JsonResponse({'MESSAGE' : 'SUCCESS'}, status=200) except KeyError: return JsonResponse({'MESSAGE' : 'KEY ERROR'}, status=400) This is my unit test code about BiddingView so far, which obviously only works for decorator @patch('users.utils.requests') def test_kakao_message_success(self, mock_requests): class … -
Django: How does django-admin-sortable2 package code work?
I am using a package called "django-admin-sortable2" but I do not understand what I am coding. May someone explain? Here's what I used: https://django-admin-sortable2.readthedocs.io/en/latest/usage.html#sortable-many-to-many-relations-with-sortable-tabular-inlines Here's the GitHub repository: https://github.com/jrief/django-admin-sortable2 Here's the code example they used: models.py from django.db.import models class Button(models.Model): """A button""" name = models.CharField(max_length=64) button_text = models.CharField(max_length=64) class Panel(models.Model): """A Panel of Buttons - this represents a control panel.""" name = models.CharField(max_length=64) buttons = models.ManyToManyField(Button, through='PanelButtons') class PanelButtons(models.Model): """This is a junction table model that also stores the button order for a panel.""" panel = models.ForeignKey(Panel) button = models.ForeignKey(Button) button_order = models.PositiveIntegerField(default=0) class Meta: ordering = ('button_order',) admin.py from django.contrib import admin from adminsortable2.admin import SortableInlineAdminMixin from models import Panel class ButtonTabularInline(SortableInlineAdminMixin, admin.TabularInline): # We don't use the Button model but rather the juction model specified on Panel. model = Panel.buttons.through @admin.register(Panel) class PanelAdmin(admin.ModelAdmin) inlines = (ButtonTabularInline,) -
Why data is not saved from the form?
I can't understand why the data from the form is not stored in the database. My code : .views.py def create(request): error = '' if request.method == 'POST': form = ProductForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: error = 'Форма некоректна' form = ProductForm() data = { 'form': form, 'error': error } return render(request, 'create_product.html', data) .forms.py class ProductForm(ModelForm): class Meta: model = Product fields = ['title','start_date','end_date','quantity_lections','photo','description','small_description',"slug"] widgets = { 'title': TextInput(attrs={'class': 'form-control', 'placeholder': 'Назва курсу'}), "slug" : TextInput(attrs={'class': 'form-control'}) , 'small_description': Textarea(attrs={'class': 'form-control','placeholder': 'Наприклад,опишіть для кого цей курс'}), 'description': Textarea(attrs={'class': 'form-control', 'placeholder': 'Опис'}), 'start_date': DateTimeInput(attrs={'class': 'form-control',"type": "date"}), 'end_date': DateTimeInput(attrs={'class': 'form-control',"type": "date"}), 'quantity_lections': NumberInput(attrs={'class': 'form-control'}), 'photo' : FileInput(attrs={'class':'form-control'}) } When I press the submit button, I get in the console POST request with code 200. -
Django subclass model gives "duplicate key value violates unique constraint" on save
I have a class with many fields: class Parent(models.Model): id = models.AutoField(primary_key=True) ... many more fields and I create a subclass class Child(Parent): other_field = models.CharField(max_length=512, blank=True, null=True) date_featured = models.DateField() After I migrate and create a Child object in the admin I get duplicate key value violates unique constraint "parent_pkey" DETAIL: Key (id)=(5) already exists. I've seen some similar questions that suggest that you modify the database but I can't easily do that. Do I need to change the id of the subclass? -
get_tenant() missing 1 required positional argument: 'request'
I'm working on Django with multi tenants package and i have followed a tutorial to have only one login page : https://blog.learningdollars.com/2020/08/02/how-to-implement-django-tenant-schemas-with-a-fixed-url/ this is my code : from datetime import date from dateutil.relativedelta import relativedelta from django.core.exceptions import ObjectDoesNotExist from django_tenants.middleware.default import DefaultTenantMiddleware from django_tenants.utils import get_public_schema_name class RequestIDTenantMiddleware(DefaultTenantMiddleware): def get_tenant(self, model, hostname, request): try: public_schema = model.objects.get(schema_name=get_public_schema_name()) except ObjectDoesNotExist: public_schema = model.objects.create( domain_url=hostname, schema_name=get_public_schema_name(), tenant_name=get_public_schema_name().capitalize(), paid_until=date.today() + relativedelta(months=+1), on_trial=True) public_schema.save() x_request_id = request.META.get('HTTP_X_REQUEST_ID', public_schema.tenant_uuid) tenant_model = model.objects.get(tenant_uuid=x_request_id) print(tenant_model, public_schema) return tenant_model if not None else public_schema i'm getting as an error : TypeError at /client get_tenant() missing 1 required positional argument: 'request' -
Reference to global variable stays on the view even after it's not getting triggered
I want to display an error message to the user when an Exception is triggered. By default, the error_message should be False and when an Exception is triggered error_message should be updated with the exception message. When the exception is triggered my html page successfully displays the error message, but when I reload the page the error message is still displayed although the exception isn't being triggered anymore. By default it needs to stay False, but why does the reference to the global variable not get overridden on a page reload? error_message = False def home_page(request): if request.method == 'POST': try: #execute mySQl query db_error_message = False except Exception as e: db_error_message = e return HttpResponseRedirect("/hardware_milestone/") context = {'error_message ': error_message } return render(request, 'home_page.html', context}) -
Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7fb2bc14aa90>": "Post.created_by" must be a "User" instance
I'm trying to make a post as a logged user but when I try to do so, I get this error: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7fb2bc14aa90>": "Post.created_by" must be a "User" instance. I figured there's an issue when it comes to keeping the user logged in since I did get the token and all the data when I logged it in but that seems to disappear the moment I go to another view in the API. How can I fix it? These are the serializers: class UserLoginSerializer(serializers.ModelSerializer): """ User Login Serializer """ username = serializers.CharField( required=True, write_only=True, ) token = serializers.CharField( allow_blank=True, read_only=True ) password = serializers.CharField( required=True, write_only=True, style={'input_type': 'password'} ) class Meta(object): model = User fields = ['id','username', 'password', 'token'] def validate(self, data): username = data.get('username', None) password = data.get('password', None) if username and password: user = authenticate(request=self.context.get('request'), username=username, password=password) if not user: msg = 'Unable to log in with provided credentials.' raise serializers.ValidationError(msg, code='authorization') else: msg = "Must include username and password." raise serializers.ValidationError(msg, code='authorization') data['user'] = user return data class PostSerializer(serializers.ModelSerializer): """ Post Serializer """ replies = serializers.SerializerMethodField('get_replies') class Meta: model = Post fields = ['category','title','body','created_at','replies'] extra_kwargs = {'created_by': {'read_only':True}} def get_replies(self, obj): serializer = … -
Login and Logout views are they necessary? ( SimpleJwt+Django rest framework)
So according to many examples out there. some projects would actually build a Loggin view that uses the AccesToken and a Logout view that could use the Blacklist. while others would just use AccesToken,Refresh , Blacklist directly and handle the login/logout from the frontend(a consumer like React,...) with out the need to use Views.py i was wondering if one is better than the other, or is there any difference (performance wise, or security,...) Thanks -
Django Queryset: Only return entries where a specific field appears greater than N times
Let's say I have a model with a user foreignkey and a charfield. How can I filter a queryset so that only users with > 3 entries are returned in one line? So something like this (which obviously does not exist yet): Post.objects.filter(user__appears__gte=2) -
Django forms, form is always invalid
Yes, I did look at the other responses to similar questions. But I haven't found one that helps me, Ive looked at all the currently available solutions. I am trying to enter a name into a textbox, and then hit submit, allowing me to create a new list of items (the items are irrelevant). But when I hit the submit button nothing happens. After many print statements, Ive deduced that the reason why is because the form.is_valid() function is returning false if response.method == "POST": # returns a dictionary of information in the form form = CreateNewList(response.POST) print(form.errors) # if the form is valid, get the name attribute and create a new ToDoList with it if form.is_valid(): n = form.cleaned_data["name"] t = ToDoList(name=n) t.save() return HttpResponseRedirect("/%i" % t.id) else: form = CreateNewList() return render(response, "main/create.html", {"form": form}) After reading some posts I found online, the next step I took was printing out the errors using forms.errors This is what I got from that print out <ul class="errorlist"><li>check<ul class="errorlist"><li>This field is required.</li></ul></li></ul> At this point, I have no clue what check is or does. One persons response online said that it is part of some dictionary and I have to do … -
Django One to Many Loose Relationship
Backstory Data is being pulled from an accounting system that can have department, market, and client relationship data associated with it. The relationship data are all TEXT/CHAR fields. They are not integer columns. There are over 2 million rows. The problem The problem I've been running into is how to add the lines without relationship validation that could fail because the related table (like Market) is missing the value or has been changed (because we are looking far back in the past). The naming of the columns in the Django database (more detail below), and querying Django models with a join that don't have a relationship attribute on the class. models.py from typing import Optional from django.db import models class Line(models.Model): entry_number: int = models.IntegerField(db_index=True) posting_date: date = models.DateField() document_number: Optional[str] = models.CharField(max_length=150, null=True, default=None) description: Optional[str] = models.CharField(max_length=150, null=True, default=None) department: Optional[str] = models.CharField(max_length=150, null=True, default=None) market: Optional[str] = models.CharField(max_length=150, null=True, default=None) amount: Decimal = models.DecimalField(max_digits=18, decimal_places=2) client: Optional[str] = models.CharField(max_length=150, null=True, default=None) # This relationship works account = models.ForeignKey(Account, on_delete=models.DO_NOTHING, related_name='lines') class Department(models.Model): code: str = models.CharField(max_length=10, db_index=True, unique=True, primary_key=True) name: str = models.CharField(max_length=100, null=True) class Market(models.Model): code: str = models.CharField(max_length=10, db_index=True, unique=True, primary_key=True) name: str = models.CharField(max_length=100, … -
Django Form doesn't show the initial value
I don't know if i'm doing something wrong but even when i set a initial value in a django form, that value doesn't show in the form. class EditForm(forms.Form): title = forms.CharField() content = forms.CharField() def edit(request, name): initial_data = { 'title' : name.capitalize(), 'content' : util.get_entry(name) } if request.method == "POST": form = EditForm(request.POST, initial=initial_data) if form.is_valid(): title = form.cleaned_data['title'] content = form.cleaned_data['content'] util.save_entry(title, content) return HttpResponseRedirect(reverse('wiki:index')) return render(request, "encyclopedia/edit.html", { "name" : name.capitalize(), "content" : util.get_entry(name), "form" : NewTaskForm() }) I'm trying to show the name and the content of a markdown archive to edit that same file, the entire app is working fine (import and saving the file). The server doesn't show any error messages and the page loads with no problems. (If somenthing is wrong if the question i apologize, my english isn't one of the best) -
Stripe: No signatures found matching the expected signature for payload using Django
While calling a Stripe Web hook, I am getting this error: No signatures found matching the expected signature for payload I am following this article: https://stripe.com/docs/billing/subscriptions/checkout#provision-and-monitor And I have following code: @csrf_exempt def saaswebhookview(request): try: stripe.api_key = settings.STRIPE_SECRET_KEY webhook_secret = 'stripe_key' request_data = request.POST if webhook_secret: try: signature = request.headers.get('stripe-signature') # signature = request.META['stripe-signature'] event = stripe.Webhook.construct_event( payload=request.POST, sig_header=signature, secret=webhook_secret) data = event['data'] except Exception as e: print(str(e)) return JsonResponse({'status': 'error', 'error': str(e)}) event_type = event['type'] else: data = request_data['data'] event_type = request_data['type'] data_object = data['object'] if event_type == 'checkout.session.completed': print(data) elif event_type == 'invoice.paid': print(data) elif event_type == 'invoice.payment_failed': print(data) else: print('Unhandled event type {}'.format(event_type)) return JsonResponse({'status': 'success'}, safe=False) except Exception as e: return JsonResponse({'status': 'success', 'error': str(e)}, safe=False) But strangely this throws me the error don't know why? -
default value not show in django formset
i'm trying to build an app which contains django inline formset , but default values only show for the first form!? this is my model class Main(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) A= models.ManyToManyField(Item,through='Child') B = models.IntegerField() class Child(models.Model): main = models.ForeignKey(Main,on_delete=models.CASCADE) item = models.ForeignKey(Item,on_delete=models.CASCADE) quantity = models.IntegerField(default=1) my views.py class CreateMainInlineFormset(LoginRequiredMixin,SuccessMessageMixin,CreateView): model = Main form_class = MainForm template_name = 'main/create.html' def get_context_data(self, *args,**kwargs): data = super().get_context_data(*args,**kwargs) if self.request.POST: data['items'] = ChildInlineFormSet(self.request.POST) data['items'].full_clean() else: data['items'] = ChildInlineFormSet() return data def form_valid(self, form): context = self.get_context_data() items = context['items'] with transaction.atomic(): self.object = form.save(commit=False) form.instance.admin = self.request.user if items.is_valid() and form.is_valid() and items.cleaned_data!={}: items.instance = self.object form.save(commit=True) items.save() else: return render(self.request,self.template_name,context) return super().form_valid(form) def get_success_url(self): return reverse_lazy('maininfo:list-item') my forms.py class ParentForm(forms.ModelForm): class Meta: model = Main fields = [ '__all__' ] class ChildForm(forms.ModelForm): class Meta: model = Child fields = [ '__all__' ] ItemInlineFormSet = inlineformset_factory( Main,Child,form=ChildForm,fields=( 'item','quantity'), extra=1 ) i have to display quantity default value for all of the forms , but it only display for the first form , the rest will be null