Django 2.2静态文件在开发中不起作用 [英] Django 2.2 staticfiles do not work in development

查看:60
本文介绍了Django 2.2静态文件在开发中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个新的django应用程序,用户可以在其中上传图像,然后将其显示在页面上.我已经阅读了Django文档10000次,但我仍然不明白为什么我的图像无法加载(DEBUG = True)

I'm making a new django app where a user can upload images and then they can be displayed on a page. I've read the django docs 10000 times through and I still don't understand why my images aren't loading (DEBUG = True)

我的所有图像都将到达应有的位置,并且在我的模型中,管理员django拥有通往图像的正确路径,但只是无法正确加载.

All my images are going to where they're supposed to be and in the admin in my models django has the right path that leads to the image but it just won't load properly.

我在settings.py中的设置:

my setup in settings.py:

STATIC_URL = '/static/'
STATIC_ROOT = 'static' # live cdn such as AWS S3

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]


MEDIA_ROOT = os.path.join(STATIC_ROOT, 'media')
MEDIA_URL = '/img/'

我的目录:

|- src
    |- myproject
        |- settings.py, views.py, urls.py etc
    |- myapp
        |- views.py urls.py models.py forms.py etc
    |- static (this folder is empty and appeared after running collectstatic
    |- templates
    |- db.sqlite3
    |- manage.py
|- static (this folder is OUTSIDE src)
    |- admin
        |- django admin stuff
    |- media
        |- img
            |- myimage.png

在myapp的models.py中,图像字段upload_to ='img/'

in models.py of myapp the imagefield upload_to = 'img/'

正如我所说,图像不会加载到页面上,而是会上传到static/media/img/image_name.png

as i said, the images don't load on the page but to upload to static/media/img/image_name.png

多年来,我一直在尝试解决此问题,但是我无法从任何人那里得到任何帮助,并且django文档和其他stackoverflow问题/答案也都没有帮助.

I've been trying to fix this for ages but i can't get any help from anyone and django docs and other stackoverflow questions/answers have been of no help too.

感谢您的帮助!

推荐答案

在开发过程中提供用户上传的文件¶

Serving files uploaded by a user during development¶

在开发过程中,您可以从MEDIA_ROOT使用django.views.static.serve()视图.

During development, you can serve user-uploaded media files from MEDIA_ROOT using the django.views.static.serve() view.

这不适合生产使用!对于一些常见的部署策略,请参阅部署静态文件.

This is not suitable for production use! For some common deployment strategies, see Deploying static files.

例如,如果您的MEDIA_URL定义为/media/,则可以执行此操作通过将以下代码段添加到您的urls.py中:

For example, if your MEDIA_URL is defined as /media/, you can do this by adding the following snippet to your urls.py:

django.conf导入设置中的

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

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

https://docs.djangoproject.com/en/2.2/howto/static-files/

这篇关于Django 2.2静态文件在开发中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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