Why am I not getting clean data when I use cleaned_data

I am trying to create a login form for my site, but when I use cleaned_data in my view.py, I do not get the required 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 this is what I get when I fill out the username and password field and click "Submit." print(form.cleaned_data) shows that in the url fields there is data that I want to use, but I can’t access it.

console

+5
source share
2 answers

your view is completely 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> 
+6
source

You have a mistake in your HTML - you should use method="post" instead of action . Right now you are sending a GET to /login/POST with the input as request parameters instead of POST in /login . This can be seen in the screenshot you attached.

The actual form should look like this:

 <form method="post"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-default">Submit</button> </form> 
+4
source

Source: https://habr.com/ru/post/1274461/


All Articles