有一种供学生注册的表格。 每个学生都在一所学校。 通过使用forms.ModelChoiceField,学校的名称将使用“选择”标签显示在模板中。 (一个下拉列表) 主要问题是,在选择“选择”标签的一个“选项”后,我无法在views.py 中获得选择的值。
models.py
class School(models.Model):
name = models.CharField(max_length=40)
def __str__(self):
return self.name
class Student(models.Model):
name = models.CharField(max_length=40)
school = models.ForeignKey(School)
def __str__(self):
return self.name
forms.py
class SchoolForm(forms.ModelChoiceField):
def label_from_instance(self, obj):
return obj.name
class StudentForm(forms.ModelForm):
student_school = SchoolForm(queryset = School.objects.all())
class Meta:
model = Student
fields = ('name', 'school')
views.py
def student_register(request):
if request.method == 'POST':
form = StudentForm(request.POST)
form.school = request.POST['school']
if form.is_valid():
form.save
else:
form = StudentForm()
return render(request, 'index.html', {'form': form})
index.html
<form method="post" action={% 'student_register' %}>
{% csrf_token %}
{{ form.name }}
<select id="id_school" name="school">
{% for name in form.student_school %}
<option value={{ name }}>
{% endfor %}
</select>
</form>