I'm new to DJango and I'm trying to make a user auth. My login is working fine but my user isn't logging out.
My Logout view is:
from django.contrib.auth import logout
from django.contrib.auth.models import User
class LogoutView(generic.View):
#staticmethod
def get(request):
if User.is_authenticated:
# Debug statement
print('if')
logout(request)
return redirect('login')
else:
return redirect('index')
My url is working fine because when i go to /logout/, My debug statement executes
but if User.is_authenticated: always returns an object(true).
How can I resolve this issue. Thanks
User.is_authenticated is not what you should do. User is class, show it will have objects which is shown on your request which is already there, and it has nothing to do with the user who is serfing. While, request is the object of the user which carry many things one of them is user.
It should be:
request.user.is_authenticated:
Related
I created a profile view for users and I want everyone to be able to see it without having to log in
But when I click on the profile while not having logged in, it automatically logs into the account of the user I clicked on!
How can I fix it?
This is the view
def public_profile(request, username):
user =
User.objects.get(username=username)
return render(request, 'users/public_profile.html', {"user": user})
This is the url
path('<str:username>/profile/', public_profile, name='public-profile'),
It likely does not log in. But some context processors will add certain elements to the context. For example the django.contrib.auth.context_processors.auth.auth context processor will add a value for the 'user' key to the context if the user is logged in. A template that thus works with {{ user }}, might assume this is the logged in user.
You therefore better pass the user you want to show under a different name, for example profile:
from django.shortcuts import get_object_or_404
def public_profile(request, username):
user = get_object_or_404(User, username=username)
return render(request, 'users/public_profile.html', {'profile' : user})
As Willem Van Onsem says, the user variable is used by the Authentication middleware to represent the current logged user, so your user object is replaced with that. Try changing the name of the variable you use.
I have login and work page.
I want user to login first and then redirect to work page. This scenario is working fine for me.
However when I try hitting the work page it is giving me error, I am checking it through session variable which I know I am doing it wrong as I am not sure which user is trying to access the page if user tries to hit the work page directly as there will be many users in database. How can I restrict user to hit the work page directly and if user does it should redirect to login page
views.py file method is as follows:-
def chatbox_index(request):
context={}
template_name = "bot/chatbot.html"
**<I have to check here if user session is active or not?>**
return render(request, template_name,context=context)
else:
return render(request,'' ,context=context)
after user login I am creating session and storing in below 2 variables:-
request.session['employee_name'] = employee.usrFirstName
request.session['employee_id'] = employee.id
Django provides login_required decorator for this:
from django.contrib.auth.decorators import login_required
#login_required
def chatbox_index(request):
context={}
template_name = "bot/chatbot.html"
return render(request, template_name,context=context)
I am using django auth framework to do user registration, and then log the user in right away. Here's my code:
class SignUpView(FormMixin, ProcessFormView):
http_method_names = ['post']
form_class = UserCreationForm
success_url = reverse_lazy('default_page')
def form_valid(self, form):
if form.cleaned_data['is_usertype_1']:
self.success_url = reverse_lazy('some_page')
form.save()
user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'])
if user is None:
raise Exception("Could not authenticate the new user")
login(self.request, user)
return super(SignUpView, self).form_valid(form)
def form_invalid(self, form):
pass
Basically, I have extended UserCreationForm to add is_usertype_1 field, and displaying it as BooleanField. And using that data, I am determining where the user gets redirected to after the signup.
But the problem arises when I try to log the created user in. No Exception gets raised, but for some reason, subsequent redirects still holds AnonymousUser in request.user. But when I log in with the created user manually, login works fine. What am I doing wrong here?
Thanks for the help in advance.
It turns out it's the same issue as Django automatic login after user registration (1.4)
Following was my import statement:
from django.contrib.auth import forms as auth_forms, views as auth_views, login, authenticate
Changed it to
from django.contrib.auth import forms as auth_forms, views as auth_views
from django.contrib.auth import login as auth_login, authenticate as auth_authenticate
and updated all the login and authenticate call to auth_login and auth_authenticate and seems to work now.
Thank you all for your help !
It's just a guess, but maybe super().form_valid() is saving the UserCreationForm a second time, which will call set_password() again, therefore setting a new salted password, invalidating your first login :)
https://docs.djangoproject.com/en/1.7/_modules/django/contrib/auth/forms/#UserCreationForm
I have a small view:
def AccountHome(request):
return render(request, 'myapp/account/accounthome.html', {
})
In previous views, I've used:
if user is not None and user.is_active
to check if a user is already authenticated or not when using native form classes like: AuthenticationForm for example when logging in a user.
But on this view I am not using that, is there someway to validate whether a user is logged in or not without using this AuthenticationForm classagain? Thisviews purpose is to show the homescreen when logged in, so it seems non-intuitive to extend thatAuthenticationForm` class again.
Any help or thoughts?
Thanks
Use is_authenticated() method
Like this: if request.user.is_authenticated():
You can find the reference here: https://docs.djangoproject.com/en/dev/ref/contrib/auth/#methods
Hi I used the django inbult auth urls and views for my project and now have finished the initial user account creation/login/reset password process.
Now, the user can log in and be redirected to the after successful login url accounts/profile/.
I have several doubts on the django login function. For convenience, I've copy paste the django inbuilt login function code below.
#sensitive_post_parameters()
#csrf_protect
#never_cache
def login(request, template_name='registration/login.html',
redirect_field_name=REDIRECT_FIELD_NAME,
authentication_form=AuthenticationForm,
current_app=None, extra_context=None):
"""
Displays the login form and handles the login action.
"""
redirect_to = request.REQUEST.get(redirect_field_name, '')
if request.method == "POST":
form = authentication_form(request, data=request.POST)
if form.is_valid():
# Ensure the user-originating redirection url is safe.
if not is_safe_url(url=redirect_to, host=request.get_host()):
redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)
# Okay, security check complete. Log the user in.
auth_login(request, form.get_user())
return HttpResponseRedirect(redirect_to)
else:
form = authentication_form(request)
current_site = get_current_site(request)
context = {
'form': form,
redirect_field_name: redirect_to,
'site': current_site,
'site_name': current_site.name,
}
if extra_context is not None:
context.update(extra_context)
return TemplateResponse(request, template_name, context,
current_app=current_app)
My questions are:
1 Is the REDIRECT_FIELD_NAME in the function set as '/profile/' in django.contrib.auth ?
I could see this variable is imported from django.contrib.auth
from django.contrib.auth import REDIRECT_FIELD_NAME, login as auth_login, logout as auth_logout, get_user_model
I don't have any setting for this variable, but after user successfully logged in, the page will be directed to /accounts/profile/
2 Has the login function passed the account info about the user? If yes, how can I access it?
From the code, if user successfully logged in, page will be redirected: return HttpResponseRedirect(redirect_to)
in my case, redirected to accounts/profile/ , initially the view for the url was simply a
HttpResponse("You have logged in successfully")
now when I am trying to implement the view function, I realize that no info about the user has been passed.
I've tried to print request in the view function, but there is no info about the user in the message printed in the server terminal, all I get is a long list of system settings or other info. However, the login should pass the info of who has just successfully logged in to the successful log in urls right?
Thank you very much for explaining.
After the login, you can access the user info by referring request.user in views and just {{user}} in templates. All you need to make sure is you're passing the RequestContext in the HttpResponse for the future request.
Yes, REDIRECT_FIELD_NAME is defined in __init__.py of django.contrib.auth which is simply a "next" what you passed from the login form.
In Django, there are more than one ways to force a user to login. By decorating a view function with #login_required, by calling the build-in login view for an user defined URL and etc., Refer about the login settings variables here. You'll get some more ideas.
Building custom login page. That link gives you an example for custom login implementaion. Consider you have decorated a view with #login_required and it's corresponding URL is /login_test/. Then the {{next}} context variable in the login form will be rendered with /login_test/. So after you login,
<input type="hidden" name="next" value="{{ next }}" />
This element's value will be taken for redirecting as per the REDIRECT_FIELD_NAME. Though I suspect that that example is missing the setting of settings.LOGIN_URL to the URL login/. Never mind, it's being passed as an argument in the decorator itself.
To override this behavior just put following in settings.py of your app :
LOGIN_REDIRECT_URL = "/"
This will redirect to your home page. You can change this url to preferred url.
Once the user is redirected to accounts/profile/ the view for that link will be returned. You can access information about the currently logged in user there as per this post by using request.user. Also tip to see what information you have access to in your views. Use import pbd; pdb.set_trace(). This pops you into a python prompt with access to all of the current variables. To see all the defined variables call locals(), though this will print out a ton of junk along with it. In the template you can display a "you can't access this page" message if the user isn't logged in.