Returning user data for forms that have errors in when using ModelForms

Posted by Sevenearths on Stack Overflow See other posts from Stack Overflow or by Sevenearths
Published on 2011-01-14T23:13:33Z Indexed on 2011/01/14 23:53 UTC
Read the original article Hit count: 253

forms.py

from django.forms import ModelForm
from client.models import ClientDetails, ClientAddress, ClientPhone
from snippets.UKPhoneNumberForm import UKPhoneNumberField

class ClientDetailsForm(ModelForm):
    class Meta:
        model = ClientDetails

class ClientAddressForm(ModelForm):
    class Meta:
        model = ClientAddress

class ClientPhoneForm(ModelForm):
    number = UKPhoneNumberField()

    class Meta:
        model = ClientPhone

views.py

from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from client.forms import ClientDetailsForm, ClientAddressForm, ClientPhoneForm

def new_client_view(request):
    formDetails = ClientDetailsForm(initial={'marital_status':'u'})
    formAddress = ClientAddressForm()
    formHomePhone = ClientPhoneForm(initial={'phone_type':'home'})
    formWorkPhone = ClientPhoneForm(initial={'phone_type':'work'})
    formMobilePhone = ClientPhoneForm(initial={'phone_type':'mobi'})
    return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))

(the new_client.html is nothing special)

How should I write views.py so that if the user's data raises an error, instead of showing them the form again with the errors in but none of their original data, it shows them the form again with the errors AND their original data?

© Stack Overflow or respective owner

Related posts about django

Related posts about django-forms