Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Django templates without the rest of Django?

I want to use the Django template engine in my (Python) code, but I'm not building a Django-based web site. How do I use it without having a settings.py file (and others) and having to set the DJANGO_SETTINGS_MODULE environment variable?

If I run the following code:

>>> import django.template >>> from django.template import Template, Context >>> t = Template('My name is {{ my_name }}.') 

I get:

ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. 
like image 858
Daryl Spitzer Avatar asked Sep 18 '08 23:09

Daryl Spitzer


People also ask

How do I override a Django template?

To override these templates, you will need to have an admin folder in your templates folder. If you do not have a templates folder, you can create it in the main project folder. To do so, you will have to change the project's settings.py . Find the TEMPLATES section and modify accordingly.

How do I access Django templates?

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.

Can you use Django without templates?

Yes. I enjoyed using DRF and am currently using it for the API of my project. The website I'm developing uses django templates with no js frameworks (only built-in browser js), but it also offers an API for developers (not for the website itself) which is built using DRF.


1 Answers

The solution is simple. It's actually well documented, but not too easy to find. (I had to dig around -- it didn't come up when I tried a few different Google searches.)

The following code works:

>>> from django.template import Template, Context >>> from django.conf import settings >>> settings.configure() >>> t = Template('My name is {{ my_name }}.') >>> c = Context({'my_name': 'Daryl Spitzer'}) >>> t.render(c) u'My name is Daryl Spitzer.' 

See the Django documentation (linked above) for a description of some of the settings you may want to define (as keyword arguments to configure).

like image 178
Daryl Spitzer Avatar answered Sep 22 '22 21:09

Daryl Spitzer