如何修复Django错误MultiValueDictKeyError

时间:2015-01-15 20:42:14

标签: django login

我尝试记录用户但是我有这个错误:/“'username'”的MultiValueDictKeyError。我关注了django文档: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>

2 个答案:

答案 0 :(得分:1)

This question可能对您有所帮助:

使用MultiValueDict的get方法。这也存在于标准dicts上,如果不存在,则提供默认值时提取值。

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

答案 1 :(得分:0)

我在你的代码中看到很多错误。

您将表单操作指向/login_user,并且在您的网址中没有定义任何/login_user,因此当您输入root /时,它将加载login_user函数。< / p>

我建议你这样做:

将您的观点更改为以下内容:

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())
模板中的

(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>
你的urls.py中的

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

这将显示一个漂亮的表格;)