Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why this intermediate Django page won't get back to the former action?
This is Django 1.11.29 and I'm trying to write a simple Django admin action with an intermediate page. I've seen something like this has been asked here but even following the response advice I can't manage to solve it. In my ModelAdmin I have this: from django.contrib.admin import helpers from django.shortcuts import render class MyModelAdmin(admin.ModelAdmin): ... actions = ['send_email'] ... So I implemented my send_email action like this: def send_email(self, request, queryset): print(request.POST) print(queryset) if 'apply' in request.POST: # Do some stuff else: return render(request, 'admin/confirm_email.html', { 'mymodels': queryset, 'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME }) This is pretty standard according to the Django documentation. The admin/confirm_email.html looks like this: {% extends "admin/base_site.html" %} {% block content %} <p>You're about to send a lot of mails!</p> <form action="" method="post"> {% csrf_token %} {% for mymodel in mymodels %} <input type="hidden" name="{{ action_checkbox_name }}" value="{{ mymodel.pk }}" /> {% endfor %} <br /> <input type="button" value="Cancel" onClick="history.go(-1); return true;" /> <input type="submit" name="apply" value="Confirm" /> </form> {% endblock %} The problem is that when the admin action is invoked, it enters the intermediate page, but when hit Confirm in the intermediate page, it won't call the admin action back, so I cannot process the answer. … -
Django redirecting to a wrong url
when i click submit on my form it goes to ../register/register/ where as my expectation is that it should go to ../register This is my main project urls.py urlpatterns = [ path('participants/', include('participants.urls')), path('admin/', admin.site.urls), ] This is my application urls.py urlpatterns = [ path('register/', views.register, name="register") ] This is my views function def register(request): if request.method == "POST": username = request.POST['username'] # email = request.POST['email'] password = request.POST['pass'] print(username, password) user = User.objects.create_user(username=username, password=password) user.save() return redirect('register') else: return render(request, 'register.html') -
Django template for loop is empty
I am trying to build a detail view in django, but nothing is displayed in the template. views.py class MyDetailView(DetailView): model = Article template_name = 'detail.html' detail.html {% extends 'base.html' %} {% load i18n %} {% endblock %} {% block content %} {% for item in itemlist %} {{item.pk}} {{item.title}} {% empty %} There are no items in this list {% endfor %} {% endblock %} Why is nothing displayed in the template here? -
KeyError at / "https://pbs.twimg.com/media/EUDjMHoWsAERZ83.jpg'"
I want to access the number of retweets and number of likes on a tweet that I get using twitterAPI. I have written the following code with some help from other sources. I am not able to understand the reason for this error. The error is in line 88 of the code. Please help me out. I am attaching the image for the error. views.py: from django.shortcuts import render from TwitterAPI import TwitterAPI from Post.models import Album import calendar from django.contrib.auth.models import User import requests import http.client,urllib.request,urllib.parse,urllib.error,base64,sys import simplejson as json consumer_key='RNBUUEtazKVJemcMedGHWgMCV' consumer_secret='zILQDS386Dd4WRr8810gD5WAGbfkeVRDT3BYWs7RKChY1U7duM' access_token_key='893345180958564352-UT4mqHeDQyYllebzbsIPItOCyjHs8eP' access_token_secret='Gv2pbj6eeKvKPWjbePfO71la7xOeib2T5lV4SaL86UUdj' api = TwitterAPI(consumer_key,consumer_secret,access_token_key,access_token_secret) me = User.objects.get(username='vedant') def newsfeed(request): hashtag_string = '#Swachh_Bharat' hashtag_string = hashtag_string.lower() if(request.GET.get('mybtn')): hashtag_string = str(request.GET.get('hashtag')) print("HashtagString :: ",hashtag_string) if hashtag_string == '#vedant': url_list = [] retweet_count_list = [] url_retweet_dict = {} url_favourite_dict = {} favourite_count_list = [] url_list_in_database = Album.objects.all().filter(user = me).values('image_url') temp = Album.objects.all().filter(user = me).values('image_url','date','retweet_count','like_count') url_list = {} for entry in temp: dt = str(entry['date'])[0:10] dt = calender.month_name[int(dt[5:7])]+" "+ dt[8:10]+"," + dt[0:4] url_list[str(entry['image_url'])] = (dt, str(entry['retweet_count']),str(entry['like_count'])) return render(request, 'Post/newsfeed.html', {'url_list': url_list}) #get the images of particular hashtag else: url_list = [] retweet_count_list = [] url_retweet_dict = {} url_favourite_dict = {} favourite_count_list = [] r = api.request('search/tweets',{'q':hashtag_string,'filter':'images','count':1000}) url_dict = {} for … -
Django with react depkoyment on google cloud
Im trying to build server for my project where frontend is react and backend is django. I did it locally works just fine, but how I should deploy it on google cloud platform, i want to make it live through external ip of my virtual machine. I tried everything what i found on google, but usually all guides are for localhost. -
How to redirect user to login page while adding items to cart?
I am newbie to django. I am creating simple order system. I want only logged in user to add items in cart. If user is not looged in, redirect user to login page and after logged in again redirect user to previous page. This is my views.py @require_POST @login_required def cart_add(request, dish_id): cart = Cart(request) dish = get_object_or_404(Dish, id=dish_id) form = CartAddDishForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(dish=dish, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') -
how to filter user created by another superuserso that it can send notice
in my forms.py class NoticeFormWarden(forms.ModelForm): class Meta: model = Noticee fields = ('name','description','users','file',) def save(self,user): owner = user issue_date = datetime.datetime.now().strftime("%Y-%m-%d") name = self.cleaned_data['name'] description = self.cleaned_data['description'] users = self.cleaned_data['users'] file = self.cleaned_data['file'] Noticee.objects.create(name=name, description=description, users=users, file=file, owner=owner, issue_date=issue_date) def __init__(self, users, *args, **kwargs): super(NoticeFormWarden, self).__init__(*args, **kwargs) self.fields['users'].queryset = User.objects.filter(is_hostelstaff=True) self.fields['name'].widget.attrs['placeholder'] = ' Subject' self.fields['file'].widget.attrs['placeholder'] = ' Subject' self.fields['description'].widget.attrs['placeholder'] = 'write your msg here . . .' self.helper = FormHelper() self.helper.form_show_labels = False in views.py def WardenCreateNotice(request): form = NoticeFormWarden(request.user, request.POST or None) if request.method == 'POST': if form.is_valid(): print('Saved notice') form.save(request.user) form = NoticeFormWarden(request.user) return redirect("warden_view:notice-warden2") context = { 'form': form, 'user': request.user, } return render(request, 'warden_view/notice.html',context) i have four type of user. admin,warden,staff,student admin create warden warden create staff and staff create student . now i want send notice so that admin send notice to warden and warden send notice to their created staff note that one warden has many staff and it can send notice to its only staff so how can i filter specific warden created staff -
Avoid duplicate entries for the same field
I have a model choice in django. which has foreign key relationship with user model and items model. Each user can choose as many items as he wants from items model, the choice model will keep track of how many users have chosen what items. a particular user could be able to choose an item only once, but my problem is that when user1 select any item no other user can choose that one again. this is my code for choice fill. Views.py def choice_fill(request, cid): item_list = item.objects.all() title = "Choice Filling" page = "Choice Filling" if request.method == "POST": usr = user.objects.get(id=request.session['id']) # return render(request, 'success.html',{'stud':stud}) if usr.isactive != 1: messages.error(request, "Your registration process is incomplete.") else: if not choice.objects.filter(item_id_id=cid, isactive=1).exists(): userid = usr.id c = choice(user_id_id=studid, item_id_id=cid, isactive=1) c.save() else: return HttpResponse('multiple Entry for same college') models.py class user(models.Model): fullname = models.CharField(max_length=50) password = models.CharField(max_length=10) email = models.EmailField(unique=True) class item(models.Model): name = models.CharField(max_length=50) password = models.CharField(max_length=10) institute_code = models.IntegerField(unique=True) class choice(models.Model): user_id = models.ForeignKey(user, on_delete=models.CASCADE) item_id = models.ForeignKey(item, on_delete=models.CASCADE) created_at = models.DateTimeField(default=timezone.datetime.now()) updated_at = models.DateTimeField(default=timezone.datetime.now()) isactive = models.BooleanField() -
Is it possible to wrap Django code to ensure all database access for the ORM has "using" set by default?
I have a Django project that handles connections with multiple databases. I have a Database Router that handles the logic of which objects to store in a specific database which I easily use in my views, so no issue there at all. For example: class ClientDatabaseRouterMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, args, kwargs): if 'client_url' in kwargs: # kwargs = {key: value.lower() for key, value in kwargs.items()} thread_local.client_url = kwargs['client_url'].lower() else: if hasattr(thread_local, 'client_url'): del thread_local.client_url class ClientDatabaseRouter: def _default_db(self): from django.conf import settings if hasattr(thread_local, 'client_url'): db = thread_local.client_url if db in settings.DATABASES: return db else: if settings.DEBUG: if hasattr(settings, 'DEBUG_CLIENT_DB'): return settings.DEBUG_CLIENT_DB return None def db_for_read(self, model, **hints): instance = hints.pop('instance', None) if instance: if instance._state.db is not None: return instance._state.db if model._meta.app_label == 'client': return 'clients' if model._meta.app_label == 'django_celery_beat': return 'default' return self._default_db() db_for_write = db_for_read def allow_relation(self, obj1, obj2, **hints): return obj1._state.db == obj2._state.db def allow_migrate(self, db, app_label, model_name=None, **hints): if db == 'default': return app_label == 'django_celery_beat' if not app_label == 'client': if db == 'clients': return False else: return db == 'clients' return None However, I also use Celery and … -
How can I retrieve form data from Django CreateView?
I have a Django blog where the users can set the status of each post (active, inactive) when creating them. I am using Django's generic class-based views and would like to redirect the user to their created post only when the status is set to "active", otherwise they should be redirected to the homepage. How can I retrieve this submitted info from the form to create an if statement? For example: if status == "a"... views.py from .models import Listing from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.messages.views import SuccessMessageMixin from django.views.generic import CreateView class PostCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = Post fields = ['title', 'status', 'content'] template_name = 'blog/post-form.html' success_message = 'Your post has been created.' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) -
How can I reference a user globally in Django for all Exceptions?
I have two questions that correlate. 1) Does django-rest-framework have a way to reference a user globally? 2) Does django / python allow me to change the generic exception class to include this user ID as meta every time it throws? I know I can create custom exception classes and raise them in code, but what about an exception I don’t correctly handle? For example, let’s say a divide by zero exception is thrown but I didn’t correctly handle it, right now my logs just say “Divide by zero exception”. Is there a way to update this globally so if a user is logged in it says “Divide by zero exception for user_id {id}“? class SomeExternalApiHelper: @staticmethod def do_api_call(): url = 'https://example.com' # do api request try: home_value = 100 / 0 except Exception as e: # Exception occurs here, I want to be able to reference user_id, without having # to pass the user_object all the way down into this call raise Exception("Something went wrong for user ID {0}".format(user_id)) class AddNewHouse(APIView): def post(self, request, format=None): # I can call request.user here and access the user object SomeExternalApiHelper.do_api_call() -
Django: Using current user as a foreign key to projects model
I am building a web-app where people can write projects. The projects are stored in a model and I want to use the user as the foreign key so I can show the user their projects on a webpage. Instances are entered through a form. The code always assigns the default value (1) and and not the user. Can any of you see what's causing this bug? Here is the code for the creation of the model in models.py: class PersonalProject(models.Model): user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField() code = models.TextField() def __str__(self): return self.title Heres the code for the form view to create the project in views.py: def newproject(request): if User is None: messages.error(request, "Must be signed in") return redirect('main:dashboard') if request.method == "POST": form = NewProjectForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('main:dashboard') else: messages.error(request, "Error") else: form = NewProjectForm() return render(request, "main/newproject.html", {"form":form}) Heres the code for the homepage view in views.py: def dashboard(request): messages.info(request, request.user.username) return render(request=request, template_name="main/dashboard.html", context={"structuredprojects": StructuredProject.objects.all(), "personalprojects": PersonalProject.objects.filter(user__username=request.user.username)}) I really hope you can help - I've been stuck on this for a while -
no python application found for uwsgi setting
I am setting with djano and uwsgi $uwsgi --ini uwsgi.ini My Django root is here /var/www/html/myapp/current It must be quite simple setting however I am not sure the yet. I have these two files /var/www/html/myapp/current/myapp/settings.py /var/www/html/myapp/current/myapp/wsgi.py [uwsgi] chdir=/var/www/html/myapp/current module=myapp.wsgi:application env DJANGO_SETTINGS_MODULE=myapp.settings http-socket = 0.0.0.0:8008 processes = 1 threasds = 1 master = 1 max-requests = 100000 The error is below, but I can't dig the detailed logs. spawned uWSGI worker 1 (pid: 27353, cores: 1) --- no python application found, check your startup logs for errors --- [pid: 27353|app: -1|req: -1/1] 172.17.1.143 () {28 vars in 334 bytes} [Thu Mar 26 17:37:01 2020] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0) -
Business logic in django manager outside of query interaction
This will be a spin-off about the infinite dispute on where to put your business logic in Django. After reading tons of related question on Stack Overflow and the django docs, I'm still undecided whether to put business logic in a separate module (e.g. service.py) or encapsulate it inside a model.Manager. What cause me esitating on using manager in this case is its intro in the django doc: A Manager is the interface through which database query operations are provided to Django models Indeed, I need to create a function which autonomously analyses data from a model and passes them to a view that will forward them to the front-end. This is not actually a query the front-end performs on the db. Rather, it's the back-end notifying the user if a particular data has been found. So, according to the django doc, this is not exactly the case for relying on manager. -
Reverse for 'remove' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['remove\\/\\(\\?P(?P<pk>[^/]+)\\\\d\\+\\)\\/\\$$']
I want the remove obj function to be triggered when the user click on it but its throwing error I have tried searching but cannot find solution I want to display a list ob objects and as soon as a user clicks on the object it gets deleted patients.html <body> {% include 'pages/nav.html' %} <div class="container"> <p>patients <a class="btn btn-primary btn-lg" role ="button" href="/patientadd">Add Patients</a> </p> <div class="list-group"> <br> <br> {% for i in names %} <a href="{% url 'remove' pk=i.pk %}" class="list-group-item">{{i}}</a> {% endfor %} </div> </div> </body> views.py not the whole view def removeObj(request, pk): object = get_object_or_404(request,pk) object.delete() model.py from django.db import models from django.contrib.auth.models import User class Patient(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) age = models.IntegerField() numvisit = models.IntegerField() detail = models.TextField(max_length=300) # url pattern urlpatterns = [ path('admin/', admin.site.urls), path('register/',register,name="register"), path('patients/',patients,name="patients"), path('patientadd/',patientAdd,name="patientadd"), path('login/',login,name="login"), path(r"remove/(?P<pk>\d+)/$",removeObj,name="remove"), path('register/logout/',logout,name="logout"), path('',home), ] -
Python anywhere deploying static django files wont work followed tutorial 100 %
I am trying to deploy my static files from my django app using python everywhere. I have followed 3 different tutorials now and none of them have worked. my STATIC_URL is set to /static/ and my STATIC_ROOT is '/home/coursePlanner/CoursePlanner/static' I collected all static files to the static root folder ('/home/coursePlanner/CoursePlanner/static) and If I use the python anywhere file broswer they are certainly all there. in my python anywhere WSGI file, path is set to '/home/coursePlanner/CoursePlanner' and os.environ['DJANGO_SETTINGS_MODULE'] is set to 'CoursePlanner.settings'. Finally, in the static files section of the webapp settings, URL = '/staitc/' and directory=/home/coursePlanner/CoursePlanner/static. When I open my webpage none of my static files load. Furthermore If I go to http://courseplanner.pythonanywhere.com/static/css/styles.css I get the following page: Page not found (404) Request Method: GET Request URL: http://courseplanner.pythonanywhere.com/static/css/styles.css Using the URLconf defined in CoursePlanner.urls, Django tried these URL patterns, in this order: admin/ [name='courseplanner-planner'] validate/ getRec/ search/ reqBarHandler/ getUnits/ The current path, static/css/styles.css, didn't match any of these. but if i go to the request URL in the python anywhere file manager, the file is present literally at that exact URL. What is going on? Any help would be greatly apperciated as Ive literally spent almost two full days trying … -
update field of queryset before passing to formset in django
i have a queryset that contains age of traveller. qset = Travellers.objects.filter(traveller_type='1') print(qset) print(qset[0].traveller_age) travellers_formset = TravellersFormset(queryset = qset) this gives give: <QuerySet [<Travellers: Travellers object (16887)>]> 33 i intend have a flag (is_renewal), which if true, should update the age of traveller by a year before passing to queryset to formset. so i'm doing something like this if travel_quote.is_renewal: print('starting renewal section') for each in qset.iterator(): print(each) print(each.traveller_age) each.traveller_age = each.traveller_age + 1 print(each.traveller_age) print('renewal section completed, checking for updated age') print(qset[0].get_fields()) this gives starting renewal section <QuerySet [<Travellers: Travellers object (16887)>]> 33 34 renewal section completed, checking for updated age 33 <<<<< i want this to be 34 instead of 33 after the loop -
how could I see in django the code of import lib utilizing shortcut keys in windows?
how to see in django the code of import lib utilizing shortcut keys in windows? Ad example the code behind djmoney etc. ? I remember that it is necessary to place the mouse on the library and press shortcut keys (ctrl+...) but I don't remember what. Thanks you and good evening from Italy -
django: python manage.py runserver issue
I am using Windows 10 and installed django via Anaconda conda install -c anaconda django after that I created a new project django-admin startproject website When I navigte into the folder where the manage.py file is an run python manage.py runserver I get the following output and nothing happens. Any ideas? -
Django : OneToOneField - RelatedObjectDoesNotExist
I have this two following classes in my model: class Answer(models.Model): answer = models.CharField(max_length=300) question = models.ForeignKey('Question', on_delete=models.CASCADE) def __str__(self): return "{0}, view: {1}".format(self.answer, self.answer_number) class Vote(models.Model): answer = models.OneToOneField(Answer, related_name="votes", on_delete=models.CASCADE) users = models.ManyToManyField(User) def __str__(self): return str(self.answer.answer)[:30] In the shell I take the first Answer: >>> Answer.objects.all()[0] <Answer: choix 1 , view: 0> I want to get the Vote object: >>> Answer.objects.all()[0].votes Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Hippolyte\AppData\Roaming\Python\Python38\site-packages\django\db\models\fields\related_descriptors.py", line 420, in __get__ raise self.RelatedObjectDoesNotExist( questions.models.Answer.votes.RelatedObjectDoesNotExist: Answer has no votes. But an error occured. I don't understand why the related_name is not recognized. Could you help me ? -
Custom vs Generic Views in Django
The question is about generic views, and their use in practice. They are presented as a better, cleaner, alternative for writing custom views, however they didn't seem to simply the view code much, and seemed very case specific. So in practice, are these generic views used extensively, with custom ones written only for very specific cases? Or is it the opposite, and generic views only exist for minimalists/case specific needs? -
Avoid race condition during creating object with incremented field
I'm trying to create MyModel object but I want to set bar field to already existed largest bar value in db for specified foo. The problem here are race conditions. I wanted to perform all logic on db side in one step without sucess. I have found solution but it's not the most elegant way. Infinite loops are always bad idea. from django.db import models, IntegrityError from django.db.models import Max class MyModel(models.Model): foo = models.UUIDField(primary_key=True, default=uuid4) bar = models.PositiveIntegerField() class Meta: constraints = [ models.UniqueConstraint( fields=['id', 'other_id'], name='unique_id_other_id' ) ] @classmethod def create_my_model(cls, data): while True: bar = (cls.objects.filter(foo=data['foo']).aggregate(Max('bar')).get('bar_max') or 0) + 1 try: cls.objects.create(bar=bar, **data) except IntegrityError: continue I will be glad if anyone can point me any direction how to handle this. BR -
Djongo not connecting to mlab server
I am using djongo with django2 to connect to mlab mongodb instance. settings.py 'default': { 'ENGINE': 'djongo', 'NAME': 'neon', 'HOST': 'mongodb://username:password@ds249605.mlab.com:49605/mlab1', } } although I am using this settings, the PyMongo connects to the local instance of mongodb. log Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/core/management/base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/backends/base/introspection.py", line 48, in table_names return get_names(cursor) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/backends/base/introspection.py", line 43, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/djongo/introspection.py", line 47, in get_table_list for c in cursor.db_conn.list_collection_names() File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/pymongo/database.py", line 856, in list_collection_names for result in self.list_collections(session=session, **kwargs)] File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/pymongo/database.py", line 819, in list_collections _cmd, read_pref, session) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/pymongo/mongo_client.py", line 1454, in _retryable_read read_pref, session, address=address) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/pymongo/mongo_client.py", line 1253, in _select_server server = topology.select_server(server_selector) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/pymongo/topology.py", line 235, in select_server … -
I need help to integrate duo_python 2FA into Django-mama-cas
I've setup django-mama-cas as a primary central authentication server for serveral department websites. The websites reside in a drupal/php web framework and use phpCAS for the CAS client. I need to integrate duo_python somehow to the django-mama-cas server. I am not sure where to start and any advice on what files or classes to edit is what I am looking for. From what I imagine those [files, classes, etc] to be, are below: settings.py import os import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType, PosixGroupType # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! with open('/n/fs/stage/signon/cas_container/casServer/secret_key.txt') as f: SECRET_KEY = f.read().strip() # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['signon.example.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mama_cas', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'casServer.urls' # Django Templates Settings: https://docs.djangoproject.com/en/2.2/topics/templates/ TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # WSGI Settings: https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ WSGI_APPLICATION = 'casServer.wsgi.application' # Database Settings: https://docs.djangoproject.com/en/2.2/ref/databases/ DATABASES = … -
login_required decorator on a class based view in django
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 ResultListView urlpatterns = [ 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.