Error404
Error404

Reputation: 45

How can I fix Django error MultiValueDictKeyError

I try to log a user but I have this error: MultiValueDictKeyError at / "'username'". I followed django documentation: https://docs.djangoproject.com/en/1.7/topics/auth/default/#django.contrib.auth.decorators.login_required

views:

def home(request):

    return render_to_response('home.html', {}, context_instance=RequestContext(request))


def login_user(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect('start.html')
        else:
            return HttpResponseRedirect('profile.html')
    else:
        return HttpResponseRedirect('home.html')

url:

 url(r'^$', 'core.views.login_user', name='login_user'),

html:

<form action="/login_user" method="POST" name="auth">
  {% csrf_token %}
  <label>Email</label>
  <input type="text" name="username">
  <label>Password</label>
  <input type="password" name="password">
  <button type="submit">Login</button>
</form>

Upvotes: 1

Views: 4771

Answers (2)

Alex Lord Mordor
Alex Lord Mordor

Reputation: 3040

I see many errors in your code.

You are pointing your form action to /login_user and in your URL you don't have any /login_user defined so when you enter to root / it will load the login_user function.

I recommend you to do this:

Change your view to something like this:

def login_user(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('home'))
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            usuario = request.POST['username']
            clave = request.POST['password']
            acceso = auth.authenticate(username=usuario, password=clave)
            if acceso is not None:
                if acceso.is_active:
                    login(request, acceso)                        
                    return HttpResponseRedirect(reverse('home'))
                else:
                    form = AuthenticationForm()
                    script = "alert('Usuario no activo');"
                    return render(request, 'login.html', locals())
            else:
                form = AuthenticationForm()
                script = "alert('Usuario y/o contraseña invalida');"
                return render(request, 'login.html', locals())
    else:
        form = AuthenticationForm()
    return render(request, 'login.html', locals())

in your template (login.html)

<form action="{% url "login" %}" method="post" accept-charset="utf-8">
    {{ form }}
    {% csrf_token %}
    <input class="btn btn-default" type="submit" value="Iniciar Sesión" />
</form>

in your urls.py:

url(r'^$', 'core.views.home', name='home'),
url(r'^login/$', 'core.views.login_user', name='login'),

With this a nice form will be shown ;)

Upvotes: 0

warchinal
warchinal

Reputation: 229

This question might help you:

Use the MultiValueDict's get method. This is also present on standard dicts and is a way to fetch a value while providing a default if it does not exist.

username = request.POST.get("username", False)
password = request.POST.get("password", False)

Upvotes: 1

Related Questions