Mike Nielsen
Mike Nielsen

Reputation: 331

Django form with __init__ doesn't clean fields

I have a django form I'm attempting to add CAPTCHA support to. However, this requires me to pass request.session to the form. To accomplish that, I added this constructor to the form:

def __init__(self, request=None, *args, **kwargs):
    super(RegistrationForm, self).__init__(*args, **kwargs)
    self.request = request

I then instantiate the RegistrationForm by passing the request object to it. However, when submitting the form, it fails to clean any of the fields. It just fails validation and passes a blank field back to the template. Here is the registration code that fails:

if request.method == 'POST':
    form = RegistrationForm(request.POST)
    if form.is_valid():
        ...do registration...
    else:
        return render(request, 'template.htm', {'form': form})

No matter what I put in the fields, it never validates. In fact, it doesn't even look like it cleans the fields. I just get back a new blank form after hitting the register button, no errors, nothing.

Any ideas?

Upvotes: 0

Views: 733

Answers (1)

Derek Kwok
Derek Kwok

Reputation: 13078

Based on the code you posted, it looks as though you are passing request.POST into the request parameter for your RegistrationForm. i.e. you are doing the equivalent of:

form = RegistrationForm(request=request.POST)

What you really want to do is this:

form = RegistrationForm(request=request, data=request.POST)

Try this and see if it works for you.

Upvotes: 2

Related Questions