[Fixed]-How to check whether user is logged in or not

10👍

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

8👍

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 %}
👤martin

4👍

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:.

1👍

In this article, we go over how to check if a user is logged in or not in Django.

So, there’s a few ways of doing this, but the way we will go over is by using the request object in Django.

By calling request.user, we are able to access the user that is currently logged in.

We then can use the is_authenticated() function to determine if a user is currently authenticated (logged into the account).

So, we’ll create a simple script that if a user is logged in, we will print, "Logged in", and if a user is not logged in, we will print out, "Not logged in"

Basically, we do this all in the views.py file, which is the file where our main Python code always goes.

The code is shown below.

def index(request):
    if request.user.is_authenticated():
        print("Logged in")
    else:
        print("Not logged in")

So in this code, in our views.py file, we have a function called index, which is passed in the argument,. request.

request.user references the user that is logged in (or not if not logged in). The function, is_authenticated(), then checks to see if the user is authenticated (logged in).

If so, we print out, "Logged in". If not, we print out, "Not logged in".

Of course, there are many other things you could do besides just print out these statements.

If a user is logged in, we could render a template. If no one is logged in, we could render another template.

Other things, we could do is if a user is logged in, we could render a template. If not, we could raise a 404 Page Not Found Error.

Another thing we could do is if a user is logged in, we could render a template. If not, we could redirect the user to the login page.

So there are several things that could be done based on whether a user is logged in or not.

Leave a comment