使某些字段不需要验证django

时间:2018-04-10 23:51:44

标签: django django-rest-framework

class DetailedUserViewSet(CreateModelMixin, GenericViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = (AllowAny,)
    def __init__(self, *args, **kwargs):
        super(DetailedUserViewSet, self).__init__(*args, **kwargs)
        self.fields['lit_points'].required = False
        self.fields['picture'].required = False

class UserSerializer(HyperlinkedModelSerializer):
    picture = CharField(source='userprofile.image_url')
    password =  CharField(write_only=True)
    mobile = CharField(source='userprofile.mobile')
    lit_points = IntegerField(source='userprofile.lit_points')
    location = SerializerMethodField()

    class Meta:
        model = User
        fields = ('id', 'mobile', 'first_name', 'last_name', 'email', 'password', 'picture', 'lit_points', 'location')
        readonly_fields = ('picture', 'lit_points', 'location')

现在它说字段没有定义。当我摆脱田野选项;它给了我

 "lit_points" =     (
        "This field is required."
    );
    picture =     (
        "This field is required."
    );

我正在尝试这样做,这两个字段在POST请求中不是必需的。

ERROR:

AttributeError: 'DetailedUserViewSet' object has no attribute 'fields'

1 个答案:

答案 0 :(得分:0)

从视图集中删除__init__()方法,如下所示,

class DetailedUserViewSet(CreateModelMixin, GenericViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = (AllowAny,)


或尝试这样的事情,

class DetailedUserViewSet(CreateModelMixin, GenericViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = (AllowAny,)


class UserSerializer(HyperlinkedModelSerializer):
    picture = CharField(source='userprofile.image_url', read_only=True)
    password = CharField(write_only=True)
    mobile = CharField(source='userprofile.mobile')
    lit_points = IntegerField(source='userprofile.lit_points', read_only=True)
    location = SerializerMethodField(read_only=True)

    class Meta:
        model = User
        fields = ('id', 'mobile', 'first_name', 'last_name', 'email', 'password', 'picture', 'lit_points', 'location')