Django-ImageField,在开发服务器中上载,存储和提供图像 [英] Django - ImageField, upload, store and serve image in development server

查看:106
本文介绍了Django-ImageField,在开发服务器中上载,存储和提供图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在管理表单中为我的模型创建一个ImageField(例如,针对个人的个人资料).我想稍后在视图中显示此图像.

I'd like to have an ImageField in the admin form for my model (say, for an individual's profile). And I'd like to display this image in a view later on.

这是我的模特:

class Individual(models.Model):
    ind_name = models.CharField(max_length=100)
    ind_photo = models.ImageField(default="default.jpg")

    def __str__(self):
        return self.ind_name

这是我网站设置中的内容:

This is what I have in the settings for my website :

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
MEDIA_URL = '/static/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,"static/media")

这些是我的应用程序的网址:

These are the urls of my app:

urlpatterns = [
    url(r'^$', views.index, name="index")
]

我知道如何使用静态文件(例如CSS,Javascript),并使它们在开发和生产环境中都能正常工作. 但是我不知道如何使图像工作.我已阅读管理静态文件部署静态文件,但是我还是不明白.

I know how to use static files (e.g. CSS, Javascript), and to get them to work in both development and production. But I have no clue how to get images to work. I've read Managing static files and Deploying static files, but I still don't get it.

使用上面的代码,图像将保存在适当的文件夹中(即,我网站级别的/static/media).但是我不知道:

With the code above the image gets saved in the proper folder (i.e. /static/media at the level of my site). But I have no clue :

1)如何在模板中显示它,

1) how to display it in a template,

2)是否最好将这些图像保存在应用程序的静态文件夹中,

2) whether it would be best to keep these images in my app's static folder,

3)和(如果是2)(每次有人在管理员中上传图片时我是否需要运行collectstatic.

3) and (if 2) whether I would need to run collectstatic every time someone uploads an image in the admin.

很抱歉,如果我不清楚,但是这种方式比我想象的要模糊得多.

Sorry if I'm unclear, but this way more obscure than I thought it would be.

推荐答案

为了在开发过程中上传和提供图片,我不得不将媒体文件夹移出静态文件夹(即在项目文件夹的根目录).

In order for the image to be uploaded and served during development, I had to move the media folder out of the static folder (i.e. create a media folder at the root of my project's folder).

在我的主要urls.py中,我必须添加:

And in my main urls.py, I had to add :

from django.conf import settings
from django.conf.urls.static import static

if settings.DEBUG: 
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

如MicroPyramid所建议.

as suggested by MicroPyramid.

为了在模板中显示它,对于给定的某人"(来自查询集),我使用:

To display it in a template, for a given Individual "somebody" (from a queryset), I use :

<img src="{{ somebody.ind_photo.url }}">

这篇关于Django-ImageField,在开发服务器中上载,存储和提供图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