如何在Django开发中提供静态文件 [英] How to serve static files in Django development

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

问题描述

这是目录结构pf项目。

Here is the directory structure pf project.

mysite
  \media
  \static
       \images
       \css
           base.css
       \js 
  \templates
       base.html
  \settings.py #and other .py files

现在说如果我有一个文件 C :\mysite\static\css\base.css 或图片 C:\mysite\static\images\ball.png 。我如何使用django开发服务器来服务它。我知道这不是推荐的方式,但只是在开发中,我希望这个工作。我已经阅读了stackoverflow上的文档和其他答案,但它们似乎不起作用。可能是我被媒体静态 urlpatterns 。我花了几个小时试图弄清楚,但还是没有运气。
我刚刚到django,所有这一切似乎对我来说只是一个过度的获取一个css或图像显示。
我需要做哪些更改或编辑才能使其工作。我将如何在模板中引用图像和CSS?

Now say if i have a file C:\mysite\static\css\base.css or an image C:\mysite\static\images\ball.png .How am i going to serve it using django development server. I know this is not the recomment way, but just in development i want this to work. I have read the docs and other answers on stackoverflow but they don't seem to work. May be i am being confused by media and static and urlpatterns. I have spent hours trying to figure this out but still no luck. I am new to django and all this seems to me just an overkill to get a css or image showing up. What changes or editing do i need to make for this to work. How will i referece the image and css in template?

推荐答案

这里是如何从 Django文档,让您全面了解

Here is the how to for static files from the Django documentation that takes you through the whole process step-by-step.

将以下内容添加到您的urls.py

Add the following to your urls.py

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

# ... the rest of your URLconf goes here ...

urlpatterns += staticfiles_urlpatterns()

然后'此视图自动启用,并将在STATIC_URL中为静态文件提供服务,在runserver管理命令。 ...这将检查您的STATIC_URL设置并连接视图以相应地提供静态文件。不要忘记设置适当的STATICFILES_DIRS设置,让django.contrib.staticfiles知道在哪里可以查找应用程序目录中的文件。

Then 'This view is automatically enabled and will serve your static files at STATIC_URL when you use the built-in runserver management command. ... This will inspect your STATIC_URL setting and wire up the view to serve static files accordingly. Don't forget to set the STATICFILES_DIRS setting appropriately to let django.contrib.staticfiles know where to look for files additionally to files in app directories.'

值得一提的是这绝对不适合部署,但可以很好的发展。

It is worth mentioning that this is most definitely inappropriate for deployment, but will work well for development.

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

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