I'm trying to create a login form for my site but when I use cleaned_data in my views.py I don't get the right data.
here is my code:
views.py
def login_page(request):
form = LoginForm(request.POST or None)
context = {
'form': form
}
if form.is_valid():
print(form.cleaned_data)
username = form.cleaned_form.get("username")
password = form.cleaned_form.get("password")
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect("/")
else:
print("Error")
return render(request, "auth/login.html", context)
forms.py
class LoginForm(forms.Form):
username = forms.CharField(
widget=forms.TextInput(
attrs={
"class": "form-control",
"placeholder": "Username"
}
)
)
password = forms.CharField(
widget=forms.PasswordInput(
attrs={
"class": "form-control",
"placeholder": "Password"
}
)
)
login.html
<form action="POST">{% csrf_token %}
{{ form }}
<button type="submit" class="btn btn-default">Submit</button>
</form>
and here is what I get when I fill username and password field and click on submit. print(form.cleaned_data)
shows there is data in url fields that I want to use but I can't access them.
your view is totally wrong, use this
def login_page(request):
form = LoginForm(request.POST or None)
context = {
'form': form
}
if request.method == 'POST':
if form.is_valid():
print(form.cleaned_data)
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect("/")
else:
print("Error")
else:
print('form not valid')
return render(request, "auth/login.html", context)
and html to
<form method="post" action="">
{% csrf_token %}
{{ form }}
<button type="submit" class="btn btn-default">Submit</button>
</form>
You have an error in your HTML - you should use method="post"
instead of action
. Right now you're sending GET at /login/POST
with inputs as query parameters instead of POST at /login
. This is evident in the screenshot you attached.
Valid form should look like:
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit" class="btn btn-default">Submit</button>
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With