I am currently learning Django framework and im doing a little project for learning purposes. I have a model class named "Conta" and it has a foreign key to the User model (the default django User). What happens is this: Whenever i try to add a new row to the model "Conta", it throws an error saying that the user already exists, even though i am not trying to create a new user. I will post my code:
SERIALIZER for the model Conta and User:
class ContaDetailsSerializer (serializers.ModelSerializer):
"""Lists the details of a conta"""
tipo_moeda = TipoMoedaSerializer()
tipo_conta = TipoDeContaSerializer()
user = UserSerializer()
# user = UserSerializer()
class Meta:
model = Conta
fields = ['id','user','nome','balanco','numero','tipo_moeda','tipo_conta','notas']
def create(self, validated_data):
tipoConta_data = validated_data.pop('tipo_conta')
tipoMoeda_data = validated_data.pop('tipo_moeda')
user_data = validated_data.pop('user')
print(tipoMoeda_data['id'])
tipo_conta = get_object_or_404(TipoConta,pk=tipoConta_data['id'])
tipo_moeda = get_object_or_404(TipoMoeda,pk=tipoMoeda_data['id'])
user = get_object_or_404(User,pk=user_data['id'])
conta = Conta.objects.create(**validated_data,tipo_conta=tipo_conta,tipo_moeda=tipo_moeda,user=user)
return conta
class UserSerializer(serializers.ModelSerializer):
"""Lists a user"""
id = serializers.IntegerField()
class Meta:
model = User
fields = ['id','username
']
View for the creating of a new "Conta":
class ContaList(APIView):
def post(self,request):
"""Creates a Conta"""
serializer = ContaDetailsSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data,status=status.HTTP_201_CREATED)
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
This is using the Django REST Framework.
What am i doing wrong ? The TipoConta and TipoMoeda are foreign keys too, and they work perfectly.
Aucun commentaire:
Enregistrer un commentaire