Dynamically added Django FormSet data not being posted - javascript

I am modifying a FormSet using JavaScript/jQuery by dynamically adding a form to a Django FormSet. For example, I start with one form asking about a User's education. The User can then press an add button to add an identical form to input information about secondary schooling (e.g. grad school). The form gets added in the browser and I can input data, but when I POST the data, it only shows one form in the FormSet with the information from the second form in the browser.
POST DATA
edu-0-degree u'Doctorate'
first_name u'User'
last_name u'One'
Submit u'Submit'
edu-0-date_started u'01/01/12'
edu-MIN_NUM_FORMS u'0'
edu-0-school u'School Two'
edu-INITIAL_FORMS u'0'
edu-MAX_NUM_FORMS u'1000'
edu-0-date_finished u'01/01/16'
edu-0-id u''
edu-TOTAL_FORMS u'2'
csrfmiddlewaretoken u'qgD2supjYURWoKArWOmkiVRoBPF6Shw0'
I'm then getting an error saying:
ValidationError: [u'ManagementForm data is missing or has been tampered with'].
Here are the relevant pieces of code:
views.py
def build_profile(request):
EducationFormset = modelformset_factory(EducationModel, AddEducationForm, extra=1)
if request.method == "POST":
education_formset = EducationFormset(request.POST, prefix='edu')
for form in education_formset:
if form.is_valid() and form.has_changed():
education = EducationModel(
school = form.cleaned_data['school'],
date_started = form.cleaned_data['date_started'],
date_finished = form.cleaned_data['date_finished'],
degree = form.cleaned_data['degree'],
user = current_user
)
education.save()
return HttpResponseRedirect(reverse('private', args=[current_user.username]))
context = {
'edu_formset' : forms['education'],
}
return render(request, "build_profile.html", context)
(Here I've tried with and without the form.has_changed() piece with the same result.)
Template build_profile.html
<h2>Education</h2>
{{ edu_formset.management_form }}
{% for form in edu_formset.forms %}
<div id="{{ form.prefix }}-row" class="dynamic-form">
{{ form|crispy }}
<div {% if forloop.first %} class="hidden" {% endif %}>
<button type="button" class="btn btn-default btn-sm delete-row">
<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>
</button>
</div>
</div>
{% endfor %}
<div class="btn-group btn-group-xs" role="group" aria-label="...">
<button type="button" class="btn btn-default add-row">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
</button>
</div>
build_profile.js (The code to dynamically add forms to the FormSet)
function updateElementIndex(el, prefix, ndx) {
var id_regex = new RegExp('(' + prefix + '-\\d+)');
var replacement = prefix + '-' + ndx;
if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement));
if (el.id) el.id = el.id.replace(id_regex, replacement);
if (el.name) el.name = el.name.replace(id_regex, replacement);
}
function addForm(btn, prefix) {
var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
var row = $('.dynamic-form:first').clone(true).get(0);
$(row).removeAttr('id').insertAfter($('.dynamic-form:last')).children('.hidden').removeClass('hidden');
$(row).children().not(':last').children().each(function() {
updateElementIndex(this, prefix, formCount);
$(this).val('');
});
$(row).find('.delete-row').click(function() {
deleteForm(this, prefix);
});
$('#id_' + prefix + '-TOTAL_FORMS').val(formCount + 1);
return false;
}
function deleteForm(btn, prefix) {
$(btn).parents('.dynamic-form').remove();
var forms = $('.dynamic-form');
$('#id_' + prefix + '-TOTAL_FORMS').val(forms.length);
for (var i=0, formCount=forms.length; i<formCount; i++) {
$(forms.get(i)).children().not(':last').children().each(function() {
updateElementIndex(this, prefix, i);
});
}
return false;
}
$(document).ready( function () {
$('.add-row').click( function () {
return addForm(this, 'edu')
});
$('.delete-row').click( function () {
return deleteForm(this, 'edu')
});
});
What am I doing wrong?

You're getting the ValidationError because edu_TOTAL-FORMS = 2 and only 1 form from the formset is in your post args. View source in the browser and make sure that the names of your forms are prefixed properly. It looks like both forms have the edu-0 prefix and when you submit only the last one on the form is posted.

Related

Javascript code within <script> tag being rendered in the page

