我正在尝试获取当前登录的用户并显示在每个视图的顶部。我已经到处搜索了这个,但我永远找不到我的问题的直接答案。
我能够在表单视图中获得它,但由于某种原因我无法在普通视图中显示它。它快把我逼疯了。
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)