模特:
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 - 但我不知道如何得到原因为什么......
UPD - 我根据评论更新了模板 - 没有结果......
(这是非常愚蠢的规则,我必须编写的代码少于问题代码 - 代码是自我解释的并且是问题的本质 - 几乎总是将问题简化为一个句子,但是没有办法减少代码)
答案 0 :(得分:16)
是的,因为你在显示之前创建了另一个空的formset。在print formset.errors
检查if
之前或之后直接添加is_valid()
。