gpt4 book ai didi

python - Django 表单 : Only show manytomany objects from logged in user

转载 作者:行者123 更新时间:2023-12-01 06:23:52 24 4
gpt4 key购买 nike

当前的问题是我的表单显示了登录用户曾经创建的所有投资组合。该表单应仅显示登录用户创建的投资组合。

类似这样的事情:

associated_portfolios manytomany field = ...objects.filter(user=user_id)

我不确定这是否应该在 forms.py 或views.py 中实现,如果是的话如何实现。我一直在浏览 django 文档并找到“formfield_for_manytomany”,但不确定这是否仅适用于管理员。

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

View .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)

表单.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,因此 linked_protfolios 字段将是 ModelMultipleChoiceField [ docs ]。该字段有一个 queryset 属性 [ docs ]。我们想要修改该属性。

Django 的 CreateView 有一个方法 get_form,在本例中它将获取您的 PostCreateForm。这是过滤字段查询集的好地方,因为我们可以访问用户:

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

关于python - Django 表单 : Only show manytomany objects from logged in user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60259091/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com