Method of calling object attribute or object in html template of django template

Keywords: Web Development Django vim Python Database

Environment: relying on the original test2 database

python3 version

Multi python environment


Enter, python 3 virtual environment, new project test4:

]# cd py3/django-test1/
]# django-admin startproject test4

To create an app bookshop:

]# cd test4
]# python manage.py startapp bookshop

Modify the settings.py main configuration file:

]# vim test4/settings.py
...
#The database is mysql, using the original test2 database name:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test2',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': '192.168.255.70',
        'PORT': '3306',
    }
}
#Add app:
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'bookshop',
)
#Add template lookup path:
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        ...
]
...

Under the project name directory, add the template directory and add the applied template directory under it:

]# mkdir -p templates/bookshop

In the main url routing profile, add a route to find the application url:

]# vim test4/settings.py 
...
urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^',include('bookshop.urls',namespace='bookshop')),
]

Create the urls.py file in the application directory:

]# vim bookshop/urls.py
from django.conf.urls import url
from .  import views

urlpatterns = [
    url(r'\^$',views.index,name='index'),
]

The above basic configuration is completed, and the following methods are introduced to invoke objects in the template:

Define model class:

In order to avoid migration, the definition of model class should be the same as test2 database structure;

]# vim bookshop/models.py
from django.db import models

class BookInfo(models.Model):
    btitle = models.CharField(max_length=20)
    bpub_date = models.DateTimeField(db_column='pub_date') #Define the field name as pub date, and the default field name is the class property, that is, the default field name is bpub date
    bread = models.IntegerField()
    bcommet = models.IntegerField()
    isDelete = models.BooleanField()

    #Define table name
    class Meta():
        db_table = 'bookinfo'
    #If the above two lines are not written, the table name defaults to the project name. Class name, that is, bookshop.bookinfo

class HeroInfo(models.Model):
    hname = models.CharField(max_length=10)
    hgender = models.BooleanField()
    hcontent = models.CharField(max_length=1000)
    isDelete = models.BooleanField()
    book = models.ForeignKey('BookInfo') #Define the foreign key. If the quotation mark can be omitted here, BookInfo can omit the quotation mark if it is defined first. If it is defined later, it needs to use quotation mark. It is absolutely right to use quotation mark. In the table, the field will automatically change to book "ID
    
    def showname(self):
        return self.hname

Define view:

]# vim bookshop/views.py
from django.shortcuts import render
from .models import *
#from models import * #Writing in python2


def index(request): #Must receive a parameter
    hero = HeroInfo.objects.get(pk=1) #Query entries with pk = 1
    context = {'hero':hero} #Must be in dictionary format
    return render(request,'bookshop/index.html',context)

Define the index.html template file:

]# vim templates/bookshop/index.html
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
</head>
<body>
{{ hero.hname }}<br><!--Properties of the calling object-->
{{hero.showname}}<!--Call the method of the object, but cannot pass parameters to the method-->

<!--Notes
#Order of point number resolution:
#1. First, use hero as the dictionary and hname as the key to find
#2. Take hero as the object and hname as the attribute or method search
#3. Finally, hero is used as the list and hname is used as the index to search
-->

</body>
</html>

Start web Service:

]# python manage.py runserver 192.168.255.70:8000
//Error reporting: error loading MySQLdb module: No module named 'MySQLdb'

Solution: since pymysql library is used in Python 3 version, there is no MySQL DB library, so it needs to be configured;


]# vim test4/__init__.py
import pymysql
pymysql.install_as_MySQLdb()

Start web service again successfully; browser access: http://192.168.255.70:8000/

The method of invoking the properties and objects of the object in the html template file is completed.

Posted by bloodgoat on Sat, 07 Dec 2019 03:25:16 -0800