实际上,我对Django和Python都很陌生。在/templates/home.html中,添加了{{ user.username }},它会显示当前登录的用户名。
<p>Welcome {{ user.username }} !!!</p>
我想在 views.py 文件中获取当前已登录的用户名。如何获取用户名?
我尝试了不同的方法,但是没有得到结果。
user = User.objects.get(username=request.user.username)
username = request.GET['username']
def sample_view(request): current_user = request.user print(current_user)
请告诉我,如何实现我的目标。
我的 views.py 看起来像这样。有问题吗?
#!python
#log/views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.template import Context
from contextlib import contextmanager
# Create your views here.
# this login required decorator is to not allow to any
# view without authenticating
@login_required(login_url="login/")
def home(request):
return render(request,"home.html")
#dummy_user = {{ username }}
#user = User.objects.get(username=request.user.username)
#username = request.GET['username']
#print(usernam
#user = request.user
#print(user)
def sample_view(request):
current_user = {}
#current_user['loggeduser'] = request.user
#or
current_user['loggeduser'] = request.user.username
return render(request,"home.html",current_user)
# print(current_user.id)
user = User.objects.get(username=request.user.username)
。 - e4c5def sample_view(request):
,因此您提到的错误绝对不可能发生。 - e4c5