pynovice
pynovice

Reputation: 7752

Form validation error message is not shown in ModelForm

I have a Model like this:

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 of the above model looks like this:

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

In my views, I am doing like this:

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

If all the forms data are filled, it successfully redirects to / but if data are not filled it redirects to website/profile.html with the form. But error messages All fields are required are not shown. What's wrong?

Upvotes: 1

Views: 1565

Answers (1)

Jesus Anaya
Jesus Anaya

Reputation: 46

Your error is that you are creating a new form when you want to send the error to template, you need send your object "form" and not "profile_form" for include the error information.

Regards.

Upvotes: 1

Related Questions