crodev
crodev

Reputation: 1491

Django REST saves Image but returns wrong path

I am trying to save Community image and it saves it to /api/media/imagename.jpg, but when I retrieve a community it gives me /media/imagename.jpg without /api and then it can't find a image.

So I have this Community model with FileField:

class Community(models.Model):
    """DB Model for Community"""
    name = models.CharField(max_length=150, unique=True)
    description = models.TextField(default="")
    created_by = models.ForeignKey(User, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    number_of_members = models.IntegerField(default=1)
    community_image = models.FileField(blank=False, null=False, default="", upload_to="")

    def __str__(self):
        return self.name

And I have this in my settings.py:

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

And then this is in my urls.py:

# urls.py in authentication_api application
router = DefaultRouter()
router.register('communities', views.CommunityViewSet)

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

if settings.DEBUG:
  urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

# urls.py in root urls file
urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('authentication_api.urls'))
]

What should I change to it returns correct path to image.

If you need any more code sample please comment.

Upvotes: 0

Views: 120

Answers (1)

Dipen Dadhaniya
Dipen Dadhaniya

Reputation: 4630

Ideally, you should store media files like:

media/api/imagename.jpg

And not:

api/media/imagename.jpg

If you want to store like:

media/api/imagename.jpg

Then in the community_image field, you just need to change:

upload_to=""

To:

upload_to="api/"

Upvotes: 1

Related Questions