Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where should authentication backends reside in a django project structure
I am setting up UAM interface to bypass default Django authentication. My question is how to place the new Backend Class in the directory structure Following is my project structure: django-app-folder - appmodule1 - appmodule2 - appmodule3 - utils - management - migrations - tests - static - templates - apps.py - admin.py - models.py - signals.py - urls.py - views.py django-soln-folder - settings.py - urls.py - wsgi.py -
The for loop variable in the for loop
I want to use the value from one for loop in another for loop. But I have 3 values in the tables variable in the context dictionary from views.py. I want to pull these values with the for loop and return them with another for loop, but the 2nd for loop sees the value from the 1st for loop as a string. {% for table in tables %} {% for music in table %} <a class="{{table}}" href="javascript:void(0);" onclick="playSong('{{music}}')">{{music}}</a> {% endfor %} {% endfor %} In Page Source : <a class="Rap" href="javascript:void(0);" onclick="playSong('R')">R</a> <a class="Rap" href="javascript:void(0);" onclick="playSong('a')">a</a> <a class="Rap" href="javascript:void(0);" onclick="playSong('p')">p</a> I want the values in the rap table, not the outputs like R, a, p in the a tag. 2. The for loop sees this as a string, but in my context dictionary there is the Rap keyword and its values. I want to draw the values of this keyword. -
Django 2 upgrade lost filter_horizontal functionality
I recently upgraded to Django 2.2.2 and Python 3.6.8, and my filter_horizontal feature in Django admin has disappeared. I tried viewing my admin in Chrome incognito mode, as some answers suggest, and I also tried changing verbose_name strings to unicode. However, none of these worked. Here is an example of a model for which I am attempting to show filter_horizontal. This worked on my app prior to the upgrades. admin.py class ResearchAdmin(admin.ModelAdmin): filter_horizontal = ('criteria', 'state') def save_model(self, request, obj, form, change): obj.save() # Update cache for tasks containing the saved goal tasks = Task.objects.filter(research__id=obj.pk).values_list('pk', flat=True) for t in tasks: cache.delete_many(['task%s' % t, 'task%s_research' % t]) models.py """ Clinical Research model """ def __str__(self): return "%s" % (self.name) name = models.CharField(max_length=50, null=True, blank=True) type = models.CharField(max_length=50, null=True, blank=True) cta = models.CharField(max_length=50, null=True, blank=True) description = models.TextField(null=True, blank=True) picture = models.ImageField(upload_to='images/%Y/%m/%d', null=True, blank=True, help_text="Upload portrait image for modal study description") layout = models.CharField(max_length=1, choices=LAYOUT_TYPE, null=False, blank=False, default='r') criteria = models.ManyToManyField('Answer', blank=True, db_index=True, help_text="Answers required for qualified patients") required_contact = models.ManyToManyField('ContactField', blank=True, db_index=True, help_text="Contact info for patient to enter") email = models.EmailField(null=True, blank=True, help_text="Sponsor email for notifying of screened patients") link = models.URLField(null=True, blank=True) state = models.ManyToManyField('State', blank=True, help_text="Qualifying states") lat = … -
Applying Django migrations once per deployment application in Kubernetes/Google CloudSQL
I'm looking for a robust and reliable strategy to apply my database migrations once per application of my Deployment yaml file to use in my CI/CD pipeline. The initial (no pun intended) plan was to use initContainers to perform the migration. The difficulty I'm encountering has to do with the method of connecting to the CloudSQL database--since I'm using the gcr.io/cloudsql-docker/gce-proxy:1.11 sidecar container to let my application containers connect, I'm not sure how to provide the database access to the initContainers because they appear to only support single containers pods. Is it possible to run the proxy container as a sidecar on the initContainers? If that is not possible, what is the preferred approach? Should the entrypoint of the application containers apply the migrations before launching the application itself? My concern is that in an initial launch of the deployments might create race conditions with multiple pods trying to apply migrations simultaneously? -
Get values from Django data base
I need to get the data from a form in a Django database. The problem when I use .cleaned_data['name'] I am getting an attribute error 'SnippetForm' object has no attribute 'cleaned_data'. when I tried passing through if old_form.is_valid(). the if is False. With my code, I can get the HTML info, but I can not parser it with .clean_data. Basically I don't want to create a regex and parse the html, I am looking for some Django Method that can help. Html code got from Django: <tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" value="Ariel" maxlength="100" id="id_name"></td></tr> <tr><th><label for="id_email">Email:</label></th><td><input type="email" name="email" value="as@onsemi.com" maxlength="254" id="id_email"></td></tr> <tr><th><label for="id_subject">Subject:</label></th><td><input type="text" name="subject" value="Test" maxlength="100" id="id_subject"></td></tr> <tr><th><label for="id_body">Body:</label></th><td><textarea name="body" cols="40" rows="10" id="id_body"> This is a test</textarea></td></tr> In my views.py def data_detail (request, request_id): data_detail_django = get_object_or_404(Snippet, pk=request_id) if request.method == "POST": #Also, it is not going throu this if... old_form = SnippetForm(request.POST, instance=data_detail_django) else: #The old_form is the html output and is get it with this old_form = SnippetForm(instance=data_detail_django) if old_form.is_valid(): print(old_form.cleaned_data['name']) return HttpResponse("contact view") In my models from django.db import models # Create your models here. class Snippet(models.Model): name = models.CharField(max_length=100, blank=True, null=True) email = models.EmailField(blank=True, null=True) subject = models.CharField(max_length=100, blank=True, null=True) body = models.TextField(blank=True, null=True) def __str__(self): … -
How to Go From 1+n to 1+1 Requests
I have a RESTful API request which returns upwards of 1,000 records in the form of JSON data. From this data I pull an ID to reference in a second API request to a different domain. The current logic results in slow page load times due to the large number of records being iterated through. How can I increase page availability and decrease wait times? Is there any way I can transition to 1+1 requests instead of 1+n? views.py cw_presales_engineers = [] for opportunity in opportunities: try: opportunity_id = str(opportunity['id']) presales_ticket = cwObj.get_tickets_by_opportunity(opportunity_id) if presales_ticket: try: cw_engineer = presales_ticket[0]['owner']['name'] cw_presales_engineers.append(cw_engineer) except: pass else: cw_engineer = '' cw_presales_engineers.append(cw_engineer) except AttributeError: cw_engineer = '' first.request def get_opportunities(self): try: r = requests.get( self.URL + 'sales/opportunities?conditions=status/id=1 OR status/id=13 AND company/name!="XYZ Test Company" &pageSize=50& &oage=1& &orderBy=company/name asc&', headers=self.Header) r.raise_for_status() except: raise return r.json() second.request def get_tickets_by_opportunity(self, request): try: r = requests.get( self.URL + 'service/tickets?conditions=opportunity/id=' + request, headers=self.Header) r.raise_for_status() except: raise return r.json() -
Creating Admin List filters for custom list_display functions?
Is it possible to create list_filters on the admin model page based on a function created to pull info on models that are a couple of Foreign Keys away? I've created the functions to display the info needed in 'list_display', but am hoping to also be able to filter using these fields. The current admin.ModelAdmin functions are seen here: class HardwareAdmin(admin.ModelAdmin): list_display = ('hardware_id', 'device_type', 'get_customer', 'network_health','get_region') def get_customer(self, obj): if obj.site: return obj.site.customer return '-' get_customer.short_description = 'Customer' get_customer.admin_order_field = 'site__customer' def get_region(self, obj): if obj.pad: return obj.pad.lease.region return '-' get_region.short_description = 'Region' How would I go about adding filters that allow me to filter by both region and customer? -
Django csrf token cookie and Cookie Policy
Is there a way not to store csrf_token cookies until users accept the Cookie Policy? -
Link multiple different forms with id
I am having one form which creates objects to Patient model with unique id and I want to create new object using Patient's object linked with id and add new data Patient's objects and create new object with new id , but I am not able to display the Patient's object data in another form template (IpdForm). One thing I want to make clear I don't want to update the patient object. I want to create new object linked with the patient id, and I want to show patient objects in new IpdForm i have already used following QuerySets: "qs = Ipd.objects.get(patient__id=patient_id)" , "qs = Ipd.objects.filter(patient__id=patient_id)" "qs = Ipd.objects.filter(patient_patient=patient_id)" models.py : ```python class Patient(models.Model): name = models.CharField(max_length=200); phone = models.CharField(max_length=20); address = models.TextField(); patient_id = models.AutoField(primary_key=True); gender= models.CharField(choices=GENDER, max_length=10) consultant = models.CharField(choices=CONSULTANT, max_length=20) def __str__(self): return self.name class Ipd(models.Model): reason_admission = models.CharField(max_length=200, blank=False) presenting_complaints = models.CharField(max_length=200,) ipd_id = models.AutoField(primary_key=True) rooms = models.ForeignKey(Rooms,on_delete=models.CASCADE, blank=False) date_of_admission = models.DateField(("Date"), default=datetime.date.today) patient = models.ForeignKey(Patient, on_delete=models.CASCADE, blank=False) def __str__(self): return self.patient.name ``` forms.py : ```python class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ['name','phone','address','patient_id','consultant','gender'] class IpdForm(ModelForm): class Meta: model = Ipd fields = ['patient', 'reason_admission', 'presenting_complaints', 'rooms', 'date_of_admission'] ``` views.py: ```python @login_required def new(request): … -
Two identical PNGs, one is corrupt
I have this PNG file, uploaded to a django REST server from an Angular front-end. About 99.9% of uploaded images work fine; you can view them in admin and download them. But every once in a while, I get these corrupt PNG images. You can see the image if you put the image URL in the address bar but you can't see it on django admin and you can't download it through right click>save. I uploaded and downloaded the image to Imgur and now it seems to be working. When I put it in the media directory of the Django development server, I can download it with the right click at the image URL. But it seems to be identical to the original file! I get nothing with a diff File sizes are the same Neither of the files seem to be open (checked with lsof) I'm out of options. I uploaded both versions of the images to my google drive and checked that if you download the images, corrupt one still seems to be corrupt. Maybe somebody can figure out what the difference between these files is. corrupt image saved and fixed image -
How to order a queryset result by the number of entries in a manytomanyfield?
Let's say that i have this queryset : result_list = [] get_result_list = [x for x in search_text_imported.split() if len(x) > 2] for keyword in get_result_list: result_list += list(Node.objects.filter((Q(name__icontains=keyword) | Q(Tags__icontains=keyword)), tree_type='root', tunisia_office=True, published=True ).order_by('-bookmarked_by')) result = list(dict.fromkeys(result_list)) models.py class Node(MPTTModel): name = models.TextField(blank=True, null=True) bookmarked_by = models.ManyToManyField(CustomUser, null=True, blank=True) I want to show first the objects that have the most number of entries in the bookmarked_by field. Is there a way to do it ? Any help is appreciated. -
How to update website and its data automatically
Basically i have a front end on Django server and back end on pycharm python. I made a website that scrape some data and stored in CSV files then i push this repository into git and then push it into heroku cloud server for hosting by the problem is the website update when i update it manually by running those python scripts and then update git repository and push it into hasting servers. I want to linked them that my python scripts run after every hour and it automatically push to my hosting server. please help me! PS: i am working on windows -
Django , Use Viewsets inside views.py
I'm Using a ViewSet to implement restful API . for a similar Operation in views.py i wanna use those API methods . how can i use api calls inside my views.py ? here is ViewSet class with one GET method : class ProductViewSet(ViewSet): @action(methods=['get'], detail=False) def get_price_with_code(self, request): some operations ... here is views.py and i wanna use get_price_with_code in index method : @csrf_exempt def index(request): if request.method == "GET": return render(request, "showProduct.html", {}) else: code = request.POST['pr_code'] phone = request.POST['phone'] # use get_price_with_code method to get results -
Django 2 annotate to prepare data for chart from Models
I'm working on a project using Python(3) and Django(2) in which I need to prepare data to display a chart. I have 2 models as: (1): UserGroup (2): VotingValuesHistory I need to aggregate all the votes in user's group. From models.py: class UserGroup(models.Model): email = models.EmailField(primary_key=True) group = models.CharField(max_length=250, default='notingroup') def __str__(self): return self.group VOTE_CHOICES = ( ('1', "helpful"), ('2', 'meh'), ('3', 'disaster') ) class VotingValuesHistory(models.Model): id = models.AutoField(primary_key=True, auto_created=True) value1 = models.CharField(max_length=40) value2 = models.CharField(max_length=40) value3 = models.CharField(max_length=40) value4 = models.CharField(max_length=40) value5 = models.CharField(max_length=40) score1 = models.CharField(choices=VOTE_CHOICES, max_length=20) score2 = models.CharField(choices=VOTE_CHOICES, max_length=20) score3 = models.CharField(choices=VOTE_CHOICES, max_length=20) score4 = models.CharField(choices=VOTE_CHOICES, max_length=20) score5 = models.CharField(choices=VOTE_CHOICES, max_length=20) user = models.EmailField(max_length=255) group = models.CharField(max_length=250, default='notingroup') date = models.DateTimeField(auto_now_add=True) Here's what I have tried: From views.py: deli_val = [] e_t_r = [] fun = [] h_o_c = [] tw = [] for i in xrange(1, 6): vv = VotingValuesHistory.objects.values('value1').annotate(Sum('score' + str(i))) deli_val.append(int(vv[0]['score' + str(i) + '__sum'])) for i in xrange(1, 6): vv = VotingValuesHistory.objects.values('group', 'value2').annotate(Sum('score' + str(i))) e_t_r.append(int(vv[0]['score' + str(i) + '__sum'])) for i in xrange(1, 6): vv = VotingValuesHistory.objects.values('group', 'value3').annotate(Sum('score' + str(i))) fun.append(int(vv[0]['score' + str(i) + '__sum'])) for i in xrange(1, 6): vv = VotingValuesHistory.objects.values('group', 'value4').annotate(Sum('score' + str(i))) h_o_c.append(int(vv[0]['score' + str(i) + '__sum'])) … -
How to hide tracebacks for users when an import csv fail using django import export library
I have implemented successfully import and export in my app. The only thing that I can't make to work is to hide the tracebacks for users when an import fails. I have tried so far: raise_errors = False in admin.py .traceback{display:none} in import.css DEBUG = False in settings.py I put wrong data starting with the column name on purpose in the csv file and I always get this per row: § Line number: 1 - "Column 'my_error' not found in dataset. Available columns are: ['column1', 'column2', 'my_err', 'column3']" row1data1, row1data2, row1data3, 0 Traceback (most recent call last): File "C:\Users\my_user\.virtualenvs\my_project-gu-pxuzP\lib\site-packages\import_export\fields.py", line 63, in clean value = data[self.column_name] KeyError: 'my_error' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\my_user\.virtualenvs\my_project-gu-pxuzP\lib\site-packages\import_export\resources.py", line 492, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "C:\Users\my_user\.virtualenvs\my_project-gu-pxuzP\lib\site-packages\import_export\resources.py", line 269, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "C:\Users\my_user\.virtualenvs\my_project-gu-pxuzP\lib\site-packages\import_export\resources.py", line 263, in get_instance return instance_loader.get_instance(row) File "C:\Users\my_user\.virtualenvs\my_project-gu-pxuzP\lib\site-packages\import_export\instance_loaders.py", line 32, in get_instance params[field.attribute] = field.clean(row) File "C:\Users\my_user\.virtualenvs\my_project-gu-pxuzP\lib\site-packages\import_export\fields.py", line 66, in clean "columns are: %s" % (self.column_name, list(data))) KeyError: "Column 'my_erro' not found in dataset. Available columns are: ['column1', 'column2', 'my_error', 'column4']" How can I get only the fisrt lines of the message?: § Line number: … -
Django - endblock. Did you forget to register or load this tag
I am having and error in endblock tag in Django and I can't seem to find any errors in my code. Here are the 2 .html files. The {% endblock %} is written right but Django throws me an error TemplateSyntaxError at / Invalid block tag on line 57: 'endblock'. Did you forget to register or load this tag? Do I miss something or did I input something wrong? I tried to search some solutions but most of them are syntax errors with the { and % have space in between. login.html {% extends 'base.html' %} {% load static %} <body> <-- some HTML codes here --> </body> {% endblock %} base.html <-- HTML tags --> <-- CSS links --> {% block content %} {% endblock %} <-- JavaScript links --> -
Not saving data of some fields
Hello I am trying to save a new registered user to database. Besides native User Model I have a Profile model with additional fields and here is my problem, after registrations fields named 'gender' and 'birthday' are not saved to database, but the user and profile is created with according fields. models.py class Profile(models.Model): GENDER_CHOICES = [ ('male', 'Male'), ('female', 'Female'), ('other', 'Other'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) image_prof = models.ImageField( default='default.jpg', upload_to='profile_pics') gender = models.CharField( max_length=100, choices=GENDER_CHOICES, default='male',) birthday = models.DateField(name='birthday', null=True) def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class ProfileGenderBirthdayForm(forms.ModelForm): YEARS = [x for x in range(1940, 2021)] birthday = forms.DateField( widget=forms.SelectDateWidget(years=YEARS), required=True) class Meta: model = Profile fields = ['gender', 'birthday'] views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, ProfileGenderBirthdayForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) bg_form = ProfileGenderBirthdayForm(request.POST) if form.is_valid(): user = … -
Cannot load media static file photo anymore after pushing to heroku a number of times
At the beggining it was fine to login but now after a number of times logging in and pushing changes to heroku, the static files stopped working. The error itself is "FileNotFoundError at /accounts/login/ [Errno 2] No such file or directory: '/app/media/profile_pics/obama.jpg'" Initially i thought it was the "" provided by the Login html django auth. This should redirect me to the index page. .settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Deployment configs # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ PROJECT_ROOT = os.path.join(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' # Extra lookup directories for collectstatic to find static files STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, '/static'), ) # Add configuration for static files storage using whitenoise STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # update the db import dj_database_url prod_db = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(prod_db) I expected after logging in to be redirected to the index page but I get Filenotfound error even though theres no call function for any filetype. My instinct is that heroku doesnt keep static files so how can i make sure it keeps. -
How do I properly provide user field to ModelSerializer in Django Rest Framwork
I have a django Profile model as: class Profile(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100, blank=True) meta = models.TextField(blank=True) def __str__(self): return self.created_by And a serializer (which I know is not currently doing much) class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' In my update method in view, I can't ever seem to validate the serializers. This is how I am going about it: profile = Profile() profile.created_by = request.user serializer = ProfileSerializer(profile) serializer.is_valid() always returns False. And by the way, request.user is an authenticated CustomUser. I have also tried setting serializer = ProfileSerializer( instance=profile, data={'created_by':request.user} ) And many combinations thereof. What am I missing that the serializer can't be validated? Clearly there's some trouble with the user here. Extra: I am new to DRF, why is the 'created_by' field set by default when DRF seems to know who the user is? -
Unable to Get a proper result from Dict in Django Template
I am unable to print the value from Dict in Django Template. {% for steam in steam_d %} <div class=""> <h2 class="page-head-title"> {{ steam.0.steam_name }} - d</h2> </div> {% endfor %} or {% for steam in steam_d %} <div class=""> <h2 class="page-head-title"> {{ steam.steam_name }} - d</h2> </div> {% endfor %} {0: {'steam_name': 'ABC', 'steam_data': }, 1: {'steam_name': 'DEF', 'steam_data': }} I have properly passed the steam_d to the template but still unable to print the 'steam_name'. Loop is also working. -
How to make a filter that filters if a certain object has already been confirmed or not? Using reverse relationship
Im have two models: Notice and ReadConfirmation, i want to filter notices by read confirmation against the logged in user. class ReadConfirmation(TimestampedModel): notice = models.ForeignKey(Notice, models.CASCADE, db_column='aviso_id', related_name='read_confirmations') user = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE) api return all notices, and i want return notices news that the user has already read, that is, they are saved in the ReadConfirmation table -
Generate separate translation files with django-admin
How I can generate separate *.po files for my Django project? This files used only for automatic database table fill. Table look's like: id | SKU | en | cz | ... I need only SKU and lang column to generate filter dropdown for the user. Command django-admin makemessages -a includes them to the one main file. There are large dataset with 2000+ entries in summary. So I want to split them into the parts. Especially, because most of them used only during table fill. I have tried pygettext.py command, but it doesnt generate *.po files for all website locales. And this command removes already translated content. -
Problem with importing some .models from the 2 folders in one bigger one
I moved my django project from Atom to PyCharm and there is a problem, when i wrote, ''' from .models import BookItem ''' I've got error I tried do fix that with double dot, with adding full path, but it still does not work, have anyone know what can i do ? i tried ''' from shelf.models import BookItem from ..models import BookItem ''' even ''' from wypozycz.shelf.models import BookItem ''' The error that i receive is: "ImportError: cannot import name 'BookItem' from 'rental.models'" -
Simple solutions to create an interface with a python script?
I coded a simple Python script to automate some accounting work at my internship and it has worked wonderfully. However, now that I am leaving I am a bit worried about the other accountants being able to use the same script from the command line or JupyterLab. It would be amazing if I could create a simple interface for them so they don't have to learn anything new (: the script is really simple: it imports an excel file from the user's computer, transforms into a data frame, replaces a few strings, does some calculations, deletes some columns, and outputs an excel file with the new formatting. The script can be viewed at my github here: https://github.com/brunnatorino/FEC/blob/master/ALL_app.py I even tried adding some user input functions so they wouldn't have to mess with the code, but that has also proven challenging for them to learn and remember. Is there any simple interface solutions where I can use my existing script? I would prefer to have the least amount of modifications to the code as I don't have a lot of time left in my internship. -
How to Dynamically Remove Form from Formset
I have a Django formset where a user can dynamically add forms through a jQuery script. How can I use jQuery to dynamically remove the last form in the formset when the user clicks the #remove_form button? template.html <div id="form_set"> {{ presales_formset.management_form }} <form action="{% url 'presales' %}" class="presales_formset" data-total-url="{% url 'presales_total' %}" id="presalesForm" method="post" name="presalesForm"> <div class="field"> <label class="label is-large">High Level Task List</label> </div> {% csrf_token %} {% for presales_form in presales_formset.forms %} {{ presales_form.field_errors }} {{ presales_form.errors }} {% endfor %} </div> <div id="empty_form" style="display: none;"> {{ presales_formset.empty_form }} <form action="{% url 'presales' %}" class="presales_formset" data-total-url="{% url 'presales_total' %}" id="emptyPresalesForm" method="post" name="presalesForm"> {% csrf_token %} <div class="field is-inline-flex"> <div class="control"> <button class="button is-success" id="add_more" name="add_more" type="button">+</button> </div> </div> <div class="field is-inline-flex"> <div class="control"> <button class="button is-danger" id="remove_form" type="button">-</button> </div> </div> <script> $(document).ready(function () { $('body').on('click', '#add_more', function () { var form_idx = $('#presalesForm-TOTAL_FORMS').val(); $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#presalesForm-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); }); </script>