过滤器在django表单中的下拉菜单



在表单中,我试图根据其组过滤属于登录用户的市场下拉字段。它列出了所有下拉字段项。我在下面试过,但我认为过滤器部分有问题。

class InfringementForm(ModelForm):
def __init__(self, user, *args, **kwargs):
super(InfringementForm,self).__init__(*args, **kwargs)
self.fields['marketplace'].queryset = 
Marketplace.objects.filter(groups__user=self.user)
class Meta:
model = Infringement
class Meta:
ordering = ['-updated', '-created']
def __str__(self):
return self.name

fields = ['name', 'link', 'infringer', 'player', 'remove', 'status', 
'screenshot','marketplace']

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)

__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)

最终答案是添加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)

试试这个方案…

基本上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

相关内容

  • 没有找到相关文章

最新更新