skip to Main Content

I was trying to create register page by using UserCreationForm but getting empty QueryDict from post method when I print it on console. There is no errors. I did research on it but could not figure it out.

this is views.py file

from django.shortcuts import render,redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import UserCreationForm
# Create your views here.
def register(request):
    print('nnnn',request.POST,'nnn')
    if request.method   == 'POST':
        form=UserCreationForm()
        if form.is_valid():
            form.save()
        return redirect('home/')
    else:
        form=UserCreationForm()
    context={'form':form}   

    return render(request,'register/register.html',context)

and this is my template:

{% extends 'base/base.html' %}

{% block content %}

<form method="POST" class="form-group" action="#%">
    {% csrf_token %}
    {{form}}
    <button type="submit", name="register", value="register1", class="btn btn-success" > Register </button>
</form>

{% endblock %}

When I hit register button on website I am getting this traceback:

September 21, 2023 - 10:00:05
Django version 4.2.5, using settings 'proproject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

<QueryDict: {}> 

[21/Sep/2023 10:00:11] "GET /register/ HTTP/1.1" 200 3702

<QueryDict: {}> 

[21/Sep/2023 10:00:11] "GET /register/ HTTP/1.1" 200 3702

Thanks for advance!

2

Answers


  1. You are initializing your form but not supplying any data to it. Change:

    if request.method == 'POST':
        form = UserCreationForm() #thisline
    

    To:

    if request.method == 'POST':
        form = UserCreationForm(request.POST)
    

    Should fix the empty dict you are getting back.

    Login or Signup to reply.
  2. I think it would be form=UserCreationForm(request.POST) instead of form=UserCreationForm(). because you are sending an empty form like that in the code. You have to populate the form by request.POST.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search