Question

I have the following form:

class GroupForm(forms.ModelForm):
    class Meta:
        model = Group

    def __init__(self, customer):
        self.customer = customer
        super(GroupForm, self).__init__()

    def clean(self):
        cleaned_data = super(GroupForm, self).clean()
        email = cleaned_data.get('email')

        print email

        try:
            groups = Group.objects.filter(email=email, customer=self.customer)
            if groups:
                messsge = u"That email already exists"
                self._errors['email'] = self.error_class([messsge])
        except:
            pass

        return cleaned_data 

I call the form from the view like so:

if request.method == "POST":
    form = GroupForm(request.POST, customer, instance=group)
    if form.is_valid():
        form.save()

The problem is that the validation is never triggered. Also the print of the email is never hit which means the clean function is never hit.

Why is this occurring?

Was it helpful?

Solution

I see this problem a lot here on SO, and the cause is usually the same. You have overridden the init method and changed the signature, so that the first element is now customer, not data. But when you instantiate it in your view, you pass request.POST first, so the parameters don't match up to the right variables.

In addition, you don't pass the parameters into the super method, so the POST is never even seen.

Do this instead:

class GroupForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.customer = kwargs.pop('customer', None)
        super(GroupForm, self).__init__(*args, **kwargs)

and in the view:

form = GroupForm(request.POST, customer=customer, instance=group)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top