Django: Displaying MySQL table records

Django Django MySQL Database
To display records from MySQL database we will create one model first. If you have checked our Django MySQL tutorial their we have already created one class student. Here it is again.
from django.db import models

# Create your models here.

class student(models.Model):
	st_name =models.CharField(max_length=100)
	st_sex  =models.CharField(max_length=20)
	st_mark =models.IntegerField()
In the above code we have created one student class and declared all fields with field types.

Inside the we will import the above class student and define the function display. Here is the code inside
from django.shortcuts import render
from .models import student

# Create your views here.

def display(request):
	st=student.objects.all() # Collect all records from table 
	return render(request,'display.html',{'st':st})
In above code inside we have declared display function and inside the function we returned display.html page.

In second line we have imported student class from file by saying from .models import student

Note the line saying st=student.bojects.all() , this collects all records from the table. It returns a list ( variable st ) with all data. We are creating a dictionary and passing the values to our display.html page.
Here display.html page will receive the data and display them. Here is the code inside display.html
{% for sts in st %}

{{sts.st_name}}, {{sts.st_class}}<br>

{% endfor %}
This will display all records of student table from our database.

Connecting to

To execute our model and display records we must add our function to file.
from django.urls import include, path
from.import views

urlpatterns = [
When we use above url, our url page inside student app will run using display function and returns display.html ( see the above code for

One sample output is here .
Alex, Four
John, Five
Albert, Six
Queen, Five

Post your comments , suggestion , error , requirements etc here

We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2020 All rights reserved worldwide Privacy Policy Disclaimer