多对多字段的 Django 表单

Django Form for ManyToMany fields

我必须设计一个表单来在我的博客中添加一个新的 post。

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" 中向新的 post 中插入目录时,总是出现指向 ManyToMany 的错误:

"Cannot set values on a ManyToManyField which specifies an intermediary model. Use CategoryToPosts Manager instead."

问题与这条指令有关:

 post.categories = post.categorytopost_set

来自 Django documentation:

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

在您的方案中,您应该手动创建包含对 PostCategory 的引用的 CategoryToPost 对象并保存它。