Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HTML - How to auto refresh the messages of a Chat-App
I'm working on a Chat-App with Django in Python. I tried some changes to auto refresh the messages of a chat but I had some problems: First time I tried: I used a javascript reloader for the div of the chat (but doing this, the send-message text input clears every time the auto refresher plays.) Second problem: the chat reset the height of the scroll every time the auto refresher plays. So I'm looking for a solution to refresh only the chat and keeping the scroll, without affecting other elements such as the text input. Here's the "chats.html" file: <div class="container-fluid h-100" style="posistion:absolute; margin-left:60;"> <div class="row justify-content-center h-100"> <div class="col-md-4 col-xl-3 chat"> <div class="card mb-sm-3 mb-md-0 contacts_card" style="max-height:700;min-height:700"> <div class="card-header"> <div class="input-group"> <input type="text" placeholder="Search..." name="" class="form-control search"> <div class="input-group-prepend"> <span class="input-group-text search_btn"><i class="fas fa-search"></i></span> </div> </div> </div> <div class="card-body contacts_body"> <ui class="contacts"> {% for group in groups %} <a href="/chats/{{ group.event_name }}/" style="text-decoration: none;"> {% if group.event_name == current_group.event_name %} <li class="active"> <div class="d-flex bd-highlight" > <div class="img_cont"> <img src="{{ group.event_img.url }}" class="rounded-circle user_img"> <span class="online_icon"></span> </div> <div class="user_info"> <span>{{ group.event_name }}</span> <p>Kalid is online</p> </div> </div> </li> {% else %} <li class=""> <div class="d-flex bd-highlight"> <div class="img_cont"> <img … -
Execute Celery task after Django model timestamp has passed
I am trying to build a Django app that reacts to certain events, and then after X amount of time, executes a celery task. Users with permissions are given the option of either vetoing the action, or expediting the action. I am using Django 4.1 and Python 3.10. Veto does not need to take effect immediately, as the celery task will just check for it once it runs. Expedite does need to take effect immediately, but must require more than a single user to vote on it. Votes may have their "expiry time" changed by an admin, and the celery task should change the eta accordingly (or the task revoked and a new one put in the queue, with the updated eta). The work must be done in near-real-time, so no having a daily task that checks for expired votes. An example might make it a lot more clear: Bob has quit his job, and therefore his user accounts and access need to be revoked. A celery task that does just that, is put into the celery queue, with an eta of 2 days into the future (the timestamp is also logged in a Django model). HR is notified that … -
Make a pie chart using chart.js in Django error
I am building a budget tracker application and in dashboard page, I'd like to list different graphs. The pie chart is for expense structure showing how much expense is spent in certain categories. I'm facing two problems mainly. First one is the data of model in view doesn't pass through the template which results graph not showing. Second one is that I'm trying to show proportion of certain categories of expense, not a proportion of every expense(sum of accumulation of expense has to be calculated if they're in same category.) If I can get help, I'd be so much appreciated. models.py class Transaction(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) TRANSACTION_CHOICES = [ ('Expense','Expense'), ('Income','Income'), ] transaction_type = models.CharField(max_length=10, blank=False, choices=TRANSACTION_CHOICES, default="Expense",null=True) title = models.CharField(blank = False, max_length=30) description = models.CharField(blank = True, max_length=200) amount = models.DecimalField(blank=False, max_digits=10, decimal_places=2) date_paid = models.DateField(auto_now_add=False, blank=True, null=True) time_paid = models.TimeField(auto_now_add=False, blank=True, null=True) CATEGORY_CHOICES = [ ('Groceries', 'Groceries'), ('Salary', 'Salary'), ('Bills', 'Bills'), ('Rent', 'Rent'), ('Gym', 'Gym'), ('Restaurant', 'Restaurant'), ('Vacation', 'Vacation'), ('Travel', 'Travel'), ('Gift', 'Gift'), ('Investments', 'Investments'), ('Savings', 'Savings'), ('Entertainment', 'Entertainment'), ('Internet', 'Internet'), ('Healthcare', 'Healthcare'), ('Lifestyle', 'Lifestyle'), ('Insurance', 'Insurance'), ('Other', 'Other'), ] category = models.CharField(max_length=50, blank=False, choices=CATEGORY_CHOICES) receipt = models.ImageField(upload_to='receipt_images', blank = True) def __str__(self): return self.title def … -
TypeError: unsupported operand type(s) for *: 'NoneType' and 'decimal.Decimal'
File "F:\Coding Related\Karmachari-BackEnd\Karmachari_App\mainapp\models.py", line 97, in calculate_net_salary gross_pay = self.hours_worked * self.basic_pay_rate ~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~ TypeError: unsupported operand type(s) for *: 'NoneType' and 'decimal.Decimal' These are the lasted error message in terminal. in my model.py i have class Payroll(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) basic_pay_rate = models.DecimalField(max_digits=8, default=10000, decimal_places=2) overtime = models.DecimalField(max_digits=8,null=True, decimal_places=2) hours_worked = models.FloatField(null=True, blank=True) deductions = models.DecimalField(max_digits=8,null=True, decimal_places=2) net_pay = models.DecimalField(max_digits=8,null=True, blank=True, decimal_places=2) def calculate_net_salary(self): gross_pay = self.hours_worked * self.basic_pay_rate net_pay = gross_pay + self.overtime - self.deductions self.net_pay.save() # def save(self, *args, **kwargs): # self.net_salary = self.calculate_net_salary() # super(Payroll, self).save(*args, **kwargs) def __str__(self): return self.user.username in my views.py i have def payroll(request): payrolls = Payroll.objects.all() for payroll in payrolls: payroll.calculate_net_salary() user_object = User.objects.get(username=request.user.username) profile = Profile.objects.get(user=user_object) context={ 'profile':profile, 'navbar':'salary', 'payroll': payroll, } return render(request,'Salary_Sheet.html',context) I want to access payroll of each employee and calculate net salary and provide them in pdf. This is my first project so I dont know the concept clearly and want a beginner friendly explanation or solution. -
How to add a favorite function?
First time asking here so be patient with me, also trying to learn django. I have the following codes : class Favorite(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) apartment = models.ForeignKey(Apartment, on_delete=models.CASCADE) class Meta: unique_together = ('user', 'apartment') and {% extends 'base.html' %} {% load static %} <head> <title>Browse Rooms</title> <link rel="stylesheet" type="text/css" href="{% static 'css/browse_rooms.css' %}"> </head> {% block content %} <div class="container mt-5"> <h2 class="mb-4"><i class="fas fa-search"></i> Browse Rooms</h2> <div class="row"> {% for apartment in apartments %} <div class="col-md-4 mb-4"> <div class="card"> {% if apartment.image %} <img class="card-img-top" src="{{ apartment.image.url }}" alt="Profile Image"> {% endif %} <div class="card-body"> <h5 class="card-title">{{ apartment.address }}, {{ apartment.city }}, {{ apartment.state }} {{ apartment.zipcode }}</h5> <p class="card-text">Price: ${{ apartment.price }}</p> <p class="card-text">Bedrooms: {{ apartment.bedrooms }}</p> <p class="card-text">Bathrooms: {{ apartment.bathrooms }}</p> <p class="card-text">Move-in Date: {{ apartment.move_in_date|date:"F j, Y" }}</p> <a href="{% url 'apartment_detail' apartment.id %}" class="btn btn-primary"><i class="fas fa-info-circle"></i> View Details</a> <a href="#" class="btn btn-outline-secondary" onclick="addToFavorites({{ apartment.id }})"><i class="fas fa-heart"></i> Add to Favorites</a> </div> </div> </div> {% empty %} <p>No apartments found.</p> {% endfor %} </div> </div> {% endblock %} I tried to search on web how to implement this function but there are many methods and i don't understand the logic behind cause they … -
Can I override Django rendering checkbox inputs inside a label?
I'm trying to render a form which allows for multiple selections via checkboxes. I've tried with django-multiselectfield (which I was already using) and the native CheckboxSelectMultiple widget. If I have a simple form like so: FAVORITE_COLORS_CHOICES = [ ('blue', 'Blue'), ('green', 'Green'), ('black', 'Black'), ] class SimpleForm(forms.Form): favorite_colors = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES, ) And if I render with widget tweaks like so: {% render_field form.favorite_colors %} <div id="id_favorite_colors"> <div> <label for="id_favorite_colors_0"> <input class="form-control" id="id_favorite_colors_0" name="favorite_colors" placeholder="Your Name" type="checkbox" value="blue" /> Blue</label> </div> <div> <label for="id_favorite_colors_1"> <input class="form-control" id="id_favorite_colors_1" name="favorite_colors" placeholder="Your Name" type="checkbox" value="green" /> Green</label> </div> <div> <label for="id_favorite_colors_2"> <input class="form-control" id="id_favorite_colors_2" name="favorite_colors" placeholder="Your Name" type="checkbox" value="black" /> Black</label> </div> </div> This is causing problems for the way I want to render my form. Is there any way I can force Django to output the input and then the label, so the html would be like so: <div id="id_favorite_colors"> <div> <input class="form-control" id="id_favorite_colors_0" name="favorite_colors" placeholder="Your Name" type="checkbox" value="blue" /> <label for="id_favorite_colors_0">Blue</label> </div> <div> <input class="form-control" id="id_favorite_colors_1" name="favorite_colors" placeholder="Your Name" type="checkbox" value="green" /> <label for="id_favorite_colors_1">Green</label> </div> <div> <input class="form-control" id="id_favorite_colors_2" name="favorite_colors" placeholder="Your Name" type="checkbox" value="black" /> <label for="id_favorite_colors_2">Black</label> </div> </div> I haven't found an easy answer to this and most … -
request Timeout Error when creating pdf export for many users - django
I want to export from my users in site. but when I want to export from many users, I see this error: request Timeout I made a thread to solve this problem. But when downloading the file, the file is not downloaded, but the error is not shown on the site. Please guide def pdf(request, users): # ceating pdf code ... with open('media/pdf-export/exports/export.zip', 'rb') as fh: response = FileResponse(fh) response['Content-Disposition'] = 'inline; filename=' + os.path.basename('media/pdf-export/exports/export.zip') return response @admin.register(User) class UserAdmin(admin.ModelAdmin): list_display = ['id', 'time', 'first_name', 'last_name', 'phone_number', 'contract_number'] sortable_by = ['time'] list_filter = ['accept', 'final_submit'] search_fields = ['first_name', 'last_name', 'phone_number'] actions = ['export_to_excel', 'export_to_pdf'] .... def export_to_pdf(self, request, users): pdf_ = threading.Thread(target=pdf, args=[request, users, ], daemon=True) pdf_.start() I used thrading for control timeout error -
IntegrityError at /adduser (1048, "Column 'username' cannot be null")
I am trying to create a simple user registration following the CRUD procedure but i encounter the following problem whenever i try to key in a user`s details. Here is my adduser function. `def adduser(request): username = request.POST.get('firstname'); email = request.POST.get('email'); password = request.POST.get('password'); newuser = User(username=username, email=email, password=password); newuser.save(); return render(request, 'vinstarapp/index.html', {}) ` I tried using first_name, last_name but had a type error at adduser/ Changed it to username and now the integrity error. -
'static' appears in my url to the next page
I've hosted my web app on pythonanywhere.com but i have a problem when trying to route to the next item in a pagination object. The home page contains a list of contents (blogs) Down below, i have a pagination. Normally, when i click on the next button, the url should be "https://domain_name/?page=page_num" but instead it turns to "https://domain_name/static/?page=page_num" and it renders a 404 page The is my static url, root and dirs settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ "blog/static/blog" ] Static url and path on pythonanywhere -
what is m2m_changed signal for one to many(foreign key)
so I have a model A which is a foreign key in model B, and I have another model C what I need to do is once B changes from A admin inline I want to get the sum of all B instances related that A and update another model C so here are the steps I want to do: 1 - (B1,B2,B3) have A1 as fk_a all of them when A1 admin form is saved 2- I want wait for all of them to finish save() then I get the sum of their quantity and do something with it in (C1,C2,C3) class A(models.Model): name = CharField(max_length=20) class B(models.Model): quantity = IntegerField() fk_a = ForiegnKey(A) def save(): sum_of_similar_b = B.objects.filter(fk_a=self.fk_a) similar_c = C.objects.filter(fk_a=self.fk_a) update_model_c(sum_of_simlar_b, similar_c) I tried post_save() signal but it's called before the foreign keys are updated and tried A save() same. tried m2m_changed signal without "through" but it doesn't get triggered -
Can I use django rest framework with simple front end app using features from bootstrap for example?
can DRF be used with simple front end app by using ready-made features from bootstrap for example or I should use regular django since I don't have experience with front end frameworks? What choice should I adopt? -
Django installed but not able to locate module
I'm using a django web project template and its my first time creating one. I had to pip install django but the code that is existing still isnt referencing it and instead its giving a green squiggle under neath anything referencing Django. I created another blank file and ran a line with import django and it removed the green squiggles and worked. But then I dont know what changed and now its back to how it was before and even running import django before my code wont fix it like last time. It still gives the error below. I havent typed any new code to this template so there should not be any errors with the code provided. I tried first to add a new empty python file and import django. It worked the first time but went away and didnt work the second time. I tried to type import django before each file that uses django functions. It didn't remove the squiggles. From what I can tell when I run the whole file it pulls up a website with django on it and does not error out. -
Django Microservices using kubernetes, rabbitmq, docker, postgres
I'm curious about how to establish communication between Django microservices while also implementing authorization and permission protocols through a JWT authentication microservice. While I understand the general concept of how this is done, I'm unsure about the technical specifics. that's why i'm looking for guidance on developing microservices in Django using RabbitMQ and Kubernetes. Can you recommend a tutorial or someone who has experience with this. I've built a JWT microservice using Djoser, and I have another microservice that requires authentication and the user ID of a logged-in user to send requests. What's the best approach to achieve this? My initial idea is to pass the JWT token as an Authorization header in the requests from the second microservice to the first microservice. The first microservice should then verify the token and extract the user ID from it, which it can send back to the second microservice to perform user-specific operations. However, I'm unsure about the technical implementation of this approach. Should I use Django's built-in authentication middleware to check the Authorization header in the incoming requests to the second microservice? Is there a better way to achieve this? Any insights or examples on how to securely communicate between Django … -
Pycharm does not recognize Django no matter how many times I install it
I'm new to programming, so please bear with me, I have a hard time understanding what my problem even is many times, let alone explain it. I am attempting to edit a Django app in Pycharm. I have managed to set up a virtual environment, then installed Django in that environment using pip in the terminal, but Pycharm still seems to treat references to Django like they're errors. Here's what it looks like in Pycharm This ends up giving me issues where my virtual environment won't run. I feel like I'm very close to finally getting this to work, but something is wrong and I don't know why. Any help would be appreciated, thanks. I tried looking up Django plugins to install through Pycharm's Marketplace section, and none existed. I then installed Django into my virtual environment using the terminal and pip, and it still doesn't recognize Django. I get error messages whenever I try to run my Django App in the virtual environment, I get error messages. -
How to add additional choices to forms which is taken from a model in django
As in the topic is it possible to add choices to the forms that take from the model. forms.py class BookGenreForm(forms.ModelForm): class Meta: model = Book fields = ('genre',) models.py class Book(Product): GENRE_CHOICES = ( ('Fantasy', 'Fantasy'), ('Sci-Fi', 'Sci-Fi'), ('Romance', 'Romance'), ('Historical Novel', 'Historical Novel'), ('Horror', 'Horror'), ('Criminal', 'Criminal'), ('Biography', 'Biography'), ) author = models.CharField(max_length=100) isbn = models.CharField(max_length=100) genre = models.CharField(max_length=100, choices=GENRE_CHOICES) I care about adding add-ons for selection, such as alphabetically, by popularity. I can handle the creation of a view. At the same time, I would not like to just add these options in the choices model unless it is possible that later in the panel the user does not have the option to add as a genre of popularity, etc. Thank you all very much. I have an idea to make individual forms.Forms for everyone and re-create elections in them but I don't think it would be a pretty way to do it -
How to extract custom information from requests in Angular like Django?
My question maybe is not clear enough because it's hard to compare between frontend and backend together however, I will try to explain it. in Django, I can get key/value from requests whatever the type or the method of this request like: request.POST or request.GET ...etc. In the same manner, I want to get the key/value from requests at this moment from Angular instead of Django, I want to create my custom logic by that. I'm good in Angular but not strong so, if anyone helps me to get the answer or at least gives me a source for something like that, I will be grateful. -
Adding nginx configuration to AWS Elastic Beanstalk
I got client request body is larger than the buffer size allowed by nginx error in the app so I decided to add an nginx.config file to fix the issue. Here is the file. user nginx; events { worker_connections 1024; } http { client_body_buffer_size 20M; client_max_body_size 20M; upstream api { server Sauftragdev-env.eba-zirmk4s9.eu-central-1.elasticbeanstalk.com:8000; } server { listen 80; location /static/ { alias /static/; } location / { proxy_pass http://api; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } } Now what do I need to add in the Elastic Beanstalk configuration to make this work? It's platform is Python 3.8 running on 64bit Amazon Linux 2/3.4.3. -
Django - revoke in celery does not cancel the task
I am trying to write Django command that will cancel existing celery task in my Django application. The idea is to use this command in APIView so user can cancel the task that is already running. When running python manage.py cancel_task I see in terminal that task was cancelled but the status of the task remains the same and it continues doing the task. In the end the status of the task is always SUCCESS. Task 0d5ffdd3-3a2c-4f40-a135-e1ed353afdf9 has been cancelled. Below is my command that I store in cancel_task.py from django.core.management.base import BaseCommand from celery.result import AsyncResult from myapp.celery import app as myapp class Command(BaseCommand): help = 'Cancel a long-running Celery task' def add_arguments(self, parser): parser.add_argument('task_id', help='ID of the task to cancel') def handle(self, *args, **options): task_id = options['task_id'] result = AsyncResult(task_id, app=myapp) if result.state not in ('PENDING', 'STARTED'): self.stdout.write(self.style.WARNING(f'Task {task_id} is not running.')) return result.revoke(terminate=True, wait=False) self.stdout.write(self.style.SUCCESS(f'Task {task_id} has been cancelled.')) I checked all answers in this post but nothing works in my application. What am I doing wrong and how to cancel task. I tried to use revoke directly in celery like this: >>> from myapp.celery import myapp >>> myapp.control.revoke(task_id) But the finnal effect is the same. I … -
how to write a comment and reply with django with this model?
im a newcomer and i have this problem that i can't send this comment to database it just refreshes the page and nothing happens def blog_detail(request , id): post = Post.objects.get(pk = id , status = True) comments = post.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': comment_content = request.POST['comment_content'] if comment_content == '' or comment_content == None : messages.error(request , 'comment is empty') try: comment = Comment.objects.get(body=comment_content,name=MyUser.first_name,email=MyUser.email,active=False) except: Comment.DoesNotExist() new_comment = None return render(request, 'blog/blog-detail.html', {'post': post, 'comments': comments, }) this is my model class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name)``` i can't idenity the problem -
I got an error for not recognizing django render partial despite of installing it.(ModuleNotFoundError: No module named 'django_render_partial')
I've installed 'django-render-partial' following the 3 steps of https://pypi.org/project/django-render-partial, but I can't run my project because of this error: ModuleNotFoundError: No module named 'django_render_partial' I've put django_render_partial in installed apps and checked 'django.template.context_processors.request' in TEMPLATES['OPTIONS']['context_processors'] -
why is the output of make_password different than expected?
Sorry if this is a dumb question, but I'm new to django here. I'm creating a signup flow, one that needs the users email id and password to create the user. I'm trying to hash and salt the password, before saving the salted password in the db, along with the email. I'm using django's default make_password(password=password, salt=get_random_string(length=32)) to hash and salt the password. But the output I get is like "!KxPs6lAiW1Im2iuBbuK1lm6dqQz5h08gPSIWlEUr" instead of being something like "algorithm$iterations$salt$hash". Here's the code: salt = get_random_string(length=32) print(salt) salted_pwd = make_password(password=password, salt=salt) print("salted", salted_pwd) Why is this happening and what am I doing wrong here? -
Folders/files permission inference
I'm having some trouble working out how to implement this approach and I was wondering if anyone might offer an advice on how to handle it. Also, if there is a better approach to do it kindly let me know as this is my first time building something like this. I'm building a file system called Data room (DR) which each user will be able to create folders and uploads files in them. The user can share either files or folders as a whole. I was wondering how can I infer the permissions from the folder to the files. Like, if the user shared Folder A to User B and Folder A has 5 files I want User B to have access to all the files in Folder A with the permission of the folder (if the folder is shared with a R permission then the files should have the R permission). The user can either share individual files or the whole folder. The data room database model is ID User ID (FK) Folder Data room ID (fk) Name private (bool) File Folder id (fk) name path private (bool) ResourceManagement invitee (fk) inviter (fk) files: [] (fk), folders: [] (fk), … -
Query that cannot be written in django orm
Can you give me an example of a sql query that can't be written with django orm? -
CSRF checking with simpleJWT and DjangoRestFramework
I'm starting to use django and I'm lost in the request verification system. I find it difficult to grasp the intricacies of authentication methods. I am using JWT authentication with restframework_simplejwt to authenticate the user. Before using the JWT, I had the CSRF checks but it seems to me that I no longer have them since I defined this authentication system. Here are my settings and my view, built with DRF's ApiView. settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } view.py from rest_framework import status from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import SessionAuthentication from rest_framework_simplejwt.authentication import JWTAuthentication from rest_framework.response import Response class MakePredictionView(APIView): authentication_classes = [JWTAuthentication,] permission_classes = [IsAuthenticated, UserPermissionSpeedX] throttle_classes = [UserThrottleSpeedX,] serializer_class = MakePredictionSerializer def post(self, request): if not self.request.session.exists(self.request.session.session_key): self.request.session.create() serializer = self.serializer_class(data=request.data) if serializer.is_valid(): profil = SpeedX( player_name=serializer.data.get('player_name'), maturite_indice=serializer.data.get('maturite_indice'), resultat_vitesse_30m=serializer.data.get('resultat_vitesse_30m'), club=serializer.data.get('club'), categorie=serializer.data.get('categorie') ) profil.save() return Response(SpeedxSerializer(profil).data, status=status.HTTP_200_OK) If I replace JWTAuthentification by SessionAuthentification for example, it asks me for the CSRF token. But, If I add SessionAuthentification with JWTAuthentication in authentication_class, it no longer asks me for CSRF, and the authentication is done with JWT, without checking the CSRF token. Is this normal? is this risky? I … -
After populate form and formset it only save last row
Here is my view formset, about main form it populate and save well if formset.is_valid(): for form in formset: type_of_service = form.data["type_of_service"] item = form.data["item"] quantity = form.data["quantity"] rate = form.data["rate"] amount = form.data["amount"] if type_of_service and item and quantity and rate and amount: Grn_LineItem(vendor_name=grnmodel, type_of_service=type_of_service, item=item, quantity=quantity, rate=rate, amount=amount).save() grnmodel.save() return redirect('purchase_order_list') Here is my template <tbody> {% for lpo_line_item in lpo_line_item %} <tr class="{% cycle row1 row2 %} formset_row-{{ formset.prefix }}"> <td><input name="type_of_service" class="form-control input" value="{{ lpo_line_item.type_of_service }}"></td> <td><input name="item" class="form-control input" value="{{ lpo_line_item.item }}"></td> <td><input name="quantity" class="form-control input quantity_qty_rec" id="qty_rec" value="{{lpo_line_item.quantity}}"></td> <td><input name="rate" class="form-control input rate" value="{{ lpo_line_item.rate }}"></td> <td><input name="amount" class="input grn_amount form-control formset-field" id="grn_amount" value="{{lpo_line_item.amount}}"></td> </tr> {% endfor %} </tbody> </table> {{ formset.management_form }} it only save the main form and last row formset Thank you for your help