1.如何为整数字段Django设置默认值,最大值和最小值?
https://www.icode9.com/content-1-230548.html
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
class Match(models.Model):
.......
overs = models.IntegerField(default=10, validators=[MinValueValidator(1), MaxValueValidator(100)])
2.设定考试成绩维护页面
#models.py
class Subject_Score(models.Model):
sid = models.AutoField(primary_key=True)
subject = models.ForeignKey(Subject,on_delete=models.CASCADE)
employee = models.ForeignKey(Employee,on_delete=models.CASCADE)
score = models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(100)],help_text='请输入0-100的整数')
def __str__(self):
return '%s : %s' % (self.subject.Subject_id, self.employee.name)
class Meta:
#增加唯一性限制
unique_together = (("subject", "employee"),)
#排序
ordering = ['subject']
#views.py
# 建立表单页for Subject_Score_Form
def Subject_Score_Form(request):
if request.method == 'POST' and request.POST:
form = SubjectScoreForm(data=request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
employee = form.cleaned_data['employee']
score = form.cleaned_data['score']
# 实例化对象
subject_instance = Subject.objects.get(Subject_id=subject)
employee_instance = Employee.objects.get(name=employee)
# 表中添加数据
Subject_Score.objects.create(subject=subject_instance,employee=employee_instance,score=score)
return HttpResponseRedirect('/admin/')
else:
form = SubjectScoreForm()
else:
form = SubjectScoreForm()
return render(request, 'myclass/SubjectScoreForm.html',context={'form':form})
#forms.py
class SubjectScoreForm(forms.Form):
subject = forms.ModelChoiceField(label=r'课程编码',queryset=Subject.objects.all())
employee = forms.ModelChoiceField(label=r'姓名',queryset=Employee.objects.all())
score = forms.IntegerField(label=r'成绩', validators=[MinValueValidator(0), MaxValueValidator(100)],help_text='请输入0-100的整数')
3.设定考试成绩查询页面
#models.py沿用Subject_Score,无需新增。
#views.py
# 建立成绩查询界面-all
def Search_Subject_Score(request):
score_list = Subject_Score.objects.order_by('sid').all()
return render(request, 'myclass/Search_Subject_Score.html',context={'score_list': score_list})
#Search_Subject_Score.html
<html>
<head>
<title>Search_Subject_Score</title>
</head>
<body>
<table>
<p>成绩查询页面</p>
<tr align="center" style="color:White;background-color:#3366FF;font-family:微軟正黑體,Tahoma,Arial,微軟雅黑體;font-size:14px;">
<th scope="col">课程</th>
<th scope="col">工号</th>
<th scope="col">学员</th>
<th scope="col">部门</th>
<th scope="col">成绩</th>
</tr>
{% for form_field in score_list %}
<tr align="center" valign="middle" style="color:Black;background-color:#EFF3FB;border-color:#E0E0E0;border-width:1px;border-style:solid;height:26px;">
<td>{{ form_field.subject }}</td>
<td>{{ form_field.employee.eid }}</td>
<td>{{ form_field.employee.name }}</td>
<td>{{ form_field.employee.dept_code }}</td>
<td>{{ form_field.score }}</td>
</tr>
{% endfor %}
</table>
</body>