Setting up Mimetype when using TemplateView in Django

Viewed 10298

Does anyboy know how do I set the desired mimetype when using TemplateView, as in:

urlpatterns = patterns('',
    url(r'^test\.txt$', TemplateView.as_view(template_name='staticpages/test.html')),

In this case, I want to set the mimtype as "text/plain"

8 Answers

I know that you ask for setting a content type with TemplateView, but I will give you different answer which I think that will be more clean and can be used in Django versions lower than 1.5.

    url(r'^robots\.txt$', 'django.shortcuts.render', kwargs={
        'template_name': 'robots.txt',
        'content_type': 'text/plain',
    })

With this approach you don't need to import anything or to subclass TemplateView and make ugly overwrites of some methods. You can simply use the old technique with function based views.

A simple example of how change content type of a TemplateView:

#views.py
from django.views.generic import TemplateView

class HomeView(TemplateView):
    template_name = "home/index.html"
    content_type = 'text/html'

# urls.py
url(r'^home/$', HomeView.as_view(), name='home_page'),
Related