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.
model.py
from django.db import models

# Create your models here.

class student(models.Model):
    
	st_name =models.CharField(max_length=100)
	st_class=models.CharField(max_length=20)
	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 views.py we will import the above class student and define the function display. Here is the code inside views.py
views.py
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 model.py we have declared display function and inside the function we returned display.html page.

In second line we have imported student class from models.py 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 urls.py

To execute our model and display records we must add our function to urls.py file.

urls.py
from django.urls import include, path
from.import views

urlpatterns = [
	path('student/display',views.display,name='display'),
]
http://127.0.0.1:8000/student/display
When we use above url, our url page inside student app will run views.py using display function and returns display.html ( see the above code for views.py)

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


plus2net.com



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 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer