用于ManyToMany字段的Django表单

时间:2015-02-26 13:32:09

标签: python django many-to-many blogs

我必须在我的博客中设计一个用于添加新帖子的表单。

Model.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”的新帖子中插入catogories时,总会有错误引用ManyToMany:

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

1 个答案:

答案 0 :(得分:0)

问题与此说明有关:

 post.categories = post.categorytopost_set

来自Django documentation

与普通的多对多字段不同,您不能使用添加,创建或分配(即beatles.members = [...])来创建关系。

在您的方案中,您应手动创建CategoryToPost对象,同时引用PostCategory并保存。