如何修复Django错误MultiValueDictKeyErr

如何修复Django错误MultiValueDictKeyErr

本文介绍了如何修复Django错误MultiValueDictKeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试登录用户,但是出现以下错误:/'用户名'"处的MultiValueDictKeyError.我遵循了django文档: https://docs.djangoproject.com/zh-CN/1.7/topics/auth/default/#django.contrib.auth.decorators.login_required

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

观看次数:

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>

推荐答案

可能会帮助您:

使用MultiValueDict的get方法.这也出现在标准字典上,并且是一种在不存在默认值的情况下获取值的方法.

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)

这篇关于如何修复Django错误MultiValueDictKeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 14:03