Django manytomany关系保存

时间:2015-04-23 20:07:16

标签: django many-to-many m2m

我有两种模式:

class Publication(models.Model):
    title = models.CharField(max_length=30)
    user = models.ManyToManyField(settings.AUTH_USER_MODEL)

class Auth_User(models.Model):
    email = models.CharField(max_length=100)

和我的观点

form = publicationform(request.POST)
if form.is_valid():
    f = form.save(commit=False)
    f.user = request.user
    f.save()
    form.save_m2m()
    return redirect('/')

和我的表格:

class publicationform(ModelForm):
    class Meta:
    model = Publication
    exclude = ['user']

但是当我保存时,请告诉我这个消息:

需要具有字段“发布”的值才能使用这种多对多关系 请问这是什么问题?

1 个答案:

答案 0 :(得分:0)

在出版物中,设置模型=出版物:

form = PublicationForm(request.POST)
if form.is_valid():
    f = form.save(commit=False)
    f.user = request.user
    f.save()
    form.save_m2m()
    return redirect('/')


class PublicationForm(ModelForm):
    class Meta:
        model = Publication
        fields = ['title']