how to check whether user is logged in or not
I know that the question was already answered, I just want to make a summary of every method for hiding/showing information to non-authenticated users.
1. Login required decorator
If you're dealing with a functional view, you can decorate it like this:
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
pass
This will only show the view to authenticated users. If anonymous, they'll be redirected to the login url (settings.LOGIN_URL)
2. LoginRequiredMixin
from django.contrib.auth.mixins import LoginRequiredMixin
class MyView(LoginRequiredMixin, View):
login_url = '/login/'
redirect_field_name = 'redirect_to'
This is for class-based views. From Django documentation:
If a view is using this mixin, all requests by non-authenticated users will be redirected to the login page or shown an HTTP 403 Forbidden error, depending on the raise_exception parameter.
Just like the previous method, you can customize the login_url
and redirect_field_name
3. Class-based view method decorator
from django.utils.decorators import method_decorator
class ProtectedView(TemplateView):
template_name = 'secret.html'
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
4. HTML templating
Lastly, if you just want to hide some specific HTML block for non-authenticated users, you can wrap it up like this:
{% if user.is_authenticated %}
<p> Hidden content! </p>
<!-- You can also access the user data like this -->
<p> {{ {{ request.user }} }} </p>
{% endif %}
Finally i got the solution that work for me
here it is
Django provides LoginRequiredMixin i used this in my invoicelistview function
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
class InvoiceListView(LoginRequiredMixin,ListView):
model = Invoicelist
template_name = 'invoicedata/home.html'
context_object_name = 'invoices'
def get_queryset(self):
return self.model.objects.all().filter(author=self.request.user).order_by('-date_posted')[:2]
and that's it. Now whenever user logout then it will redirect to login page
In the HTML context, you can do:
{% if user.is_authenticated %}
# some arbitary stuff
<li class="nav-item">
<a class="nav-link" href="#"><strong>{{ user.username }}</strong></a>
</li>
{% endif %}
and then in the python context you can do:
from django.contrib.auth.decorators import login_required
@login_required
function stuff():
.....
where @login_required
should prefix any function that should only be run by a logged-in user.
Edit: and to address your specific use case, you want to do just:
if request.user.is_authenticated:
.