简体   繁体   English

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

[英]Not being able to set the path for an image related to a model properly in Django

I need to set a profile picture for a model in Django. 我需要为Django中的模型设置配置文件图片。 I am using Pillow. 我正在使用枕头。 My problem is that the path that I set on models.py (where the images go when I upload them using admin) is not the same as the one used by the template and so the images never show. 我的问题是,我在models.py上设置的路径(当我使用admin上传图像时图像所在的位置)与模板所使用的路径不同,因此图像从不显示。

My static folder is in the app's folder (this is a simple project with just one app) but admin uploads the images in some folder outside the app folder. 我的静态文件夹位于应用程序的文件夹中(这是一个只有一个应用程序的简单项目),但是管理员将图像上传到应用程序文件夹之外的某个文件夹中。

This my code in models.py: 这是我在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')

And this is the code in the template: 这是模板中的代码:

{% if artist.profile_picture %}
                <img src="{{ artist.profile_picture.url }}" alt="Artist pic" style="width: 200px;">
{% endif %}

Can somebody help me please? 有人可以帮我吗? Thanks in advance! 提前致谢!

First of all: django provides 2 separate sets of files: static and media and their usages are different: 首先:django提供了两套独立的文件集: static文件和media文件,它们的用法不同:

  • static files are served with your project code and are connected to that code. 静态文件随您的项目代码一起提供,并已连接到该代码。 This can be for example CSS files, JavaScript, images that are part of your style or HTML layout in general. 例如,这可以是CSS文件,JavaScript,属于样式或HTML布局的图像。
  • media files are uploaded into your project by scripts, in admin etc and are connected with data in your database. 媒体文件通过脚本,管理员等上载到项目中,并与数据库中的数据连接。 This can be photo in your article, avatar of user on your site etc. 这可以是您文章中的照片,您网站上用户的头像等。

Both groups of files should be served directly by your HTTP server. 两组文件都应由HTTP服务器直接提供。 Both files are kept inside global folders for each project - in case of static files: they are collected from all of used apps, in case of media files: they are uploaded from web. 这两个文件都保存在每个项目的全局文件夹中-如果是静态文件:它们是从所有使用过的应用程序收集的,如果是媒体文件,则是从Web上传的。 None of them should be served from app directory. 它们都不应该从应用程序目录中提供。

Secondly: you shouldn't specify static or media folder in upload_to, it will be added by django based on your settings. 其次:您不应在upload_to中指定静态或媒体文件夹,django将根据您的设置添加该文件夹。

This should work well for you and you are working with media files not static which I made all the proper switches down below, static files are css js, and images not downloaded by the users themselves. 这对您应该很好,并且您正在使用非静态的媒体文件,我在下面进行了所有适当的切换,静态文件是css js,以及用户自己未下载的图像。 But if you have any questions please leave a comment. 但是,如果您有任何疑问,请发表评论。

settings.py - add this to your context_processors, and make sure you media root and media URL are configured this way 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 <--- the path, the rest of your models look fine 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 - make the changes I made to your html the path should show up as media/media/images/instance.id/profile_picture.jpeg, the instance.id and file name are made up but you get what I am saying. 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