FormForm中未显示表单验证错误消息

时间:2013-10-01 04:35:03

标签: django django-forms

我有一个这样的模型:

class Client(models.Model):

    user = models.OneToOneField(User)

    # True if the signed up user is client
    is_client = models.BooleanField(default=True)   

    # Which company the client represents
    company = models.CharField(max_length=200, null=True)

    # Address of the company
    address = models.CharField(max_length=200, null=True)

    company_size = models.ForeignKey(CompanySize, null=True)

    account_type = models.ForeignKey(AccountType)

    billing_address = models.CharField(max_length=254, null=True)
上述模型的

ModelForm如下所示:

class ProfileForm(ModelForm):

    class Meta:
        model = Client
        exclude = ['user', 'is_client']


    def clean(self):

        cleaned_data = super(ProfileForm, self).clean()

        if not cleaned_data:
            raise forms.ValidationError("Fields are required.")

        return cleaned_data

在我看来,我这样做:

def post(self, request, user_id):
        # Get the profile information from form, validate the data and update the profile
        form = ProfileForm(request.POST)

        if form.is_valid():
            account_type = form.cleaned_data['account_type']
            company = form.cleaned_data['company']
            company_size = form.cleaned_data['company_size']
            address = form.cleaned_data['address']
            billing_address = form.cleaned_data['billing_address']

            # Update the client information
            client = Client.objects.filter(user_id=user_id).update(account_type=account_type, company=company,
                                            company_size=company_size, address=address, billing_address=billing_address)        

            # Use the message framework to pass the message profile successfully updated
            #messages.success(request, 'Profile details updated.')
            return HttpResponseRedirect('/')


        else:
            profile_form = ProfileForm()
            return render(request, 'website/profile.html', {'form': profile_form})

如果所有表单数据都已填充,则会成功重定向到/,但如果未填充数据,则会使用表单重定向到website/profile.html。但是未显示错误消息All fields are required。怎么了?

1 个答案:

答案 0 :(得分:1)

您的错误是当您要将错误发送到模板时创建新表单,您需要发送您的对象“表单”而不是“profile_form”以包含错误信息。

问候。