I'm trying to make an endpoint for updating the profile image of a user. However, whenever I make the PATCH request, the profile_image field does not change to the uploaded file. I've tested on postman using form-data and I get the response "Updated completed" but the profile_image field remains null.
views.py
class ProfileImageView(APIView):
parser_classes = [MultiPartParser, FormParser]
def patch(self, request, user_email, format=None):
print(request.data)
profile = ProfileImage.objects.get(user_email=user_email)
serializer = ProfileImageSerializer(profile, data=request.data, partial=True)
data = {}
if serializer.is_valid():
serializer.update(profile, request.data)
data["response"] = "Update completed."
data["user_email"] = user_email
data["profile_image"] = (
profile.profile_image.url if profile.profile_image else None
)
return Response(serializer.data)
data["response"] = "Wrong parameters."
return Response(data)
models.py
class ProfileImage(models.Model):
user_email = models.CharField(max_length=255)
profile_image = models.ImageField(
upload_to="uploads/",
height_field=None,
width_field=None,
null=True,
blank=True,
)
serializers.py
class ProfileImageSerializer(serializers.ModelSerializer):
class Meta:
model = ProfileImage
fields = ["user_email", "profile_image"]
urls.py
urlpatterns = [
path("api-auth/", include("rest_framework.urls")),
path("admin/", admin.site.urls),
path("register/", RegisterView.as_view(), name="register"),
path("login/", obtain_auth_token, name="login"),
path("log/add/", LogView.as_view(), name="log"),
path("log/all/", LogView.getAll, name="logall"),
path("log/<str:user_email>/", LogView.getByUserEmail, name="logbyuseremail"),
path("profile/<str:user_email>/", ProfileView.profile, name="profile"),
path("edit-profile/<str:user_email>/", ProfileView.as_view(), name="profile"),
path(
"profile-image/<str:user_email>/",
ProfileImageView.getProfileImage,
name="profile-image",
),
path(
"edit-profile-image/<str:user_email>/",
ProfileImageView.as_view(),
name="profile-image",
),
path("events/", EventView.as_view(), name="events"),
]
urlpatterns = staticfiles_urlpatterns()
urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
CodePudding user response:
You need to use .save()
for your serializer instead like this:
if serializer.is_valid():
try:
serializer.save()
except ValueError:
return Response({"detail": "Serializer is not valid"}, status=400)
return Response({"detail": "Updated."})
else:
return Response(serializer.errors)
This is also going to return the exact errors from the serializer when you are updating.