Django:如何显示每个模型对象的表单错误

时间:2013-05-16 11:48:29

标签: django django-forms django-templates django-admin django-views

views.py

def add_phone(request):
    user=request.user
    try:
        phone = Phone_info.objects.get(user=request.user)
    except:
        phone = None
    save_msg = ''
    form_error = False
    phoneForm = PhoneForm({'user':request.user})
    phoneForm = PhoneForm(instance=phone)
    if request.method=='POST':
        phoneForm = PhoneForm(request.POST,instance=phone)    
        if phoneForm.is_valid():
            phone=phoneForm.save(commit=False)
            phone.user = user
            phone.save()
            save_msg = "Your details have been saved"


    return render_to_response('incident/add_phone.html',
    {
    'about_menu': True,
    'PhoneForm' :phoneForm,
    'save_msg':save_msg,
    'form_error':form_error,
    },
    context_instance=RequestContext(request))

forms.py

class PhoneForm(forms.ModelForm):
    emergency = forms.CharField(required=True)
    emergency_number = forms.IntegerField(required=True)
    class Meta:
        model = Phone_info
        fields = ['name1','number1','name2','number2','name3','number3','emergency','emergency_number']


def clean(self):
    name1 = self.cleaned_data.get("name1", None)
    number1 = self.cleaned_data.get("number1", None)
    name2 = self.cleaned_data.get("name2", None)
    number2 = self.cleaned_data.get("number2", None)
    name3 = self.cleaned_data.get("name3", None)
    number3 = self.cleaned_data.get("number3", None)
    if name1 and not number1:
        raise forms.ValidationError("This field is required")
    if number1 and not name1:
        raise forms.ValidationError("This field is required")
    if name2 and not number2:
        raise forms.ValidationError("This field is required")
    if number2 and not name2:
        raise forms.ValidationError("This field is required")
    if name3 and not number3:
        raise forms.ValidationError("This field is required")
    if number3 and not name3:
        raise forms.ValidationError("This field is required")

    return self.cleaned_data

template.html

<table width="100%"  cellpadding="0" cellspacing="0" id="phone">

                <tr>
                    <td colspan="2"><h1 align="left">Call - default telephone numbers</h1>        </td>

                <tr>
                    <td>Person or area</td>
                    <td>Phone number</td>
                </tr>

                <tr>
                    <td>{{ PhoneForm.name1 }}{{ PhoneForm.name1.errors }}</td>
                    <td>{{ PhoneForm.number1 }}{{ PhoneForm.number1.errors }}</td>
                </tr>
                <tr>
                    <td>{{ PhoneForm.name2 }}{{ PhoneForm.name2.errors }}</td>
                    <td>{{ PhoneForm.number2 }}{{ PhoneForm.number2.errors }}</td>
                </tr>
                <tr>
                    <td>{{PhoneForm.name3}}{{ PhoneForm.name3.errors }}</td>
                    <td>{{PhoneForm.number3}}{{ PhoneForm.number3.errors }}</td>
                </tr>
                <tr>
                    <td>Emergency</td><td>Phone number</td>
                </tr>
                <tr>
                    <td>{{ PhoneForm.emergency }}{{ PhoneForm.emergency.errors }}</td>
                    <td>{{ PhoneForm.emergency_number }}{{ PhoneForm.emergency_number.errors }}</td>
                </tr>
                <tr><td colspan="2" align="right"> <p style=margin-top:2cm;>{% include "buttons/save.html" %}</p></td></tr>

            </table></form>

它没有抛出表单验证的个别错误消息。我正在使用PhoneForm并且对于单个字段,应该发生个别错误消息。我检查了它,我无法找到我遗漏的东西。这可能是愚蠢的需要帮助修复。

由于

1 个答案:

答案 0 :(得分:2)

但是你没有对各个字段进行检查。您正在定义整体clean()方法,并抛出一般错误 - 您所说的只是“此字段是必需的”,而不定义您正在谈论的字段。我不知道你对Django的了解程度如何。

正常的做法是覆盖特定的字段清理方法,例如clean_number1等。你不这样做是正确的,因为每个字段都取决于另一个字段,所以clean()是正确的的地方。

但正如文档所示,您可以使用常规clean方法inject field-specific errors

self._errors['number1'] = self.error_class(['This field is required'])
del self.cleaned_data['number1']