Models and Templates in Django

Welcome to the 3rd thread of Hello Django. Here we will cover, Template rendering, Model creation (Database) and also retrieving those data entries from database into our html file.

Django was designed to interact with database, so it makes it very easy to do so. Considering the previous project file nomenclature, in order to define the the classes which will define the types of data being stored in the database we will be editing the appname/  file with below given piece of code.

from django.db import models
class Student(models.Model):
      first_name = models.CharField( max_length = 50 )
      last_name = models.CharField( max_length = 50 )
      roll_no = models.IntegerField()
      def __str__(self):
            return f"{self.firs_name} {self.last_name}"

This will create an sqlite database with table name Student. The __str__() method is python way of converting the objects into string

Now to retrieve the database entries update the appname/  file with below given code:

from django.shortcuts import render
from .models import Student

# Define your views here

def index(request):
      db = Student.objects.all() # Take all the entries from Student model
      return render(request, "index.html", { "data" : db }

The render() is used to define the HTML file name to be render whenever a user visits the particular route. Django by default looks for the template folder in the projectname/appname/ dir.

P.S. It is a good practice to create a separate folder inside template directory for all the applications you create in the root application_folder. It helps in reducing the ambiguity while defining the n number of urls.

Create a new file with .html extension named index (as already mentioned in in appname/templates/ dir and add the below given code inside <body> tag.

      {% for item in data %}
      {% endfor %}

Django comes with built-in admin dashboard, which can be used to perform CRUD operations over the Django-models,for which we have to register the model we created before.

Edit the appname/  file in order to do so.

from django.contrib import admin
from .models import Student

# Register your models here.

Here we are done with the coding part and now its time to write some commands over cmd.

Whenever the model file is updated, it is mandatory to migrate all the changes we made, and to do so run below given commands one-by-one in project root directory.

>>> python makemigrations
>>> python migrate

Now, to create the login credentials for admin user run, python createsuperuser  and follow the instructions.

That’s it, we are done! Now go and hit the runserver command to run the django project and visit the localhost port :8000

To login into admin dashboard visit localhost:8000/admin   and enter the admin credentials.

Watch this short video for better reference for the topic. Render HTML Model Handling

In our next blog, we will see how Django handles multiple routes and static files like CSS, JS, and images. ‘Till then Happy Coding :]

One thought on “Models and Templates in Django

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s