1

greetings dear django experts, i am having an issue with my website i am using the defualt login view in django from

from django.contrib.auth import views as auth_views

the code is working
like this inside the urls.py file :

from django.contrib.auth import views as auth_views

path('login/',auth_views.LoginView.as_view(template_name='website/login.html'), name='login-page'),

but using this methode i don't have a view inside my views.py file. the problem is i need to define a view inside my viwes.py to record logs for any one accessing this page the problem is when i tried the following code i get the error "'function' object has no attribute 'get'" error snapshot

the code that gives me the error is as the following: views.py

from django.contrib.auth import views as auth_views  

def login(request):
    ip = get_client_ip(request)
    logger.info(f'user access: {request.user} via ip:{ip}')
    return auth_views.LoginView.as_view(template_name='website/login.html')

urls.py

 path('login/',views.login, name='login-page'),

1 Answer 1

2

.LoginView.as_view() does not process the request, it simply returns a function that will dispatch the request, you thus need to call the function that is the result of .as_view(…) with the request as parameter:

from django.contrib.auth import views as auth_views  

def login(request):
    ip = get_client_ip(request)
    logger.info(f'user access: {request.user} via ip:{ip}')
    return auth_views.LoginView.as_view(template_name='website/login.html')(request)

That being said, it looks a bit odd to do this. Why not just subclass the LoginView and register that view?

You thus can do this with:

# appname/views.py

from django.contrib.auth.views import LoginView

class MyLoginView(LoginView):
    template_name='website/login.html'

    def setup(self, request, *args, **kwargs):
        super().setup(request, *args, **kwargs)
        ip = get_client_ip(request)
        logger.info(f'user access: {request.user} via ip:{ip}')

and then register your MyLoginView instead:

from appname.views import MyLoginView

path('login/', MyLoginView.as_view(), name='login-page'),
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for your answer i know it seems odd but i am building this as website for security testing purposes. thank you for the suggestion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.