这是我第一次使用django rest框架创建api rest,我到达了Register用户并用token登录的位置,我的问题是我可以使用Django的默认用户来完成所有这些工作,在我的情况下需要具有另一个布尔变量is_technical(is_technical)的个性化用户。我将输入到目前为止的代码,但要清楚一点,我想使用DRF和一对一链接创建登录系统...
models.py(我尝试多次重写create方法,但是它不起作用)
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 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)
class PedidoViewSet(viewsets.ModelViewSet):
lookup_field = 'id'
serializer_class = PedidoSerializer
queryset = Pedido.objects.all()
# class PedidoMiUsuarioSet(viewsets.ModelViewSet):
# serializer_class = PedidoSerializer
# queryset = Pedido.objects.all().order_by('-id').filter(autor = "3")
class Registrar(mixins.CreateModelMixin, viewsets.GenericViewSet):
serializer_class = UsuarioSerializer
def create(self, request, *args, **kwargs):
# Creando un nuevo usuario
username = request.POST.get('user.username')
password = request.POST.get('user.password')
es_tecnico = request.POST.get('user.es_tecnico')
print(username)
user = User.objects.create_user(username, password)
user.save()
token = Token.objects.create(user=user)
# usuario = Usuario.objects.create(user, es_tecnico)
# usuario.save()
return Response({'detail': 'El usuario fue creado con el token: ' + token.key})
class LoginView(mixins.CreateModelMixin, viewsets.GenericViewSet):
serializer_class = LoginSerializer
def create(self, request):
serializer = LoginSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data["usuario"]
django_login(request, user)
token, created = Token.objects.get_or_create(user=user)
return Response({"token": token.key}, status=200)
class LogoutView(mixins.CreateModelMixin, viewsets.GenericViewSet):
authentication_classes = (TokenAuthentication, )
def create(self, request):
django_logout(request)
return Response(status=204)
enter code here
serializers.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
# class TecnicoSerializer(serializers.ModelSerializer):
# class Meta:
# model = Tecnico
# fields = ('id',
# 'email',
# 'password')
class PedidoSerializer(serializers.ModelSerializer):
class Meta:
model = Pedido
fields = ('id',
'tipo_de_pedido',
'autor',
'tecnico_asignado',
'asunto',
'detalles',
'prioridad',
'sistema',
'fecha',
'archivo_adjunto')
class LoginSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
def validate(self, data):
username = data.get("username", "")
password = data.get("password", "")
if username and password:
user = authenticate(username=username, password=password)
if user:
if user.is_active:
data["user"] = user
else:
msg = "Usuario desactivado"
raise exceptions.ValidationError(msg)
else:
msg = "Imposible loguear con los parametros dados"
raise exceptions.ValidationError(msg)
else:
msg = "Se necesita el username y password"
raise exceptions.ValidationError(msg)
return data
如果您需要更多信息或代码,请告诉我,我将尽快答复。或者,如果您推荐其他框架与“自定义用户”一起使用,我会很感激
答案 0 :(得分:2)
更改
usuario = Usuario.objects.create(user, es_tecnico)
到
usuario = Usuario.objects.create(user=user, es_tecnico=es_tecnico)
在/misitio/pedidos/views.py
中,第58行