1

我有一个这样的模型:

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但未显示错误消息。怎么了?

4

1 回答 1

1

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

问候。

于 2013-10-01T06:08:31.450 回答