Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add csv file that has foreign key value
I am trying to upload a csv file to my system with one foreign key.There are two models involved - Namelist.model : is used to insert the csv file and Groupinfo.model: one of the attribute in namelist is a FK to the groupinfo. Namelist.model: class Namelist(models.Model): name = models.CharField(max_length=100) program = models.CharField(max_length=10) year = models.IntegerField(default=1) studType = models.CharField(max_length=15) courseType = models.CharField(max_length=15) nationality = models.CharField(max_length=20) VMSAcc = models.CharField(max_length=30) classGrp = models.ForeignKey('GroupInfo', on_delete=models.SET_NULL, null=True) GroupInfo.model: class GroupInfo(models.Model): classGrp = models.CharField(max_length=10) day = models.CharField(max_length=15) time = models.CharField(max_length=20) venue = models.CharField(max_length=10) language = models.CharField(max_length=30) Below is my view code: def import_studName(request): template = "import_stud.html" prompt = { 'order' : 'Order of the CSV should be id, name, program, year, studType,courseType,nationality,VMSAcc,classGrp' } if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'This is not a csv file') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created = Namelist.objects.update_or_create( id=column[0], name=column[1], program=column[2], year=column[3], studType=column[4], courseType = column[5], nationality=column[6], VMSAcc = column[7], classGrp =column[8]) context = {} return render(request,template, context) my template: {{order}} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label>Upload file</label> <input type="file" name="file"> <p>only accept csv file</p> <button type="submit">Submit</button> {% endif %} my urls … -
In Django getting errors based on dropdown selection
Getting error when fields are selected from the down. Not seeing why it is throwing error Django Dropdown form.error: ERROR ALERT: location_name Select a valid choice. That choice is not one of the available choices. Here is the model, form, view and html looks like MODEL class Code (models.Model): name = models.CharField(max_length=4, default=None, blank=True) def __str__(self): return self.name class Device (models.Model): code = models.ForeignKey(Code, on_delete=models.CASCADE, null=True) ip = models.GenericIPAddressField(protocol='IPv4', unique=True) def __str__(self): return self.ip class SiteData (models.Model): site = models.ForeignKey(Code, on_delete=models.SET_NULL, null=True) site_ip = models.ForeignKey(Device, on_delete=models.SET_NULL, null=True) site_data1 = models.CharField(max_length=3, default='120') class CombineData(models.Model): location = models.ForeignKey(Code, on_delete=models.SET_NULL, null=True) device = models.ForeignKey(AddData, on_delete=models.SET_NULL, null=True) locdata = models.ForeignKey(SiteData, on_delete=models.SET_NULL, null=True) FORM class CombineData_form(forms.ModelForm): class Meta: model = P2_NexusLeafPair fields = '__all__' VIEW def comboView(request, *args, **kwargs): template_name = 'site_display.html' code = Code.objects.order_by('-name') device = Device.objects.order_by('-ip') sitename = SiteData.objects.order_by('-site') content = { 'code': code, 'device': device, 'sitename': sitename } if request.method == 'POST': form = CombineData_form(request.POST or None) print(form.is_valid()) #print(form.errors) if form.is_valid(): . . . else: messages.error(request, form.errors) else: form = CombineData_form() return render(request, template_name, content) HTML <form id="comboView" class="post-form" role=form method="POST" action="comboView">{% csrf_token %} <div name="code" class="dropdown" id="mainselection" required> <select name="dc_name"> <option class="dropdown-item" value="">---------</option> {% for item in code %} <option value="{{ … -
I can't sign into the Django admin login page
I have started multiple Django projects with like four different tutorials. Every single time I try "python manage.py createsuperuser", the admin login page just loads and loads and never goes anywhere. I want to make it absolutely clear that I haven't touched a thing in the code and everything is default code. I migrated everything before login. I've tried deleting the database and re-migrating. None of that works. Can someone help me? I have made around 10-15 accounts and NONE of them work. The page just keeps loading indefinitely and never goes anywhere. I've looked at EVERY stackoverflow post and no answers work. I started a virtualenv, downloaded Django, didn't touch the code, made migrations, I followed every tutorial TOO THE LETTER(!!!) and this is what I keep getting. The current tutorial hasn't changed in default code and he signed in with no problems. I'm assuming if he did, I can...I don't think putting code in is necessary since it's all virgin code, never touched. I didn't even make any apps yet. I've tried deleting database and re-migrating changing the password of current superuser deleting the entire project and following everything the instructor said (TO THE LETTER!!!) I have made … -
django rest-auth email confirmation with postmark
I've seen a fair bit about how to override the email templates, but they seem to mostly involve creating HTML templates and overriding the file location. I'm using postmark's templating which involves sending a post request with the email variables. I'm handling that with anymail, as shown below with a form that sends my customer service address an email: class PartnerContact(APIView): """Sends email to Partners@***.com""" @authentication_classes([]) @permission_classes([]) def post(self, request): """Sends Form Data""" print("PartnerContact data", request.data) status_code = status.HTTP_400_BAD_REQUEST msg = EmailMessage( from_email='Partners@***.com', to=['Partners@***.com'], reply_to=[request.data['email']] ) msg.template_id = *** logo = attach_inline_image_file(msg, finders.find("***.png")) msg.merge_global_data = { **{**request.data, **{"logo":logo} } } # <img alt="Logo" src="cid:{logo_cid}"> msg.send() status_code = status.HTTP_200_OK return Response(status=status_code) My goal is to use postmark templates for the account confirmation & password reset emails also, but I'm having a hard time figuring out how to override the send methods. -
Django ModelFormset error empty form field
Django has decided to throw an error when I am submitting the form. The form is a modelformset and I have made absolutely no change to the default, merely clicking on submitting button. Django complains that the only empty form needs to have a value and when I change it to required = False: forms.CharField(max_length = 40, required = False) it stops complaining. Here is my form: class RateForm(ModelForm): costcode = forms.CharField(max_length = 40, required = False) class Meta: model = Rate fields = ['costcode', 'rate', 'UOM', ] class BaseRateFormSet(BaseModelFormSet): def clean(self): ''' No custom cleaning at this point.''' cd = super(BaseRateFormSet, self).clean() To see what is going on, I wrote the custom cleaning and saw that the cd is None when I added assert False after it. the view: rate_formset = RateFormSet(request.POST if any(request.POST) else None, prefix = user.short_name, form_kwargs = the_form_kwargs, **user_form_kwargs) In reality, the field costcode should be required, but Django should realize that the user does not wish to submit any additional form, so it does not generate the error. How do I get Django to not throw an error on an empty form? -
Cannot import ReportLab or FPDF in Django project
I am trying to create a pdf in a Django project, I pip installed the latest version of reportlab successfully but when I tried to import reportlab.pdfgen I got an error modulenotfound for reportlab. So next I tired FPDF and I received the same results. I was able to successfully import both packages out side the Django project the only issues is once it is with in the Django project. -
How to extract a count from QuerySet relations?
I have the follow .model structure: class ArtistWorkPlaceQuerySet(models.QuerySet): def with_related(self): return self.select_related('artist','work', 'place') class ArtistWorkPlaceManager(models.Manager): pass class PersonWorkPlace(models.Model): artist = models.ForeignKey(Artist, verbose_name=_('artist'), related_name='work', on_delete=models.CASCADE) work = models.ForeignKey(Work, verbose_name=_('work'), related_name='place', on_delete=models.CASCADE) place = models.ForeignKey(Place, verbose_name=_('place'), on_delete=models.CASCADE) objects = PersonWorkPlaceManager.from_queryset(PersonWorkPlaceQuerySet)() class Work(models.Model): piece_type = models.CharField(max_length=100, null=True, blank=True) //This is like paintings or sculptures class Artist(models.Model): name = models.CharField(max_length=100) class Place(models.Model): name = models.CharField(max_length=200, null=True, blank=True) Through this query I can get all of the work by this artist: works = PersonWorkPlace.objects.filter(person=self.kwargs['pk']) How do I go further and search for the number (a count) of works of the same the 'piece_type' at a particular place by the same artist? I would like to pass or extract from context for a particular view the following information: Artist A has 2 painting and 2 sculpture at Place A and 4 paintings at Place B 'context': { (place: 'Place A', painting: '2', sculpture: '2'), (place: 'Place B', painting: '4') } -
Django: How to Get the Result of a Raw SQL "COUNT(*)" Query?
I have a table of keywords that looks like this: CREATE TABLE `keywords` ( `keyword` VarChar( 48 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `id` Int( 11 ) AUTO_INCREMENT NOT NULL, `blog_posts_fulltext_count` Int( 11 ) NOT NULL, PRIMARY KEY ( `id` ) ) I also have a table of blog posts that looks like this: CREATE TABLE `blog_posts` ( `id` Int( 11 ) AUTO_INCREMENT NOT NULL, `title` LongText CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL, `summary` LongText CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL, PRIMARY KEY ( `id` ) ); CREATE FULLTEXT INDEX `title_summary_fulltext` ON `blog_posts`( `title`, `summary` ); As you can see, I have a full text index on the fields title, summary in blog_posts. The following search works correctly: select count(*) from blog_posts where match(title,summary) against ('paid'); Now I'd like to populate the field keywords.blog_posts_fulltext_count with the number of rows in blog_posts that the keyword appears in. When I run this: keywords = Keywords.objects.all() for the_keyword in keywords: query = "select count(id) from BlogPosts where match(title,summary) against ('{0}')".format(the_keyword.keyword) number_of_mentions = blog_posts.objects.raw(query) for obj in number_of_mentions: a = obj ...the RawQuerySet number_of_mentions appears to return without errors, and number_of_mentions.query contains: 'select count(id) from blog_posts where match(title,summary) against ('paid')' But when … -
How can I add parent fields to a Django InlineFormSet?
How can I add a parent field to an InlineFormSet? My attempt: models.py: from django.db import models class Parent(models.Model): parent_name = models.CharField(max_length=45) class Child(models.Model): child_name = models.CharField(max_length=45) parent = models.ForeignKey(Parent, on_delete=models.CASCADE) forms.py: from .models import Parent, Child from django import forms FormSet = forms.inlineformset_factory(Parent, Child, fields='__all__' ) views.py: from .models import Parent from .forms import FormSet def view(req): instance = Parent.objects.get(pk=1) form = FormSet(instance=instance) This results in all of the fields from Child being displayed, but none from Parent. -
How to ignore certain Python errors from Sentry capture
I have Sentry configured to capture all errors from a Django+Celery application. It works ok, but I'm finding an obnoxious use case is when I have to restart my Celery workers, PostgreSQL database or messaging server, which causes thousands of various kinds of "database/messaging server cannot be reached" errors. This pollutes the Sentry reports, and sometimes even exceeds my event quota. Their docs mention an "ignore_exceptions" parameter, but it's in their old deprecated client that I'm not using, nor is recommended to be used for new projects. How would you do this in the new API? -
How to add prefetch_related to __str__
I would like to make my django admin faster and not do multiple queries. I know I can acievie such thing with for example prefetch_related/select_related, but I'm not sure how can I add the functionality of it to the str function. Below is my model: class Work(models.Model): id = models.AutoField(primary_key=True) date = models.DateField(null=True, blank=True) book = models.ForeignKey('Chapter', on_delete=models.CASCADE) job = models.ForeignKey('Job', on_delete=models.CASCADE) user = models.ForeignKey('users.User', on_delete=models.CASCADE, null=True, blank=True) prev_work = models.ForeignKey('self', on_delete=models.CASCADE, editable=False, null=True, blank=True) I would like to see something like this: def __str__(self): return self.book.project.slug + "-" + str(self.book.number) + "-" + self.job.name And once again - I know why it does so many queries, but I'm not sure what would be the best practice to fix the issue. -
Django: Improve queryset
I currently have the following query set and I wonder if there is a way to bring that part question.answers.all() into the questions= query set. def get_questions_and_answers(self): questions = ( self.request.event.surveys.get(template=settings.SURVEY_POST_EVENT) .questions.exclude(focus=QuestionFocus.EMAIL) .all() ) questions_and_answers = {} for question in questions: questions_and_answers[question] = question.answers.all() return questions_and_answers models.py class Question(TimeStampedModel[...]): survey = models.ForeignKey(related_name='questions') type = models.CharField([...]) focus = models.CharField([...]) class Answer(TimeStampedModel): question = models.ForeignKey(related_name='answers') response = models.ForeignKey(related_name='answers') answer = models.TextField([...]) class Survey(TimeStampedModel): event = models.ForeignKey(related_name='surveys') template = models.CharField([...]) -
How to create API to insert data in MySQL passing json with dublicate keys
I am creating a REST API using Django-Rest-Framework to insert data in MySQL database. The table has column like - id, meta key, meta value i.e for particular id it can have duplicate meta keys and their corresponding meta value. I want to pass all the meta keys and meta values of corresponding id in the json but it says Json does not support duplicate keys. What should be my approach to create the api which creates two rows in database if I am passing 2 meta key and value for a same id? The json looks like "order_item_id_2":"154", "meta_key":"_product_id", "meta_value":"602", "meta_key":"_variation_id", "meta_value":"0" "meta_key":"qty", "meta_value":"20" The table should look like: Final table should look like this -
facing problems in verify a token generated link
I am building my own password reset link. Since i do not want to use the default provided by django . Well i am facing a problem creating a token for the user This view get anonymous user email, search if this email is associated to a user. def Get_email(request): email_address= request.POST.get('emailadrees') user=User.objects.filter(email=email_address).first() try: if user is not None: current_site = get_current_site(request) mail_object= 'Password reset' message=render_to_string('password_reset/password_reset_email.html', { 'user':user, 'domain':current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':reset_password_token.make_token(user), }) to_email=user.email email=EmailMessage(mail_subject,message,to=[to_email]) email.send() This link receives the token and let the user change their password def Change_password(request,uidb64,token): try: uid=force_text(urlsafe_base64_decode(uidb64)) user=CustomUser.objects.get(pk=uid) if user is not None and reset_password_token.check_token(user,token): pass else: return HttpResponse("Activation link is invalid! ") except (TypeError,ValueError,OverflowError,CustomUser.DoesNotExist): return HttpResponse("Activation link is invalid! ") My token.py file class TokenGeneratorResetPassword(PasswordResetTokenGenerator): def _make_hash_value(self,user,timestamp): return(six.text_type(user.pk)+user.password+six.text_type(timestamp)) reset_password_token=TokenGeneratorResetPassword() The problem i am facing is like " reset_password_token.make_token(user) " does not create token for the user. What i am doing wrong? The link sent to the email, does not validate in "Change_password" function. -
How I do render a queryset in a Django base template?
I have a base template which extends to almost every other templates in my project. I am trying to populate my categories navigation bar with some queryset from my database but am failing with my approach. Since the base template has no url, I am finding it difficult to render. This is what I've tried: this is my views function def base(request): categories = list(Category.objects.all()) context = { 'categories': categories } return render(request, 'ads/base.html', context) this is my html {% for category in categories %} <div class="nav-item dropdown"> <a href="#" class="nav-link dropdown-toggle" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> { category.name }}&nbsp; <span class="float-right text-muted"> <small> <i class="fas fa-chevron-down"></i> </small> </span> </a> </div> {% endfor %} I just want to populate my navbar with the categories queryset -
Issue with creating an edit view in django
Trying to allow users to edit their data. However, when the link that would take them to the edit page is clicked, I get a "NoReverseMatch" error. I'm pretty sure that it has to do with my view. Any help would be greatly appreciated. I'm stuck like chuck... models.py class Rider(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) birthdate = models.DateField(verbose_name=None, auto_now=False) NOVICE = 'N' BEGINNER = 'B' COMPETENT = 'C' PROFICIENT = 'P' EXPERT = 'E' skill_level_choices = [ ('NOVICE', 'Novice'), ('BEGINNER', 'Beginner'), ('COMPETENT', 'Competent'), ('PROFICIENT', 'Proficient'), ('EXPERT', 'Expert') ] skill_level = models.CharField( max_length=20, choices = skill_level_choices, default = NOVICE, ) def __str__(self): return self.last_name + ', ' +self.first_name views.py def edit_rider(request, riders_id): riders = Rider.objects.get(id=riders_id) if request.method != 'POST': form = RiderForm(instance=riders) else: form = RiderForm(instanse=riders, data=request.POST) if form is valid(): form.save() return HttpResponseRedirect(reverse('riding_schedule:index')) context = {'riders':riders, 'form':form} return render(request, 'riders/edit_rider.html', context) urls.py path('edit_rider/<int:riders_id>', views.edit_rider, name = 'edit_rider'), edit_rider.html {% extends "riding_schedule/base.html" %} {% block content %} <p>Edit rider:</p> <form action="{% url 'riders:edit_rider' rider.id %}" method='post'> {% csrf_token %} {{ form.as_p }} <button name = "submit">save changes</button> </form> {% endblock content %} Exception Type: NoReverseMatch at /riders/edit_rider/8 Exception Value: Reverse for 'edit_rider' with arguments '('',)' not found. 1 pattern(s) … -
In Django How to inherit field to populate data
In Django, how to populate data based on selected value from dropdown. Also those fields are inherited from another Model. For example: Class DeviceInfo has for 4 fields, like to inherit in to Class Links. How to setup view so that with dropdown selection of name it will pre-populate location, type and then user can fill out rest fields. MODEL: class DeviceInfo(models.Model): name = models.CharField(max_length=20, default='') location = models.GenericIPAddressField(protocol='IPv4', default='0.0.0.0') type = models.ForeignKey(Types, on_delete=models.SET_NULL, null=True) class Links(DeviceInfo, models.Model): {other fields} FORM class DeviceInfo_form(forms.ModelForm): class Meta: model = DeviceInfo fields = '__all__' field_classes = { 'json_field': JSONFormField, } Thanks for the taking your time, answering. -
Can't update datefield to null
cant insert and update datefield to null err ["'' value has an invalid date format. It must be in YYYY-MM-DD format."] `class StudentUserMedicalRecord(models.Model): ImmnunBCGDateFirstDose=models.DateField(null=True, blank=True) ImmnunBCGDateSecondDose=models.DateField(null=True, blank=True) ImmununBCGDateThirdDose=models.DateField(null=True, blank=True) ImmnunBCGDateBooster1=models.DateField(null=True, blank=True) ImmnunBCGDateBooster2 = models.DateField(null=True, blank=True) def __str__(self): suser = '{0.Student_Users}' return suser.format(self) //my html <td><input type='date' name='firstdate' /></td> <td><input type='date' name='seconddate' /></td> <td><input type='date' name='thirddate' /></td> <td><input type='date' name='firstbooster' /></td> <td><input type='date' name='secondbooster' /></td> //my views first = request.POST['firstdate'] second = request.POST['seconddate'] third = request.POST['thirddate'] booster = request.POST['firstbooster'] secondbooster = request.POST['secondbooster'] V_insert_data = StudentUserMedicalRecord( ImmnunBCGDateFirstDose=first, ImmnunBCGDateSecondDose=second, ImmununBCGDateThirdDose=third, ImmnunBCGDateBooster1=booster, ImmnunBCGDateBooster2=secondbooster, ) V_insert_data.save() -
Stripe cancellation of subscription not working Django
I'm trying to create a cancellation page to remove a subscription. However, it's not working. In that, I cannot find the customer when I try to call Stripe API. The customer and subscription I think are being created, at least, the charge is going through. Here is where I create the subscription in views.py: def charge(request): stripe.api_key = settings.STRIPE_SECRET_KEY if request.method == 'POST': try: token = request.POST.get('stripeToken') user = request.user plan = 'plan_xxxxxx' order_number = X customer = stripe.Customer.create(description='Membership', source=token, email=user.email, plan=plan) charge = stripe.Subscription.create( customer=customer.id, items=[{'plan': plan}] ) return render(request, 'charge.html') Here is where I try to cancel the subscription: def cancel_subscription(request): customer = stripe.Customer.retrieve('request.user.stripe_id') customer.cancel_subscription(at_period_end=True) return render(request, 'cancel.html') This is the error that I get: Request cus_xxxxxxxx: No such customer: request.user.stripe_id -
How does two client javascript files interact with each other, when the server is running seperately?
I have created a django application. There are two different html pages, which run different scripts in each other. I want to share data between the two script files, so while I update the variables in one script, I can send the updated data to the other script file, and make the corresponding changes to the variable present in the other script file. As I researched, one way I found to do that is to use websockets, where a regular connection is built with the django server and the client. But, it is limited to single client. So, through websockets, I can not share data between two different client pages. What other methods, can I use to share data between the two script files in the client? -
jinja is not wroking properly in django
In django created template directory, with three html files. index.html {% extends "web/header.html" %} {% block content %} { % include 'web/includenippet.html' %} <p> hello this is my page.</p> {% endblock %} header.html <h2>hey iam there in header of login page</h2> {% block content %} {% endblock %} <h2>hey iam there in footer of login page</h2> incl.html {% block content %} <p>iam in include file</p> {% endblock %} expected output is hey iam there in header of login page iam in include file hello this is my page. hey iam there in footer of login page But the actual output is hey iam there in header of login page { % include 'web/includenippet.html' %} hello this is my page. hey iam there in footer of login page I added jinja2 and django-jinja in django project using setting->project_interpreter -
Python 2 timezone.utc in Django project
What is the alternative for python 2 : user_last_seen = datetime.now(timezone.utc) Thank you -
Stuck on Django project tutorial I'm doing on Udemy - OperationalError at /admin/jobs/job/add/ no such table: main.auth_user__old
I am doing a Django tutorial I bought off Udemy. It's titled "Django 2.2 & Python | The Ultimate Web Development Bootcamp", in case some of you know this tutorial by instructor Nick (something, forgot last name). I'm using Django 2.0.2, exactly what was asked in the tutorial. SQLite3 database version 3.27.2, using up-to-date version of Spyder with Anaconda prompt, I'm on Windows 10 Pro, latest versions of "virtualenv" and "pip" as well. So on the tutorial, I had to sign into the admin page and create an app called "jobs", with a jobs.models.py class called "Job". It adds this to the admin UI and then click on it and add (using "+" icon at top right) a "Job", which is adding an ImageField and a CharField that gets added. I get an error on the django admin page when I click "Save". The name of my project is "portfolio-project", sub-folders include "portfolio","blog", and "jobs". I went back and re-did all the steps up to that point in the tutorial, and did it "to the letter". I've researched many questions for that error and can't find anything that works. I tried makemigrations, then migrate. It's possible it's a bug with … -
python logging: also show few lines of code above and below at that location
I am working on a django project. I have the following logging config in settings.py file LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(funcName)s() %(pathname)s[:%(lineno)s] %(name)s \n%(message)s' } }, 'handlers': { 'console': { 'level': 'DEBUG', 'formatter': 'verbose', 'class': 'logging.StreamHandler', }, 'loggers': { 'custom_string': { 'level': 'DEBUG' if DEBUG else 'INFO', 'handlers': ['console'] } } } We can see that verbose shows the '%(levelname)s %(funcName)s() %(pathname)s[:%(lineno)s] %(name)s \n%(message)s. It shows the filename, line number and function. I have to open that file and see that line number to get have a look at the code around the logger. Now suppose i have the following code in views.py from django.http import HttpResponse import logging logger_custom_string = logging.getLogger("custom_string") def test_log(request): from django import db user_set = User.objects.all() logger_custom_string("*********testing logging*********") for user in user_set: pass html = "<html><body>testing</body></html>" return HttpResponse(html) The logging will show in the console: DEBUG test_log() ./django_log_project/views.py[:13] custom_string *********testing logging********* What i want to see is DEBUG test_log() ./django_log_project/views.py[:13] custom_string Code: 11 from django import db 12 user_set = User.objects.all() 13 logger_custom_string("*********testing logging*********") 14 for user in user_set: 15 pass output: *********testing logging********* This will show me the code line +2/3 and -2/3 lines from … -
Auto increment of number input in Django Formset
I am using django formset for adding multiple periodic inputs of price range WarehousePriceSpacetSet = formset_factory(WarehouseSpacePricePerdayForm, extra=1) this is my formset. I need to append from input data with respect previous to data. Here is the example Here the first row saving the prices of 1 to 10 So next Period from field should auto fill 11 I have tried with Jquery by appending value when to field change function. for(i=0;i<=pallet_num;i++){ $(".pallet_to").change(function() { $("#id_palletss-"+i+"-period_from_pallet").val($(this).val()); // $(".pallet_to").closest(".pallet_from").val($(this).val()); }); } But the change function working only for first periods row. Because others are adding dynamically by clicking "Add more" in form-set. Please help me to find a solution. Thanks in advance