Django is not serving my image asset, using rest framework

Viewed 13

I am uploading an image file from Flutter to Django, the image is getting saved properly in my backends directory under assets/images, and when I query the database with a get I get the proper path of the file. But when I go to the URL in the browser the image does not appear and I get an error. I am using rest-framework for my app.

Model:

class Product(models.Model):
    supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
    name = models.CharField(max_length=200)
    quantity = models.IntegerField(default=0)
    barcode = models.CharField(max_length=200)
    cost_price = models.FloatField(default=0)
    selling_price = models.FloatField(default=0.0)
    image = models.ImageField(upload_to='images/', null=True)

Settings.py:

MEDIA_ROOT = os.path.join(BASE_DIR, 'assets')
MEDIA_URL = '/pm/assets/'

Urls.py:

urlpatterns = [
    path('', include(router.urls)),
]

urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Serializer:

class SuppliersSerializer(serializers.ModelSerializer):
    product_set = ProductsSerializer(read_only=True, many=True)
    class Meta:
        model = Supplier
        fields = ['pk','user','name','email','phone','product_set']

class ProductsSerializer(serializers.ModelSerializer):
    transactions_set = TransactionsSerializer(read_only=True, many=True)
    class Meta:
        model = Product
        fields = ['pk','name','quantity','barcode','cost_price','image', 'selling_price', 'transactions_set']

JSON response:

{
                    "pk": 13,
                    "name": "pi3",
                    "quantity": 3,
                    "barcode": "11111",
                    "cost_price": 10.0,
                    "image": "/pm/assets/images/533a6ac0-f682-4814-9237-89df8e02fda715039130977982609.jpg",
                    "selling_price": 20.0,
                    "transactions_set": []
                },

But when visiting: http://localhost:8000/pm/assets/images/533a6ac0-f682-4814-9237-89df8e02fda715039130977982609.jpg

I get this error:

enter image description here

1 Answers

Solution was that it was trying to use the URL /pm/pm/assets/images, I changed in my settings.py:

MEDIA_ROOT = os.path.join(BASE_DIR, 'assets')
MEDIA_URL = '/assets/'

The image is now being served by django successfully

Related