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/models.py  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/views.py  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 views.py) in appname/templates/ dir and add the below given code inside <body> tag.

      {% for item in data %}
        <li>{{item}}</li>
      {% 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/admin.py  file in order to do so.

from django.contrib import admin
from .models import Student

# Register your models here.

admin.site.register(Student)

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 manage.py makemigrations
>>> python manage.py migrate

Now, to create the login credentials for admin user run, python manage.py 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 :]



Categories: Django, Python

Tags: , , , , , , ,

1 reply

Trackbacks

  1. Static files and URL’s handling in Django – THE NUCLEAR GEEKS

Leave a Reply

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

WordPress.com Logo

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

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s

%d bloggers like this: