[FIXED] Admin User model

Issue

Admin user model does not update new records when registered using UserCreationForm.

Go to github code

Her Usercreationform is shown below with imported views and I did all the coding for the views. I don’t know where I went wrong. It also rendered the form correctly in the template. But the annoying part is after filling out the form. Even if I access it, it is not updated in the admin panel

// view

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

Deaf Home (request):
    If request.method == "POST":
        Form = UserCreationForm(request.POST)
        For form.is_valid() :
            form.save()
    context = {'form':form}
    return render(request, 'main/index.html', context)

// template




    
    
    
    Documents


    
{% csrf_token %} {{form.as_p}}

Solution

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

Answer Checked By – Marie Seifert (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published