Python 如何在django中将下拉列表值保存到数据库

Python 如何在django中将下拉列表值保存到数据库,python,django,database,sqlite,dropdown,Python,Django,Database,Sqlite,Dropdown,我正在做一个考勤系统,学生可以通过在下拉列表中查找他们的名字来标记他们的考勤。然后学生将按submit,信息将存储在MarkAtt数据库中。目前,它没有相应地显示班级的学生姓名,当我单击提交时,它会显示以下错误:“valueerror”出现。ValueError异常值:无法分配“,…”MarkAtt.studName“必须是“名称列表”实例。我需要每次单击将选定的学生姓名存储在数据库中 class MarkAtt(models.Model): studName = models.Foreign

我正在做一个考勤系统,学生可以通过在下拉列表中查找他们的名字来标记他们的考勤。然后学生将按submit,信息将存储在MarkAtt数据库中。目前,它没有相应地显示班级的学生姓名,当我单击提交时,它会显示以下错误:“valueerror”出现。ValueError异常值:无法分配“,…”MarkAtt.studName“必须是“名称列表”实例。我需要每次单击将选定的学生姓名存储在数据库中

 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}} 
Forms.py

班级学生考勤表(forms.ModelForm): 类元: 型号=MarkAtt 字段=['studName'] 标签={ “姓名”:“学生姓名” }

def __init__(self,*args, **kwargs):
    super(studentAttendanceForm, self).__init__(*args,**kwargs)
    self.fields['studName'].label = "Select your name:" 

但是,表单没有显示在模板页面中,我无法将值保存在数据库中。非常感谢您的帮助。非常感谢。

您必须在视图中分离
获取
发布
请求,例如:

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})  
对于您的表单,最好使用
字段
而不是
排除

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\u p
,则不必调用
form.att.label\u tag
,也不必将其放在
tag
见文件:

您的视图中没有包含
今天
,因此应该是不打印任何内容。
因为在渲染函数中,只发送
信息
表单

今天没有

返回呈现(请求,'namelist.html',{'information':信息,'form':form})

为了提高代码的可读性,最好这样编写:

context = {
    'information': information,
    'form': form,
    'group': ......, # fill this
    'today': ...... # fill this too
}
return render(request, 'namelist.html', context)
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})

编辑

要根据组id指定下拉列表,您可以传递组对象并在
\uuuu init\uuuu
表单中使用
.queryset

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)

我认为您的表单不会显示,因为它仅在“尝试和例外”部分中定义。请尝试使用如下代码:

context = {
    'information': information,
    'form': form,
    'group': ......, # fill this
    'today': ...... # fill this too
}
return render(request, 'namelist.html', context)
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})

共享您的表单。py文件对不起,编辑了我上面的问题。尝试更改。但表单仍然没有显示在我的模板页面中…好的,因此您的代码中存在一些问题,我编辑了我的回答,再次尝试,但没有效果..不确定为什么它没有显示下拉列表。是否需要指定任何内容以让他们知道我想要它b下拉列表中的e?您是否尝试了
{{{form.studName}}
而不是
{form.as_p}}
?它成功显示,因为我没有调用视图。当我单击提交时,出现了一个错误,“valueerror”。valueerror异常值:无法分配“
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)
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})