在ModelSerializer中添加额外字段不起作用

时间:2015-10-08 10:39:19

标签: django django-rest-framework django-rest-auth

serializers.py:

from rest_framework import serializers
from django.utils.translation import ugettext_lazy as _
import models


class ExtensibleModelSerializerOptions(serializers.Serializer):

    def __init__(self, meta):
        super(ExtensibleModelSerializerOptions, self).__init__(meta)
        self.model = getattr(meta, 'model', None)
        self.read_only_fields = getattr(meta, 'read_only_fields', ())
        self.non_native_fields = getattr(meta, 'non_native_fields',())


class ExtensibleModelSerializer(serializers.ModelSerializerOptions):

    _options_class = ExtensibleModelSerializerOptions

    def restore_object(self, attrs, instance=None):

        for field in self.opts.non_native_fields:
            attrs.pop(field)

        return super(ExtensibleModelSerializer, self).restore_object(attrs, instance)

    def to_native(self, obj):

        ret = self._dict_class()
        ret.fields = {}

        for field_name, field in self.fields.items():
            # --- BEGIN EDIT --- #
            if field_name in self.opts.non_native_fields:
                continue
            # --- END --- #
            field.initialize(parent=self, field_name=field_name)
            key = self.get_field_key(field_name)
            value = field.field_to_native(obj, field_name)
            ret[key] = value
            ret.fields[key] = field
        return ret

class OptiUserSerializer(ExtensibleModelSerializer):
    password_confirmation = serializers.CharField(max_length=models.OptiUser._meta.get_field('password').max_length)
    company_id = serializers.PrimaryKeyRelatedField(queryset=models.Company.objects.all(), many=False)
    password = serializers.CharField(
        style={'input_type': 'password'}
        )

    def validate_password_confirmation(self, attrs, source):
        password_confirmation = attrs[source]
        password = attrs['password']

        if password_confirmation != password:
            raise serializers.ValidationError(_('Password confirmation mismatch'))

        return attrs

    class Meta:
        model = models.OptiUser
        fields = ('id', 'username', 'company_id', 'first_name', 'last_name', 'is_active', 'is_admin', 'password', 'password_confirmation',)
        non_native_fields = ('password_confirmation',)

我正在为我的应用设置自定义用户模型。我正在使用DRF创建Web Web服务。我正在尝试按照上面的说明制作用户注册序列化程序。一切正常,除非我添加'password_confirmation'字段,它引发异常“model_name”对象没有属性password_confirmation“。我发现上面的代码片段我正在尝试使用上面。但遗憾的是它似乎没有非常有帮助。

我的问题是,是否可以添加这样的字段并对其进行一些比较。有没有优雅的方法呢?

请建议修复。

谢谢!提前。

1 个答案:

答案 0 :(得分:1)

我认为你不需要import os, random, string length = 13 chars = string.ascii_letters + string.digits + '!@#$%^&*()' random.seed = (os.urandom(1024)) print ''.join(random.choice(chars) for i in range(length)) 。将字段设置为ExtensibleModelSerializer

write_only