Django UserCreationForm not responding when button clicked with input in fields

Viewed 104

I'm having trouble getting my register application in Django to work. I am using the built-in UserCreationForm form. I can go to the URL and the form shows up but when I put info into the fields and click the submit button nothing happens. It should pop up an error screen saying "missing the csrf_field" (I know this because I'm following TechWithTim's tutorial and that's what happens to him). But when I click the "Register" button nothing happens.

views.py:

from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm

# Create your views here.
def register(response):
    form = UserCreationForm()
    return render(response, "register/register.html", {"form":form})

register.html:

{% extends "main/base.html" %}

{% block title %}Create an Account{% endblock %}

{% block content %}
    <form method="POST" class="form-group">
        {{form}}
        <button type="submit" class="btn btn-success">Register</button>
    </form>
{% endblock %}

urls.py:

from django.contrib import admin
from django.urls import path, include
from register import views as v

urlpatterns = [
    path('', include("main.urls")),
    path("register/", v.register, name="register"),
    path('admin/', admin.site.urls),
]

main/urls.py

from django.urls import path

from . import views

urlpatterns = [
path("<int:id>", views.index, name='index'),
path("", views.home, name='home'),
path("create/", views.create, name='create'),
]

I added the application to my settings.py file as well.

This is my first question on here and I tried to format it properly so sorry if I didn't

1 Answers

In order for Django to recieve the data the user entered in the form, you need to pass the request's POST data to the form, if it exists. That would look like this:

form = UserCreationForm(response.POST)

But note that response.POST will not exist if it's not a POST request. (For example, if the user is viewing the form for the first time.) The Django docs have an example of how to process form data.

Alternatively, you can look at the tutorial you're using, which has an example of how to get the POST data out of the form:

# views.py
from django.shortcuts import render, redirect
from .forms import RegisterForm


# Create your views here.
def register(response):
    if response.method == "POST":
        form = RegisterForm(response.POST)
        if form.is_valid():
            form.save()

        return redirect("/home")
    else:
        form = RegisterForm()

    return render(response, "register/register.html", {"form":form})

(Source.)

Related