I am fairly new to the js and the referencing of the script. I have a particular js code in my partial view. The actual code is:
<script>
var bID = #businessIDScript;
var gID = #groupIDScript;
var dID = #departmentIDScript;
var aID = #areaIDScript;
if (!(aID > 0)) {
$("#createIdlerButton").attr("disabled", "disabled");
$("#importIdlerButton").attr("disabled", "disabled");
}
if (#sapEnabled == true) {
$("#sapIdlerReport").show();
$("#sapIdlerReportAnchor").removeAttr('onClick');
$("#sapIdlerReportAnchor").attr('onClick', 'PDS.IdlerManagement.sapIdlerReport(' + bID + ',' + gID + ',' + dID + ',' + aID + ')');
} else {
$("#sapIdlerReport").hide();
}
</script>
complete razor view page is:
#using PDS.Domain.EF6.Resources.Web
#using Kendo.Mvc.UI
#using PDS.Web.Areas.PlannedInspections.Models;
#using PDS.Web.Utils;
#{
var sapEnabled = ViewBag.SAPEnabled.ToString().ToLower();
var isLaidOutHide = (string)ViewData["isLaidOutHide"];
var EnforceUserDropDown = (string)ViewData["EnforceUserDropDown"].ToString().ToLower();
var CurrentLevelIsDashboard = false;
bool.TryParse(ViewData["CurrentLevelIsDashboard"].ToString(), out CurrentLevelIsDashboard);
var WorkOrderDashboardParameters = ViewData["WorkOrderDashboardParameters"] != null ?
(WorkOrderDashboardParameters)ViewData["WorkOrderDashboardParameters"] : null;
var importDataName = ViewData["importDataName"]?.ToString() ?? "";
var importTemplateUrl = ViewData["importTemplateUrl"]?.ToString() ?? "";
var importActionUrl = ViewData["importActionUrl"]?.ToString() ?? "";
var areaId = ViewData["areaId"]?.ToString().Trim() ?? "";
var areaIDScript = string.IsNullOrEmpty(areaId) ? "0" : areaId;
var breadcrumbTitle = ViewData["breadcrumbTitle"]?.ToString().Trim() ?? "";
var areaIdStr = ViewData["areaId"]?.ToString().Trim() ?? null;
var departmentIdStr = ViewData["departmentId"]?.ToString().Trim() ?? null;
var groupIdStr = ViewData["groupId"]?.ToString().Trim() ?? null;
var businessIdStr = ViewData["businessId"]?.ToString().Trim() ?? null;
var businessId = "";
if (!string.IsNullOrEmpty(businessIdStr))
{
businessId = businessIdStr;
}
else
{
using (var context = PDS.Domain.EF6.EF.CcMSEntitiesv6.CreateForUser(User))
{
if (!string.IsNullOrEmpty(groupIdStr))
{
var id = int.Parse(groupIdStr);
businessId = context.vwAreas.FirstOrDefault(x => x.GroupID == id)?.BusinessID.ToString() ?? "";
}
else if (!string.IsNullOrEmpty(departmentIdStr))
{
var id = int.Parse(departmentIdStr);
businessId = context.vwAreas.FirstOrDefault(x => x.DepartmentID == id)?.BusinessID.ToString() ?? "";
}
else if (!string.IsNullOrEmpty(areaIdStr))
{
var id = int.Parse(areaIdStr);
businessId = context.vwAreas.FirstOrDefault(x => x.AreaID == id)?.BusinessID.ToString() ?? "";
}
}
}
var businessIDScript = string.IsNullOrEmpty(businessId) ? "0" : businessId;
var groupIDScript = string.IsNullOrEmpty(groupIdStr) ? "0" : groupIdStr;
var departmentIDScript = string.IsNullOrEmpty(departmentIdStr) ? "0" : departmentIdStr;
}
<div id="idler-grid-toolbar" class="toolbarGridContainer">
<div class="pull-left">
#(Html.Kendo().DropDownList()
.Name("GridFilter")
.HtmlAttributes(new { data_column = "IsAtRisk" })
.Items(items =>
{
items.Add().Text(IdlerManagement.IdlerTag_Dropdown_HideReplaced).Value("active");
items.Add().Text(General.All).Value("all");
items.Add().Text(IdlerManagement.IdlerTag_Dropdown_AtRisk).Value("atrisk");
})
.Events(ev => ev.Change("PDS.IdlerManagement.activeIdlerDashboardFilterChanged"))
)
#(Html.Kendo().DropDownList()
.Name("IdlerGridFilter")
.HtmlAttributes(new { data_column = "Idler" })
.Items(items =>
{
items.Add().Text(IdlerManagement.Idlers).Value("true");
items.Add().Text(IdlerManagement.Structures).Value("false");
items.Add().Text(General.All).Value("all");
})
.Events(ev => ev.Change("PDS.IdlerManagement.activeIdlerDashboardFilterChanged2"))
)
#if (!CurrentLevelIsDashboard)
{
<span class="pull-right">
<button type="button" id="schematicsButton" class="btn btn-default" title='#IdlerManagement.Schematics_Button' onclick="PDS.IdlerManagement.editSchematic(this, '#areaId')">
#IdlerManagement.Schematics_Button
</button>
</span>
}
#if (User.IsInRole("Power User") || User.IsInRole("Business Administrator") || User.IsInRole("System Administrator"))
{
<div class="pull-right">
<div class="dropdown shutdown-planner-dropdown">
<button type="button" id="shutdownPlannerTags" class="btn btn-default dropdown-toggle" title='#IdlerManagement.ShutdownPlanner_Button' data-toggle="dropdown">
#IdlerManagement.ShutdownPlanner_Button
<span role="button" unselectable="on" class="k-select" aria-label="select">
<span class="k-icon k-i-arrow-60-down"></span>
</span>
</button>
<ul class="dropdown-menu dropdown-menu-right" style="transform:translate3d(0px, 51px, 0px); overflow-y:auto">
<li>
#IdlerManagement.ShutdownPlanner_Button_Add
</li>
<li>
#IdlerManagement.ShutdownPlanner_Button_Remove
</li>
</ul>
</div>
</div>
#Html.Partial("_IdlerShutdownPlannerTemplate")
}
#if (!User.IsInRole("Read Only User"))
{
<button class="btn btn-default " onclick="PDS.IdlerManagement.closeOutIdlerTags(this, #EnforceUserDropDown, '#User.Identity.Name')" disabled="disabled" id="closeOutIdlerTags">#IdlerManagement.IdlerTag_Button_CloseOut</button>
<button class="btn btn-default #isLaidOutHide" onclick="PDS.IdlerManagement.laidOutIdlerTags(this, #EnforceUserDropDown, '#User.Identity.Name')" disabled="disabled" id="laidOutIdlerTags">#IdlerManagement.IdlerTag_Button_LaidOut</button>
}
</div>
#if (WorkOrderDashboardParameters != null)
{
<span class="pull-right">
<button type="button" data-role="close" id="viewAsset" class="btn btn-default" title="#General.Close" onclick="PDS.Common.UrlHistory.navigateBack()">
<i class="fa fa-times"></i>
</button>
</span>
}
<span class="pull-right">
#Html.Partial("_QuickReport", new ViewDataDictionary() { { "groupName", "Idler Management" } })
</span>
#Html.Partial("_ImportExportButtons", new ViewDataDictionary() { { "DownloadTemplateUrl", $"/GlobalImportExport/ImportWizard/DownloadImportTemplateByEntity?entityName=IdlerTag" }, { "EntityName", "IdlerTag" } })
#if (!User.IsInRole("Read Only User"))
{
if (!CurrentLevelIsDashboard)
{
<div class="pull-right">
<div class="dropdown create-idlerstructure-button-dropdown">
<button type="button" id="createIdlerButton" class="btn btn-default dropdown-toggle" title="#IdlerManagement.IdlerTag_Tooltip_CreateRecord" data-toggle="dropdown"><i class="fa fa-plus"></i></button>
<ul class="dropdown-menu dropdown-menu-right">
<li>
#IdlerManagement.IdlerTag_Button_CreateIdler
</li>
<li>
#IdlerManagement.IdlerTag_Button_CreateStructure
</li>
</ul>
</div>
</div>
}
}
</div>
#Html.Partial("_ImportTemplate", new ViewDataDictionary() { { "importTemplateUrl", importTemplateUrl }, { "importActionUrl", importActionUrl } })
<script>
var bID = #businessIDScript;
var gID = #groupIDScript;
var dID = #departmentIDScript;
var aID = #areaIDScript;
if (!(aID > 0)) {
$("#createIdlerButton").attr("disabled", "disabled");
$("#importIdlerButton").attr("disabled", "disabled");
}
if (#sapEnabled == true) {
$("#sapIdlerReport").show();
$("#sapIdlerReportAnchor").removeAttr('onClick');
$("#sapIdlerReportAnchor").attr('onClick', 'PDS.IdlerManagement.sapIdlerReport(' + bID + ',' + gID + ',' + dID + ',' + aID + ')');
} else {
$("#sapIdlerReport").hide();
}
</script>
The display looks like this: As you can see in the image below some of the js code is being rendered in the main page. I am having hard time fixing this issue.
Note: There is no issue with the functionality of the code it works perfectly fine. Even tried doing console.log("Hello World"). Throws the same dark half baked js in the page. Any help would be appreciated.
Thank you in advance.
What i have tried:
Initially, I thought this issue was due to some missing tags and closure in html tags but i fixed those issues and resolved up the console errors and warnings that i was getting for those tags. Also, i found out that "display none" on the script tag fixed that issue but my senior won't allow it saying its not the solution just a hack. I don't have a clue what is causing this issue because there are no warning nor any errors in VS. also i tried doing document.Ready function for this script but that failed miserably as well. Now i am out of depth and have no idea what is causing this error. Another solution i discovered was if i move this whole script inside a new <div> tag, it resolves the issue.
Expectation:
--> The js should not be rendered in the page.
Below will help
can you please try it with script rendering section on you layout page and then render your script on that scope.
// use this on your layout page-- bottom of page once all plugin scripts are rendered
#RenderSection("scripts", required: false)
// use below on your partial
#section scripts{
<script type="text/javascript">
var bID = #businessIDScript;
var gID = #groupIDScript;
var dID = #departmentIDScript;
var aID = #areaIDScript;
if (!(aID > 0)) {
$("#createIdlerButton").attr("disabled", "disabled");
$("#importIdlerButton").attr("disabled", "disabled");
}
if (#sapEnabled == true) {
$("#sapIdlerReport").show();
$("#sapIdlerReportAnchor").removeAttr('onClick');
$("#sapIdlerReportAnchor").attr('onClick', 'PDS.IdlerManagement.sapIdlerReport(' + bID + ',' + gID + ',' + dID + ',' + aID + ')');
} else {
$("#sapIdlerReport").hide();
}
}
It looks like the page is rending the script tag as html.
A quick and simple fix would be to hide the script tag like so:
<script style="display:none;">
If you could move that functionality outside of the razor page and into a dedicated javascript/typescript page it would probably fix the render issue aswell.
Have you tried moving the script to a different location and see what happens? Kendo template might be rendering that JavaScript snippet to the datagrid columns/header as text. I guess what you can do is do first is do a trial and error determine where the code would work and the same time wont render as text. Maybe somewhere common like the layout page or something? Afterwards you can then do a proper fix like where the code should be best placed.

