Search code examples
djangodjango-templatesdjango-viewsdjango-logindjango-messages

How do I greet the user when they log into my website?


I'm trying to greet the user when they log into my django website, but using the django login has made it too difficult to send a message to my template and redirect to the new url behind the scenes. How can I greet the user(preferrably with that user's name) on the template of the url I redirect to?

I've tried working with messages, but redirecting to the new url always overrides the message and it never appears. Regular logging in and out works fine, I'm just trying to figure out how to display welcome text to the user to let them know they have successfully logged in and are using their own account.

views.py

def loginPage(request):
    return render(request, "registration/login.html")

def login(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        #Success!
        messages.success(request, "Welcome " + user) #NOT WORKING :(
        login(request, user)
    else:
        return HttpReponseRedirect("/DataApp/accounts/login/")

settings.py

# Application definition

INSTALLED_APPS = [
    'DataApp.apps.DataappConfig',
    'session_security',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'session_security.middleware.SessionSecurityMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'WebscrapeApp.urls'

TEMPLATES = [
{
   'BACKEND': 'django.template.backends.django.DjangoTemplates',
   'DIRS': [os.path.join(BASE_DIR, '/DataApp/templates')],
   'APP_DIRS': True,
   'OPTIONS': {
     'context_processors': [
       "django.template.context_processors.debug",
       'django.template.context_processors.request',
       'django.contrib.auth.context_processors.auth',
       'django.contrib.messages.context_processors.messages',
     ],
   },
 },
]

WSGI_APPLICATION = 'WebscrapeApp.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'America/New_York'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'

LOGIN_URL = "/DataApp/accounts/login/"
LOGIN_REDIRECT_URL = "/DataApp/search/"

SESSION_EXPIRE_AT_BROWSER_CLOSE = True

SESSION_SECURITY_WARN_AFTER = 900
SESSION_SECURITY_EXPIRE_AFTER = 1200

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

base.html

<!-- This is nested in a div tag inside of the html class body -->
{% if messages %}
        <ul class="messages">
            {% for message in messages %}
            <li{% if message.tags %} class="{{ message.tags }}" {% endif %}>
                {{ message }}</li>
                {% endfor %}
        </ul>
{% endif %}

I wanted the message to appear within base.html after passing it but it appears django's login function overrides the sending of the message behind the scenes.

Solution:

base.html

<p>
    {% if not user.is_anonymous %}
        <font color="#00ccff">
            Welcome {{ user }}
        </font>
    {% endif %}
</p>

views.html

def login_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        #Success!
        login(request, user)
        context = {
            "user": user
        }
        return render(request, "base.html", context)
    else:
        return HttpReponseRedirect("/DataApp/accounts/login/")

Solution

  • first rename login function, like login_view etc. if that doesn't solve your problem, do these also

    if user is not None:
        login(request, user)
        context = {
            "user": user
        }
        return render(request, "base.html", context)
    
    {% if user %}
      Welcome {{ user }}
    {% endif %}