2013-01-20 78 views
6

我試圖抓住當前登錄的用戶並顯示在每個視圖的頂部。我已經在這個地方搜索了所有地方,但我無法找到對我的問題的直接答案。使用Django類視圖抓取當前登錄的用戶?

我能夠在窗體視圖中獲取它,但由於某種原因,我無法在普通視圖中顯示它。這讓我瘋狂。

from django.http import HttpResponse, Http404 
from django.views.generic import ListView, DetailView, FormView 
from django.template import RequestContext, loader, Context 
from django.core.urlresolvers import reverse 
from boards.models import Links, LinksCreateForm, Category 
from django.contrib.auth.models import User 


def get_user(request): 
    current_user = request.get.user 
    return current_user 


class LinksListView(ListView): 
    model = Links 


class LinksDetailView(DetailView): 
    model = Links 


class LinksCreateView(FormView): 
    template_name = 'boards/link_create.html' 
    form_class = LinksCreateForm 

    def form_valid(self, form): 
     name = form.cleaned_data['name'] 
     description = form.cleaned_data['description'] 
     user = self.request.user 
     category = Category.objects.get(id=form.cleaned_data['category'].id) 
     link = Links(name=name, description=description, user=user, category=category) 
     link.save() 
     self.success_url = '/boards/' 

     return super(LinksCreateView, self).form_valid(form) 

回答

8

在您的通用視圖的實現則需要延長get_context_data

def get_context_data(self, **kwargs): 
# Call the base implementation first to get a context 
     c = super(ReqListView, self).get_context_data(**kwargs) 
     user = self.request.user 
     return c 

那就要看你的需求,你想要什麼與此相關。

Extending generic view classes for common get_context_data

+0

工作完美,謝謝。 –

+0

該解決方案不是真正的django-ish。查看答案sneawo的答案。 – migajek

+1

那麼問題是在視圖中詢問用戶,而不是在模板中。 sneawo的答案是完美的,否則。 –

5

在您看來,您可以訪問請求(因此用戶):

self.request.user 

既然你是在談論在的「查看」上顯示它,我相信你想要在模板中訪問它。

你應該能夠訪問它在你的模板爲:

{{ request.user }} 
+0

這裏最簡單的答案。 – Zeretil

6

可以在settings.py添加'django.core.context_processors.request'TEMPLATE_CONTEXT_PROCESSORS,然後訪問當前用戶爲{{ request.user }}。如果你還沒有這個變量,你可以將它列爲:

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth', 
    'django.core.context_processors.request', 
    'django.core.context_processors.debug', 
    'django.core.context_processors.i18n', 
    'django.core.context_processors.media', 
    'django.core.context_processors.static', 
    'django.core.context_processors.tz', 
    'django.contrib.messages.context_processors.messages' 
) 

https://docs.djangoproject.com/en/1.4/ref/settings/#std:setting-TEMPLATE_CONTEXT_PROCESSORS

0

增加模板context處理器爲@sneawo尖是最好的一段路要走。不過,我更喜歡不是爲了覆蓋的默認值,而是爲擴展而已。像這樣:

from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP 
# ... 
TEMPLATE_CONTEXT_PROCESSORS = TCP + (
    'django.core.context_processors.request', 
) 

爲什麼?因爲django中的默認上下文處理器列表因版本而異。某些內置/附帶(contrib)庫的內容取決於默認設置。一般來說,我相信最好不要重寫默認值,除非必須。

相關問題