DRF(Django Rest Framework)中的自定义用户身份验证

时间:2018-06-27 20:02:14

标签: python django django-rest-framework token

我已经使用django默认的User类进行了有效的auth.token注册,但是我被要求向User添加一个新字段,我调查了AbtractUser,AbstractBaseUser等问题。我认为最好的解决方案是OneToOneField“方法”。

这是我尝试做的事情:

models.py:

do.call(rbind,lapply(split(df, df["ID"]), findit))

serializers.py

class Usuario(models.Model):
    user = models.OneToOneField(User, on_delete = models.CASCADE)
    es_tecnico = models.BooleanField(name = 'es_tecnico', default = False, blank = True)

views.py:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username',
                  'password')

class UsuarioSerializer(serializers.ModelSerializer):
    user = UserSerializer(required=True)

    class Meta:
        model = Usuario
        fields = ('user',
                  'es_tecnico')

    def create(self, validated_data):
        """
        Overriding the default create method of the Model serializer.
        :param validated_data: data containing all the details of student
        :return: returns a successfully created student record
        """
        user_data = validated_data.pop('user')
        user = UserSerializer.create(UserSerializer(), validated_data=user_data)
        usuario, created = Usuario.objects.update_or_create(user=user,
                            es_tecnico=validated_data.pop('es_tecnico'))
        return usuario

我想使它尽可能简单,这就是我使用命令“ python3 manage.py makemigrations”时得到的:

class UsuarioViewSet(viewsets.ModelViewSet):
    lookup_field = 'id'
    serializer_class = UsuarioSerializer
    queryset = Usuario.objects.all().filter(es_tecnico = False)


class TecnicoViewSet(viewsets.ModelViewSet):
    lookup_field = 'id'
    serializer_class = UsuarioSerializer
    queryset = Usuario.objects.all().filter(es_tecnico = True)

当我尝试其他stackoverflow问题的解决方案时,出现此错误:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/home/stalker/PycharmProjects/ingSoft/servidor/virenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/home/stalker/PycharmProjects/ingSoft/servidor/virenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/stalker/PycharmProjects/ingSoft/servidor/virenv/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/stalker/PycharmProjects/ingSoft/servidor/virenv/lib/python3.5/site-packages/django/core/management/base.py", line 332, in execute
    self.check()
  File "/home/stalker/PycharmProjects/ingSoft/servidor/virenv/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/stalker/PycharmProjects/ingSoft/servidor/virenv/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/stalker/PycharmProjects/ingSoft/servidor/virenv/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/stalker/PycharmProjects/ingSoft/servidor/virenv/lib/python3.5/site-packages/django/contrib/auth/checks.py", line 29, in check_user_model
    if not isinstance(cls.REQUIRED_FIELDS, (list, tuple)):
AttributeError: type object 'Usuario' has no attribute 'REQUIRED_FIELDS'

如果有使用OneToOneField插入的简单方法,我会很感激

这些是我现在遇到问题的观点: views.py:

AttributeError: type object 'Usuario' has no attribute 'USERNAME_FIELD'

1 个答案:

答案 0 :(得分:0)

在这种情况下,您只是extending Django User model,因此您不应覆盖AUTH_USER_MODEL

settings.py文件中删除以下代码行:AUTH_USER_MODEL = "pedidos.Usuario" ,并且在代码中,如果您想使用User模型,则应使用以下模型:

from django.contrib.auth.models import User

(正如我们所说的,您只是扩展Django User模型),也可以使用方便的功能get_user_model()

  

get_user_model():

     

您应该代替直接指代用户,   使用django.contrib.auth.get_user_model()引用用户模型。   此方法将返回当前活动的用户模型–自定义   用户模型(如果已指定),否则,则为用户。

如果要获取es_tecnico的属性User,可以使用:

>>> from django.contrib.auth.models import User
>>> u = User.objects.get(username='Juan')
>>> juan_es_tecnico = u.usuario.es_tecnico

或使用get_user_model()

>>> from django.contrib.auth import get_user_model
>>> my_user = get_user_model()
>>> u = my_user.objects.get(username='Juan')
>>> juan_es_tecnico = u.usuario.es_tecnico

编辑:

class Registrar(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = UsuarioSerializer

    def create(self, request, *args, **kwargs):
        #  Creando un nuevo usuario
        username = request.POST.get('username')
        email = request.POST.get('email')
        password = request.POST.get('password')

        user = User.objects.create_user(username, email, password)
        user.save()

        token = Token.objects.create(user=user)

        return Response({'detail': 'El usuario fue creado con el token: ' + token.key})

Regitrar类中,使用User模型而不是Usuario

我希望这会有所帮助。