'Update Nested User Serializer With Image avatar
I want to add an avatar image to my profile serializer which is nested in the User Serializer as a one-to-one field. Im having issues getting the file to upload on the front end and I want to make sure I have everything correct in my backend Django DRF. I am using Djoser for the urls with DRF API. Please take a look and let me know if there is anything I might be missing. I have no errors with the "put" request on the frontend but the file is not being uploaded to my avatar file path and obviously not saving in the nested user object neither. I can update the avatar from the DRF with no issues as well.
Model.py
class Profile(models.Model):
user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)
name = models.CharField(max_length=100, blank=True, null=True)
occupation = models.CharField(max_length=100, blank=True, null=True)
residence = models.CharField(max_length=100, blank=True, null=True)
email = models.CharField(max_length=100, blank=True, null=True)
active_id = models.BooleanField(default=True)
avatar = models.ImageField(null=True, blank=True, upload_to ='uploads/profile_pics',default='uploads/default.jpg')
def __str__(self):
return self.user.username
# def get_image(self):
# return self.avatar.path
def save(self, *args, **kwargs):
super(Profile, self).save(*args, **kwargs)
img = Image.open(self.avatar.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.avatar.path)
Serializers.py
class ProfileSerializer(serializers.ModelSerializer):
user = serializers.StringRelatedField(read_only=True)
class Meta:
model = Profile
fields = ("__all__")
class UserSerializer(serializers.ModelSerializer):
profile = ProfileSerializer(required=False, allow_null=True)
parser_classes = (MultiPartParser, FormParser)
class Meta:
model = User
fields = ['username', 'profile', 'password', 'id']
extra_kwargs = {"password":{'write_only': True}}
def update(self, instance, validated_data):
if 'profile' in validated_data:
nested_serializer = self.fields['profile']
nested_instance = instance.profile
nested_data = validated_data.pop('profile')
nested_serializer.update(nested_instance, nested_data)
# for key, value in nested_data.items():
# setattr(instance.profile, key, value)
# instance.profile.save(update_fields=nested_data.keys())
return super(UserSerializer, self).update(instance, validated_data)
def create(self, validated_data):
return User.objects.create_user(**validated_data)
Signals.py
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from .models import Profile
User = get_user_model()
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
print('created:', created)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
Please take a look! I have been very stuck on this (still learning!) and Im not sure what Im doing wrong. I want to be sure the backend is all fine before I go continue researching the payload on the frontend. Any help really appreciated.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
