I have two models, User and EcoUser, with a one-to-one relationship (I have omitted some fields for simplicity in this example):
class User(AbstractUser):
picture_url = models.ImageField(upload_to='logos/', blank=True)
class EcoUser(models.Model):
user = models.OneToOneField(User, related_name='eco_user')
document = models.CharField(max_length=45, blank=True)
def __str__(self):
return str(self.user)
To handle the data of both tables with a single post or put request, I use a NestedSerializer. This allows me to update the data when registering without any issues:
Here is the serializer I use:
class EcoUserSerializer(serializers.ModelSerializer):
user = UserSerializer(required=True)
class Meta:
model = EcoUser
fields = '__all__'
def update(self, instance, validated_data):
instance.document = validated_data.get('document', instance.document)
instance.save()
user_data = validated_data.pop('user')
user = instance.user
user.picture_url = user_data.get('picture_url', user.picture_url)
user.save()
return instance
And in my viewset:
class EcoUserViewSet(viewsets.ModelViewSet):
serializer_class = EcoUserSerializer
queryset = EcoUser.objects.all()
pagination_class = None
parser_classes = (MultiPartParser,)
@transaction.atomic
def update(self, request, *args, **kwargs):
with transaction.atomic():
try:
instance = self.get_object()
instance.id = kwargs.get('pk')
serializer = EcoUserSerializer(instance=instance, data=request.data)
print(serializer)
if serializer.is_valid(raise_exception=True):
self.perform_update(serializer)
return Response({"status": True, "results": "Data updated successfully"},
status=status.HTTP_201_CREATED)
except ValidationError as err:
return Response({"status": False, "error_description": err.detail}, status=status.HTTP_400_BAD_REQUEST)
Everything was working fine until I added the ImageField and encountered a 400 bad request error when trying to update the data. I make this update request using Vue.js and Axios:
const bodyFormData = new FormData();
bodyFormData.append('user.picture_url', this.params.user.picture_url.name);
bodyFormData.append('document', this.params.document);
this.axios.put(`/users/${this.params.id}/`, bodyFormData, { headers: { 'Content-Type': 'multipart/form-data' } })
.then((response) => {
this.isSending = false;
this.$snackbar.open(response.data.results);
});
Is it correct to use user.picture_url as the field name in the append method? This is because picture_url is nested within the user object, and I need to update it accordingly.