django里使用静态文件,貌似有这么几种办法:
1. 在setting.py里面:
把静态文件所在目录设到STATICFILES_DIRS里。
静态文件就可以通过 /static/xxx这样的url访问了。不过缺点是STATIC_URL不可以设为空(一定要有个前缀)。所以像robots.txt这样的一定要放在根目录的文件就不行了(http://example.com/robots.txt)。
2. 将静态页面设置为模板,通过direct_to_template函数直接显示
direct_to_template的说明:[url]https://docs.djangoproject.com/en/1.2/ref/generic-views/[/url]
3. 如果静态页面非常简单,也可以通过lambda表达式(匿名函数)直接写在urlpatterns里
lambda后面的r,指view的参数request。
1. 在setting.py里面:
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(os.path.dirname(__file__), '../static').replace('\\','/'),
)
把静态文件所在目录设到STATICFILES_DIRS里。
静态文件就可以通过 /static/xxx这样的url访问了。不过缺点是STATIC_URL不可以设为空(一定要有个前缀)。所以像robots.txt这样的一定要放在根目录的文件就不行了(http://example.com/robots.txt)。
2. 将静态页面设置为模板,通过direct_to_template函数直接显示
from django.views.generic.simple import direct_to_template
urlpatterns = patterns('',
(r'^robots\.txt$', direct_to_template, {'template': 'robots\.txt', 'mimetype': 'text/plain'}),
)
direct_to_template的说明:[url]https://docs.djangoproject.com/en/1.2/ref/generic-views/[/url]
3. 如果静态页面非常简单,也可以通过lambda表达式(匿名函数)直接写在urlpatterns里
urlpatterns = patterns('',
(r'^robots\.txt$', lambda r: HttpResponse("User-agent: *\nDisallow: /", mimetype="text/plain"))
)
lambda后面的r,指view的参数request。