0
votes

I am new to Django and I am currently having problems in showing uploaded images in Django Admin. I have followed many posted Q and A here in stackoverflow but of those worked in my problem. I hope any active of the coding ninja here could help me with this problem. Here is the detailed view of the problem:

  1. I have defined the MEDIA_ROOT and MEDIA_URL in settings.py

    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    MEDIA_ROOT = os.path.join(BASE_DIR, "media")
    MEDIA_URL = "/media/"
    
  2. This is my upload model in models.py:

    from django.utils.html import mark_safe
    
    class ImageDetails(models.Model):
        image = models.ImageField(null=True)    
    
        def image_img(self):
            if self.image:
                return mark_safe('<img src="%s" height="125px" width="125px"/>' % (self.image.url))
            else:
                return '(No image found)'
        image_img.short_description = 'Thumbnail'
    
  3. In my Application urls.py:

    urlpatterns = [
        url(r'^inputImage', views.inputImage, name='inputImage'),
        url(r'', views.index),
    ]
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    
  4. In my admin.py:

    class ImageDetailsAdmin(admin.ModelAdmin):
        fields = ["image"]  #for file upload
        list_display = ("image_img",)
    
    admin.site.register(ImageDetails, ImageDetailsAdmin)
    

The image was successfully stored at ProjectDIR/media. The HTML returns the url: http://127.0.0.1:8000/media/imagename.jpg at img tag. But the page fails to load the image (I will be redirected to index page whenever when using the url http://127.0.0.1:8000/media/imagename.jpg). I am using Django version 1.10

1
Check MEDIA_URL - you have assigned twice. I think you meant to use MEDIA_ROOT in the first occurrence.Abhinav
Opps. that was actually media root in the original code here. Done editing here.jonilyn2730

1 Answers

0
votes

As suspected, this problem is about URLs in Django. The problem occurred because I declared the following urlpattern in an app urls.py:

     url(r'', views.index, name='index'),

I solved the problem by changing the code to:

     url(r'^$', views.index, name='index'),

And adding the following code at the project's main urls.py:

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