gpt4 book ai didi

python - create() 接受 1 个位置参数,但给出了 3 个

转载 作者:行者123 更新时间:2023-11-30 22:06:32 25 4
gpt4 key购买 nike

这是我第一次使用 django 休息框架创建 api 休息,我到了注册用户并使用 token 记录它们的地步,我的问题是我可以使用 Django 的默认用户完成所有这些操作,在我的情况下,我需要一个具有另一个名为 is_technical (is_technical) 的 bool 变量的个性化用户。我将放置到目前为止我所做的相关代码,但要清楚的是,我想制作一个带有 DRF 和一对一链接的登录系统...

models.py(我尝试多次重写创建方法,但不起作用)

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

View .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

序列化器.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

如果您需要更多信息或代码,请告诉我,我会尽快回复。或者,如果您推荐另一个与“自定义用户”一起使用的框架,我将不胜感激

最佳答案

改变

usuario = Usuario.objects.create(user, es_tecnico)

usuario = Usuario.objects.create(user=user, es_tecnico=es_tecnico)

/misitio/pedidos/views.py中,第58行

关于python - create() 接受 1 个位置参数,但给出了 3 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52693914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com