Django:保存ModelForm的ManyToMany对象时出错

时间:2013-10-07 16:07:03

标签: django

我在保存m2m字段时遇到以下错误

Poll object needs to have a value for field "poll" before this many-to-many relationship can be used.

models.py

class Poll(models.Model):
    title = models.CharField(max_length=200)
    created_on = models.DateField(auto_now=True)
    created_by = models.ManyToManyField(User)
    category = models.ManyToManyField("PollCategory")

forms.py

class PollForm(forms.ModelForm):
    class Meta:
        model = Poll
        exclude = ('created_by', 'created_on', 'category')

    def __init__(self, *args, **kwargs):
        super(PollForm, self).__init__(*args, **kwargs)
        self.fields['title'].error_messages = {'required': 'Please enter title'}
在views.py中

if request.method== "POST":
        form = PollForm(request.POST)
        if form.is_valid():
            #......code added
            poll=form.save(commit=False)
            poll.category = cat =request.POST['category']   #...manyTomany
            poll.created_by = request.user
            poll.save()
            form.save_m2m()
我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

您无需手动设置poll_form.category:由save_m2m设置。

(另请注意poll_form是一个误导性的名称:它不是表格,而是一个民意调查实例。)