使用POST时Django中的MultiValueDictKeyError [英] MultiValueDictKeyError in Django when use POST

查看:839
本文介绍了使用POST时Django中的MultiValueDictKeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Django休息框架的新手,被要求写入我们项目的令牌认证部分。有一点需要注意的是,我将来不会使用默认的管理员网站,我写了登录,注销,注册功能,并通过POSTMAN测试功能。我现在要做的是让新用户注册,登录和注销。当用户登录时,我发给他/她一个令牌。一切都只是以最简单的方式表演。



但是我仍然无法解决问题。我搜索了所有相关问题,但仍然无法解决我的问题。如果有人知道该怎么办,请帮我!
以下是详细信息。



当我使用GET时,一切都正常。但是当我使用POST时,我得到MultiValueDictKeyError。我不知道为什么。



View.py

来自rest_framework.response的回应
从django.contrib.auth导入验证
从rest_framework.authtoken.models导入令牌
从rest_framework导入状态
从django .contrib.auth.models import来自rest_framework.authentication import的用户
来自rest_framework.permissions import的
从rest_framework.permissions import导入IsAuthenticated
从django.contrib.auth.signals导入user_logged_in,user_logged_out
从rest_framework .decorators import di_view,authentication_classes,permission_classes
from django.views.decorators.csrf import csrf_exempt,requires_csrf_token
@csrf_exempt
@requires_csrf_token
@api_view(['POST'])
def create_user_view(request):
如果request.method =='POST':
username = request.POST ['username']
email = request.POST ['email']
password = request.POST ['password']
user = User.objects.create_user(username = username,email = email,password = password)
user.save()
return Response({'detail':Create user})


@csrf_exempt
def login_view(request):
如果request.method =='POST':
username = request.POST ['username']
password = request.POST ['password']
user = authenticate(username = username ,password = password)
如果用户不是None:
user_logged_in.send(sender = user .__ class__,request = request,user = user)
token = Token.objects.get_or_create(user = user)
return响应({
'detail':'POST答案','标记':令牌[0] .key,
})
else:
return响应({'detail':
状态:status.HTTP_404_NOT_FOUND})

@csrf_exempt
def logout_view(请求):
如果request.method = ='POST':
user = getattr(request,'user',None)
如果hasattr(user,'is_authenticated')而不是user.is_authenticated():
user = None
user_logged_out.send(sender = user .__ class__,request = request,user = user)
if hasattr(request,'user'):
from django.contrib.auth.models import AnonymousUser

request.user = AnonymousUser()
返回响应({'detail':您已经成功注销)

Test_app / Urls.py

  from django.conf.urls import patterns,url 
from rest_framework.urlpatterns import format_suffix_patterns
from test_app import views
urlpatterns = patterns('test_app.views',
url(r'^ signup',views.create_user_view),
url(r'^ login',views.login_view),
url(r'^ logout',views.logout_view),
url(r'^ auth',views.AuthView),

urlpatterns = format_suffix_patterns(urlpatterns)

Models.py(是的,我只在文件中放了两行)

 从django.db导入模型

我也修改了settings.py,如教程所说。



现在的问题是:

 请求方式:POST 
请求URL:http://127.0.0.1:8000/signup?username=haha&email=haha@gmail.com&password=okok
Django版本:1.8.2
异常类型:MultiValueDictKeyError
异常值:
'username'
异常位置:/Users/wyq/PycharmProjects/env/lib/python2.7/site-packages/django/utils/datastructures.py __getitem__,第322行

任何人都可以帮忙?非常感谢!

解决方案

MultiValueDictKeyError 发生在 QueryDict 当您尝试访问的密钥不存在于QueryDict。您的请求方法说POST,但是url方案表明您传递的参数将会转到 request.GET dict。



您需要通过表单或其他东西提交参数,以便在 request.POST中访问.POST QueryDict


I am new to Django rest framework and was asked to write the token authentication part of our project. One thing to note is, as I would use not use the default admin site in future, I write login, logout, signup functions, and test the functionality by POSTMAN. What I want to do now is to let new user signup, login and logout. When a user log in, I issue him/her a token. Everything just perform in the easiest way.

But I still can't work it out. I searched all the related questions but still cannot solve my problem. If someone know how to do, please help me! Following is the details.

When I am using GET, everything works fine. But when I am using POST, I get MultiValueDictKeyError. I don't know why.

View.py

    from rest_framework.response import Response
    from django.contrib.auth import authenticate
    from rest_framework.authtoken.models import Token
    from rest_framework import status
    from django.contrib.auth.models import User
    from rest_framework.authentication import TokenAuthentication
    from rest_framework.permissions import IsAuthenticated
    from django.contrib.auth.signals import user_logged_in, user_logged_out
    from rest_framework.decorators import api_view, authentication_classes, permission_classes
    from django.views.decorators.csrf import csrf_exempt, requires_csrf_token
    @csrf_exempt
    @requires_csrf_token
    @api_view(['POST'])
    def create_user_view(request):
        if request.method == 'POST':
            username = request.POST['username']
            email = request.POST['email']
            password = request.POST['password']
            user = User.objects.create_user(username=username, email=email,     password=password)
            user.save()
            return Response({'detail': "Create user"})


    @csrf_exempt
    def login_view(request):
         if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
         if user is not None:
            user_logged_in.send(sender=user.__class__, request=request, user=user)
            token = Token.objects.get_or_create(user=user)
            return Response({
                           'detail': 'POST answer', 'token': token[0].key,
                           })
        else:
            return Response({'detail': "The username or password were incorrect.",
           status: status.HTTP_404_NOT_FOUND})

    @csrf_exempt
    def logout_view(request):
        if request.method == 'POST':
            user = getattr(request, 'user', None)
            if hasattr(user, 'is_authenticated') and not user.is_authenticated():
                user = None
                user_logged_out.send(sender=user.__class__, request=request, user=user)
            if hasattr(request, 'user'):
                 from django.contrib.auth.models import AnonymousUser

                 request.user = AnonymousUser()
           return Response({'detail': "You have logged out successfully."})

Test_app/Urls.py

    from django.conf.urls import patterns, url
    from rest_framework.urlpatterns import format_suffix_patterns
    from test_app import views
    urlpatterns = patterns('test_app.views',
                           url(r'^signup', views.create_user_view),
                           url(r'^login', views.login_view),
                           url(r'^logout', views.logout_view),
                           url(r'^auth', views.AuthView),
                           )
    urlpatterns = format_suffix_patterns(urlpatterns)

Models.py(Yes, I only put two lines in the file)

    from django.contrib.auth.models import User
    from django.db import models

I also modified settings.py as tutorial said.

The problem now is:

Request Method: POST
Request URL:    http://127.0.0.1:8000/signup?username=haha&email=haha@gmail.com&password=okok
Django Version: 1.8.2
Exception Type: MultiValueDictKeyError
Exception Value:    
"'username'"
Exception Location: /Users/wyq/PycharmProjects/env/lib/python2.7/site-packages/django/utils/datastructures.py in __getitem__, line 322

Can anyone help? Thank you very much!

解决方案

MultiValueDictKeyError occurs in a QueryDict when the key you are trying to access is not present in the QueryDict. Your request method says POST but the url scheme suggests that the parameters you are passing will go the request.GET dict.

You need to submit the parameters via a form or something for them to be accessible in the request.POST QueryDict

这篇关于使用POST时Django中的MultiValueDictKeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