如何在ListView中获取当前用户?

时间:2017-01-09 15:08:05

标签: django django-views

如何在ListView的以下实现中获取当前用户。我想在uname

reverse_lazy参数中使用“当前用户”
class ListMessages(ListView, ModelFormMixin):
    model = Message
    template_name = 'accounts/list_messages.html'
    context_object_name = 'messages'
    form_class = MessageHiddenUserForm
    success_url = reverse_lazy('accounts:list_messages', kwargs={'uname': })

4 个答案:

答案 0 :(得分:1)

我认为你可以通过覆盖success_url

来做到
class ListMessages(ListView, ModelFormMixin):
    model = Message
    template_name = 'accounts/list_messages.html'
    context_object_name = 'messages'
    form_class = MessageHiddenUserForm

    def get_success_url(self):
        return reverse_lazy('accounts:list_messages', kwargs={'uname': self.request.user.username })

答案 1 :(得分:0)

如果您有登录用户,可以在以下视图中呼叫他:

self.request.user

https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.HttpRequest.user

答案 2 :(得分:0)

您应该覆盖函数

,而不是包含success_url变量
def get_success_url(self):
     return reverse_lazy('accounts:list_messages', kwargs={'uname': self.request.user})

答案 3 :(得分:0)

这对我有用:

class LineView(ListView):
context_object_name = 'object_list'

def get_queryset(self):
    queryset = self.request.user
    return queryset

template_name = "backend/line/list.html"