Sunday, 18 August 2013

Validating changed queryset not working - Django

Validating changed queryset not working - Django

I want to do the following: A user sees all eventrecords he previously
created on one page and can edit them.
The problem I have is that if he edits one or more of them and inputs an
invalid choice no validation errors are shown. Instead, nothing happens
(if I have if changed_events.is_valid() in the code) or I get "ValueError
at /coding/assignment/3/ The EventRecord could not be changed because the
data didn't validate." If the user puts in valid data, saving works just
fine.
I would like to show validation errors on the page, the way it is already
working when creating new entries.
Following my code:
The view (I'm not posting my whole view, as it's fairly complex and
everything else is working fine. These are the parts responsible for
what's not working):
##### 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")
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()
redirect_to = "?page=%s" % current_page
return HttpResponseRedirect(redirect_to)
The template:
{% for eventrecord in coded_events %}
{{ eventrecord.id }}
<div class="form-container">
{% if eventrecord.non_field_errors %}
{{form.non_field_errors}}
{%endif%}
{% for field in eventrecord %}
{% if field.errors %}
<li>{{ field.errors|striptags }}</li>
{% endif %}
{% endfor %}
Has anyone an idea what I'm doing wrong? Clearly Django is recognizing
that something is going wrong, but why doesn't it show it in the template
but creates an error-page? Why does nothing happen when I include the
is_valid()? I really don't know what I'm supposed to do, any help is
greatly appreciated!

No comments:

Post a Comment