In previous part of this tutorial series, we show how you can create simple web application using Django. how to develop basic and very first Website using Django.
In this post we are going to see ho we can use Templates in Django to render HTML code on Web page. Initially we hard coded the HTML part in views (views.py)
Let's start with very basic idea about how template works. Goto the directory you created in previous part(or any other Django project) and run python manage.py shell (It is necessary that you open terminal using this command)
Run the following commands,
What we have done is,- Imported template module.
- Created template using Template() method. Everything inside the '{{}}' are variables. In our example we have two variables name and age.
- To assign value to this variable, we used Context() method, which takes python dictionary as argument.
- Now we render the template using render() method. It takes template.Context as argument and return Unicode String. You can render Template with various Context.
Now to use this in Project. you can write following code in your views.py.
Open your urls.py and set URL for this(hello()) method/View. Also note the use of for loop. Using template does not solve the problem of hard coded HTML.
To solve this problem Django provides get_template() method. Before using this method you have set TEMPLATE_DIRS in your settings.py. Open settings.py and add path to directory in which you want to store your HTML files.
Now create hello.html file in template directory(you have to create this Dir.) and write any code in it. In our case we will write following code.
Now open views.py file of your project and add following method.
Open your urls.py and set URL for this(hello2()) method/View.
Django also provides shortcut for this. You can use following method as shortcut.
We will also set URL for this(hello3()) View. at the your urls.py will look someting like this.
That is all about using template in Django.
Tidak ada komentar:
Posting Komentar