显示模特

时间:2015-09-15 18:00:52

标签: django

我是Python和Django的初学者。我不知道如何从模型中显示图像。

这是我的代码:

models.py

class Blog(models.Model):
    title = models.CharField(max_length = 100)
    content = models.TextField(max_length = 5000)
    publication_date = models.DateField(blank=True, null=True)
    image = models.ImageField(upload_to='photo',verbose_name='My Photo')
    author = models.CharField(max_length=50)
    def __str__(self):
        return self.title

views.py

 def index(request):
    songs = models.Blog.objects.all()
    context = Context({
        'songs_list': songs
        })
    return render(request, 'music.html', context)

music.html

{% if songs_list %}
    <ul>
    {% for songs in songs_list %}

        <li>
            <span style= "color:green">  {{songs.title}}</span>
            <span style= "color:red"> - {{songs.author}}</span>
            <img src="{{ songs.image }}" />      
        </li>

    {% endfor %}
    </ul>
{% else %}
    <p>No song is made. </p>
{% endif %}

urls.py

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', 'blog.views.index', name='index'),
]

当我加载页面时,它不会显示图片,请查看链接以查看图片:http://postimg.org/image/i1c8ju9e5/

1 个答案:

答案 0 :(得分:1)

您可以使用ImageField的{​​{3}}属性在模板中显示图片。

{{songs.image}}更改为模板中的{{songs.image.url}},它应该会在模板中显示图片。

{% if songs_list %}
    <ul>
    {% for songs in songs_list %}

        <li>
            <span style= "color:green">  {{songs.title}}</span>
            <span style= "color:red"> - {{songs.author}}</span>
            <img src="{{ songs.image.url }}" />      
        </li>

    {% endfor %}
    </ul>
{% else %}
    <p>No song is made. </p>
{% endif %}