Django表单:仅显示已登录用户的许多对象 [英] Django Form: Only show manytomany objects from logged in user
问题描述
当前问题是我的表单向登录用户显示了曾经创建的所有投资组合.该表单仅应显示已登录用户创建的投资组合.
The current problem is that my form shows the logged in user all Portfolios ever created. The form should only show portfolios that the logged-in user created.
类似这样的东西:
associated_portfolios manytomany field = ...objects.filter(user=user_id)
我不确定是否应该在Forms.py或views.py中实现它,以及如何实现.我一直在浏览django文档,发现'formfield_for_manytomany',但不确定这是否仅适用于管理员.
I'm not sure if this should be implemented in the forms.py or views.py and if so how. I've been going through the django documentation and found 'formfield_for_manytomany' but not sure if this is only meant for admin.
Models.py
Models.py
class Portfolio(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=20)
description = models.CharField(max_length=250, blank=True, null=True)
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=50)
body = RichTextUploadingField(blank=True, null=True)
associated_portfolios = models.ManyToManyField(Portfolio, blank=True)
created_on = models.DateField(auto_now_add=True, editable=False)
Views.py
class PostCreate(CreateView):
model = Post
form_class = PostCreateForm
def formfield_for_manytomany(self, db_field, request, **kwargs):
self.fields['associated_portfolios'] = Portfolio.objects.filter(user=self.request.user)
return super().formfield_for_manytomany(db_field, request, using=self.using, **kwargs)
forms.py
class PortfolioCreateForm(ModelForm):
class Meta:
model = Portfolio
fields = ['user', 'name', 'description']
class PostCreateForm(ModelForm):
class Meta:
model = Post
fields = ['user', 'title', 'body', 'category', 'associated_portfolios']
推荐答案
由于您使用的是 ModelForm
,因此 associated_protfolios
字段将是 ModelMultipleChoiceField
[ docs ].此字段具有 queryset
属性[文档].我们要修改该属性.
Since you're using a ModelForm
, the associated_protfolios
field will be a ModelMultipleChoiceField
[docs]. This field has a queryset
attribute [docs]. We want to modify that attribute.
Django的 CreateView
具有方法 get_form
,在这种情况下,它将获取您的 PostCreateForm
.这是过滤字段的查询集的好地方,因为我们可以访问用户:
Django's CreateView
has a method get_form
, which in this case will grab your PostCreateForm
. This is a good spot to filter the field's queryset, since we have access to the user:
class PostCreate(CreateView):
model = Post
form_class = PostCreateForm
def get_form(self, *args, **kwargs):
form = super().get_form(*args, **kwargs) # Get the form as usual
user = self.request.user
form.fileds['associated_portfolios'].queryset = Portfolio.objects.filter(user=user)
return form
这篇关于Django表单:仅显示已登录用户的许多对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!