如何使用Django中的checkbox小部件从MultipleChoiceField保存数据

时间:2012-05-23 07:34:18

标签: django django-models django-forms django-views django-orm

我有一个Tutor模型,它有一个名为Subjects的模型的ManyToManyField,我正在尝试使用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)

我用一些对象填充了我的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

2 个答案:

答案 0 :(得分:0)

更改表单:

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

您的观点:

if form.is_valid():
    form.save() 

答案 1 :(得分:-1)

将表单编辑为:

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']