Search code examples
pythondjangopython-3.xdjango-registration

How to diagnose a Django registration form that appears to do nothing?


I'm making a registration system for my django website and this registration form isn't working. I don't know why, I fill out the form and it does nothing. It doesn't redirect to my register_success page. Here is my code so you can help diagnose the issue.

Views.py:

def register_user(request):
    if request.method == 'post':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/accounts/register_success')

    args = {}
    args.update(csrf(request))
    args['form'] = UserCreationForm()
    print(args)
    return render_to_response('register.html', args)


def register_success(request):
    return render_to_response('register_success.html')

Register.html:

<html>
<body>
{% block content %}
    <h2>Register</h2>
    <form action="/accounts/register/" method="post">{% csrf_token %}
        {{ form }}
        <input type="submit" value="Register"/>
    </form>
{% endblock %}
</body>
</html>

Register_success.html:

<html>
<body>
{% block content %}
    <h2>You have registered</h2>
    <p>Click <a href="/accounts/login/">here</a> to login.</p>
{% endblock %}
</body>
</html>

Solution

  • The problem is that you are always creating a blank form. This means that you will not see any errors in your form.

    args['form'] = UserCreationForm()
    

    You can fix this by changing your view as follows.

    from django.shortcuts import render
    
    def register_user(request):
        if request.method == 'POST':
            form = UserCreationForm(request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect('/accounts/register_success')
        else:
            form = UserCreationForm()
    
        return render(request, 'register.html', {'form': form})
    

    Note that the first if statement should be if request.method == 'POST':, as spotted by yedpodtrzitko in their answer. I've switched from the deprecated render_to_response to render, which simplifies things. I recommend you update your success view as well.

    def register_success(request):
        return render(request, 'register_success.html')