Django学生管理系统

setting.py

"""
Django settings for djangostumanager project.

Generated by 'django-admin startproject' using Django 2.1.1.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '!+z-dij7o##_rqami-)jc1rwvsz!3&sdo1ny0s_)7vlk@mt9m$'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'stuapp.apps.StuappConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'djangostumanager.urls'

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',
            ],
        },
    },
]

WSGI_APPLICATION = 'djangostumanager.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'student',
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': 'localhost'
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'

urls.py

from django.contrib import admin
from django.urls import path
from stuapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index, name='index'),
    path('add/', views.add, name='add'),
    path('select/', views.select, name='select'),
    path('delete/', views.delete, name='delete'),
]

models.py

from django.db import models

# Create your models here.

class Student(models.Model):
    sname = models.CharField(max_length=20)
    sage = models.IntegerField()

    class Meta:
        db_table = 'student'

views.py

from django.shortcuts import render
from .models import Student
# Create your views here.

def index(request):
    # 访问首页,页面中展示所有学员的信息
    stus = Student.objects.all()
    if stus:
        # 如果结果集存在,将这个结果集渲染到模版中。
        return render(request, template_name='index.html', context={'students': stus})
    else:
        return render(request, template_name='index.html', context={'message': '暂无学员信息!'})

def add(request):
    print(request.method)
    if request.method == "GET":
        return render(request, 'add.html')
    elif request.method == "POST":
        name = request.POST.get('sname')
        age = request.POST.get('sage')
        s = Student(sname=name, sage=age)
        s.save()
        return render(request, 'add.html', {'result': '学员添加成功!'})


def select(request):
    if request.method == "GET":
        return render(request, 'select.html')
    elif request.method == "POST":
        # 接收学员ID值,取数据库中查询数据
        stu_id = request.POST.get('sname')
        try:
            student = Student.objects.get(id=stu_id)
            return render(request, 'select.html', {'student': student})
        except:
            return render(request, 'select.html', {'message': '没有查找到id={}相关信息!'.format(stu_id)})

def delete(request):
    if request.method == "GET":
        return render(request, 'delete.html')
    elif request.method == "POST":
        # 接收学员ID值,取数据库中查询数据
        stu_id = request.POST.get('sname')
        try:
            Student.objects.get(id=stu_id).delete()
            return render(request, 'delete.html', {'message': '删除id={}的学员成功!'.format(stu_id)})
        except:
            return render(request, 'delete.html', {'message': '没有查找到id={}相关信息!'.format(stu_id)})

templates下add.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>添加学员</title>
    </head>
    <body>
        <a href="/index/">< 返回首页</a>
        <hr>
        <form action="/add/" method="post">
            {% csrf_token %}
            {# label中的for属性的值等于input中的id属性的值。只有值一致,才能让label起到定位光标的作用。 #}
            {# name="sname" 该属性的值用在views.py中:request.POST.get('sname')中的sname就是name属性的值。 #}
            <label for="uname">姓名:</label>
            <input type="text" name="sname" id="uname" placeholder="输入姓名">
            <br>
            <label for="uage">年龄:</label>
            <input type="text" name="sage" id="uage" placeholder="输入年龄">
            <br>
            <button type="submit">添加</button>
        </form>
        {% if result %}
            {{ result }}
        {% endif %}
    </body>
</html>

delete.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>删除学员</title>
    </head>
    <body>
        <a href="/index/">< 返回首页</a>
        <hr>
        <form action="/delete/" method="post">
            {% csrf_token %}
            <label for="uname">ID:</label>
            <input type="text" name="sname" id="uname" placeholder="输入学员ID">
            <button type="submit">删除</button>
        </form>
        {% if message %}
            <h1>{{ message }}</h1>
        {% endif %}
    </body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>学生管理系统</title>
    </head>
    <body>
        <a href="/add/">添加学员</a><br>
        <a href="/select/">查询学员</a><br>
        <a href="/delete/">删除学员</a><br>

        <ul>
            {% if message %}
                {# 如果message这个键存在,说明是没有学员信息的。 #}
                <h1>{{ message }}</h1>
            {% else %}
                {# 如果message这个键不存在,说明传过来的是结果集students #}
                {% for student in students %}
                    <li>ID:{{ student.id }}; NAME:{{ student.sname }}; AGE:{{ student.sage }}</li>
                {% endfor %}
            {% endif %}
        </ul>
    </body>
</html>

select.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>查询学员</title>
    </head>
    <body>
        <a href="/index/">< 返回首页</a>
        <hr>
        <form action="/select/" method="post">
            {% csrf_token %}
            <label for="uname">ID:</label>
            <input type="text" name="sname" id="uname" placeholder="输入学员ID">
            <button type="submit">查询</button>
        </form>
        {% if student %}
            <p>{{ student.id }}-{{ student.sname }}-{{ student.sage }}</p>
        {% elif message %}
            <h1>{{ message }}</h1>
        {% endif %}
    </body>
</html>

猜你喜欢

转载自www.cnblogs.com/chensang/p/10001957.html