Home > Enterprise >  Filter dropdown in django forms
Filter dropdown in django forms

Time:11-14

In forms, I am trying to filter marketplace drop down field that belong to the logged in user based on its group. Its listing all the dropdown field items. I tried below but I think something is wrong with the filter part.

 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)

CodePudding user response:

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)

CodePudding user response:

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)

CodePudding user response:

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
  • Related