问题:如何直接转到Django的urls.py中的模板?

我希望它转到模板robots.txt,而不是views.py。

Instead of going to views.py, I want it to go to to a template, robots.txt.


回答 0

Django 2.0以上

使用基于类的通用视图,但要使用django 2.0+模式进行注册。

from django.urls import path
from django.views.generic import TemplateView

urlpatterns = [
    path('foo/', TemplateView.as_view(template_name='foo.html'))
]

https://docs.djangoproject.com/zh-CN/2.0/ref/class-based-views/base/#templateview

Django 1.5以上

使用基于类的通用视图。

from django.views.generic import TemplateView

urlpatterns = patterns('',
    (r'^foo/$', TemplateView.as_view(template_name='foo.html')),
)

Django <= 1.4

文档:https : //docs.djangoproject.com/zh-CN/1.4/ref/generic-views/#django-views-generic-simple-direct-to-template

urlpatterns = patterns('django.views.generic.simple',
    (r'^foo/$',             'direct_to_template', {'template': 'foo_index.html'}),
    (r'^foo/(?P<id>\d+)/$', 'direct_to_template', {'template': 'foo_detail.html'}),
)

Django 2.0+

Use the class based generic views but register with the django 2.0+ pattern.

from django.urls import path
from django.views.generic import TemplateView

urlpatterns = [
    path('foo/', TemplateView.as_view(template_name='foo.html'))
]

https://docs.djangoproject.com/en/2.0/ref/class-based-views/base/#templateview

Django 1.5+

Use the class based generic views.

from django.views.generic import TemplateView

urlpatterns = patterns('',
    (r'^foo/$', TemplateView.as_view(template_name='foo.html')),
)

Django <= 1.4

Docs: https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-simple-direct-to-template

urlpatterns = patterns('django.views.generic.simple',
    (r'^foo/$',             'direct_to_template', {'template': 'foo_index.html'}),
    (r'^foo/(?P<id>\d+)/$', 'direct_to_template', {'template': 'foo_detail.html'}),
)

回答 1

有关此网站的最新哑剧类型的最新更新,包括:

http://www.techstricks.com/adding-robots-txt-to-your-django-project/

from django.conf.urls import url
from django.views.generic import TemplateView

urlpatterns = [
    #... your project urls
    url(r'^robots.txt$', TemplateView.as_view(template_name="robots.txt", content_type="text/plain"), name="robots_file")
]

A further update for more recent versions and including mime type from this site:

http://www.techstricks.com/adding-robots-txt-to-your-django-project/

from django.conf.urls import url
from django.views.generic import TemplateView

urlpatterns = [
    #... your project urls
    url(r'^robots.txt$', TemplateView.as_view(template_name="robots.txt", content_type="text/plain"), name="robots_file")
]

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。