这是我的第一个Django项目,我已经完成了95%的工作。我已经建立了两个模型;学生和签到记录。我有一个视图,该视图传递签入历史记录和一个允许学生签入的表格。然后,模板将呈现签入的学生。如果我使用管理页面更新结帐字段,则该学生将不再出现在主页上。
但是,我仍然沉迷于如何使用网页模板来更新模型中的签出字段。
Model.py
from django.db import models
from django.utils import timezone
# Create your models here.
class Student(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField(max_length=254)
student_id = models.IntegerField(max_length=6)
birth_date = models.IntegerField(max_length=6, default=None)
photo = models.ImageField(null=True, blank=True, default='default.jpg')
@property
def full_name(self):
return f"{self.first_name} {self.last_name}"
def __str__(self):
return self.full_name
class History(models.Model):
student = models.ForeignKey(Student,on_delete=models.CASCADE)
# check_in = models.DateTimeField(default=timezone.now)
check_in = models.DateTimeField(auto_now_add=True)
check_out = models.DateTimeField(null=True,blank=True)
@property
def duration(self):
if self.check_out is None:
return str(timezone.now() - self.check_in)[:-10]
else:
return str(self.check_out - self.check_in)
class Meta:
verbose_name_plural = "History"
ordering = ['-check_in']
def __str__(self):
return f"{self.student.full_name} - {self.duration}"
views.py
from django.shortcuts import render
from .models import History, Student
from .forms import CheckIn
from django.http import HttpResponse
# Create your views here.
def checkin(request):
if request.method == "GET":
print(request.GET)
if request.method == "POST":
print(request.POST)
form = CheckIn(request.POST)
if form.is_valid():
student_id = form.cleaned_data['student_id']
birth_date = form.cleaned_data['birth_date']
for student in Student.objects.all():
if student.student_id == student_id and student.birth_date == birth_date:
check_in = History(student=student)
check_in.save()
form = CheckIn()
else:
print("Not Valid")
form = CheckIn()
else:
form = CheckIn()
context = {"StudentsChecked": History.objects.all(),
"form": form}
return render(request=request, template_name="CheckIn.html", context=context)
谢谢。