Search code examples
djangodjango-modelsdjango-viewsdjango-media

Why cannot I see the image file in django?


I tried to load an image file, but it didn't work. I uploaded the image file by admin. Thanks for the help!

here is my code

in urls.py

path('main/archive/<int:video_id>/', views.loadphoto, name='loadphoto'),

in views.py

def loadphoto(request, video_id):
     target_img=get_object_or_404(Record, pk=video_id)
     context={'target_img':target_img.picture}

in models.py

class Record(models.Model):
    record_text = models.CharField(max_length=50)
    pub_date = models.DateTimeField('date published')
    picture=models.ImageField(blank=True)

    def __str__(self):
        return self.record_text

in img.html

<img src="target_img">

<a href="{%url 'main'%}">Main</a>

Solution

  • First You Need To Join Your Media directory to your app

    Here is the Way You Can Do That:

    First You Need To Add This in Your Setting.py

    MEDIA_URL = '/media/'
    
    MEDIA_ROOT = os.path.join(BASEDIR,'your folder directory')
    
    #for example app/media or something
    

    Then You Need To Create Media Url Here is The Way:

    Then You Need To Add in your urls.py

    from django.conf import settings
    from django.conf.urls.static import static
    
    urlpatterns = [
        path('main/archive/<int:video_id>/', views.loadphoto,name='loadphoto'),
    
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    

    Then You Need To Add This in Your Html File

    <img src='{{ target_img.url }}'>
    

    You Can See More Details Here:

    https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.fields.files.FieldFile.url