繁体   English   中英

无法在Django中正确设置与模型相关的图像的路径

[英]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文件,它们的用法不同:

  • 静态文件随您的项目代码一起提供,并已连接到该代码。 例如,这可以是CSS文件,JavaScript,属于样式或HTML布局的图像。
  • 媒体文件通过脚本,管理员等上载到项目中,并与数据库中的数据连接。 这可以是您文章中的照片,您网站上用户的头像等。

两组文件都应由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.

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