我有两种模式:
class ArticleTemplate(models.Model):
title = models.CharField(max_length=250)
text = models.TexField()
[...]
owner = models.ForeignKey(user)
class Article(models.Model):
template = models.ForeignKey(ArticleTemplate)
title = models.CharField(max_length=250)
text = models.TexField()
[...]
owner = models.ForeignKey(user)
文章形式:
class ArticleForm(models.Model):
class Meta:
model = Article
fields = ('id', 'template', 'title', 'text')
但是select会显示所有模板,也不是request.user。
所拥有的模板如何仅显示分配给已登录用户的数据?
答案 0 :(得分:1)
您可以在视图中通过调用queryset过滤Django ModelForm中的外键选择:
form.template.queryset = ArticleTemplate.objects.filter(owner=request.user)
答案 1 :(得分:0)
向ArticleForm添加__init__
方法:
def __init__(self, *args, **kwargs):
logged_user = kwargs.pop("logged_user")
super(ArticleForm, self).__init__(*args, **kwargs)
templates = logged_user.article_template_set.all()
self.fields['template'].queryset = templates
从视图:
form = ArticleForm(logged_user=request.user) #GET request
form = ArticleForm(request.POST, logged_user=request.user) #POST