Sorry if this is a noob question. I'm creating a login form for a Django app, but I'm having trouble getting it to work. request.POST.get() doesn't return anything, so the authentication always fails. Am I missing something obvious?
login.html:
{% extends "base.html" %}
{% block content%}
<h2>Welcome! Please login to continue.</h2> <br>
<form action="{% url 'account:authenticate' %}" method="post">
{% csrf_token %}
<div >
<label for='username'> Username: </label>
<input type='text' name='Username' id='username'> <br><br>
<label for='password'>Password: </label>
<input type='password' name='Password' id='password'><br><br>
<input type='submit' value='Login'>
</div>
</form>
relevant part of views.py:
from django.shortcuts import render, get_object_or_404
from datetime import datetime
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.template import loader
from random import randrange
from django.contrib.auth import authenticate
def login(request):
return render (request, 'login.html')
def authenticate(request):
usern = request.POST.get('username', '')
passw = request.POST.get('password', '')
user = authenticate(username = usern, password = passw)
if user is not None:
authenticate.login(request, user)
return HttpResponseRedirect('/voters/instructions')
else:
return HttpResponseRedirect('/account/loginfail')
def loginfail(request):
return render (request, 'loginfail.html')
I'm using Django 1.10. Thanks!
GET and POSTDjango's login form is returned using the POST method, in which the browser bundles up the form data, encodes it for transmission, sends it to the server, and then receives back its response. GET , by contrast, bundles the submitted data into a string, and uses this to compose a URL.
When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function. Each view is responsible for returning an HttpResponse object.
It shows the MIME type of the request, parsed from the CONTENT_TYPE header. It returns a dictionary of key/value parameters included in the CONTENT_TYPE header. It returns a dictionary-like object containing all given HTTP GET parameters. It is a dictionary-like object containing all given HTTP POST parameters.
The result of request. method == "POST" is a boolean value - True if the current request from a user was performed using the HTTP "POST" method, of False otherwise (usually that means HTTP "GET", but there are also other methods).
Check out the names in the form input fields they are case sensitive. in Django do this
usern = request.POST.get('Username', '')
passw = request.POST.get('Password', '')
or in html form make them lowercase the input name field
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