消息中的Django友谊构成

时间:2010-10-28 08:29:40

标签: django django-forms django-apps

我正在使用django-friends和django-messages。

我修改了我的自定义撰写表单以提取以下信息,我的朋友还显示他们的全名而不仅仅是用户名。

我遇到的一个问题是,我似乎无法以签名用户身份访问自己,要完成查询,我必须对其进行硬编码。

class MyComposeForm(forms.Form):
    """
    A simple default form for private messages.
    """
    recipient = forms.ModelChoiceField(queryset=Friendship.objects.all(), label=_(u"Recipient"))
    #recipient = forms.ModelChoiceField(queryset=User.objects.all(), label=_(u"Recipient"))
    subject = forms.CharField(label=_(u"Subject"))
    body = forms.CharField(label=_(u"Body"),
        widget=forms.Textarea(attrs={'rows': '2', 'cols':'55'}))

    def __init__(self, *args, **kwargs):
        recipient_filter = kwargs.pop('recipient_filter', None)
        super(MyComposeForm, self).__init__(*args, **kwargs)
        ### underneath here I have to hardcode with my ID to pull the info.
        friends = Friendship.objects.filter(from_user=1)
        self.fields['recipient'].choices = [(friend.to_user.pk, friend.to_user.get_full_name()) for friend in friends]
        if recipient_filter is not None:
            self.fields['recipient']._recipient_filter = recipient_filter

如何访问我的用户实例?

我尝试将request添加到__init__并使用request.user,但这似乎不起作用。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您可以在表单中传递请求,如:

form = MyComposeForm(request.POST,request) 

在views.py文件中,表单已实例化。然后,您可以访问请求对象:

requestObj = kwargs.pop('request', None)

您的代码将如下所示:

def __init__(self, *args, **kwargs):
    recipient_filter = kwargs.pop('recipient_filter', None)
    requestObj = kwargs.pop('request', None)
    super(MyComposeForm, self).__init__(*args, **kwargs)