Python 如何在django表单中指定希望通过下拉列表将特定值插入数据库中

Python 如何在django表单中指定希望通过下拉列表将特定值插入数据库中,python,django,database,dropdown,Python,Django,Database,Dropdown,我正试图将学生的名字保存在数据库中。现在,它正在保存学生的ID而不是姓名。我正在使用django表单,我不确定hw是否会告诉django表单我想在数据库中插入学生姓名。下面是我的forms.py代码: class studentAttendanceForm(forms.ModelForm): class Meta: model = MarkAtt fields = ['studName'] def __init__(self,*args, **kwargs): cl

我正试图将学生的名字保存在数据库中。现在,它正在保存学生的ID而不是姓名。我正在使用django表单,我不确定hw是否会告诉django表单我想在数据库中插入学生姓名。下面是我的forms.py代码:

class studentAttendanceForm(forms.ModelForm):
class Meta:
    model = MarkAtt 
    fields = ['studName']


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)
模板:

 <h6 style=" display: inline;"> Lab Group: {{group.classGrp}} </h6>
<h6 style="padding-left:70px; display: inline;">Day: {{group.day}} </h6>
<h6 style="padding-left: 70px;display: inline;">Time: {{group.time}} </h6>
<h6 style="padding-left: 70px;display: inline;"> Today's date: {{date.today}}</h6>

<br>
<br>

{{ form.as_p }} 

<button type ="submit" class="btn btn-outline-success" >Mark Attendance</button>
现在保存为:

id att studName classId周日期

421012019-09-15

我想存为


42 1 testName 1 0 2019-09-15默认情况下,Django
ForeignKey
字段将使用相关模型的主键作为存储在数据库列中的值,默认情况下这是
id
字段/列。您可以通过传递到
ForeignKey

class MarkAtt(models.Model):
    studName = models.ForeignKey(
        Namelist,
        on_delete=models.SET_NULL,
        blank=True,
        null=True,
        default=None,
        to_field='name' # Not sure what this should be as I don't know your NameList model
    )

使用的字段必须是唯一的

您可以共享您的模型吗?好的,完成@Iainshelvington我需要进行迁移和迁移吗?因为当我这样做时,它会说django.db.utils.OperationalError:外键不匹配-“namelist\u markatt”引用“namelist\u namelist”。我已经在上面添加了我最有名的模型,但我没有成功迁移。运行并单击“提交”时:错误“外键约束失败”
class MarkAtt(models.Model):
    studName = models.ForeignKey(
        Namelist,
        on_delete=models.SET_NULL,
        blank=True,
        null=True,
        default=None,
        to_field='name' # Not sure what this should be as I don't know your NameList model
    )