【问题标题】:Django Form for ManyToMany fields多对多字段的 Django 表单
【发布时间】:2015-02-26 13:32:09
【问题描述】:

我必须设计一个表格,以便在我的博客中添加新帖子。

模型.py

class Category(models.Model):
    title = models.CharField(max_length=200)
    ...
    ...
    def __unicode__(self):
        return self.title

class Post(models.Model):

    title = models.CharField(max_length=80)
    pub_date = models.DateTimeField()
    text = models.CharField(max_length=140)
    ...

    categories = models.ManyToManyField(Category, blank=True, null=True, through='CategoryToPost')

    def __unicode__(self):
        return self.title

class CategoryToPost(models.Model):

    post = models.ForeignKey(Post)
    category = models.ForeignKey(Category)

Views.py

def add_post(request):

form = PostForm()
if request.method == "POST":
    form = PostForm(request.POST)
    if form.is_valid():
        form = PostForm(request.POST)
        post = form.save(commit=False)
        post.author = User.objects.get(id = request.user.id)
        post.categories = post.categorytopost_set
        ...
        post.save()
        return HttpResponseRedirect('/')
    else:
        return render(request, 'add_post.html', {'error': True, 'form': form})
else:
    return render(request, 'add_post.html', {'error': True, 'form': form})

Form.py

class PostForm(ModelForm):

    class Meta:
        model = Post
        fields = ('title', 'text', 'categories', 'tags')

当我尝试从模板“add_post.html”在新帖子中插入类别时,总是会出现一个错误,指的是 ManyToMany:

“无法在指定中间模型的 ManyToManyField 上设置值。请改用 CategoryToPosts Manager。”

【问题讨论】:

  • 您为什么要手动将categories 字段添加到您的ModelForm?为什么不直接将它包含在 fields 元组中?
  • 那么显式直通表的意义何在?
  • 另外,如果你说“总是出错”,你应该告诉我们它是什么。
  • 我已经编辑了我的问题

标签: python django many-to-many blogs


【解决方案1】:

问题与这条指令有关:

 post.categories = post.categorytopost_set

来自 Django documentation

与普通的多对多字段不同,您不能使用 add、create 或 assignment(即 beatles.members = [...])来创建关系。

在您的场景中,您应该手动创建 CategoryToPostobject 并同时引用 PostCategory 并保存它。

【讨论】:

  • 在 QueryDIct 的关键“类别”中使用“for”来创建和保存多个类别。