4

由于某种原因,我的表单集在我提交后将无法验证。关于这种情况可能发生的任何想法?

#models.py

class Department(models.Model):
  department = models.CharField(verbose_name = "Department Name", max_length=100)
  description = models.TextField(verbose_name = "Description", blank=True, null=True)
  sp_description = models.TextField(verbose_name = "Description (Spanish)", blank=True, null=True)
  phone = PhoneNumberField()
  phone_ext = models.CharField(max_length=10, blank=True)

  #Relations
  provider = models.ForeignKey(Provider, blank=True, null=True)
  services_offered = models.ManyToManyField(ServiceType)

  def __unicode__(self):
    return self.department

#view.py

def display_step5(request):
    msg = ''
    email = request.session.get('email')
    provider_obj = retrieve_provider_instance(email)
    AddDepartmentFormSet = inlineformset_factory(Provider, Department, extra=0)
    if is_authenticated(request):
        AddDepartmentFormSet = inlineformset_factory(Provider, Department, extra=0)
        if request.method=='POST':
            if 'add_department' in request.POST:
                cp = request.POST.copy()
                cp['department-TOTAL_FORMS'] = int(cp['department-TOTAL_FORMS'])+ 1
                new_department = AddDepartmentFormSet(cp, prefix='department', instance=provider_obj)
            elif 'submit' in request.POST:
                formset = AddDepartmentFormSet(request.POST, instance=provider_obj)
                instances = formset.save(commit=False)
                for instance in instances:
                    instance.provider = provider_obj
                    instance.save()
                return HttpResponse("Departments have been added")
        else:
            new_department = AddDepartmentFormSet(prefix='department', instance=provider_obj)

    else:
        return HttpResponseRedirect(reverse('health.register.views.display_auth'))
    return render_to_response('step5-test.html',
{'department': new_department}, context_instance=RequestContext(request))

step5-test.html

<form method='post' action='{{request.path}}'>{% csrf_token %}
  <fieldset>
    <legend>Departments</legend>
      {{ department.management_form }}
      {% for form in department.forms %}
        <HR> <div><table>{{form.as_table}}</table></div>
      {% endfor %}
     <BR/> 
     <input title='Add a new department' type='submit' name='add_department' value='Add-Another-Department' />
    </fieldset>
    <BR/><BR/>
    <input title='Submit this form' type='submit' name='submit' value='Submit' />
</form>

跟进(解决方案):

Brant 提供了一些关于错误发生原因的见解。就我而言,他的洞察力帮助我构建了一个更适合我的情况的 hack。此 hack 似乎适用于可能已在模板中以某种方式修改的表单集。就我而言,我的表单集变得复杂,需要一些 ajax 来使其更加用户友好。

“retrieve_provider_instance(email)”是一种基于数据库中设置的各种标准(大约 200 行代码呕吐)检索提供者对象的动态方式。

在进行了一些广泛的调试之后,以下 hack 对我有用。我通过在模板的“for”循环中 添加以下隐藏字段来解决它

{% {for form in formset.forms %}
                     <tr>
                      <td>
                         {% if form.instance.pk %} <!--- if instance already exists on db --->  
                         {{ form.DELETE }}
                         <input type='hidden' name="department_set-{{ forloop.counter0 }}-id" id="id_department_set-{{ forloop.counter0 }}-id"  value={{ form.instance.pk }} />
                         {% endif %}
                      Name: <br/> {{ form.department}} <br/>
                      Phone Number: <br/> {{ form.phone }} <br/>
                      Phone Ext: <br/> {{ form.phone_ext }}</td>
                      <td>Description: <br/> {{ form.description }}</td>
                      <td>Description (Spanish): <br/> {{ form.sp_description }}</td>
                      <td>Services Provided: <br/> {{ form.services_offered }}</td>
                      <td></td>
                   </tr>
                   {% endfor %} 

我接受了马克的回答,因为它更适用于我提出的具体问题。希望这将有助于将来尝试实现此示例的其他用户。事实上,在提交时分配“前缀”是正确的方法,也是最有意义的。

感谢您的所有回复。

最好的问候,马特


跟进:我想我可能已经找到了我的部分问题。但是,还没有解决。

以下是一些可能有助于解决问题的附加信息。不正确的 POST 数据会搞砸吗?如果是这样,我该如何解决这个问题?

这是我提交表单集后发生的情况(在这种情况下只有一个表单):

回溯如下:

_management_form 68 中的文件“/home/mhjohnson/webapps/resourcedb/lib/python2.6/django/forms/formsets.py”。引发 ValidationError('ManagementForm 数据丢失或已被篡改')

这是我的 POST 数据:

department-0-phone_ext -----> u'222'

department-0-id -----> u''

department-0-services_offered -----> u'2'

department-0-phone -----> u'222-222-2222'

department-INITIAL_FORMS -----> u'0'

submit -----> u'Submit'

department-MAX_NUM_FORMS -----> u''

department-0-department -----> u'Test 1'

department-0-provider -----> u''

department-TOTAL_FORMS -----> u'1'

csrfmiddlewaretoken -----> u'92a39322b16ed7e5e10dbd6c5ac64bf4'

department-0-description -----> u'Blah blah'

department-0-sp_description -----> u'....'

有任何想法吗?

4

2 回答 2

6

你的问题在这里:

       if request.method=='POST':
            if 'add_department' in request.POST:
                cp = request.POST.copy()
                cp['department-TOTAL_FORMS'] = int(cp['department-TOTAL_FORMS'])+ 1
                new_department = AddDepartmentFormSet(cp, prefix='department', instance=provider_obj)
            elif 'submit' in request.POST:
                formset = AddDepartmentFormSet(request.POST, instance=provider_obj)
                instances = formset.save(commit=False)
                for instance in instances:
                    instance.provider = provider_obj
                    instance.save()
                return HttpResponse("Departments have been added")
        else:
            new_department = AddDepartmentFormSet(prefix='department', instance=provider_obj)

如果没有 POST,则传递“部门”前缀。如果“add_department”在 POST 中,则传递“department”前缀。但是,当“提交”在 POST 中时,您不会传递前缀。如果没有前缀,表单集将无法在 POST 中找到正确的数据。

于 2011-01-11T13:17:51.450 回答
3

有两件事突然出现在我身上......

首先,您不需要执行此部分:

for instance in instances:
   instance.provider = provider_obj
   instance.save()

当你这样做时,这已经被照顾了:

formset = AddDepartmentFormSet(request.POST, instance=provider_obj)

其次,您的代码在顶部:

provider_obj = retrieve_provider_instance(email)

可能无法正常工作。在您提供的回溯中,看起来提供者并没有到达那里......

department-0-provider -----> u''
于 2011-01-11T12:17:22.260 回答