Admin User model

Question:

My admin user model does not update new record when I register using UserCreationForm.

Access the github code

in the views I have imported Usercreationform has shown below and I did all the views coding. I do not know where I went wrong. I also rendered the form correctly into the template. But the annoying part comes after filling the form. It doesn’t update in the admin panel once I accessed it

// View file:

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

def home(request):
    if request.method == "POST":
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
    context = {'form':form}
    return render(request, 'main/index.html', context)

// Template file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="" method="POST">
        {% csrf_token %}
        {{form.as_p}}
        <input type="submit" value="register">
    </form>
</body>
</html>
Asked By: Mathew Leggeson

||

Answers:

An excerpt from the docs:

You should always return an HttpResponseRedirect after successfully dealing with POST data. This tip isn’t specific to Django; it’s good web development practice in general.

So try the following view:

from django.shortcuts import redirect

def home(request):
    if request.method == "POST":
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect("success_page")
        else:
            return redirect("some_error_page")
    else:
        form = UserCreationForm()
    return render(request, 'main/index.html', {'form':form})

def success(request):
    return render(request, 'main/success.html')

Your urls.py should be:


urlpatterns=[
    path('', v.home, name='home')
    path('success/', v.success, name='success_page')
]

success.html

<body>
    <h1> The form has been successfully submitted. </h1>
    
    <a href="{% url 'home' %}"> Go to homepage </a>
</body>

The same URL pattern and HTML page, you can make for displaying error if the form is not valid.

You can also remove empty action attribute as Django by default takes current page route so the template should be like:

<form method="POST">
        {% csrf_token %}
        {{form.as_p}}
        <input type="submit" value="register">
</form>
Answered By: Sunderam Dubey