To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.
How do you pass a Python variable to a template? And this is rather simple, because Django has built-in template modules that makes a transfer easy. Basically you just take the variable from views.py and enclose it within curly braces {{ }} in the template file.
Being able to capture one or more values from a given URL during an HTTP request is an important feature Django offers developers. We already saw a little bit about how Django routing works, but those examples used hard-coded URL patterns. While this does work, it does not scale.
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
Use the class based generic views.
from django.views.generic import TemplateView
urlpatterns = patterns('',
(r'^foo/$', TemplateView.as_view(template_name='foo.html')),
)
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'}),
)
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")
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With