在哪里放置应该直接在服务器根目录下提供的静态文件?

Sem*_*mel 2 django

我刚刚迁移了一个旧的Django项目来使用staticfiles应用程序.在此之前,我将所有需要的文件放在名为static的目录中,该目录直接在服务器根目录下提供.此目录现在在STATIC_URL下提供,除了应直接在服务器根目录下提供的文件外,这个目录很好.

我知道如何直接从root提供文件(如/favicon.ico或/robots.txt),但我应该把它放在哪里?如果我把它们放在STATIC_ROOT下面的任何地方,它们将由两个URL(例如/file.txt和/static/foobar/file.txt)提供服务,这不是一个好习惯.

有任何想法吗?

Rau*_*eta 10

我已经解决了url.py中的两个问题(favicon.ico,robots.txt)但有一些差异.我不喜欢首先想到的解决方案是执行render_to_response的解决方案.

编辑:从Django 1.5 direct_to_template和redirect_to被弃用,所以现在你可以使用基于类的视图.

对于Django 1.5:

对于robots.txt,将以下行添加到urlpatterns:

from django.views.generic.base import RedirectView, TemplateView

(r'^robots\.txt$', TemplateView.as_view(template_name="robots.txt",
                                        content_type='text/plain')),
Run Code Online (Sandbox Code Playgroud)

我使用泛型类视图TemplateView,并指定要使用的模板(应该在模板目录中的robots.txt)和mimetype.

对于favicon.ico,将以下行添加到urlpatterns:

(r'^favicon\.ico$', RedirectView.as_view(
                            url=settings.STATIC_URL + 'img/favicon.ico')),
Run Code Online (Sandbox Code Playgroud)

这将/favicon.ico重定向到STATIC_URL + img/favicon.ico(例如:/static/img/favicon.ico)favicon.ico将在您的静态目录中.

这些方法可用于任何媒体或html内容.

对于以前版本的Django,您可以使用:

(r'^robots\.txt$', direct_to_template, {'template': 'robots.txt',
'mimetype': 'text/plain'}),

(r'^favicon\.ico$', redirect_to, 
{'url': settings.STATIC_URL + 'img/favicon.ico'}),
Run Code Online (Sandbox Code Playgroud)