ManyToMany不保存到db Django

时间:2018-05-17 06:18:31

标签: django django-models django-forms

我有一个ManytoMany字段,CheckboxSelectMultiple的结果不会保存在数据库中,我不明白为什么。它一定很简单但是......

以下是代码:

  

models.py

class Person(models.Model):

    last_name = models.CharField(max_length = 50)
    first_name = models.CharField(max_length = 50)

    def __str__(self):
        return self.last_name +" "+self.first_name

class Event(models.Model):
        owner = models.ForeignKey(User, on_delete=models.SET_NULL, null = True)
        person = models.ManyToManyField(Person)
  

forms.py

class EventForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.user = kwargs.get('user',None)
        #self.user = kwargs.pop('user',None)
        super(EventForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.form_method = 'POST'
        #self.helper.form_action = reverse_lazy('simpleuser')
        self.helper.add_input(Submit('submit', 'Submit', css_class='btn-success'))     

    class Meta:
        model = Event
        fields = ['person']
        widgets ={
        'person': forms.CheckboxSelectMultiple,
        }
  

views.py

def uploadevent(request):

    if request.method == "POST":
        form =EventForm(request.POST)
        if form.is_valid():
            event = form.save(commit=False)
            event.owner = request.user
            event.save()
    else:
        form = EventForm()

    return render...

2 个答案:

答案 0 :(得分:1)

请参阅此stackoverflow问题的回复:Saving Many To Many data via a modelform in Django

引用OP:

  

使用commit = False时,必须调用save_m2m()

     

m2m关系要求首先保存父对象   你没有使用commit = False

只需在event.save()

下面添加此行即可
    if form.is_valid():
        event = form.save(commit=False)
        event.owner = request.user
        event.save()
        form.save_m2m()

参考:https://docs.djangoproject.com/en/2.0/topics/forms/modelforms/#the-save-method

答案 1 :(得分:0)

为了节省许多费用,您应该在使用save_m2m()时致电commit=False(查看详细信息here):

if form.is_valid():
        event = form.save(commit=False)
        event.owner = request.user
        event.save()
        form.save_m2m()