I have a model with an ImageField:
image_url = models.ImageField(upload_to=upload_to, blank=True, null=True)
I did include it in my serializer in this way:
image_url = serializers.ImageField(required=False, use_url=True)
This is my viewset:
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.order_by('-id')
serializer_class = ProductSerializer
parser_classes = (MultiPartParser, FormParser)
permission_classes = [
permissions.IsAuthenticatedOrReadOnly]
def perform_create(self, serializer):
serializer.save()
The media root and url:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
My urls.py:
urlpatterns = [
path("users/", include("user.urls")),
path("products/", include("products.urls")),
path("utils/", include("utils.urls")),
path("auth/", include("djoser.urls")),
path("auth/", include("djoser.urls.jwt")),
path("graphql/", csrf_exempt(GraphQLView.as_view(schema=schema, graphiql=True))),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
It get listed properly:
But the problem is that once I click on the url of the image (that is inside the media folder), it shows me a 404 error in this url: http://127.0.0.1:8000/media/images/base_bWxtftQ.png. But the image is in that folder.
The problem was that I did append the static content to the api urlpattern. Instead of that is necessary append the static content to the root urlpattern (that one defined in the ROOT_URLCONF of the settings).