[英]Not being able to set the path for an image related to a model properly in Django
我需要為Django中的模型設置配置文件圖片。 我正在使用枕頭。 我的問題是,我在models.py上設置的路徑(當我使用admin上傳圖像時圖像所在的位置)與模板所使用的路徑不同,因此圖像從不顯示。
我的靜態文件夾位於應用程序的文件夾中(這是一個只有一個應用程序的簡單項目),但是管理員將圖像上傳到應用程序文件夾之外的某個文件夾中。
這是我在models.py中的代碼:
def get_image_path(instance, filename):
return os.path.join('static/artists/images', str(instance.id), filename)
class Artist(models.Model):
name = models.CharField(max_length=255)
soundcloud = models.URLField(max_length=255, blank=True, null=True)
description = models.TextField()
profile_picture = models.ImageField(upload_to=get_image_path, blank=True, null=True)
current_roster = models.BooleanField(default=True)
def __str__(self):
return self.name.encode('utf8')
這是模板中的代碼:
{% if artist.profile_picture %}
<img src="{{ artist.profile_picture.url }}" alt="Artist pic" style="width: 200px;">
{% endif %}
有人可以幫我嗎? 提前致謝!
首先:django提供了兩套獨立的文件集: static
文件和media
文件,它們的用法不同:
兩組文件都應由HTTP服務器直接提供。 這兩個文件都保存在每個項目的全局文件夾中-如果是靜態文件:它們是從所有使用過的應用程序收集的,如果是媒體文件,則是從Web上傳的。 它們都不應該從應用程序目錄中提供。
其次:您不應在upload_to中指定靜態或媒體文件夾,django將根據您的設置添加該文件夾。
這對您應該很好,並且您正在使用非靜態的媒體文件,我在下面進行了所有適當的切換,靜態文件是css js,以及用戶自己未下載的圖像。 但是,如果您有任何疑問,請發表評論。
settings.py-將其添加到context_processors中,並確保以這種方式配置了媒體根目錄和媒體URL
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.media', ###add this string here
'django.contrib.messages.context_processors.messages',
],
},
},
]
MEDIA_URL='/media/'
MEDIA_DIRS=[os.path.join(BASE_DIR, 'media')]
models.py-media / media / images / 1 / file.jpeg <---路徑,其余模型看起來很好
def get_image_path(instance, filename):
return os.path.join('/media/images', str(instance.id), filename)
###### added media to the path #######
template.html-進行我對html的更改,路徑應顯示為media / media / images / instance.id / profile_picture.jpeg,instance.id和文件名已組成,但您明白了我的意思。
{% if artist.profile_picture %}
<img src="{{ MEDIA_URL }}/{{ artist.profile_picture }}" alt="Artist pic" style="width: 200px;">
{% else %}
<p> you can download a picture one day. </p>
{% endif %}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.