我要设计一个表格,在我的博客里添加一个新帖子。在
在模型.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。”
问题与此说明有关:
^{1}$从Djangodocumentation:
与普通的多对多字段不同,您不能使用add、create或assignment(即。,甲壳虫乐队成员=[…]),以创建关系。
在您的场景中,您应该手动创建},并保存它。在
CategoryToPost
对象,同时引用Post
和{相关问题 更多 >
编程相关推荐