【问题标题】:Form validation error message is not shown in ModelForm表单验证错误消息未显示在 ModelForm 中
【发布时间】:2013-10-01 04:35:03
【问题描述】:

我有一个这样的模型:

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。怎么了?

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

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

    问候。

    【讨论】:

    • 我怎么会忘记呢?非常感谢!
    猜你喜欢
    • 2022-11-09
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    • 2022-06-20
    相关资源
    最近更新 更多