开发者

Is there a way DJANGO to create a specific Form instance?

I have a form with a ModelMultipleChoiceField() field. The form i开发者_StackOverflow社区s 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?


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)
    [...]


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