保存 m2m 字段时出现以下错误
Poll object needs to have a value for field "poll" before this many-to-many relationship can be used.
模型.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")
表格.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()
我在这里做错了什么?