Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check whether user is logged in or not

I am working on invoice management system in which user can add invoice data and it will save in database and whenever user logged in the data will appear on home page but whenever user logout and try to access home page but it is giving following error.

TypeError at /

'AnonymousUser' object is not iterable

i tried AnonymousUser.is_authenticated method but still not working.

i want if user is logged in then home.html should open otherwise intro.html

here is my code views.py


from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import (
    ListView,
    DetailView,
    CreateView,
    UpdateView,
    DeleteView
)
from .models import Invoicelist

def home(request):

    if request.user.is_authenticated():
        context = {
        'invoices': Invoicelist.objects.all()
        }
        return render(request, 'invoicedata/home.html', context)

    else:
        return render(request, 'invoicedata/intro.html', context)

home.html

{% extends "invoicedata/base.html" %}
{% block content %}
      {% for invoice in invoices %}
      <article class="media content-section">
        <div class="media-body">
          <div class="article-metadata">
            <small class="text-muted">{{ invoice.date_posted|date:"F d, Y" }}</small>
            <h2><a class="article-title" href="{% url 'invoice-detail' invoice.id %}">{{ invoice.issuer }}</a></h2>
          </div>

          <p class="article-content">{{ invoice.invoice_number }}</p>
          <p class="article-content">{{ invoice.date }}</p>
          <p class="article-content">{{ invoice.amount }}</p>
          <p class="article-content">{{ invoice.currency }}</p>
          <p class="article-content">{{ invoice.other }}</p>
          <div class="article-metadata">
            <small class="text-muted">{{ invoice.author }}</small>
          </div>

        </div>
      </article>
      {% endfor %}
{% endblock content %}

intro.html

{% extends "invoicedata/base.html" %}
{% block content %}
    <h2>login to your portal for great auditing services</h2>
{% endblock content %}
like image 887
Mayur Satav Avatar asked Apr 26 '20 12:04

Mayur Satav


People also ask

How can I tell if a user is logged in?

Right-click the taskbar, then select “Task Manager“. Select the “Users” tab. Details on the users logged into the machine are displayed.

How do we check if a user is logged in web development?

This can also be used to re-direct the user if they haven't been logged in: <? php // check that the session variable does exist // check that the user 'LoggedIn' has been set to 1 (true) if (! isset($_SESSION['LoggedIn']) && $_SESSION['LoggedIn'] !=

How can I check if a user is logged in PHP?

If you have two PHP applications on a webserver, both checking a user's login status with a boolean flag in a session variable called 'isLoggedIn', then a user could log into one of the applications and then automagically gain access to the second without credentials.


2 Answers

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

like image 80
Mayur Satav Avatar answered Oct 01 '22 02:10

Mayur Satav


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 %}
like image 31
Martín Schere Avatar answered Oct 01 '22 02:10

Martín Schere