Django project configuration database

Install the dependencies required to connect to the MySQL database in the virtual environment

pip install mysqlclient

Modify the settings.py file of the project,

DATABASES = {
    'default': {
        # 数据库引擎配置
        'ENGINE': 'django.db.backends.mysql',
        # 数据库的名字
        'NAME': 'vote',
        # 数据库服务器的IP地址(本机可以写localhost或127.0.0.1)
        'HOST': 'localhost',
        # 启动MySQL服务的端口号
        'PORT': 3306,
        # 数据库用户名和口令
        'USER': 'hellokitty',
        'PASSWORD': 'Hellokitty.618',
        # 数据库使用的字符集
        'CHARSET': 'utf8',
        # 数据库时间日期的时区设定
        'TIME_ZONE': 'Asia/Chongqing',
    }
}

First build the database table, and then automatically generate the orm object (reverse engineering)

As follows, polls is the application name

python manage.py inspectdb > polls/models.py

First write the orm object code, and then automatically generate the database table (forward engineering)

Modify the models.py file and add the following code to the file:

class User(models.Model):
    """用户"""
    no = models.AutoField(primary_key=True, verbose_name='编号')
    username = models.CharField(max_length=20, unique=True, verbose_name='用户名')
    password = models.CharField(max_length=32, verbose_name='密码')
    tel = models.CharField(max_length=20, verbose_name='手机号')
    reg_date = models.DateTimeField(auto_now_add=True, verbose_name='注册时间')
    last_visit = models.DateTimeField(null=True, verbose_name='最后登录时间')

    class Meta:
        db_table = 'tb_user'
        verbose_name = '用户'
        verbose_name_plural = '用户'

Execute the following command

python manage.py makemigrations polls
python manage.py migrate polls

Use Django background management model

Migrate the tables required by the admin application to the database

pip install Pillow # 如果已经安装了可以不安装
python manage.py migrate

Create a superuser account to access the admin application

python manage.py createsuperuser

image

Startup project

python manage.py runserver

Browser access, enter the account password you just created (admin/123456)

http://127.0.0.1:8000/admin/

Register the model class and modify the admin.py file in the application directory

from django.contrib import admin

from polls.models import Subject, Teacher

admin.site.register(Subject)
admin.site.register(Teacher)

image

Register the model management class. By registering the model management class, you can better manage the model in the background management system. For this reason, we will modify the admin.py file

from django.contrib import admin

from polls.models import Subject, Teacher


class SubjectModelAdmin(admin.ModelAdmin):
    list_display = ('no', 'name', 'intro', 'is_hot')
    search_fields = ('name', )
    ordering = ('no', )


class TeacherModelAdmin(admin.ModelAdmin):
    list_display = ('no', 'name', 'sex', 'birth', 'good_count', 'bad_count', 'subject')
    search_fields = ('name', )
    ordering = ('no', )


admin.site.register(Subject, SubjectModelAdmin)
admin.site.register(Teacher, TeacherModelAdmin)

image

In order to view the model better, we add the __str__ magic method to the Subject class and return the subject name in this method. In this way, when the subject of the teacher is displayed on the page of viewing the teacher as shown in the figure above, it is no longer such obscure information as Subject object (1), but the name of the subject.

Realize the effect of subject page and teacher page

  1. Modify the settings.py file to configure the path where the template file is located
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates'), ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
  1. Modify the polls/views.py file and write the view function to render the subject page and teacher page.
from django.shortcuts import render, redirect

from polls.models import Subject, Teacher


def show_subjects(request):
    subjects = Subject.objects.all().order_by('no')
    return render(request, 'subjects.html', {'subjects': subjects})


def show_teachers(request):
    try:
        sno = int(request.GET.get('sno'))
        teachers = []
        if sno:
            subject = Subject.objects.only('name').get(no=sno)
            teachers = Teacher.objects.filter(subject=subject).order_by('no')
        return render(request, 'teachers.html', {
            'subject': subject,
            'teachers': teachers
        })
    except (ValueError, Subject.DoesNotExist):
        return redirect('/')
  1. Modify the templates/subjects.html template page
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>学科信息</title>
   <style>
       #container {
           width: 80%;
           margin: 10px auto;
       }
       .user {
           float: right;
           margin-right: 10px;
       }
       .user>a {
           margin-right: 10px;
       }
       #main>dl>dt {
           font-size: 1.5em;
           font-weight: bold;
       }
       #main>dl>dd {
           font-size: 1.2em;
       }
       a {
           text-decoration: none;
           color: darkcyan;
       }
   </style>
</head>
<body>
   <div id="container">
       <div class="user">
           <a href="login.html">用户登录</a>
           <a href="register.html">快速注册</a>
       </div>
       <h1>扣丁学堂所有学科</h1>
       <hr>
       <div id="main">
           {% for subject in subjects %}
           <dl>
               <dt>
                   <a href="/teachers/?sno={
   
   { subject.no }}">{
   
   { subject.name }}</a>
                   {% if subject.is_hot %}
                   <img src="/static/images/hot-icon-small.png">
                   {% endif %}
               </dt>
               <dd>{
   
   { subject.intro }}</dd>
           </dl>
           {% endfor %}
       </div>
   </div>
</body>
</html>
  1. Modify the templates/teachers.html template page
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>老师信息</title>
    <style>
        #container {
            width: 80%;
            margin: 10px auto;
        }
        .teacher {
            width: 100%;
            margin: 0 auto;
            padding: 10px 0;
            border-bottom: 1px dashed gray;
            overflow: auto;
        }
        .teacher>div {
            float: left;
        }
        .photo {
            height: 140px;
            border-radius: 75px;
            overflow: hidden;
            margin-left: 20px;
        }
        .info {
            width: 75%;
            margin-left: 30px;
        }
        .info div {
            clear: both;
            margin: 5px 10px;
        }
        .info span {
            margin-right: 25px;
        }
        .info a {
            text-decoration: none;
            color: darkcyan;
        }
    </style>
</head>
<body>
    <div id="container">
        <h1>{
   
   { subject.name }}学科的老师信息</h1>
        <hr>
        {% if not teachers %}
            <h2>暂无该学科老师信息</h2>
        {% endif %}
        {% for teacher in teachers %}
        <div class="teacher">
            <div class="photo">
                <img src="/static/images/{
   
   { teacher.photo }}" height="140" alt="">
            </div>
            <div class="info">
                <div>
                    <span><strong>姓名:{
   
   { teacher.name }}</strong></span>
                    <span>性别:{
   
   { teacher.sex | yesno:'男,女' }}</span>
                    <span>出生日期:{
   
   { teacher.birth | date:'Y年n月j日'}}</span>
                </div>
                <div class="intro">{
   
   { teacher.intro }}</div>
                <div class="comment">
                    <a href="">好评</a> (<strong>{
   
   { teacher.good_count }}</strong>)
                        
                    <a href="">差评</a> <strong>{
   
   { teacher.bad_count }}</strong>)
                </div>
            </div>
        </div>
        {% endfor %}
        <a href="/">返回首页</a>
    </div>
</body>
</html>
  1. Modify the vote/urls.py file to realize the mapping URL.
from django.contrib import admin
from django.urls import path

from polls.views import show_subjects, show_teachers

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', show_subjects),
    path('teachers/', show_teachers),
]
  1. Access address http://127.0.0.1:8000/
    image

Click on Python full-stack development to jump to the page
image

Guess you like

Origin blog.csdn.net/cz285933169/article/details/121681103