返回使用ModelForms时出现错误的表单的用户数据

时间:2011-01-14 23:13:33

标签: django django-forms

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

new_client.html

<form action="." method="POST">
    <table>
        <tr>
            <td>
                <table>
                    {{ formDetails.as_table }}
                    {{ formAddress.as_table }}
                </table>
            </td>
            <td>
                <table>
                    {{ formHomePhone.as_table }}
                    {{ formWorkPhone.as_table }}
                    {{ formMobilePhone.as_table }}
                </table>
            </td>
        </tr>
    </table>
    <input type="submit" value="Submit">
</form>

我应该如何编写views.py,以便如果用户的数据引发错误,而不是再次显示表单中的错误但没有原始数据,则会再次向其显示表单错误及其原始数据?

1 个答案:

答案 0 :(得分:1)

正如MYYN所说,请看这里:http://docs.djangoproject.com/en/dev/topics/forms/#using-a-form-in-a-view

ModelForms也是Forms,使用它们也没有什么不同。

if request.method == 'POST': # If the form has been submitted...
    form = ContactForm(request.POST) # A form bound to the POST data
    # now your form contains the values submitted
else:  
    form = ContactForm() # empty form

django表单应始终返回错误及其最初提交的数据。

如果您做了类似的事情,例如将空字典传递给表单,那么获取错误而不是数据的唯一方法就是。

您的示例永远不会显示任何错误,因为您从未传递数据以进行验证。它总是显示一个空的形式。

初始不是传递用户提交数据的地方

f = Form(initial={'foo':'bar'})
f.is_valid()
False
f.errors # will not validate or show you errors

传递POST词典

f = Form({'foo':'bar'})
f.is_valid()
False
f.errors
{'baz': [u'This field is required.']}