简体   繁体   中英

django template doesn't load image uploaded in ImageField properly

i know this question have been brought up a lot of times,but i have tried a lot of different things,not working add.i belive i might have forget to add something silly in my code,just cant figure out what.below is the code of my heading model:

class Heading(models.Model):
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=5000)
    content = RichTextField()
    image= models.ImageField(null=True,blank=True)
    date = models.DateField(default=datetime.now())
    time = models.TimeField(default=datetime.now())
    slug = models.SlugField(unique=True, null=True, blank=True)

i have also added below codes in my projects settings.py

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

below is my urls.py

from django.conf.urls import include, url ,patterns
from django.contrib import admin
from django.conf import settings

urlpatterns = [
    url(r'^tinymce/', include('tinymce.urls')),
    url(r'^ckeditor/', include('ckeditor_uploader.urls')),
    url(r'^grappelli/', include('grappelli.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^news/', include('news.urls')),
]
if settings.DEBUG:
    urlpatterns += patterns(
        'django.views.static',
        (r'^media/(?P<path>.*)',
        'serve',
        {'document_root': settings.MEDIA_ROOT}), )

this is how my directory is set up 目录

below is my template code

{% extends "base.html" %}

        {%block main_meat%}
        {%if headings%}
                {%for heading in headings%}
                    <h1><a href="/news/headline/{{heading.slug}}">{{heading.title}}</a></h1>
                    <br>
                    <img src='{{heading.image}}'>
                    {{heading.content|safe}}
                {%endfor%}

        {%endif%}
    {%endblock%}

when i inspect element on a webbrowser,this is the path of image that i get

<img src="./image_name.png">

subash is the name of my project and news is the name of the app.i know i have posted a long question with lots of codes,please if anyone can point out what i am missing.

In your template intead of:

<img src='{{heading.image}}'>

try:

{% if heading.image %}
    <img src='{{heading.image.url}}'>
{% endif %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM