Django不好请求400?

时间:2016-02-16 07:29:53

标签: python angularjs django

关于错误代码400,我已经阅读了很多关于SO的问题,并且理解问题主要是当客户端没有发送api时,api正在期待。但是,我无法解决我的错误代码400问题。我正在关注this thinkster djangular教程,在注册新用户部分,我遇到了错误的请求400.

views.py

from rest_framework import permissions, viewsets, status
from rest_framework.response import Response

from authentication.models import Account
from authentication.permissions import IsAccountOwner
from authentication.serializers import AccountSerializer


class AccountViewSet(viewsets.ModelViewSet):
    lookup_field = 'username'
    queryset = Account.objects.all()
    serializer_class = AccountSerializer

    def get_permissions(self):
        if self.request.method in permissions.SAFE_METHODS:
            return (permissions.AllowAny(),)

        if self.request.method == 'POST':
            return (permissions.AllowAny(),)

        return (permissions.IsAuthenticated(), IsAccountOwner(),)

    def create(self, request):
        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            Account.objects.create_user(**serializer.validated_data)

            return Response(serializer.validated_data, status=status.HTTP_201_CREATED)

        return Response({
            'status': 'Bad request',
            'message': 'Account could not be created with received data.'
        }, status=status.HTTP_400_BAD_REQUEST)

这里的create方法是否应该覆盖CreateModelMixin Class中的create方法?

这是我的serializers.py

from django.contrib.auth import update_session_auth_hash

from rest_framework import serializers

from authentication.models import Account


    class AccountSerializer(serializers.ModelSerializer):
        password = serializers.CharField(write_only=True, required=False)
        confirm_password = serializers.CharField(write_only=True, required=False)

        class Meta:
            model = Account
            fields = ('id', 'email', 'username', 'created_at', 'updated_at',
                      'first_name', 'last_name', 'tagline', 'password',
                      'confirm_password',)
            read_only_fields = ('created_at', 'updated_at',)

            def create(self, validated_data):
                return Account.objects.create_user(**validated_data)

            def update(self, instance, validated_data):
                instance.username = validated_data.get('username', instance.username)
                instance.tagline = validated_data.get('tagline', instance.tagline)

                instance.save()

                password = validated_data.get('password', None)
                confirm_password = validated_data.get('confirm_password', None)

                if password and confirm_password and password == confirm_password:
                    instance.set_password(password)
                    instance.save()

                update_session_auth_hash(self.context.get('request'), instance)

                return instance

使用序列化程序的.save()方法创建对象时,将按字面设置对象的属性。这意味着注册密码“password”的用户将其密码存储为“密码”。这有几个原因:1)以明文形式存储密码是一个巨大的安全问题。 2)Django在比较之前散列并加密密码,因此用户无法使用“密码”作为密码登录。 我们通过覆盖此视图集的.create()方法并使用Account.objects.create_user()创建Account对象来解决此问题。

真的一无所知... ...

2 个答案:

答案 0 :(得分:0)

之后尝试serializer.errors
if serializer.is_valid():
            Account.objects.create_user(**serializer.validated_data)

            return Response(serializer.validated_data, status=status.HTTP_201_CREATED)

这样做会给你这样的错误

[{'username': [u'This field cannot be blank.']}, this might help you in finding out what is missing in your request.
顺便说一下,我本来可以把它放在评论中,但还没有特权。

答案 1 :(得分:0)

我也遇到了同样的问题。最后解决了,使用下面的代码。这将显示控制台错误以理解问题。

views.py

import json

from django.contrib.auth import authenticate, login, logout

from rest_framework import permissions, status, views, viewsets
from rest_framework.response import Response

from authentication.permissions import IsAccountOwner
from authentication.models import Account
from authentication.serializers import AccountSerializer

from django.http import HttpResponse
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser

class JSONResponse(HttpResponse):
    """
    An HttpResponse that renders its content into JSON.
    """
    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)

class AccountViewSet(viewsets.ModelViewSet):
    lookup_field = 'username'
    queryset = Account.objects.all()
    serializer_class = AccountSerializer

    def get_permissions(self):
        if self.request.method in permissions.SAFE_METHODS:
            return (permissions.AllowAny(),)

        if self.request.method == 'POST':
            return (permissions.AllowAny(),)

        return (permissions.IsAuthenticated(), IsAccountOwner(),)

    def create(self, request):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            Account.objects.create_user(**serializer.validated_data)

            return Response(serializer.validated_data, status=status.HTTP_201_CREATED)
        return JSONResponse(serializer.errors, status=400)