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)
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)
- [Answered ]-What is the best way to fill the pdf form with pdftk in python django
- [Answered ]-Django Celery set individual logfile path for each task
- [Answered ]-Integrity Error *_id may not be null
- [Answered ]-Django:adding more than one value in model field
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
- [Answered ]-Django form geocoding – where to geocode, how to validate, how to pass geocode result
- [Answered ]-Django model foreign key to one in a list of models
- [Answered ]-How to Join (NOT COMBINE) two more django querysets?
- [Answered ]-How do I successfully integrate a second database with Django South?
- [Answered ]-Get_form throws TypeError after upgrading Django to 1.10
Source:stackexchange.com