views:

54

answers:

3

I have a form with a ModelMultipleChoiceField() field. The form is used to send a message to user's friends. That means that instead of a generic queryset (e.g. Friends.objects.all()) I want to put something like queryset = user.friends.all().

Is this possible?

A: 

Question answered here:

Murkin
A: 

The easiest way is to make a closure. Don't worry if you don't know what that is, just define your Form inside your view like this

def my_view(...):
    user = ...
    class MessageForm(ModelForm):
        friends = forms.ModelMultipleChoiceField(queryset=user.friends.all())
        text = ...
    form = MessageForm(...)

There are other ways but that is by far the easiest.

Nick Craig-Wood
+2  A: 

Something like this:

#forms.py
class YourForm:
    def __init__(data, user):
       self.base_fields['your_field'].queryset = user.friends.all()
       super(YourForm, self).__init__(data)


#views.py
def your_view(request):
    if request.method == 'POST':
        form = YourForm(request.POST, request.user)
    else:
        form = YourForm(user=request.user)
    [...]
Pydev UA