how can i create a table entry in django views

I want to make a system of likes on the site, and I need to create an entry in the table on the button. When a person clicks on like, the table writes row 1 and when dislike 0
views.py
def forum(requset):
model = Quetions.objects.all()
answer = Answer.objects.all()
count = Answer.objects.all().count()
count_answer = Quetions.objects.all().count()
paginator = Paginator(model, 1) # Show 25 contacts per page.
page_number = requset.GET.get('page')
question_id = requset.GET.get('id',False)
page_obj = paginator.get_page(page_number)
requestanswer = requset.GET.get('id',False)
like_disli = like.objects.filter(like_dislike = "1").count()
dislike = like.objects.filter(like_dislike = "0").count()
createlike =
objects = {
'model': page_obj,
'answer':answer,
'count':count,
'count_question':count_answer,
'page_obj':page_obj,
'question':question_id,
'id':model,
'request':requestanswer,
'like':like_disli,
'dislike':dislike,
'createlike':createlike,
}
return render(requset,'forum.html',objects)
forum.html
<span>
<i class="fas fa-thumbs-up" style="color: blue;margin-right: 5px;" onclick="incrementClick()"></i>{{like}}<i class="fas fa-thumbs-down" style="color: red;margin-right: 5px;margin-left: 10px;" onclick="dislikeclick()"></i>{{dislike}}
</span>
{% block js %}
<script>
var a = "{{createlike}}"
function incrementClick() {
a
}
function dislikeclick() {
dislikedisplay(++dislikecounter);
}
function updateDisplay(val) {
document.getElementById("counter-label").innerHTML = val;
}
function dislikedisplay(val){
document.getElementById("counter").innerHTML = val
}
</script>
{% endblock js %}
tell me how to do it???

