2016-11-29 27 views
0

我創建了一個網頁Python-Django在application.I文件models.py設置album_logo領域,我試圖通過Python Shell中上傳圖片的URL使用的代碼在Django應用程序的圖像不工作

>>>from music.models import Album, Song 
>>>Album.objects.all() 
[] 
>>>a = Album(artist="Taylor Swift", album_title="Red", genre=" Country", album_logo="http://carywebdesigns.com/wp-content/uploads/2015/02/www2.jpg") 
>>>a.save() 
>>>a.artist 
'Taylor Swift' 
>>>a.album_title 
'Red' 
>>>a.id 
1 
>>>a.pk 
1 

模型。 PY

from django.db import models 

# Create your models here. 

class Album(models.Model): 
    artist = models.CharField(max_length=250) 
    album_title = models.CharField(max_length=500) 
    genre = models.CharField(max_length=100) 
    album_logo = models.CharField(max_length=1000) 

    def __str__(self): 
     return self.album_title + ' - ' + self.artist 

我使用python manage.py runserver運行此代碼,我得到了正確的answer.But未加載圖像。 而我有2個模板文件。 的index.html

{% if all_albums %} 
    <h3>Here are all my Albums:</h3> 
    <ul> 
     {% for album in all_albums %} 
     <li><a href="/music/{{ album.id }}/">{{ album.album_title }}</a></li> 
     {% endfor %} 
    </ul> 
{% else %} 
    <h3>You don't have any albums</h3> 
{% endif %} 

detail.html

<img src="{{ album.album_logo }}"> 

<h1>{{ album.album_title }}</h1> 
<h3>{{ artist }}</h3> 

<ul> 
     {% for song in album.song_set.all %} 
       <li>{{ song.song_title }} - {{ song.file_type }}</li> 
     {% endfor %} 

我怎麼能提前解決這個problem.Please幫助me.Thanks ..

+0

你怎麼顯示圖像?請分享模板代碼 – Kroenig

回答

1

例如,你需要創建的列表對象Album型號:

def listAlbum(request): 
    album_list = Album.objects.all() 
    return render(request, '/your/template.html', {'album_list':album_list}) 

在這種情況下顯示對象的模板應該是這樣的形象:

{% for a in album_list %} 
    <img src="{{a.album_logo}}> 
{% endfor %} 

如果你想顯示具體對象,那麼您認爲應該是這樣的:

def detailAlbum(request, pk): 
    album = Album.objects.get(pk=pk) 
    return render(request, '/your/template.html', {'album':album}) 

在這種情況下,您的模板應該看起來像這樣的:

<img src="{{a.album}}> 

希望它可以幫助你