许多字段的Django表单

2024-04-26 23:33:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我要设计一个表格,在我的博客里添加一个新帖子。在

在模型.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)

在视图.py在

^{pr2}$

在表单.py在

class PostForm(ModelForm):

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

当我试图从模板“add”中插入catogories时_帖子.html“总是有很多错误:

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


Tags: py模型selfmodeltitlemodelsdefunicode
1条回答
网友
1楼 · 发布于 2024-04-26 23:33:33

问题与此说明有关:

^{1}$

从Djangodocumentation

与普通的多对多字段不同,您不能使用add、create或assignment(即。,甲壳虫乐队成员=[…]),以创建关系。

在您的场景中,您应该手动创建CategoryToPost对象,同时引用Post和{},并保存它。在

相关问题 更多 >