我有一个 Tutor 模型,它有一个 ManyToManyField 到一个名为 Subjects 的模型,我正在尝试使用 MultipleChoiceField 渲染 Tutor 表单,虽然它被正确渲染,但值没有保存在数据库中,我想我是在我看来做错了什么。
供参考,这里是模型
class Subjects(models.Model):
subject = models.CharField(max_length=100)
class TutorProfile(models.Model):
user = models.OneToOneField(User, primary_key=True)
subject = models.ManyToManyField(Subjects)
我已经用一些对象填充了我的主题模型
这是表格,
class TutorForm(forms.Form):
subjectfield = forms.MultipleChoiceField(choices = ((sub.pk, sub.subject) for sub in Subjects.objects.all()), widget=forms.CheckboxSelectMultiple())
这是视图,
def someview(request):
if request.method == 'POST':
form = TutorForm(request.POST)
if form.is_valid():
subjects = form.cleaned_data['subjectfield']
for sub in subjects:
form.subject.add(sub)
form.save()
但是这些值没有保存在数据库中,请帮助:(
编辑
我终于在 Mohasen Hassani 的回答的帮助下弄清楚了
必须根据下面 Mohasen 的回答编辑表格,但必须像这样更改视图,
def someview(request):
if request.method == 'POST':
form = TutorForm(request.POST)
if form.is_valid():
t = TutorProfile(user.username=somebody)
t.save()
subjects_list = request.POST.getlist('subject')
counter = 0
for sub in subjects_list:
sub_pk = subjects_list.__getitem__(counter)
sub_entity = Subjects.objects.get(pk=sub_pk) #The model to which we are related
data.subject.add(sub_entity)
counter = counter+1