[Answered ]-Filter dropdown in django forms

0👍

final answer is adding self.user = user in the forms and adding user in the view.

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)
👤Farid

1👍

Try this inside __init__() method:

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)

0👍

Try this solution…

Basically groups is foreign key in Marketplace model it returns a full object of the Group model.

you tried to filter with the full object it’s not possible in a query, so you can filter using id of the user instance

Code becomes like this

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

Leave a comment