jQueryを使用してフォームを動的に追加し、djangoバックエンドで処理するWebアプリを作成しています。https://docs.djangoproject.com/en/dev/topics/forms/formsets/のドキュメントに従ってdjangoでフォームセットを使用し、 http ://stellarchariot.com/blog/2011の例に従おうとしました/02/dynamically-add-form-to-formset-using-javascript-and-django/および stackoverflowの Ajax を使用して Django フォームセットにフォームを動的に追加します。
私が抱えている問題は、フォームを送信しても POST データが得られないことです。変数 {{ formset.management_form}} を削除すると、データは POST に送信されますが、[u'ManagementForm データが見つからないか、改ざんされています] というエラーが表示されます。管理フォームをテンプレートに入れると(そうすべきです)、POSTデータが得られません。誰でもこれの解決策を知っていますか?
forms.py
from django import forms
from busker.models import *
from django.forms import ModelForm
class UploadFileForm(ModelForm):
class Meta:
model = UploadFile
class Category(models.Model):
category = models.CharField(max_length = 50)
def __unicode__(self):
return self.name
models.py
from django.db import models
class UploadFile(models.Model):
title = models.CharField(max_length = 50)
file = models.FileField(upload_to = 'test')
def __unicode__(self):
return self.name
class CategoryForm(ModelForm):
class Meta:
model = Category
ビュー.py
def submit(request,action=''):
if request.user.is_authenticated():
class RequiredFormSet(BaseFormSet):
def __init__(self, *args, **kwargs):
super(RequiredFormSet, self).__init__(*args, **kwargs)
for form in self.forms:
form.empty_permitted = False
UploadFileFormSet = formset_factory(UploadFileForm,extra=2, max_num=10, formset=RequiredFormSet)
if request.method == 'POST':
uploadfile_formset = UploadFileFormSet(request.POST, request.FILES,prefix='songs')
category_form= CategoryForm(request.POST,prefix = 'category')
if uploadfile_formset.is_valid and category_form.is_valid:
return HttpResponseRedirect('/') #going to the home root
else:
return HttpResponseRedirect('/contact') #testing to see if it fails
else:
uploadfile_formset = UploadFileFormSet(prefix = 'songs')
category_form= CategoryForm(prefix = 'category')
t = loader.get_template('submit.html')
c = RequestContext(request, {
'uploadfile_formset': uploadfile_formset,
'category_form': category_form,
'head_title': u'Submit Song',
'page_title': 'Submit Song',
})
return HttpResponse(t.render(c))
テンプレート (submit.html)
<form id="songform" name="songform" enctype="multipart/form-data" action="" method="POST">{% csrf_token %}
{{uploadfile_formset.management_form}}
<div id="songforminputs">
{{category_form.as_p}}
{% for formset in uploadfile_formset %}
<div id="dynamicInput">
<p class = "songSubmitForm" > Song {{forloop.counter}} </p>
{% for field in formset %}
<label class="submitForm" for="title">{{ field.label }}</label>
{{field|add_class:"submitForm" }}
</br>
{% endfor %}
</div>
{% endfor %}
</div>
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
<input type="button" value="Remove a text input" onClick="removeInput('dynamicInput');">
<input type="submit" name="submitbutton" id="submitbutton" value="" >
</form>
jQuery/javascript部分
<script type="text/javascript">
var counter = 2;
var minimum = 2;
var limit = 5;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.id = "dynamicInput";
newdiv.innerHTML = "<p class = 'songSubmitForm' > Song " + (counter+1) +"</p>" + "<label for='title' class='submitForm' >Title</label>" + "<input id ='id_form-" + (counter)+ "-title'type='text' class='contact' name='form-" + counter +"-title'>" + "</br>" + "<label for='file' class='submitForm' >File</label>" + " <input id='id_form-"+counter+"-file' type='file' class='contact' name='form-"+counter+"-file'>" + "</br>" + "</br>";
document.getElementById('songforminputs').appendChild(newdiv);
counter++;
}
}
function removeInput(divName){
if (counter == minimum) {
alert("You need at least " + counter + " inputs");
}
else {
$('div#dynamicInput:last-child').remove()
counter--;
}
}
</script>