0

I'm building a project in Django starting with DjangoX and am simply trying to get the currently logged in username or userid. I've tried all kinds of combinations and approaches, some of them I've left in comments, based on other on-line questions and answers and not getting this to work.

views.py:

from django.views.generic import TemplateView, CreateView
from requests import request # <-- tried this, didn't help got AttributeError no 'user'
from django.contrib.auth import get_user_model
from django.conf import settings

class HomePageView(TemplateView):

    # get user model and current user information
    umodel = get_user_model()
    # current_user = request.user  # produces NameError: name 'request' is not defined
    # u = user  # get error that user is not defined
    # u = umodel.id # <django.db.models.query_utils.DeferredAttribute...blah blah blah>

    template_name = 'pages/home.html'
...

in my .html file, I can use this to display exactly what I'm trying to access in my View!

home.html (this works)

<p>user = {{ user }}</p>
<p>user.id = {{ user.id }}</p>

urls.py

...
urlpatterns = [
    path('', IndexPageView.as_view(), name='index'),
    path('home/', HomePageView.as_view(), name='home'),
...
S Shepard
  • 3
  • 1

1 Answers1

1

This is a class-based view. You can't write request-dependent code at class level. Either switch to a function-based view, or put that code into the get_context_data method.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895