Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Set Django REST Frmework JWT in cookies
I am using djangorestframework-jwt to authenticate users. I have overridden the builtin JSONWebTokenAPIView to return user details in the response as well. And I am also setting the token in cookies in my view. def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): user = serializer.object.get('user') or request.user token = serializer.object.get('token') response_data = { 'access_token': token, 'user': UserInfoSerializer(user).data } response = Response(response_data, status=status.HTTP_200_OK) if api_settings.JWT_AUTH_COOKIE: expiration = (datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA) response.set_cookie(api_settings.JWT_AUTH_COOKIE, response.data['access_token'], expires=expiration, httponly=True) return response return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) It works fine on Django server. I can see the token in cookies when I verify the api using REST browseable api view. But my frontend (React) app is running on localhost:3000 and when i hit this api from my frontend server I receive the success response but token is not being set in the cookies. Do I need to set the cookie domain as well? -
Django: Query Database
Here's my model, class Question(models.Model): ... timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) How can I filter out the Questions asked in last 14 hours? Thank You :) -
Django authentication LDAP and token management locally
I am trying to use LDAP to authenticate my users. In addition, I would like to manage the tokens. I am assuming I can't do that using ldap (correct me if I am wrong), so I am trying to find an alternative using Django. Currently, I am creating a dummy mirror user on my system with a default 'abcd1234' password. Once the ldap authenticates the user, my code uses the Django auth module to authenticate the mirror user locally and give him a token that is managed in my app with a timeout. I am sure there must be a better way, my management is double. -
Django, apidoc js What to add in a PUT method?
I have read the apidoc.js documentation and i have a dilemma. I don't exactly know the difference between @apiParam and @apiSucces, the documentation doesn't explain properly what they really do. For example i have a get and a put with these parameters in the get: I am using apidoc in django and this is my view: class LocationView(APIView): """ @api {get} /locations/:id/ Location id - details @apiName GetLocation @apiGroup Locations @apiParam {integer} [id] Location id. @apiParam {string} [name] Location name. @apiParam {object} [company] Company name. @apiParam {string} [website] Location website. @apiSuccess {object[]} results List with location details """ serializer_class = LocationSerializer permission_classes = (IsAuthenticatedOrReadOnly,) def get_object(self, pk): try: return Location.objects.get(pk=pk) except Location.DoesNotExist: raise Http404 def get(self, request, pk): serializer = LocationSerializer(self.get_object(pk)) return Response(serializer.data) def put(self, request, pk): location = self.get_object(pk) serializer = LocationSerializer(location, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk): location = self.get_object(pk) location.save() return Response(status=status.HTTP_204_NO_CONTENT) I want to create the put apidoc. What do i have to write in it for modifying? Do i have to write every parameter again? or use apiSuccess? An example would be great. -
Globally getting context in Wagtail site
I am working on a Wagtail project consisting of a few semi-static pages (homepage, about, etc.) and a blog. In the homepage, I wanted to list the latest blog entries, which I could do adding the following code to the HomePage model: def blog_posts(self): # Get list of live blog pages that are descendants of this page posts = BlogPost.objects.live().order_by('-date_published')[:4] return posts def get_context(self, request): context = super(HomePage, self).get_context(request) context['posts'] = self.blog_posts() return context However, I would also like to add the last 3 entries in the footer, which is a common element of all the pages in the site. I'm not sure of what is the best way to do this — surely I could add similar code to all the models, but maybe there's a way to extend the Page class as a whole or somehow add "global" context? What is the best approach to do this? -
Fixture not loading in Django
Settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) FIXTURE_DIRS = ( os.path.join(BASE_DIR, '/deals/fixtures/'), ) test_deals.py: import unittest from deals.models import Retailer import django.test class TestRetailer(django.test.TestCase): def setUp(self): fixtures = ['deals_test_data.json'] self.bestbuy = Retailer(Retailer.objects.get(pk=1)) def test_name(self): self.assertEqual(self.bestbuy.name, 'Best Buy US') Project structure: project - deals - fixtures - test_deals_data.jason - tests - test_deals.py Error: Traceback (most recent call last): File "/home/danny/PycharmProjects/askarby/deals/tests/test_deals.py", line 10, in setUp self.bestbuy = Retailer(Retailer.objects.get(pk=1)) File "/home/danny/.virtualenvs/AskArby/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/danny/.virtualenvs/AskArby/lib/python3.5/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name deals.models.DoesNotExist: Retailer matching query does not exist. Destroying test database for alias 'default'... Process finished with exit code 1 I've tried not using FIXTURES_DIR but instead using fixtures=['../deals_test_data.jason']. I've tried removing the slashes at the front and back of the string in my FIXTURES_DIR. No joy. How can I make my fixtures load? -
How to develop web Unix terminal using Python3 [on hold]
i am developing free online python tutorial. can somebody assist me what are the library i can use to develop web Unix console using python & django. -
Spyne - change name of part in wsdl message "wsdl:part"
in my case, in order to keep conformance with some existing SOAP client "name" of "part" in "message" element of WSDL needs to be "parameters" like here <wsdl:message name="Notify"> <wsdl:part name="parameters" element="tns:Notify"/> </wsdl:message> <wsdl:message name="NotifyResponse"> <wsdl:part name="parameters" element="tns:NotifyResponse"/> </wsdl:message> Currently I don't see any way of doing that in Spyne. I went through documentation, source code and it seems that WSDL generator always takes the same value for "name" of "part" as for "name" of whole "message" (spyne/interface/wsdl/wsdl11.py) def add_messages_for_methods(self, service, root, messages): for method in service.public_methods.values(): self._add_message_for_object(root, messages, method.in_message, method.in_message.get_element_name()) (...) def _add_message_for_object(self, root, messages, obj, message_name): (...) message = SubElement(root, WSDL11("message")) message.set('name', message_name) (...) for obj in objs: part = SubElement(message, WSDL11("part")) part.set('name', obj.get_element_name()) part.set('element', obj.get_element_name_ns(self.interface)) So basically "name" for "message" message_name is method.in_message.get_element_name() and that's the same case for "name" in "part" as obj.get_element_name() -> method.in_message.get_element_name() However, in Python I've never done anything larger then 3 lines of code and it took my a while to understand all of this (Swift/Objc programmer here) I might be missing something and maybe there's some nice easy method to do that ? As a quick and poor hack/workaround I've just changed part.set('name', obj.get_element_name()) into part.set('name', 'parameters') and in my case … -
How make a get request with an atribute from another class in Django?
Basically i want to make a get method that when filled with a ID from a Person, list all the addresses of that person in json format. Already tried many other methods but none came close from django.db import models from django.core.validators import RegexValidator # Create your models here. class Address(models.Model): zipcode = models.CharField(max_length=8) state = models.CharField(max_length=100) city = models.CharField(max_length=100) street = models.CharField(max_length=100) number = models.IntegerField() person_id = models.ForeignKey('Person', on_delete=models.CASCADE, related_name="addresses") class Person(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() -
Homepage in Django isn't working
I'm currently trying to create a homepage for Django, but when I test it, it just shows me a blank page with nothing on it. This is what I have so far. First is my URL page from mysite: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'',include('firstapp.urls')), ] and my url page from firstapp: from django.conf.urls import url from firstapp.views import HomePage urlpatterns = [ url(r'^$', HomePage.as_view(), name='home'), ] this is my views page: from django.shortcuts import render from django.views.generic import TemplateView class HomePage(TemplateView): template_name = 'home/home.html' def home(request): return render(request, self.template_name) this is the base.html which extends to home.html {% load staticfiles %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Home</title> <link rel='stylesheet' href='{% static "css/base.css" %}'/> </head> <html> <p>{{ variable }}</p> <script src= '{% static "js/base.js" %}'></script> </body> </html> And finally home.html itself. {% extends 'base.html' %} {% block body %} <div class="container"> <p>Testing Home</p> </div> {% endblock %} Now if it works, I should be seeing "Testing Home"...but...I see nothing. I just get an empty white page. Any idea why this is happening? -
Django SMTPServerDisconnected error on password reset (but works elsewhere)
I'm trying to set up self-serve password resets on a django setup. I have configured it to use the in-built password reset system, and have tested everything on my dev machine, and works fine. However, in production (i.e. actually sending emails), when I try to get a password reset email, it throws an SMTPServerDisconnected error: [22/Sep/2017 15:04:59] ERROR [django.request:256] Internal Server Error: /password_reset/ Traceback (most recent call last): File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/utils/decorators.py", line 145, in inner return func(*args, **kwargs) File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/utils/decorators.py", line 110, in _wrapped_view response = view_func(request, *args, **kwargs) File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/contrib/auth/views.py", line 182, in password_reset form.save(**opts) File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/contrib/auth/forms.py", line 256, in save html_email_template_name=html_email_template_name) File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/contrib/auth/forms.py", line 213, in send_mail email_message.send() File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/core/mail/message.py", line 303, in send return self.get_connection(fail_silently).send_messages([self]) File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 107, in send_messages sent = self._send(message) File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 123, in _send self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n')) File "/usr/lib/python2.7/smtplib.py", line 735, in sendmail self.rset() File "/usr/lib/python2.7/smtplib.py", line 469, in rset return self.docmd("rset") File "/usr/lib/python2.7/smtplib.py", line 394, in docmd return self.getreply() File "/usr/lib/python2.7/smtplib.py", line 368, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") SMTPServerDisconnected: Connection unexpectedly closed I'm using G-Suite (Google) as the SMTP relay; the settings I'm using are: EMAIL_HOST = 'smtp-relay.gmail.com' EMAIL_PORT … -
best way to send files to GCS with Django
what is the best way to send files to Google cloud storage with django. this moment I'm getting the file with a post method file = request.FILES['image'] but when I try to send to GCS from google.cloud import storage client = storage.Client(projectName) bucket = client.get_bucket(bucketName) blob = bucket.blob(fileName) blob.upload_from_filename(file) I get this erros InMemoryUploadedFile so I have to save the file in a temp and after that send to GCS, but it is slow. -
TemplateDoesNotExist at / What is wrong?
I got an error,TemplateDoesNotExist at / app/index.html or index.html . app(child app) is in testapp(parent app),and app has index.html・urls.py・views.py .urls.py of app is from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] views.py of app is from django.shortcuts import render def index(request): return render(request, 'app/index.html') urls.py of testapp is from django.conf.urls import include, url from django.contrib import admin from app.views import index urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', index, name='index'), ] render's argument of views.py in app was changed into 'index.html',but same error happens.What is wrong?(the way to write directory?) How should I fix this? -
Best Practices for retrieving Django Model Fields that may be "None"
I have a Django model that looks something like this : class Candidate(models.Model): first_name = models.CharField(max_length=30, blank=True, null=True) middle_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30, blank=True, null=True) current_job = models.ForeignKey( Job, on_delete=models.SET_NULL, blank=True, null=True, default=None, ) I get an instance of "Candidate", and try to save some of the values into a dictionary candidate = Candidate.objects.get(first_name = "John") data['first_name'] = candidate.first_name data['last_name'] = candidate.last_name data['company_name'] = candidate.current_job.company This works fine when all values and foreign-keys are properly populated. However, when any of the values of the fields are None, especially important regarding the ForeignKey relationships, I'll hit an AttributeError, something like : 'NoneType' object has no attribute 'company' I want to properly handle the "None" case for any Field in the Model. I've found these two work-arounds for it right now, but neither seem satisfactory to me. A) I can put a try-except around EACH and EVERY field (which doesn't seem correct as my models get to ~20 fields) try: data['first_name'] = candidate.first_name data['last_name'] = candidate.last_name except: pass try: data['company_name'] = candidate.current_job.company B) I can convert the instance to a dict like this and use a .get() since that never raises an Exception. candidate_dict = candidate.__dict__ data['first_name'] = candidate_dict.get('first_name') … -
django Markdown problems
Django:1.11.5 Python:3.5.2 Markdown 2.6.9 Code picture Code picture Django Version: 1.11.5 Exception Type: AttributeError Exception Value: 'DeferredAttribute' object has no attribute 'strip' Exception Location: /usr/local/lib/python3.5/dist-packages/markdown/init.py in convert, line 355 Python Executable: /usr/bin/python3 Python Version: 3.5.2 Python Path: ['/data/mysite', '/usr/local/bin', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-i386-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages'] Do not know where there is a problem. Remove Post.content = markdown.markdown (Post.content), show normal! -
Django 1.9 form not valid
I try to make simple form: class ContactUsForm(forms.Form): name = forms.CharField(label=(u'Name')) phone = forms.CharField(label=(u'Phone')) email = forms.CharField(label=(u'E-mail')) here is html of this form: <form action="/contact_us/" method="POST"> {% csrf_token %} {{contact_us.errors}} {{contact_us}} <input type="submit" class="button" value="Submit"> </form> And here is the view of action: def contact_us(request): if request.POST: form = ContactUsForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] phone = form.cleaned_data['phone'] mail = form.cleaned_data['email'] return HttpResponseRedirect('/thanks/') else: return HttpResponse(form.errors) else: form = ContactUsForm() return HttpResponseRedirect('/') I don't know why, but my form always not valid. Can you help me with it? Thanks a lot. -
how to update another field on admin django
models.py Good night friends, I would like to know if there is a possibility that every time I register a new move, the django administrator checks what is a 'hydrographic region' and adds the value that is entering with the 'balance_box'. class Movement(models.Model): TYPE_MOVE = ( ('1', 'Receita'), ('2', 'Despesa'), ) regiao_hidrografica = models.ForeignKey(RegiaoHidrografica, verbose_name="Região Hidrografica", null=False) origem = models.ForeignKey(Origem, verbose_name="Origem", null=False) finalidade_recurso = models.ForeignKey(FinalidadeRecursos, verbose_name="Finalidade de Recursos", null=True) descricao = models.TextField("Descrição", null=True) valor = MoneyField(max_digits=10, decimal_places=2, default_currency='BRL') data_refencia = MonthField("Data de Referencia", help_text="Informe mês e ano") # data_refencia = models.DateField("Data de Referencia", null=True, blank=True, default=None) tipo_movimento = models.CharField(max_length=1, default=1, choices=TYPE_MOVE) def __str__(self): return self.descricao def update_total_valor(self): total = 0 self.movimento_set: total += mov.valor self.saldo_caixa = total self.save() class RegiaoHidrografica(models.Model): name = models.CharField("Nome", max_length=100, null=False) sigla = models.CharField("Sigla", max_length=10, null=True) taxa_inea = models.IntegerField(default=10, null=True) taxa_trans = models.IntegerField(default=0, null=True) saldo_caixa = MoneyField('Saldo em caixa estimado', max_digits=10, decimal_places=2, null=True, default=0, default_currency='BRL') saldo_cc = MoneyField('Saldo em conta estimado', max_digits=10, decimal_places=2, null=True, default=0, default_currency='BRL') def __str__(self): return self.name I tried something like this, create this method in the 'class MovimentoAdmin(admin.ModelAdmin)', but it did not work. admin.py def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for instance in instances: instance.save() formset.save_m2m() instance.RegiaoHidrografica.update_total_valor() Would anyone … -
TypeError: 'NoneType' object is not subscriptable followed by AttributeError: 'NoneType' object has no attribute 'split'
Using django. I have the following model: class Postagem(models.Model): id = models.AutoField(primary_key=True, editable=False) descricao = models.CharField(max_length=50) area = models.ForeignKey('core.Area', null=True) user = models.ForeignKey('User') categoria = models.CharField(max_length=50, null=True) post = models.FileField(upload_to='posts/', null=True) thumbnail = models.FileField(upload_to='posts/', null=True) def __str__(self): return self.descricao The Following form: class PostForm(forms.ModelForm): categoria = forms.ChoiceField(choices=[("Video","Vídeo"),("Audio","Aúdio"),("Imagem","Imagem"),("Musica","Música")], required=True) thumbnail = forms.FileField(required=False) class Meta: model = Postagem fields = ['descricao', 'area', 'user', 'post'] View: def profileView(request): context = getUserContext(request) if request.method == 'POST': exception=None userDict = {} userDict["user"] = context["user"].id if "categoria" in request.POST: newPost = request.POST.copy() newPost.update(userDict) form = PostForm(newPost,request.FILES) print("postform POST: ",newPost, " File ",request.FILES) if form.is_valid(): print("valid") try: form.save() print("saved") return HttpResponseRedirect(reverse_lazy('accounts:profile')) except IntegrityError as e: print("Integrity Error") exception=e else: print("PostForm error") print(form.errors) form.non_field_errors=form.errors if exception is not None: form.non_field_errors.update(exception) context['form']=form posts = Postagem.objects.get_queryset().order_by('id') paginator = Paginator(posts, 12) page = request.GET.get('page') context["areas"] = Area.objects.all() try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. posts = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. posts = paginator.page(paginator.num_pages) context["posts"]=posts return render( request, 'accounts/profile.html', context ) And at last the template: {% for post in posts %} {% if forloop.counter0|divisibleby:4 or forloop.counter0 == 0 %} … -
I am not sure my django app and LDAP work properly
Please help. I am not sure how my django app can work with LDAP server. I am attached here my project configuration for your references Thanks for all, Joe Nguyen [DC][1] [Login page][2] [configuration 1][3] [configuration 2][4] -
where clean garbage?? In TearDown or function's end?
Here is the story: when I request one view, the view will create some resource, now we need to clean it to let them not affect next test. (ps: garbage is something like directory or network device) class SomeViewTest(TestCase): def setUp(self): self.init_sth() def tearDown(self): self.clean_init_sth() # is there to clean the garbage?? def test_view(self): self.client.post(url, data={}) # here generate the garbage self.assertTrue() # is there to clean the garbage?? I think if put clean in tearDown, the clean will execute, even the view failed, it let me more convenient that not need to clean garbage manual.(for example, rm -rf /garbage_directory), but now setUp and tearDown is not equivalent create and destroy. -
Overflow after inserting image in column
I know this is a one setting issue but I'm quite new and don't know what the exact terminology to get the answer i'm looking for. I'm using Bootstrap CSS 3.3.7 on Django 1.11 When I insert an image the first column and row I get an overflow into the second column. With image Columns without image works correctly. <div class="tab-content"> <div class="tab-pane active" id="{{vg.grouper.id}}{{fg.grouper.id}}hari_ini"> <div class="row"> {% for sg in show_list2 %} {% if sg.grouper %} {% for sh in sg.list %} <div class="col-xs-3 col-xs-spl col-xs-npr"> <div class="contain"> {% load static %} {% ifchanged %} {% static sh.film.poster %}' width= 100% /> {% endifchanged %} </div> </div> <div class="col-xs-3 col-xs-npl col-xs-npr"> <div class="content"> <ul> <li> <p class=p1>{{ sh.show_time_today }}</p> </li> </ul> </div> </div> <div class="col-xs-3 col-xs-npl col-xs-npr"> <div class="content"> <ul> <li> <p class=p1>{{ sh.rps_price }}</p> </li> </ul> </div> </div> <div class="col-xs-3 col-xs-npl col-xs-npr"> <div class="content"> <ul> <li> <p class=p1>{{ sh.rps_price }}</p> </li> </ul> </div> </div> {% endfor %} {% endif %} {% endfor %} </div> </div> I've tried the css below which does not help. .contain { height: /* max height you want */ width: 95% /* max width you want */ overflow: hidden; } I've tried adding a … -
unknown BadRequestError - No exception message supplied- Django - SynapseAPI
I am getting an error and i have no idea what it means in relation to the project that I am working on. I am trying to create a user though the synapse api. After a profile is created, I want to call the method that creates the user and grab information from the newly created profile within the application, to create a user in the synapse api. The error I am getting is a lack of exception message. I have no idea what this means or how to fix it. can anyone help me. Here is the code that I have. Here is the profile processing and the call to create the user is at the bottom of the snippet: cd = form.cleaned_data first_name = cd['first_name'] last_name = cd['last_name'] dob = cd['dob'] city = cd['city'] state = cd['state'] phone = cd['phone'] privacy = cd['privacy'] ssn = cd['ssn'] # this is the new record that is going to be created and saved new_profile = Profile.objects.create( user = currentUser, first_name = first_name, last_name = last_name, dob = dob, city = city, state = state, phone = phone, privacy = privacy, ) # createUserDwolla(request, ssn) # searchUserDwolla(request) createUserSynapse(request) return redirect('home_page') Here is … -
Hello everybody. I would like to ask you How i can connect and implement websockets with django?
I would like to use websockets for my projects , but i have no idea what do i need to do. I use django for back end. how I can combine them.? this is the only question i have. thanks guys.) -
Wordpress on subdirectory of django site via alias in virtual host
I'm trying to run wordpress on the /blog subdirectory of my main django site. I tried many things but no matter what, I keep getting the 404 page of the root site when I go to example.com/blog. For some reason the server isn't picking up the alias... Here is the code from my default virtual host file: Alias /blog "/var/www/blog" <Directory "/var/www/blog"> Options FollowSymLinks AllowOverride All </Directory> and in my .htaccess I have RewriteBase /blog/ Any idea what the problem could be? Thanks ahead of time -
TypeError: __init__() missing 1 required positional argument: 'get_response'
when i run my server python3 manage.py runserver the browser returns A server error occurred. Please contact the administrator. then i get this error `Traceback (most recent call last): File "/usr/lib/python3.5/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/usr/local/lib/python3.5/dist-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/wsgi.py", line 170, in __call__ self.load_middleware() File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 52, in load_middleware mw_instance = mw_class() TypeError: __init__() missing 1 required positional argument: 'get_response' my settings file is like that INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'web.middleware.LoginRequiredMiddleware', ] and in may project i created middleware.py and also it looks like this from django.conf import settings class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response so anay idea?!