How to filter Django Forms by the User

So how do you add a custom filter to your Django Forms?

"All uri's included"

I read and tried several solutions for customizing the view and form but nothing seemed to work. The most promising seemed to be to use

self.fields['website'].queryset = Website.objects.filter(organization__primary_account=self.request.user)

The tricky bitch of it was that the request object wasn't accessible via self or a directly passed parameter.

Because this shit works; well it works for 1 person yet at the same time is a giant security issue for that user.

self.fields['website'].queryset = Website.objects.filter(organization__primary_account=1)

So after much hand wringing and searching I couldn't find a solution that worked for me. I know I should be ashamed to call myself a djangonaut. In my defense, I suck and don't really get to program that often.

IRC #django to the rescue.

So I posted my questions and after about 20 minutes my new best friend mayhew responded with an answer.

Sometimes in retrospect the answer seems so obvious and the simple it is the more obvious it had to be.

So in the view, you need to pass the request object when you instantiate your form.

MyModelForm(request=request)

Mayhew's initial suggestion was to add it to the self instance.

self.request  = kwargs.pop('request')

Boom! Now this works.

self.fields['website'].queryset = Website.objects.filter(organization__primary_account=self.request.user)

The crazy shit was that I knew that at some point I'd tried to access the kwargs to find the request object but it never worked.

class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request') # Bingo! We have our request object.
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields['website'].queryset = Website.objects.filter(organization__primary_account=request.user)

This fails because super kills the kwargs data.

class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.request = kwargs.pop('request') # Big fat KeyError FAIL because now the kwargs = {}
        self.fields['website'].queryset = Website.objects.filter(organization__primary_account=request.user)

Here's the Solution.

Only my uri

views.py

def faq_submit(request):
    if request.method == 'POST':
        form = MyModelForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
    else:
        form = MyModelForm(request=request)
    return render(request, "submit_question.html", {
                  "form": form,
                  })

forms.py

class MyModelForm(forms.ModelForm):
    def __init__(self, request, *args, **kwargs):
        # request is a required parameter for this form.
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields['website'].queryset = Website.objects.filter(organization__primary_account=request.user)


Author:

Previous: 10 Tips to Increase Donations and Sales

Tags: django

Comments powered by Disqus