How to submit a Django form using JavaScript (jQuery)

I'm working on a web app project. I had a problem with file upload. Then I realized that my team mate changed the default submit button in create_form.html. It works like in 5. and 6. and i need to collect file data as well.
What should I add to .js files to submit and save file?
forms.py
class DocumentUpload(forms.ModelForm):
class Meta:
model = Form
fields = ('file',)
models.py
class Form(TimeStampedModel, TitleSlugDescriptionModel):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=512)
is_final = models.BooleanField(default=False)
is_public = models.BooleanField(default=False)
is_result_public = models.BooleanField(default=False)
file = models.FileField(null=True, blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('form-detail', kwargs={'slug': self.slug})
views.py
def create_form(request):
if request.method == 'POST':
user = request.user
data = ParseRequest(request.POST)
print(data.questions())
print(data.form())
parsed_form = data.form()
parsed_questions = data.questions()
# tworzy formularz o podanych parametrach
formfile = DocumentUpload(request.POST, request.FILES or None)
if formfile.is_valid():
form = formfile.save(commit=False)
print(form)
form.author = user
form.title = parsed_form['title']
form.is_final = parsed_form['is_final']
form.is_result_public = parsed_form['is_result_public']
form.description = parsed_form['description']
form.save()
# zapisuje pytania z ankiety wraz z odpowienimi pytaniami
for d in parsed_questions:
question = Question(form=form, question=d['question'])
question.save()
# dla kazdego pytania zapisz wszystkie opcje odpowiadania
for opt in d['options']:
option = Option(question=question, option=opt)
option.save()
return render(request, 'forms/form_form.html', {})
else:
form = DocumentUpload()
return render(request, 'forms/form_form.html', {'form': form})
create_form.html
Here I have to submit {{ form.as_p }} <- I have to submit this input in JS**
{% block content %}
<form method="post" id="form" enctype='multipart/form-data'>
{%csrf_token %}
<div class="form-group">
{% csrf_token %}
<label for="form-title">Tytuł formularza</label>
<input id="form-title" class="form-control" type="text"
placeholder="Tytuł" required/>
</div>
{{ form.as_p }}
.... more divs ...
<input class="btn btn-default" type="submit" value="zapisz"/>
</form>
{% endblock %}
collect_data.js
This is my function called to save inputs from create_form.html instead of:
<input class="btn btn-default" type="submit" value="zapisz"/>
but I don't know how to save input from:
{{ form.as_p }}
function collect_data() {
var csrftoken = getCookie('csrftoken');
var data = {
form_title: $('#form-title').val(),
is_final: $('#form-is-final').prop('checked'),
is_public: $('#form-is-public').prop('checked'),
is_result_public: $('#form-is-result-public').prop('checked'),
description: $('#description').val(),
questions: [],
num_questions: num_questions,
csrfmiddlewaretoken: csrftoken
};
for (var k = 0; k < num_questions; k++) {
var my_data = {};
var question_k = $('#question-' + k);
my_data.question = question_k.find('#question-text').val();
my_data.answer_type = question_k.find('select').val();
my_data.options = [];
for (var j = 0; j < num_question_options[k]; j++) {
var answer = question_k.find('#answer-' + j).val();
if (answer !== '') {
my_data.options.push(answer)
}
}
my_data.num_options = my_data.options.length;
data.questions.push(my_data)
}
return data
}
submit_data_create.js
$(document).ready(function (event) {
$(document).on('submit', '#form', function (e) {
e.preventDefault();
var data = collect_data();
$.ajax({
type: 'POST',
url: '/form/create/',
data: data,
success: function (data, textStatus) {
window.location.href = '/form/list/'
},
fail: function (response) {
alert('Coś poszło nie tak.');
}
});
})
});

Form in modal with symfony2 and jquery is not being submitted with data

I have a list of Schools displayed in my list.html.twig. For each school I need to insert some data which is filled in a form inside a modal. I need that once the form is filled, the modal is submitted and closes, showing again the background page. Normally the submit action of the modal causes page refresh, and I want to avoid that obviously.
The inspiration for the code was this tutorial, specifically I followed the creation of the form...
//school controller
$school = new School();
$form = $this->createForm(
new SchoolFormType($param),
$school,
array(
'action' => $this->generateUrl("school_modal_vp", array(
'param' => $param,
)),
'method' => 'POST'
));
if($request->isMethod('POST')) {
$form->handleRequest($request);
if($form->isValid()) {
$data = $form->getData();
$em->persist($data);
$em->flush();
$response = new Response(json_encode([
'success' => true,
]));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
... and the function which "replaces" the submit action of the modal with a AJAX call with form data, storing it to database and closing modal.
<script>
var param_id = '{{ param.id }}';
function sendForm(form, callback) {
// Get all form values
var values = {};
$.each( form[0].elements, function(i, field) {
if (field.type != 'checkbox' || (field.type == 'checkbox' && field.checked)) {
values[field.name] = field.value;
}
});
// Post form
console.log(values);
$.ajax({
type : form.attr( 'method' ),
url : form.attr( 'action' ),
data : values,
success : function(result) { callback( result ); }
});
}
$(function() {
$("#school_"+param_id+"_save").on("click", function( e ) {
e.preventDefault();
sendForm($("#myModalSchool_" + param_id).find('form'), function (response) {
$("#myModalSchool_" + param_id).modal('hide');
});
});
});
</script>
However, this works only for the last modal created while listing the schools. Any help is appreciated, and please if you need ask for details.
EDIT 1:
This is the template as requested
<div class="modal fade" data-backdrop="static" id="myModalSchool_{{ param.id }}">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="modal-title">
School
</h3>
</div>
<div class="modal-body">
<form id="school_{{ param.id }}" name="school_{{ param.id }}" method="post" action="{{ path('school_modal_vp', {param_id: param.id, }) }}" class="form-horizontal">
{{ form_errors(form) }}
{{ form_rest(form) }}
{{ form_end(form) }}
</div>
</div>
</div>
I think the main problem is the var param_id = '{{ param.id }}'; which is defined manually in your javascript.
First, I advise you to add a class on all your save button (e.g modal-submit) and a data-id on each button.
Example:
<button type="button" class="btn btn-primary modal-submit" data-id="{{myData.id}}">Submit</button>
Then in your javascript when you click on a save button (with modal-submit), you retrieve the id from the data-id and execute the sendForm($("#myModalSchool_" + param_id).find('form'),....
Example:
$(function() {
$(".modal-submit").on("click", function( e ) {
e.preventDefault();
var param_id = $(this).attr('data-id');
sendForm($("#myModalSchool_" + param_id).find('form'), function (response) {
$("#myModalSchool_" + param_id).modal('hide');
});
});
});
EDIT:
Saved multiple times issue ?
Moreover, i think you defined the javascript above in each modal. That's why the save is called multiple times. You need to have only one instance of this javascript (so it can't be placed in your modal view). Try to put the javascript in your global layout.
Hope it will help

Django formset.js : Can't delete a from

We're using formset.js in our django project to add or delete forms in a form.
I can't make the delete button work.
I see in the formset.js (available here https://pypi.python.org/pypi/django-formset-js/0.4.0 )
this code :
Formset.prototype.bindForm = function($form, index) {
var prefix = this.formsetPrefix + '-' + index;
$form.data(pluginName + '__formPrefix', prefix);
var $delete = $form.find('[name=' + prefix + '-DELETE]');
// Trigger `formAdded` / `formDeleted` events when delete checkbox value changes
$delete.change(function(event) {
if ($delete.is(':checked')) {
$form.attr('data-formset-form-deleted', '');
$form.trigger('formDeleted');
} else {
$form.removeAttr('data-formset-form-deleted');
$form.trigger('formAdded');
}
}).trigger('change');
var $deleteButton = $form.find(this.opts.deleteButton);
$deleteButton.bind('click', function() {
$delete.attr('checked', true).change();
});
};
My problem is that i don't find any checkbox in the code. The template shows this :
<div data-formset-body>
<!-- New forms will be inserted in here -->
{% for form in formset %}
<div data-formset-form>
{{ form.as_p }}
<!-- ajout YCO pour progresser dans le delete
<input type="checkbox" name="form-{{ forloop.counter0 }}-DELETE">
-->
<div class="hidden">{{ form.DELETE }}</div>
<a data-formset-delete-button >{% trans "Delete form" %}</a>
<!-- onclick ="$(this).parent().remove();" -->
</div>
{% endfor %}
</div>
Could someone tell me :
Is there a checkbox needed somewhere or if that property is added by the script to the delete button ?
Where should i write the code <input type="checkbox" name="form-0-DELETED"> ?
Is there a working sample of a working delete button available somewhere ?
When using yourform.DELETE in template, must use with can_delete formset parameter as below.
from django import forms
from django.forms.formsets import formset_factory
class YourForm(forms.Form):
date = forms.DateField()
YourFormSet = formset_factory(YourForm, can_delete = True)
Django document "Formsets"

Categories