【发布时间】:2015-07-21 05:14:18
【问题描述】:
我已经成功地将自定义用户注册系统构建为一个模块,并且我还有另一个名为 article 的模块。我想在文章模块的模板中显示从我的自定义用户注册模块登录的用户。 我正在使用 {{if user.is_authenticated}} display {{user}} 在我的模板中显示用户名。
我可以在自定义用户注册模板中访问它,但不能在文章模板中访问它。我想在导航栏上显示两个应用程序相同的用户名。
我应该怎么做才能在整个项目中访问用户名,而不仅仅是在呈现的模板中。
我使用的是 django 1.8,我也尝试在我的 views.py 文件中创建一个会话变量,但它也适用于同一个应用程序。
项目的views.py
from django.shortcuts import render, render_to_response, RequestContext
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf
from custom_user.forms import CustomUserCreationForm
from django.utils import timezone
def login(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def auth_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
request.session['user_id'] = user.id
request.session['user_email'] = user.email
return render(request, "loggedin.html", {},context_instance=RequestContext(request))
else:
return HttpResponseRedirect('/accounts/invalid')
def loggedin(request):
return render_to_response('loggedin.html', {})
def invalid_login(request):
return render_to_response('invalid_login.html')
模板base.py
<ul class="nav navbar-nav navbar-right">
<li><a href="/subscribe/">Subscribe</a></li>
{% if user.is_authenticated %}
<li><a href="/">{{user}}</a></li>
<li><a href="/accounts/logout/">Logout</a></li>
{% else %}
<li><a href="/accounts/login/">Login</a></li>
{% endif %}
</ul>
文章应用的views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext
from django.template.loader import get_template
from django.shortcuts import render_to_response
from django.conf import settings
from article.models import Article, Comment, Subscribers
from forms import ArticleForm, CommentForm, SubscriptionForm, ActivateSubscriberForm
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from django.utils import timezone
from django.core.mail import send_mail
from random import randrange
from signup.views import *
# from .forms import RegistrationForm
# Create your views here.
def articles(request):
return render_to_response('articles.html',
{'articles':Article.objects.all().order_by('-id'),'last':Article.objects.earliest('-pub_date')})
def article(request, article_id=1):
return render_to_response('article.html',
{'article':Article.objects.get(id=article_id)})
当用户通过身份验证后,login.html 会被渲染,并且我已经创建了一个链接来访问使用相同 base.py 模板的文章应用程序。
【问题讨论】:
标签: python django variables templates session