login_required decorator on a class based view in django

2024/10/4 11:29:11

I have a working class based view. But when adding @login_required I get the error:

AttributeError: 'function' object has no attribute 'as_view'

Something is happening to the ResultListView here:

from django.urls import path
from .views import ResultListViewurlpatterns = [path('meetings/', ResultListView.as_view(), name='meetings'),
]

My views.py:

@login_required
class ResultListView(ListView):template_name = ...def get_queryset(self):return Result.objects.filter(rider__user=self.request.user)

Which is all working fine until I put the decorator in. Very confused now, I don't see why ResultListView should loose its attributes when sending it through the decorator.

Answer

The @login_required decorator only decorates functions, not classes, you can make use of a mixin, or decorate the function that is the result of the .as_view() call.

Option 1: Using the LoginRequiredMixin

You can make use of the LoginRequiredMixin [Django-doc] that you need to put before the ListView in the parent classes:

from django.contrib.auth.mixins import LoginRequiredMixinclass ResultListView(LoginRequiredMixin, ListView):template_name = …def get_queryset(self):return Result.objects.filter(rider__user=self.request.user)

Option 2: decorate the .as_view() result

An alternative is to decorate the outcome of the .as_view, which is indeed a function:

from django.urls import path
from .views import ResultListView
from django.contrib.auth.decorators import login_requiredurlpatterns = [path('meetings/', login_required(ResultListView.as_view()), name='meetings'),
]
https://en.xdnf.cn/q/70618.html

Related Q&A

Generic way to get primary key from declaratively defined instance in SQLAlchemy

Does SQLAlchemy offer a generic way to get the primary key from a declaratively defined instance, so that if:Base = declarative_base()class MyClass(Base):__tablename__ = mytablekey = Column(Integer, pr…

Add column after another column

How can I add a column after another column to a database using Alembic or SQLAlchemy? That would be equivalent to this SQL clause: ALTER TABLE foo CHANGE COLUMN bar bar COLUMN_DEFINITION_HERE AFTER …

Scrapy Images Downloading

My spider runs without displaying any errors but the images are not stored in the folder here are my scrapy files:Spider.py:import scrapy import re import os import urlparse from scrapy.spiders import …

A full and minimal example for a class (not method) with Python C Extension?

Everywhere, I can easily find an example about writing a method with Python C Extensions and use it in Python. Like this one: Python 3 extension example$ python3 >>> import hello >>> …

Python: Grouping into timeslots (minutes) for days of data

I have a list of events that occur at mS accurate intervals, that spans a few days. I want to cluster all the events that occur in a per-n-minutes slot (can be twenty events, can be no events). I have …

signal.alarm not triggering exception on time

Ive slightly modified the signal example from the official docs (bottom of page).Im calling sleep 10 but I would like an alarm to be raised after 1 second. When I run the following snippet it takes way…

Execute Python (selenium) script in crontab

I have read most of the python/cron here in stackoverflow and yet couldnt make my script run. I understood that I need to run my script through shell (using zsh & ipython by the way), but really I …

Get post data from ajax post request in python file

Im trying to post some data with an ajax post request and execute a python file, retrieving the data in the python file, and return a result.I have the following ajax code$(function () {$("#upload…

How to implement maclaurin series in keras?

I am trying to implement expandable CNN by using maclaurin series. The basic idea is the first input node can be decomposed into multiple nodes with different orders and coefficients. Decomposing singl…

Rowwise min() and max() fails for column with NaNs

I am trying to take the rowwise max (and min) of two columns containing datesfrom datetime import date import pandas as pd import numpy as np df = pd.DataFrame({date_a : [date(2015, 1, 1), date(2012…