how to check whether a user is logged in in django? - django

I know about request.user.is_authenticated() but i created a custom user(model) and created login page for it
now how can we know if the user is logged in?

In views.py once the user logs in redirect to a url that calls a view
#login_required()
def login_success(request):
and render a welcome message

Related

how to use django message framework for #login_required to show message

I am using #login required decorator in my most of views so what I want is to use message in my login page telling user if you want to open that page you have to login first so how I can achieve that I know I cannot achieve that on my views so anyone does that and know how to do please tell me how to achieve that if a user redirected to login because of #login required I want to show message please login to continue
I also looked on some of the same question I am looking for answer which got implemented on all the login required decorator so I don't have to change code everywhere it already got implemented in all of the login required decorator in my whole app
my login view
def my_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
remember_me = form.cleaned_data['remember_me']
user = authenticate(username=username, password=password)
if user:
login(request, user)
if not remember_me:
request.session.set_expiry(0)
return redirect('accounts:home')
else:
request.session.set_expiry(1209600)
return redirect('accounts:home')
else:
return redirect('accounts:login')
else:
return redirect('accounts:register')
else:
form = LoginForm()
return render(request, "login.html", {'form': form})
Solution 1:
In your view, check the query parameter "next", as if the user is redirected to the login view, it would come with the ?next=/whatever in the URL. You can do
if 'next' in request.GET:
messages.add_message(request, messages.INFO, 'Hello world.')
Solution 2 (not recommended, this makes it confusing to debug for others):
Python being a dynamic language, you can hijack the behaviour of login_required with your version.
in your manage.py and wsgi.py and maybe asgi.py you would need to "monkey patch" the login_required decorator.
from django.contrib.auth import decorators
def my_login_required(...):
# you can look at the implementation in the answer by LvanderRee mentioned in the comments
decorators.login_required = my_login_required
Now, because these files will be the first code to execute before Django even starts, this will replace the built-in login_required with your version.
Based on this Stack Overflow post, using multiple answers, to redirect to another page, either:
Set LOGIN_URL in settings.py. This is the URL that Django will redirect to if a user that's not yet logged in attempts to log in.
or Inline:
from django.contrib.auth.decorators import login_required
#login_required(login_url='/example url you want redirect/') #redirect when user is not logged in
def myview(request):
do something
return something #returns when user is logged in
Of course, you still need to have the login view setup.
If you want to check if the user is authenticated in the HTML, you can use the templating system: (For clarity this is something I just whipped up right now, it's not from the Stack Overflow post mentioned above)
{% if user.is_authenticated %}
// Display something if authenticated maybe
{% else %}
// Display something like "You are not logged in etc"
{% endif %}

Logging in user through Django rest framework

I'm trying to log in a user through DRF view.
#list_route(methods=['post'])
def login(self, request, *args, **kwargs):
login_form = LoginForm(request, data=request.data or None)
if login_form.is_valid():
_login(request._request, login_form.get_user())
else:
raise forms.ValidationError("login wrong")
return Response({})
Above code runs without exception, but it doesn't seem to actually log in the user.
When I refresh the browser, the user is still not logged in.
How can I log in the user?
Please don't use DRF to log people in with session.
The warning a few lines after the SessionAuthentication gives you more details about it.
Seems that the _login() method doesn't do what you expect.
As you mention in your your comment. you were using:
from django.contrib.auth.views import login as _login
but this method:
Displays the login form and handles the login action.
You should (as you do) use:
from django.contrib.auth import login as _login
which:
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in.

Django registration - redirect from login/register after successful login

I'm using django-registration and I need to prevent access to login, register etc when the user is logged in. Now, when the user is logged in I can access `/accounts/register/``. How to prevent this?
I think to overwrite this view but I don't know how.
I've only used the built-in Django auth, but could you redirect the user in your 'register' view based on whether or not they're logged in?
def register(request):
user = None
if request.user.is_authenticated():
return render(request, 'already_logged_in.html')
else:
return render(request, 'register.html')

Django admin login for particular url

i'm using Django admin for admin operation on Movies model like :
urls.py
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/movies/', include('movies.adminurls')),
when request comes like **http://127.0.0.1:8000/admin/** it shows admin-login page
there is Movie model which i can mange from there.
since Movies model have 15 fields , it would be tedious task to fill in data for 100 movies from admin site.
For that i have created a view add_movie in which i'll populate Movies table through json data.
movies.adminurls
url(r'^add/', 'add_movie' , name="admin_add_movie"),
for add_movie admin must be logged in. request is like
http://127.0.0.1:8000/admin/movies/add/
if superuser is not logged in then it should display admin-login form. and when superuser is successfully logged in then it should redirect to add_movie view
So
is it possible to show admin-login for that url?
Redirect to the admin login form if user is not superuser:
def add_movie(request, *args, **kwargs):
if not (request.user.is_authenticated() and request.user.is_superuser):
return HttpResponseRedirect(settings.LOGIN_URL+'?next=/admin/movies/add/')
do_your_stuff(...)
If it is an API, you may want to raise PermissionDenied instead.
After facing your problem I finally find a django decorator with check whether user is admin or logged in and shows your view else returns login form and after login redirects to your page.
from django.contrib.admin.views.decorators import staff_member_required
#staff_member_required
def media_browser(request):
return HttpResponse("You logged in")

Signing in leads to /accounts/profile/ in Django

I have created user profiles for the user and already added
AUTH_PROFILE_MODULE = 'app.ModelName'
But when the user successfully logs in, he/she are redirected to /accounts/profile/ by default.
How to change this? I would like them to go /profile/ and have created a view for them.
def Profile(request):
'''
profile view
'''
return render(request,'profile.html')
Change the value of LOGIN_REDIRECT_URL in your settings.py.