2

我有一个 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
4

2 回答 2

0

编辑您的表格以:

subjects = forms.ModelMultipleChoiceField(
        queryset=Subjects.objects.all(),
        widget=forms.CheckboxSelectMultiple)

在视图中:您必须首先创建/保存没有主题的 TutorProfile,然后单独提供其主题字段。像这样:

def someview(request):
    if request.method == 'POST':
      form = TutorForm(request.POST)
      if form.is_valid():
        t = TutorProfile(user.username=somebody)
        t.save()
        t.subjects = form.cleaned_data['subjects']
于 2012-05-23T09:12:43.810 回答
0

更改您的表格:

class TutorForm(forms.ModelForm):
    class Meta:
        fields = ('subject',)

而你的观点:

if form.is_valid():
    form.save() 
于 2012-05-23T07:36:09.993 回答