Templates and Views in Django
Django, as a powerful framework for web development, provides many options for managing templates and views. In this content, we want to delve into how to set up templates and use them in views. This is a very important discussion because it allows developers to create web pages with a proper and logical structure detached from the visual design, making it clearer for programmers to depict information.
First of all, understanding the concept of templates is very important. In general, templates in Django include HTML accompanied by code named template tags that allow you to receive dynamic data from views and display it in various ways. This issue has led to Django becoming one of the most popular web frameworks in the world.
Now, let's talk a bit about views. In Django, views serve as the intermediary between data models and templates. That is, views receive data from models and pass them to templates for display. This mechanism helps to clearly delineate the program structure.
Below is a simple example of creating a view. You can use this to create a simple structure from a Django program that transfers data from a view to a template for display.
from django.shortcuts import render
def my_view(request):
context = {
'title': 'Main Page',
'message': 'Welcome to our site!'
}
return render(request, 'index.html', context)
Code Explanation
from django.shortcuts import render
This line imports the render library from the Django shortcuts module, which helps us use it to render templates.
def my_view(request):
This defines a function that serves as a view. This function processes a request that includes data from the user's HTTP request.
context = {...}
Here, a dictionary is created that includes keys and values for the data we want to send to the template.
return render(request, 'index.html', context)
The render function sends the template 'index.html' along with the context data to display.