Django ··· 6 ModelForm的關係表應用
阿新 • • 發佈:2020-08-05
settings資料庫等修改
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'djangostudent', # 資料庫名字 'USER': 'root', # 賬號 'PASSWORD': 'root', # 密碼 'HOST': 'localhost', # IP 'PORT': '3306', # 埠 } }
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False
建表
(1)建學生表,學生詳情表,學院表,課程表
from django.db import models # Create your models here. class Student(models.Model): name = models.CharField(verbose_name='姓名',max_length=30,null=False) age = models.SmallIntegerField(verbose_name='年齡',null=True) sex= models.SmallIntegerField(default=1) phone = models.CharField(max_length=30,default='') QQ = models.CharField(default='', max_length=30) c_time = models.DateTimeField(verbose_name='建立時間',auto_now_add=True) e_time = models.DateTimeField(verbose_name='修改時間',auto_now=True) grade = models.ForeignKey('Grade',on_delete=models.SET_NULL,null=True,related_name='grade') def __str__(self): return self.name class Grade(models.Model): name = models.CharField(verbose_name='班級名稱',max_length=30) year = models.CharField(verbose_name='學年',max_length=30) def __str__(self): return self.name class StudentDetail(models.Model): student = models.OneToOneField('Student',on_delete=models.CASCADE,related_name='studentdetail') card_num = models.CharField(verbose_name='學生證號碼',max_length=30) college = models.CharField(verbose_name='學院名稱',max_length=30,default='學院資訊不詳') class Course(models.Model): name = models.CharField(verbose_name='課程名稱',max_length=30) student = models.ManyToManyField('Student',related_name='student',through='Enroll') def __str__(self): return self.name class Enroll(models.Model): student = models.ForeignKey('Student',on_delete=models.CASCADE) course = models.ForeignKey('Course',on_delete=models.CASCADE) c_time = models.DateTimeField(auto_now_add=True) paid = models.FloatField(verbose_name='付款',default=0)
(2)註冊遷移
from django.contrib import admin from sapp import models # Register your models here. admin.site.register(models.Student) admin.site.register(models.Course) admin.site.register(models.Grade) admin.site.register(models.StudentDetail) admin.site.register(models.Enroll)
執行makegrations和migrate
配置url
from django.contrib import admin from django.urls import path,re_path from sapp import views urlpatterns = [ path('studentinfo/', views.stu_info, name='stu_info'), path('showstudentinfo/', views.stu_info, name='stu_show_info'), path('courseinfo/', views.course_info, name='course_info'), path('showcourseinfo/', views.course_info, name='course_show_info'), path('enrollinfo/', views.enroll_info, name='enroll_info'), path('gradeinfo/', views.grade_info, name='grade_info'), ]
新建forms.py 檔案,
一個表建立一個類,繼承ModelForm
類中新建Meta類,指定模型和其它資訊
from django import forms from sapp.models import Student,StudentDetail,Course,Enroll,Grade class StudentForm(forms.ModelForm): class Meta: model = Student exclude =['e_time'] class StudentDetailForm(forms.ModelForm): class Meta: model = StudentDetail exclude = ['student'] class CourseForm(forms.ModelForm): class Meta: model = Course exclude = ['student'] class EnrollForm(forms.ModelForm): class Meta: model = Enroll exclude = [] class GradeForm(forms.ModelForm): class Meta: model = Grade exclude = []
views處理邏輯
from django.urls import reverse from sapp.forms import StudentForm, StudentDetailForm,CourseForm,EnrollForm,GradeForm from django.shortcuts import render,redirect def stu_info(request): section = '新增學生資訊' if request.method == "GET":#返回ModelForm stu_info_from = StudentForm() stu_d_info_from = StudentDetailForm() context={ 'stuform': stu_info_from, 'section': section, 'studform': stu_d_info_from, } return render(request, 'studentinfo/addstudent.html', context=context) if request.method == "POST":#處理提交的資訊 stu_info_from = StudentForm(request.POST) stu_d_info_from = StudentDetailForm(request.POST)#處理onetoone關係 if stu_info_from.is_valid() and stu_d_info_from.is_valid(): stu_d_info = stu_d_info_from.save(commit=False) # stu_info = stu_info_from.save() # 真儲存,已儲存到資料庫 stu_info.studentdetail = stu_d_info# 新增關係 stu_d_info.save() #真儲存stu_d_info redirect(reverse('stu_show_info')) return render(request, 'studentinfo/addshow.html', context={ 'stuformadd': stu_info, 'section': section, 'studformadd': stu_d_info, }) def course_info(request): section = '新增課程資訊' if request.method == "GET": course_info_from = CourseForm() context={ 'stuform': course_info_from, 'section': section, } return render(request, 'studentinfo/addcourse.html', context=context) if request.method == "POST": course_info_from = CourseForm(request.POST)#處理manytomany關係 if course_info_from.is_valid(): course_info = course_info_from.save() # 真儲存,已儲存到資料庫 redirect(reverse('course_show_info')) return render(request, 'studentinfo/addcshow.html', context={ 'couseformadd': course_info, 'section': section, }) def enroll_info(request): section = '為學生新增課程' if request.method == "GET": enroll_info_from = EnrollForm() context={ 'stuform': enroll_info_from, 'section': section, } return render(request, 'studentinfo/addenroll.html', context=context) if request.method == "POST": enroll_info_from = EnrollForm(request.POST) if enroll_info_from.is_valid(): enroll_info = enroll_info_from.save() redirect(reverse('enroll_info')) return render(request, 'studentinfo/addeshow.html', context={ 'enrollformadd': enroll_info, 'section': section, }) def grade_info(request): section = '新增課程資訊' if request.method == "GET": grade_info_from = GradeForm() context={ 'stuform': grade_info_from, 'section': section, } return render(request, 'studentinfo/addgrade.html', context=context) if request.method == "POST": grade_info_from = GradeForm(request.POST) if grade_info_from.is_valid(): grade_info = grade_info_from.save() # 真儲存,已儲存到資料庫 redirect(reverse('grade_info')) return render(request, 'studentinfo/addgshow.html', context={ 'couseformadd': grade_info, 'section': section, })
效果: