Skip to content Skip to sidebar Skip to footer

How To Set Django Middleware In Settings File

Hi all i am trying to add middleware to my app and the app is located in this location myapp/sitemanager/middleware/__init__.py myapp/sitemanager/middleware/redirects.py what is t

Solution 1:

You'd make sure that your Python path is properly configured. Suppose (in your project) your directory structure resembling this: Django 1.4

/mysite
/mysite/mysite #defult settings.py gonna here...
/mysite/apps
/mysite/apps/__init__.py
/mysite/apps/main
/mysite/apps/main/__init__.py
/mysite/apps/main/models.py
/mysite/apps/main/views.py
/mysite/apps/main/middleware/__init__.py
/mysite/apps/main/middleware/log.py

It is my simple midlleware logger exemple (in log.py):

from django.http import HttpRequest
import datetime

classLogger(object):
    defprocess_request(self, request):
        f = open('/tmp/log.txt', 'w')            
        f.write(str(datetime.datetime.now()))

Note that my custom middleware class (in log.py) is under my middleware python package, that is under main app.

So, you should put in your settings.py something like this:

import sys
sys.path.append(MY_PROJECT_ROOT)

and in middleware tuple:

MIDDLEWARE_CLASSES = (
'...', 
'apps.main.middleware.log.Logger',
)

Post a Comment for "How To Set Django Middleware In Settings File"