The form is invalid ... WHY?

model:

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) 

the code:

 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) 

template: UPDATED:

 <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> 

I found that form.is_valid () = false - but I have no idea how to get the reason WHY ...

UPD I updated the template in accordance with the comment - nothing worked ....

(this is a very silly rule that I should write less code than the question - the code itself explains and is the essence of the question - almost always the question comes down to one sentence, but there is no way to reduce the code)

+4
source share
1 answer

Yes, because you create another empty set of forms before displaying it. Add print formset.errors before or immediately after if to verify is_valid() .

+13
source

Source: https://habr.com/ru/post/1413384/


All Articles