14

该模型:

class Operation(models.Model):
  operation_type = models.ForeignKey(OperationType)
  category = models.ForeignKey(Category, default=0)
  related_account = models.ForeignKey(Account, related_name = 'related_account', null = True)
  comments = models.TextField(null = True)

编码:

def detail(request, category_id):
  class OperationCategoryOnlyForm(forms.ModelForm):
    class Meta:
      model = Operation
      fields = ('operation_type', 'category', 'related_account', )

  from django.forms.models import modelformset_factory
  OperationFormSet = modelformset_factory(Operation, form=OperationCategoryOnlyForm)
  if request.method == "POST":
    formset = OperationFormSet(request.POST, queryset=Operation.objects.filter(category=category_id))
    if formset.is_valid():
      formset.save()
# HERE IS THE FORMSET, WHICH OVERLAPS THE POSTED FORMSET - this was intentionaly to get the current result not result before save, but when you want to debug - you should pay attention at such things.    
#  formset = OperationFormSet(queryset=Operation.objects.filter(category=category_id))

  c = {"formset" : formset,}
  c.update(csrf(request))
  return render_to_response("reports/operation_list.html", c)

模板:更新:

<form method="post" action="">
  {% csrf_token %}
  {{ formset.management_form }}
  {{ formset.errors }}
  {{ formset.non_field_errors }}
  {{ formset.non_form_errors }}
<table>
 {% for form in formset.forms %}
tr><td> {{ form.errors }} </td><td> {{ form.non_field_errors }}</td></tr>
<tr><td>{{ form.id }}</td><td>{{ form.instance.comments }}</td><td>{{ form.operation_type }}<br>{{ form.related_account }}</td><td>{{ form.category }}</td></tr>
  {% endfor %}
</table>
<input type="submit" value="submit">
</form>

我发现 form.is_valid() = false - 但我不知道如何得到原因 WHY...

UPD - 我根据评论更新了模​​板 - 没有结果......

(这是非常愚蠢的规则,我必须编写比问题更少的代码 - 代码是自我解释的,是问题的本质 - 几乎总是问题会简化为一句话,但没有办法减少代码)

4

1 回答 1

29

是的,因为您在显示之前创建了另一个空表单集。在检查print formset.errors之前或之后直接添加。ifis_valid()

于 2012-05-20T15:46:37.513 回答