【发布时间】:2021-01-05 17:34:06
【问题描述】:
在表单处理期间,当用户从下拉列表中选择一个值时,我希望能够在模型对象的基本模型上设置外键字段。
models.py
class Question(models.Model):
question = models.CharField(max_length=200)
class Teacher(models.Model):
name = models.CharField(max_length=200)
l_name = models.CharField(max_length=200)
class Student_Answer(models.Model):
teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)
question = models.ForeignKey(Question, on_delete=models.CASCADE)
answer = models.SmallIntegerField(choices=RATING_CHOICES)
例如,我在模型 A 中有 5 条记录,在模型 B 中有两条记录,我有两个模型表单。
forms.py
class AnswerForm(ModelForm):
class Meta:
model = Student_Answer
fields = ('answer',)
widgets = { 'answer': RadioSelect(choices=RATING_CHOICES),}
class TeacherForm(ModelForm):
name = ModelChoiceField(queryset=Teacher.objects.all())
class Meta:
model = Teacher
fields = ('name',)
对于问题,我只是直接在视图中分配它们,然后在验证后将实例提供给外键。现在,如果我对老师做同样的事情,我的意思是这个 teacher = Teacher.objects.get(id=2) 然后 choice.teacher = teacher 它将完美地工作.但这不是我想要的。教师将由用户选择。我正在寻找类似下图的方式。
views.py
def index(request):
question1 = Question.objects.get(id=6)
question2 = Question.objects.get(id=7)
if request.method == "POST":
teacher_form = TeacherForm(request.POST)
form = AnswerForm(request.POST, prefix='question1')
form1 = AnswerForm(request.POST, prefix='question2')
if (form.is_valid):
choice = form.save(commit=False)
choice.question = question1
choice.teacher = teacher_form
choice.save()
choice = form1.save(commit=False)
choice.teacher = teacher_form
choice.question = question2
choice.save()
return HttpResponseRedirect('/submited/')
else:
teacher_form = TeacherForm()
form = AnswerForm(prefix='question1')
form1 = AnswerForm(prefix='question2')
context = {
'teacher_form': teacher_form,
'form': form,
'form1': form1,
'all_questions': Question.objects.all(),
}
return render(request, 'index.html', context)
上面例子的问题就是这个错误:
ValueError: Cannot assign "<TeacherForm bound=True, valid=Unknown, fields=(name)>": "Student_Answer.teacher" must be a "Teacher" instance.
如果我包含实例 choice.teacher =teacher_form.instance 则会出现此错误:
Exception Value:
save() prohibited to prevent data loss due to unsaved related object 'teacher'.
如果我在验证后将表单保存在第一行,它将为教师类创建一个新记录。我不想保存新记录,我只想将所选值存储在模板中并将该值存储给 Student_Answer 类。有没有办法解决这个问题?
index.html
<form action="{% url 'evaluation:index'%}" method="POST">
{% csrf_token %}
{{ teacher_form }}
{{ all_questions.0 }}
{{ form }}
{{ all_questions.1}}
{{ form1 }}
<input type="submit" value="Vote">
</form>
【问题讨论】: