I'm trying to upload a picture (with Postman at the moment) and save it in the "media" directory but although the server returns 200 status code, nothing's saved in the project.
urls.py:
urlpatterns = [
path('users/sign-up', views.RegisterAPI.as_view()),
path('users/login', views.LoginAPI.as_view()),
path('users/<int:id>', views.UserProfile.as_view()),
path('users/<int:id>/bill', views.UploadPicture.as_view()),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
models.py:
class UserBill(models.Model):
bill_picture = models.ImageField(default='bill_pic', null=True, blank=True)
sender = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='user')
created_at = models.DateTimeField(auto_now=True, auto_now_add=False)
status = models.IntegerField(null=True)
views.py:
class UploadPicture(generics.GenericAPIView):
permission_classes = [IsAuthenticated, IsAccountOwner]
def post(self, request, *args, **kwargs):
new_data = request.data
new_data['user'] = request.user.id
new_data['status'] = PaymentStat.PENDING.value
serializer = UserBillSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
bill = serializer.save()
return Response({
"bill": UserBillSerializer(bill, context=self.get_serializer_context()).data,
}, status=status.HTTP_200_OK)
serializers.py
class UserBillSerializer(serializers.ModelSerializer):
class Meta:
model = UserBill
fields = '__all__'
def create(self, validated_data):
user = User.objects.all().get(id=self.initial_data.get('user'))
bill = UserBill.objects.create(**validated_data, sender=user)
return bill
def update(self, instance, validated_data):
obj = super().update(instance, validated_data)
obj.is_regular = True
obj.save()
return obj
I still don't understand why this isn't working, but I tried an alternative approach and it worked.
Now, I create the new UserBill in 2 steps:
1- I send a POST request to the server, including all the data I want to be saved for the new bill, except the picture itself.
2- I send a PUT request including only the picture and edit the bill created in the previous step.
Hope it helps you too.