Forums

"if request.method == 'POST':" seems to fail

Hi I have a very bizarre problem. I have a very simple registration form, which doesn't react at all when filling out. I can't see any errors logged. And because the submit button doesn't react at all I assume that the

if request.method == 'POST':

fails silently.

Do you see any errors? What do I miss?

forms.py

from django import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _

class RegistrationForm(forms.Form):

    username = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Username"), error_messages={ 'invalid': _("This value must contain only letters, numbers and underscores.") })
    email = forms.EmailField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Email address"))
    password1 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password"))
    password2 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password (again)"))

    def clean_username(self):
        try:
            user = User.objects.get(username__iexact=self.cleaned_data['username'])
        except User.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError(_("The username already exists. Please try another one."))

    def clean(self):
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError(_("The two password fields did not match."))
        return self.cleaned_data

views.py:

from django.shortcuts import render

from accounts.forms import RegistrationForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
from django.views.decorators.csrf import csrf_protect
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.contrib.auth.models import User

@csrf_protect
def ClientRegistration(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
            username=form.cleaned_data['username'],
            password=form.cleaned_data['password1'],
            email=form.cleaned_data['email']
            )
            user.save()
            return HttpResponseRedirect('/accounts/RegSuccess/')
    else:
        form = RegistrationForm()
    #context = {'form': form}


    #return render(request, 'registration.html', context)

    variables = RequestContext(request, {
    'form': form
    })
    return render_to_response(
    'registration.html',
    variables,
    )

registration.html

<section id="about">
        <div class="container-fluid">
            <div class="row text-center">
                <div class="col-lg-12">

                    <hr class="colored">
                </div>
            </div>
            <div class="container-fluid">
            <div class="row text-center content-row">

                    <form action="/accounts/ClientRegistration/" method="post">{% csrf_token %}
                    {{ form.as_p }}
                    <input type="submit" value="Submit" />
                    </form>

            </div>
            </div>
        </div>
</section>

I don't see anything obviously wrong. When you say

the submit button doesn't react at all

...does anything happen at all? That is, does the page reload, for example?

Could you give us a URL where we could try hitting the form ourselves?

The form is here:

http://kbrothers.pythonanywhere.com/accounts/ClientRegistration/

No the page does not reload

Very strange I tried the following:

In the statement:

if request.method == 'POST':

I added after "else":

return HttpResponseRedirect('/main_app/index/')

Now the registration page doesn't open. I'm immediately redirected to the home page.

I guess you backed out the last change, because when I go to http://kbrothers.pythonanywhere.com/accounts/ClientRegistration/ I get a registration form.

The error appears to be that your app is using jQuery, but it's not being loaded -- check out the JavaScript console to see the error. It looks like you're trying to load it from http://kbrothers.pythonanywhere.com/static/js/jquery.min.map -- I can see that you do have a static file mapping set up for /static/, but without looking at your files (which we never do without your permission) I can't tell whether the directory you have set up there contains a directory called js which has a file called jquery.min.map. Could you check?

Indeed there is no jquery.min.map @giles. please have a look yourself in my directory

Right, I can see that there is a file called jquery-1.10.2.js. So you need to either change the template to match the filename, or rename the file to match the template.

but

<script src="{{STATIC_URL}}js/jquery-1.10.2.js"></script>

is loaded in my base.html

Hmm, good point. So something else is trying to load the one without the version number -- though I must admit I can't see what it might be. And perhaps that's not really what's causing the problem.

However, it's definitely worth looking more into what happens in the JavaScript when you try to register on that page. I see an error like this:

Uncaught TypeError: Cannot read property 'indexOf' of undefined contact_me.js:17
$.jqBootstrapValidation.submitSuccess contact_me.js:17
(anonymous function) jqBootstrapValidation.js:76
x.event.dispatch jquery-1.10.2.js:5
v.handle jquery-1.10.2.js:5

Now, at line 17 in contact_me.js, we see this:

        var name = $("input#name").val();
        var email = $("input#email").val();
        var phone = $("input#phone").val();
        var message = $("textarea#message").val();
        var firstName = name; // For Success/Failure Message
        // Check for white space in name for Success/Fail message
        if (firstName.indexOf(' ') >= 0) {

Line 17 is the last one. So, firstName is undefined. So we try entering $("input#name") into the JS console, and we get this:

> $("input#name")
< []

Which means that there's no input with the ID name. Indeed, looking at the form, it looks like there's no phone number either. So my guess is that you've got some kind of JavaScript validation logic attached to this form that's actually meant for another form somewhere else. Does that sound plausible?

Thank you so much for the hint. I found the problem. It was

<script src="{{STATIC_URL}}js/plugins/jqBootstrapValidation.js"></script>

that caused the problem. I'm not sure really why but there must have been some interference with some form functionalities.

As usual thanks a lot Giles!

Excellent, glad I could help :-)