提交的Django表单在使用formset/{management_Form}}variab时没有POST数据

2024-04-20 16:14:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个web应用程序来使用jQuery动态添加表单并使用django后端处理它们。我在django中使用了表单集,如文档中的https://docs.djangoproject.com/en/dev/topics/forms/formsets/所示,并尝试遵循http://stellarchariot.com/blog/2011/02/dynamically-add-form-to-formset-using-javascript-and-django/和{a3}处stackoverflow的例子。在

我遇到的问题是,当我提交表单时,我没有得到任何POST数据。当我删除变量{表单集管理}}我获取要发布的数据,但得到错误[u'ManagementForm数据丢失或已被篡改']。如果我把管理表格放在模板中(我应该这样做),我就不会得到过账数据。有人知道解决办法吗?在

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

在模型.py在

^{pr2}$

在视图.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))

模板(提交.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>

Tags: divformidforinputiftitlerequest
1条回答
网友
1楼 · 发布于 2024-04-20 16:14:30

我不认为你说你使用的是django crispy表单,但是,我会把这个贴在这里,任何遇到这个错误的人,谁知道,也许它也会帮助你。在

我最近在尝试使用多个crispy内联表单集时遇到了一个非常类似的问题。我在使用^{之前添加了{{ formset.management_form }}。在

掌心

当我把管理表格包括在内时,表格中的数据在邮寄时是不可用的。当我没有包括管理表单时,django用[u'ManagementForm data is missing or has been tampered with']抱怨。在

要解决这个问题,只需使用crispy表单的设计方式:{% crispy formset formset.form.helper %}。这样就不需要在它自己的标记中包含管理表单,这似乎只是混淆了Django。在

相关问题 更多 >