Django學生管理系統
阿新 • • 發佈:2018-11-22
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_)[email protected]$' # 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>