Search code examples
djangodjango-modelsdjango-viewsdjango-templatesdjango-bootstrap4

Display username in template with custom user model as welcome message


I want to display username in base.html but it's not working.I am learning django if you see any mistake please tell.

# settings.py
AUTHENTICATION_BACKENDS = ( 
'django.contrib.auth.backends.ModelBackend', 
'allauth.account.auth_backends.AuthenticationBackend',
'social_core.backends.twitter.TwitterOAuth',
'social_core.backends.facebook.FacebookOAuth2',

)

User model

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>

Solution

  • request always is added in context for rendering template, so you can code like below:

    <li><a href="#">{{ request.user.username }}</a></li>