在django rest框架

时间:2016-01-04 12:20:29

标签: python django django-rest-framework

我正在尝试使用django rest框架扩展User类并为其编写序列化程序,我正在尝试将mobileNumber字段添加到User。以下是我正在使用的代码:

models.py

from django.db import models

# Create your models here.
    from django.contrib.auth.models import User

class ValidateMeUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    mobileNumber = models.BigIntegerField(blank=True, null=True)

serializers.py

from django.contrib.auth.models import User
from rest_framework import viewsets
from rest_framework import serializers
from phone.models import ValidateMeUser

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'email','password')
    extra_kwargs = {'password': {'write_only': True}, }

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user


class ValidateMeUserSerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = ValidateMeUser
        fields = ('mobileNumber','user')

    def create(self, validated_data):
        user_data = validated_data.pop('user')
        user = User.objects.create_user(**user_data)
        validateMeUser = ValidateMeUser.objects.create(user=user, **validated_data)
        return validateMeUser

views.py

from django.shortcuts import render

# Create your views here.

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

from phone.serializers import ValidateMeUserSerializer
from phone.models import ValidateMeUser

@api_view(['GET', 'POST'])
def user_list(request):
    """
    List all snippets, or create a new snippet.
    """
    if request.method == 'GET':
        users = ValidateMeUser.objects.all()
        serializer = ValidateMeUserSerializer(users, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = ValidateMeUserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

urls.py

from django.conf.urls import include, url
from django.contrib import admin
from phone import views

urlpatterns = [
    url(r'^list/$', views.user_list),
    url(r'^admin/', include(admin.site.urls)),
]

当我运行curl命令时,我收到以下消息:

curl --data "username=user123455&password=sdasd&mobileNumber=2618221" http://127.0.0.1:8000/list/

{"user":{"username":["This field is required."],"password":["This field is required."]}}

在我看来,UserSerializer要么没有被调用,要么没有正确初始化。任何人都可以帮助我解决可能导致此问题的原因。提前谢谢。

1 个答案:

答案 0 :(得分:0)

您正在定义嵌套的序列化程序并提供平面数据。 如果您想保持数据平坦,您只需要一个序列化程序并为其添加额外的字段:

class ValidateMeUserSerializer(serializers.ModelSerializer):
    username = serializers.CharField(...)
    email = serializers.CharField(...)
    password = serializers.CharField(...)

    class Meta:
        model = ValidateMeUser
        fields = ('mobileNumber', 'username', 'email', 'password')

    def create(self, validated_data):
        username = validated_data.pop('username')
        ...
        user = User.objects.create_user(username=username, ...)
        validateMeUser = ValidateMeUser.objects.create(user=user, **validated_data)
        return validateMeUser