好吧,我已经验证了我的表单,以便用户必须提交位置。
用户可以编辑eventrecords
,当他的更改保存在那里时(显然)也需要是表单中设置的位置。
当我测试用户不这样做时会发生什么,我收到以下错误:
ValueError at ....
The EventRecord could not be changed because the data didn't validate.
我想要的是,页面上显示的验证错误,例如提交新表单时可能发生的验证错误。
这是我的观看代码:
##### Show already created events on the page
current_article = paginator.page(current_page).object_list[0]
EventFormSet = modelformset_factory(EventRecord, can_delete=True, exclude=('coder','article','url','last_updated'), extra=0)
event_queryset = EventRecord.objects.filter(article__id=current_article.id).filter(coder=request.user.id)
coded_events = EventFormSet(queryset=event_queryset, prefix="event_form")
这是用于创建新表单和显示验证错误的模板代码:
{% for form in formset %}
<div class="form-container">
{% if form.non_field_errors %}
{{form.non_field_errors}}
{%endif%}
{% if form.errors %}
{% for field in form %}
{% if field.errors %}
<li>{{ field.errors|striptags }}</li>
{% endif %}
{% endfor %}
{% endif %}
这里的代码不适用于已经coded_events
:
{{ coded_events.management_form }}
{% if coded_events.forms %}
<strong>Coded Events:</strong>
{% for eventrecord in coded_events %}
{% if eventrecord.errors %}
{% for field in eventrecord %}
{% if field.errors %}
<li>{{ field.errors|striptags }}</li>
{% endif %}
{% endfor %}
{% endif %}
对coded events
的更改按如下方式处理:
elif 'save_changes' in request.POST:
formset = CodingFormSet(prefix="coding_form")
changed_events = EventFormSet(request.POST, prefix="event_form")
instances = changed_events.save()
上面有if changed_events.is_valid():
个实例,但如果我这样做,我甚至不再看到Django错误页面了,所以这就是为什么它不在那里。
希望你们中的任何人都有解决方案,谢谢!
编辑: 要查看完整视图,您可以查看this question of mine。 处理当前问题的部分就是这个(我试着再次使用is_valid(),但它仍然不起作用)
elif 'save_changes' in request.POST:
formset = CodingFormSet(prefix="coding_form")
changed_events = EventFormSet(request.POST, prefix="event_form")
if changed_events.is_valid():
instances = changed_events.save()
try:
history_record = ArticleHistory.objects.filter(article__id=paginator.page(current_page).object_list[0].id).filter(coder=request.user.id)[0]
history_record.last_updated = datetime.datetime.now()
history_record.save()
except:
history_form = ArticleHistoryForm()
article_history = history_form.save(commit=False)
article_history.article = paginator.page(current_page).object_list[0]
article_history.coder = request.user
article_history.last_updated = datetime.datetime.now()
article_history.save()
#EventFormSet = modelformset_factory(EventRecord, can_delete=True, exclude=('coder','article','url','last_updated'), extra=0)
#event_queryset = EventRecord.objects.filter(article__id=current_article.id).filter(coder=request.user.id)
#coded_events = EventFormSet(queryset=event_queryset, prefix="event_form")
redirect_to = "?page=%s" % current_page
return HttpResponseRedirect(redirect_to)
update_location_set(formset, coded_events, location_queryset)
insert_article_pubdate(formset, current_article)