[Answer]-Django Form not raising error

1👍

Your pattern is slightly wrong:

if request.method =='POST':
    form = NewMessageForm(request.POST)
    if form.is_valid():
        recipient = form.cleaned_data['recipient']
        subject = form.cleaned_data['subject']
        message = form.cleaned_data['message']
        thread = Thread.objects.create(subject=subject,user=request.user)
        recipient = User.objects.get(username=recipient)
        message = Message.objects.create(user=request.user,recipient=recipient,body=message,thread=thread)
        return HttpResponseRedirect(reverse('world:message'))
else:
    form = NewMessageForm()

Idea is that you first check if it’s a POST, ok – is it working? Great- return correct flow – otherwise fall-through and pass form with errors attached by is_valid() to context. In case it’s a new one – create it as a last resort since it doesn’t hold any information yet.

Also don’t forget form.non_field_errors since it will contain errors that are not specific to any field.

Leave a comment