我試圖抓住當前登錄的用戶並顯示在每個視圖的頂部。我已經在這個地方搜索了所有地方,但我無法找到對我的問題的直接答案。使用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)
工作完美,謝謝。 –
該解決方案不是真正的django-ish。查看答案sneawo的答案。 – migajek
那麼問題是在視圖中詢問用戶,而不是在模板中。 sneawo的答案是完美的,否則。 –