使用自定义用户模型在模板中显示用户名作为欢迎消息
Display username in template with custom user model as welcome message
我想在 base.html 中显示用户名,但它不是 working.I 我正在学习 django 如果您发现任何错误请告诉我。
# settings.py
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
'social_core.backends.twitter.TwitterOAuth',
'social_core.backends.facebook.FacebookOAuth2',
)
用户模型
class accountUser(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username',]
base.html
<li><a href="#">{{ accountUser.username }}</a></li>
<li><a href="{% url 'account_logout' %}">Logout</a></li>
请求总是添加到渲染模板的上下文中,所以你可以像下面这样编码:
<li><a href="#">{{ request.user.username }}</a></li>
如果您想将其传递给 base.html
#views.py
from django.shortcuts import render
def myview(request):
return render(request, 'base.html`, context={"user": request.user})
#base.html
<li><a href="#">{{ user.username }}</a></li>
我想在 base.html 中显示用户名,但它不是 working.I 我正在学习 django 如果您发现任何错误请告诉我。
# settings.py
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
'social_core.backends.twitter.TwitterOAuth',
'social_core.backends.facebook.FacebookOAuth2',
)
用户模型
class accountUser(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username',]
base.html
<li><a href="#">{{ accountUser.username }}</a></li>
<li><a href="{% url 'account_logout' %}">Logout</a></li>
请求总是添加到渲染模板的上下文中,所以你可以像下面这样编码:
<li><a href="#">{{ request.user.username }}</a></li>
如果您想将其传递给 base.html
#views.py
from django.shortcuts import render
def myview(request):
return render(request, 'base.html`, context={"user": request.user})
#base.html
<li><a href="#">{{ user.username }}</a></li>