我正在使用一个考勤系统,该学生可以通过在下拉列表值中查找他们的姓名来标记他们的出勤。然后,学生将按Submit(提交),信息将存储在MarkAtt数据库中。当前它没有显示与班级相应的学生姓名,当我单击“提交”时,它显示以下错误:出现“ valueerror”。 ValueError异常值:无法分配“,,......” MarkAtt.studName“必须是” Namelist“实例。我需要将选定的学生姓名每单击一次存储在数据库中。...< / p>
class MarkAtt(models.Model):
studName = models.ForeignKey(Namelist,on_delete=models.SET_NULL,blank=True, null=True, default=None)
classGrp = models.ForeignKey('GroupInfo', on_delete=models.SET_NULL, null=True)
currentDate = models.DateField(default=now())
week = models.IntegerField(default=0)
attendance = models.IntegerField(default=1) #1 is present
该模板在一个淹死列表框中显示班级信息,今天的日期和学生的姓名。
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
Lab Group: {{group.classGrp}} //this is from another view
Day: {{group.day}}
Time: {{group.time}}
Today's date: {{today.date}}
{{form.as_p}}
视图:
def mark_stud(request,id):
group = GroupInfo.objects.get(id=id)
studName = Namelist.objects.filter(classGrp=id)
information = {}
information['group'] = group
information['studName'] =studName
if request.method == 'POST':
form = studentAttendanceForm(request.POST)
if form.is_valid():
att = form.save(commit=False)
att.studName = information['studName']
att.currentDate = datetime.datetime.now.date()
form.save()
return redirect('namelist.html')
else:
form = studentAttendanceForm()
return render(request, 'namelist.html', {'information' :information, 'form':form})
Forms.py
class studentAttendanceForm(forms.ModelForm): 类Meta: 型号= MarkAtt 字段= ['studName'] 标签= { '姓名':'学生姓名' }
def __init__(self,*args, **kwargs):
super(studentAttendanceForm, self).__init__(*args,**kwargs)
self.fields['studName'].label = "Select your name:"
但是,表单未显示在模板页面中,并且我无法将值保存在数据库中。非常感谢您的帮助。非常感谢。
答案 0 :(得分:2)
您必须在视图中分离GET
和POST
请求,例如:
if request.method == POST:
form = studentAttendanceForm(request.POST)
if form.is_valid():
att = form.save(commit=False)
att.studName = information['studName']
att.currentDate = datetime.datetime.now.date()
form.save()
return redirect('namelist.html')
else: # for GET request
form = studentAttendanceForm()
return render(request, 'namelist.html', {'information' :information, 'form':form})
对于您的表单,最好使用fields
而不是exclude
:
class studentAttendanceForm(forms.ModelForm):
class Meta:
model = MarkAtt
fields = ('studName')
def __init__(self, *args, **kwargs):
super(studentAttendanceForm, self).__init__(*args, **kwargs)
self.fields['studName'].label = "Select your name:"
然后在您的模板中
如果您使用form.as_p
,则不必调用form.att.label_tag
,也不必将其放在<p>
标签内
查看文档:{{3}}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
...
{{form.as_p}}
...
另一个问题是,模板中的group
和today
是什么?
Lab Group: {{group.classGrp}}
Day: {{group.day}}
Time: {{group.time}}
Today's date: {{today.date}}
您的视图中未包含group
和today
,因此不应打印任何内容。
因为在渲染功能中,您仅发送information
和form
,
没有group
和today
return render(request, 'namelist.html', {'information' :information, 'form':form})
为了增加可读性代码,最好这样写:
context = {
'information': information,
'form': form,
'group': ......, # fill this
'today': ...... # fill this too
}
return render(request, 'namelist.html', context)
编辑
要基于组ID指定下拉列表,您可以传递组对象并以.queryset
格式使用__init__
group = GroupInfo.objects.get(id=id)
if request.method == 'POST':
form = studentAttendanceForm(request.POST, class_group=group)
...
else:
form = studentAttendanceForm(request.POST, class_group=group)
def __init__(self,*args, **kwargs):
class_group = kwargs.pop('class_group')
super(studentAttendanceForm, self).__init__(*args,**kwargs)
self.fields['studName'].label = "Select your name:"
self.fields['studName'].queryset = Namelist.objects.filter(classGrp=class_group)
答案 1 :(得分:-1)
我认为您的表单不会显示,因为它仅在“ try andexcept”部分内定义。尝试使用如下代码:
def mark_stud(request, class_id,id):
form = studentAttendanceForm(request.POST)
if (not class_id or not id):
return HttpResponseForbidden()
else:
try:
classGrp = None
information = {}
information['studName'] = Namelist.objects.get(name=id)
if form.is_valid():
att = form.save(commit=False)
att.studName = information['studName']
att.currentDate = datetime.datetime.now.date()
form.save()
return redirect('namelist.html')
except ObjectsDoesNotExist:
print("no entries")
return redirect('namelist.html')
return render(request, 'namelist.html', {'information' :information, 'form':form})