django表单中的过滤器下拉列表

8ftvxx2r  于 2022-11-18  发布在  Go
关注(0)|答案(3)|浏览(181)

在表单中,我尝试根据登录用户的组筛选属于登录用户的市场下拉字段。它列出了所有下拉字段项。我在下面尝试了,但我认为筛选部分有问题。
第一次
models.py

class Marketplace (models.Model):
name = models.CharField(max_length=100)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
groups = models.ForeignKey(Group, on_delete=models.CASCADE,default=1)
k3bvogb1

k3bvogb11#

__init__()方法内尝试以下操作:

def __init__(self, user, *args, **kwargs): 
    self.user = user     
    super(InfringementForm,self).__init__(*args, **kwargs)
    self.fields['marketplace'].queryset = Marketplace.objects.filter(groups__user=self.user)
icnyk63a

icnyk63a2#

最后的答案是在表单中添加self.user = user,在视图中添加user。
forms.py

class InfringementForm(ModelForm):
  def __init__(self, user, *args, **kwargs):
  self.user = user  
  super(InfringementForm,self).__init__(*args, **kwargs)
  self.fields['marketplace'].queryset = 
  Marketplace.objects.filter(groups__user=self.user)
  class Meta:
  model = Infringement
    
  fields = ['name', 'link', 'infringer', 'player', 'remove', 'status', 
  'screenshot', 'marketplace']

views.py

@login_required(login_url='login')
  def createInfringement(request):
  user=request.user
  form = InfringementForm(user=request.user)
  if request.method == 'POST':
  
  form = InfringementForm(user, request.POST, request.FILES)
  if form.is_valid():
     
     form.save()
  return redirect('home')    context ={'form': form}    return render (request, 'base/infringement_form.html', context)
u0sqgete

u0sqgete3#

尝试此解决方案...
基本上,groupsMarketplace模型中的外键,它返回Group模型的完整对象。
您尝试使用完整对象进行筛选,但在查询中不可能,因此您可以使用用户示例的id进行筛选

代码变成这样

class InfringementForm(ModelForm):

 def __init__(self, user, *args, **kwargs):
 super(InfringementForm,self).__init__(*args, **kwargs)
 self.fields['marketplace'].queryset = 
 Marketplace.objects.filter(groups__user__id=self.user.id)

  class Meta:
    model = Infringement

相关问题