Python code in django template

How to Pass a Python Variable to a Template in Django

In this article, we show how to pass a Python variable to a template in Django.

Basically, this is it. You have the part in your Django package, where you keep your main Python code. Normally, this would be the models.py (for database connection) and views.py (for variables and variable manipulation) and such.

Outside of this, you have a template or templates, where you have your frontend stuff, such as your HTML file that forms the frontend of your website, what the user sees.

Django allows for separation of Python code (backend code) with frontend code (such as HTML, CSS, and Javascript).

This way, frontend sofware developers can work on frontend things, like backend developers can focus on backend things.

However, the frontend files (HTML template files) may need Python code added to it from the backend code (found in models.py or views.py). So, it is important to know how to add Python code to a frontend file in Django.

So, basically you do all your backend work in the models.py and view.py files and then at the end, a backend engineer can just add the code to finished frontend file that a frontend engineer has made.

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.

We won’t go into a database example for this one. We’ll do a very simple example in the views.py file and then transfer to the template we are working with.

This will pass the Python variable to a template in Django.

views.py File

So, in this code, we create a Python variable called Craig.

We will then pass this into the template file we are dealing with Greeting.html.

You’ll see exactly what’s going on.

The code for this views.py file that we have is shown below.

So now we’ll go over each line of code.

First, we must import render from django.shortcuts, so that we can render in the template file that we are working with.

Next, we create a function called index that always must have a request parameter.

We create a dictionary named person that has attributes firstname and lastname. Craig is the person’s first name and Daniels is the person’s last name.

We also create a variable called weather and set it equal to «sunny».

We then create a dictionary named context. In this dictionary context, we pass every variable into that we want passed to the template file.

Context is a special dictionary that holds every variable that you want passed into the template file that you are working with.

In our line of code, we render into the template context and request. So, basically, we pass in the person and weather variables to the greetings.html template file.

This concludes the views.py file.

Template File- greetings.html

So, next, we have our template file, which is greetings.html.

In this file, we keep it very basic. We just want to focus on how to display the variables that we had present in the views.py file.

So, this is the composition of the views.py file.

So, this file is very simple.

In h1 header tags, we say Hi, followed by > > followed by closing the header tags.

So, remember to display variables in Django, you use double opening and closing curly braces, >. Inside of these curly braces, you specify the variable that you want to display. So, we created a dictionary named person that contains the person’s first and last name. Therefore, we call the first name, by person.firstname and the last name by person.lastname.

Next, we create another header tag and say «Today it is » followed by the variable weather. Remember weather was set to «sunny». Therefore, in this line we are saying, Today it is sunny.

And this is all that is needed to pass Python variables to a template in Django.

Running this code, I get the following output shown below.

Django template with Python variables passed to it

You can see that we’ve successfully passed the Python variables from the views.py file to the template, greetings.html.

So, you can see that transferring from Python code to templates is very simple.

Источник

Templates¶

Being a web framework, Django needs a convenient way to generate HTML dynamically. The most common approach relies on templates. A template contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted. For a hands-on example of creating HTML pages with templates, see Tutorial 3 .

A Django project can be configured with one or several template engines (or even zero if you don’t use templates). Django ships built-in backends for its own template system, creatively called the Django template language (DTL), and for the popular alternative Jinja2. Backends for other template languages may be available from third-parties. You can also write your own custom backend, see Custom template backend

Django defines a standard API for loading and rendering templates regardless of the backend. Loading consists of finding the template for a given identifier and preprocessing it, usually compiling it to an in-memory representation. Rendering means interpolating the template with context data and returning the resulting string.

The Django template language is Django’s own template system. Until Django 1.8 it was the only built-in option available. It’s a good template library even though it’s fairly opinionated and sports a few idiosyncrasies. If you don’t have a pressing reason to choose another backend, you should use the DTL, especially if you’re writing a pluggable application and you intend to distribute templates. Django’s contrib apps that include templates, like django.contrib.admin , use the DTL.

For historical reasons, both the generic support for template engines and the implementation of the Django template language live in the django.template namespace.

The template system isn’t safe against untrusted template authors. For example, a site shouldn’t allow its users to provide their own templates, since template authors can do things like perform XSS attacks and access properties of template variables that may contain sensitive information.

The Django template language¶

Syntax¶

This is an overview of the Django template language’s syntax. For details see the language syntax reference .

A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags.

A template is rendered with a context. Rendering replaces variables with their values, which are looked up in the context, and executes tags. Everything else is output as is.

The syntax of the Django template language involves four constructs.

Variables¶

A variable outputs a value from the context, which is a dict-like object mapping keys to values.

Variables are surrounded by > like this:

My first name is  first_name >>. My last name is  last_name >>.

With a context of , this template renders to:

My first name is John. My last name is Doe.

Dictionary lookup, attribute lookup and list-index lookups are implemented with a dot notation:

 my_dict.key >>  my_object.attribute >>  my_list.0 >> 

If a variable resolves to a callable, the template system will call it with no arguments and use its result instead of the callable.

Tags¶

Tags provide arbitrary logic in the rendering process.

This definition is deliberately vague. For example, a tag can output content, serve as a control structure e.g. an “if” statement or a “for” loop, grab content from a database, or even enable access to other template tags.

Tags are surrounded by like this:

Most tags accept arguments:

Some tags require beginning and ending tags:

 if user.is_authenticated %>Hello,  user.username >>. endif %> 

Filters¶

Filters transform the values of variables and tag arguments.

The Web Framework For Perfectionists With Deadlines

Some filters take an argument:

Источник

Читайте также:  Chrome extension bgnkhhnnamicmpeenaelnjfhikgbkllg pages options html
Оцените статью