15.1 Templates in Django: Introduction to Django
Django is a high-level framework, written in Python, that encourages rapid development of clean, pragmatic web applications. It is designed to help developers take their applications from concept to completion as quickly as possible. One of the main features of Django is its templating system, which is an essential component for building robust and scalable web applications.
Model Concept in Django
In Django, a model is the representation of a database object. It is a description of how data should be stored and manipulated. Every model in Django is a Python class that inherits from django.db.models.Model, and the attributes of the class represent database fields.
Templates are used to create, retrieve, update, and delete records in your database using the Django ORM (Object-Relational Mapping). Django's ORM lets you interact with your database as if you were writing pure Python.
Creating a Model in Django
To create a model in Django, you first need to define a class that inherits from django.db.models.Model. Next, you define your template's fields. Each field is represented by an instance of a Field class - for example, CharField for character fields and DateTimeField for dates and times. When instantiating a field, you can specify a variety of attributes. For example, you can use the 'max_length' attribute to limit the maximum length of a CharField.
class Book(models.Model):
title = models.CharField(max_length=200)
publication_date = models.DateTimeField()
Once the model is defined, Django will create a database table for that model. The table name is the model name, in all lower case.
Template Manipulation in Django
With the templates defined, you can use the Django ORM to create, retrieve, update, and delete records in your database. To create a new record, you instantiate a new model and call the save() method.
book = Book(title='The Django Book', publication_date=datetime.now())
book.save()
To retrieve records, you use the objects attribute of the model, which is a Manager. The Manager is an interface through which database operations are provided. You can use methods like get() and filter() to retrieve records.
book = Book.objects.get(title='The Django Book')
books = Book.objects.filter(publication_date__year=2020)
To update a record, you change the model's attributes and call the save() method. To delete a record, you call the delete() method.
book.title = 'The Django Book: Second Edition'
book.save()
book.delete()
In short, models in Django are a powerful tool for dealing with databases. They let you interact with your database as if you were writing pure Python, and they provide a convenient way to define the structure of your data. With Django templates, you can focus on writing your code instead of worrying about your database quirks.