Unable to set up Jinja2 with Django - django

I've installed Django 1.9.7, and I have Pythons 3.4.3 and 2.7.10 on Ubuntu.
These are the steps I've followed:
Made a new project with django-admin startproject testproject
cd testproject/testproject
Made an app within the project with django-admin startapp testapp
Made a directory for templates in that app with mkdir testapp/templates and added a very basic index.html template in there
Edited settings.py to change the template backend to django.template.backends.jinja2.Jinja2, by editing line 57 of the default settings file, and to add testproject.testapp to INSTALLED_APPS; the TEMPLATES section is therefore like this:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'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',
],
},
},
]
Edited urls.py, adding from testproject.testapp import views and a URL pattern url(r'^$', views.index),
Edited testapp/views.py adding
def index(request):
return render(request, 'index.html')
cd ..
Ran the server with python3 manage.py runserver, or python manage.py runserver -- very similar effect
Take a browser to http://localhost:3000
I get an error. On the command line I get this:
Internal Server Error: /
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/django/template/utils.py", line 86, in __getitem__
return self._engines[alias]
KeyError: 'jinja2'
Followed by another exception caused "during handling of the above exception", which matches the exception I see in the browser:
Environment:
Request Method: GET
Request URL: http://localhost:3000/
Django Version: 1.9.7
Python Version: 3.4.3
Installed Applications:
['django.contrib.staticfiles', 'testproject.testapp', 'webpack_loader']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/usr/local/lib/python3.4/dist-packages/django/template/utils.py" in __getitem__
86. return self._engines[alias]
During handling of the above exception ('jinja2'), another exception occurred:
File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py" in get_response
174. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py" in get_response
172. response = response.render()
File "/usr/local/lib/python3.4/dist-packages/django/template/response.py" in render
160. self.content = self.rendered_content
File "/usr/local/lib/python3.4/dist-packages/django/template/response.py" in rendered_content
135. template = self._resolve_template(self.template_name)
File "/usr/local/lib/python3.4/dist-packages/django/template/response.py" in _resolve_template
90. new_template = self.resolve_template(template)
File "/usr/local/lib/python3.4/dist-packages/django/template/response.py" in resolve_template
80. return select_template(template, using=self.using)
File "/usr/local/lib/python3.4/dist-packages/django/template/loader.py" in select_template
55. engines = _engine_list(using)
File "/usr/local/lib/python3.4/dist-packages/django/template/loader.py" in _engine_list
143. return engines.all() if using is None else [engines[using]]
File "/usr/local/lib/python3.4/dist-packages/django/template/utils.py" in all
110. return [self[alias] for alias in self]
File "/usr/local/lib/python3.4/dist-packages/django/template/utils.py" in <listcomp>
110. return [self[alias] for alias in self]
File "/usr/local/lib/python3.4/dist-packages/django/template/utils.py" in __getitem__
101. engine = engine_cls(params)
File "/usr/local/lib/python3.4/dist-packages/django/template/backends/jinja2.py" in __init__
35. self.env = environment_cls(**options)
Exception Type: TypeError at /
Exception Value: __init__() got an unexpected keyword argument 'context_processors'
I get very similar traces with Python 2.
I found this question which has a similar error message (KeyError: 'jinja2') but seems to be a separate problem, and this bug report which has the same error again whose solution is to install jinja2, but jinja2 is definitely installed. At least, I can run python or python3 and then import jinja2. pip says jinja2 is up to date.
I must be missing something crucial -- any ideas?

The error about context_processors is because the Jinja2 backend does not support that argument.
You should add an additional backend to your TEMPLATES setting, rather than replacing the existing backend from django to jinja2. See this answer for more information. If you replace the existing backend, then apps that require Django templates will not work, including the admin.
Finally, the jinja2 backend will look for templates in testapp/jinja2, not testapp/templates.

Related

Django HTTP Error 404: Not Found: Using a config.json file in my views

I have 3 apps and one is called 'cv' but for this app I use a config.json file but it keeps giving me a 404-error when loading the page.
My project is called "project_1" and my urls.py is defined as:
urlpatterns = [
path("", include("cv.urls")),
path("admin/", admin.site.urls),
path("projects/", include("projects.urls")),
path("blog/", include("blog.urls")),
]
http://127.0.0.1:8000/admin
http://127.0.0.1:8000/projects
and
http://127.0.0.1:8000/blog
can be reached, but when I open
http://127.0.0.1:8000
It gives me the error.
In the cv-directory, I have my urls.py defined as:
urlpatterns = [
path("", views.index, name="cv_index"),
]
And my cv/views.py as:
def index(request):
BASEURL = request.build_absolute_uri()
url = BASEURL + "/static/configuration/configuration.json"
response = urllib.request.urlopen(url)
configuration = json.loads(response.read())
return render(request, "index.html", configuration)
Where my json configuration is located in the cv directory under static>configuration>configuration.json
When I change my index function in cv/views.py to just render the request and give back my index.html file, it goes fine. So I expect it has something to do with this piece of code:
BASEURL = request.build_absolute_uri()
url = BASEURL + "/static/configuration/configuration.json"
response = urllib.request.urlopen(url)
configuration = json.loads(response.read())
My traceback looks like this:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.2.6
Python Version: 3.9.9
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'projects',
'blog',
'cv']
Installed 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']
Traceback (most recent call last):
File "C:\Users\s.pauly\Github\portfolio\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\s.pauly\Github\portfolio\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\s.pauly\Github\portfolio\cv\views.py", line 8, in index
response = urllib.request.urlopen(url)
File "C:\Users\s.pauly\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 214, in urlopen
return opener.open(url, data, timeout)
File "C:\Users\s.pauly\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 523, in open
response = meth(req, response)
File "C:\Users\s.pauly\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 632, in http_response
response = self.parent.error(
File "C:\Users\s.pauly\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 561, in error
return self._call_chain(*args)
File "C:\Users\s.pauly\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 494, in _call_chain
result = func(*args)
File "C:\Users\s.pauly\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 641, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
Exception Type: HTTPError at /
Exception Value: HTTP Error 404: Not Found
In your settings.py, what does your static files configuration look like? More specifically, have you defined the STATIC_ROOT and STATIC_URL variables?
You should be accessing static assets via the STATIC_URL.
Additionally, I would highly advise against sending a urllib.request inside a view function to access a static asset. Instead (assuming you are using a modern version of Django), access the file in your view function like so:
from django.templatetags.static import static
def index(request):
# use the imported static function to access the file as you would in a template
config_file = static('configuration/configuration.json')
# parse the json
config_json = json.loads(config_file)
# return your template and payload
return render(request, "index.html", configuration)
However, have you ran python manage.py collecstatic, and verified that the configuration.json is collected and placed in your static directory defined under the STATIC_ROOT variable in settings.py? I would suggest starting here.
Another potential issue could be your app namespacing. What does the directory structure of your STATIC-ROOT directory look like? I highly recommend installing the Django Extensions plugin for development; the added python manage.py show_urls command is incredibly useful for debugging errors such as these.
I don't have enough rep yet to comment on other answers, but #Marco: json.loads() will deserialize a valid json instance to a Python object (dict), so passing configuration in his render statement should be fine, assuming the json is valid. The issue right now is accessing the file itself-- OP's solution of sending a GET request to his /static/ path is returning a 404.
Django documentation for render says:
render(request, template_name, context=None, content_type=None, status=None, using=None)
So, you should pass those configuration probably as context if it's an dictionary:
return render(request, "index.html", context=configuration)
context: A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the view will call it just before rendering the template.

Cannot overwrite Django authentication templates in AWS

I have developped a Django application and I have been using the django-authtools module to be able to login using email. It is working great on my laptop but when I tried to deploy it in production in AWS using Beanstalk, it seems Django does not recognize the overwrite of the authentication module and is forcing redirection to the django built-in authentication module. Everything else seems to work fine (from a deployment and application point of view).
It results in a 500 error:
xxx.xxx.xxx.xxx (-) - - [04/Jul/2017:19:07:54 +1000] "GET /accounts/login/ HTTP/1.1" 500 7807 "http://<removed>.ap-southeast-2.elasticbeanstalk.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
Internal Server Error: /accounts/login/
Traceback (most recent call last):
File "/opt/python/run/venv/lib/python3.4/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/opt/python/run/venv/lib/python3.4/site-packages/django/core/handlers/base.py", line 217, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/opt/python/run/venv/lib/python3.4/site-packages/django/core/handlers/base.py", line 215, in _get_response
response = response.render()
File "/opt/python/run/venv/lib/python3.4/site-packages/django/template/response.py", line 107, in render
self.content = self.rendered_content
File "/opt/python/run/venv/lib/python3.4/site-packages/django/template/response.py", line 82, in rendered_content
template = self.resolve_template(self.template_name)
File "/opt/python/run/venv/lib/python3.4/site-packages/django/template/response.py", line 64, in resolve_template
return select_template(template, using=self.using)
File "/opt/python/run/venv/lib/python3.4/site-packages/django/template/loader.py", line 53, in select_template
raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: registration/login.html
Again this is working perfectly fine on my laptop, but not on the AWS server. I cannot find any difference between the 2 and they are running same version of django and django-authools:
$ pip freeze
[...]
Django==1.11.2
django-authtools==1.5.0
django-extensions==1.7.6
django-phonenumber-field==1.3.0
django-qsstats-magic==0.7.2
django-simple-captcha==0.5.5
django-storages==1.6.1
[...]
The only difference seems to be the version of python, 3.4.3 on AWS and 3.5.2 on my laptop.
On the server, my settings.py file is the same as on my laptop:
myproject/settings.py:
INSTALLED_APPS = [
'myapp.apps.MyappConfig',
'authtools',
'captcha',
'storages',
'phonenumber_field',
'django_extensions',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
AUTH_USER_MODEL = "authtools.User"
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'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',
],
},
},
]
myapp/urls.py:
from authtools import urls
[...]
url(r'^accounts/', include('authtools.urls')),
[...]
authtools/url.py:
from django.conf.urls import url
from authtools import views as authools_views
urlpatterns = [
url(r'^login/$', authools_views.LoginView.as_view(), name='login'),
url(r'^logout/$', authools_views.LogoutView.as_view(), {'next_page': '/accounts/login'}, name='logout'),
url(r'^password_change/$', authools_views.PasswordChangeView.as_view(), name='password_change'),
url(r'^password_change/done/$', authools_views.PasswordChangeDoneView.as_view(), name='password_change_done'),
url(r'^password_reset/$', authools_views.PasswordResetView.as_view(), name='password_reset'),
url(r'^password_reset/done/$', authools_views.PasswordResetDoneView.as_view(), name='password_reset_done'),
url(r'^reset/done/$', authools_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'),
url(r'^reset/(?P<uidb36>[0-9A-Za-z]{1,13})-(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
authools_views.PasswordResetConfirmView.as_view()),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
authools_views.PasswordResetConfirmView.as_view(),
name='password_reset_confirm'),
]
I have also tried to pass the template in the url statement directly (LoginView.as_view(template_name='myapp/login.html')) but same result.
Extract of authtools/view.py:
class LoginView(AuthDecoratorsMixin, WithCurrentSiteMixin, WithNextUrlMixin, FormView):
print('ENTERING LOGIN VIEW')
form_class = AuthenticationForm
template_name = 'myapp/login.html'
allow_authenticated = True
success_url = resolve_url_lazy(settings.LOGIN_REDIRECT_URL)
# BBB: This is deprecated (See LoginView.get_allow_authenticated)
disallow_authenticated = None
The template showed in the error "registration/login.html" is the built-in template and not the one provided by the authtools module which should overwrite it.
Also when navigating to the /admin/ of my website, I can login correctly with my super user and when going back to the site I am then detected as being authenticated. The logout action though redirects me to the default logout page and is not using my custom template provided in the authtools module (so same behavior).
If any one would have a solution or any idea of where to investigate that would be greatly appreciated!
Thanks!
I am adding my beanstalk config file just in case it helps, even though I don't believe this is a problem related to beanstalk itself.
.ebextensions# cat 001_set_env.config
option_settings:
"aws:elasticbeanstalk:application:environment":
PYTHONPATH: /opt/python/current/app/myapp:/opt/python/current/app/authtools:$PYTHONPATH
"aws:elasticbeanstalk:container:python":
WSGIPath: "myproject/wsgi.py"
.ebextensions# cat 002_deploy.config
commands:
01_update_pip:
command: "/opt/python/run/venv/bin/pip install --upgrade pip"
02_set_time_zone:
command: ln -f -s /usr/share/zoneinfo/Australia/Sydney /etc/localtime
container_commands:
01_makemigration:
command: "source /opt/python/run/venv/bin/activate && python manage.py makemigrations --noinput"
leader_only: true
02_migrate:
command: "source /opt/python/run/venv/bin/activate && python manage.py migrate --noinput"
leader_only: true
03_initialize_db:
command: "source /opt/python/run/venv/bin/activate && python manage.py initializedb"
leader_only: true
04_create_superuser:
command: "source /opt/python/run/venv/bin/activate && python manage.py createsu"
leader_only: true
I suggest you stop editing the code in authtools. It is not clear how you are doing it, and since the error is showing the missing template is registration/login.html, it is now working in production.
If you rename your template from myapp/templates/myapp/login.html to myapp/templates/registration/login.html, then the app directories loader should find your template.
Finally, as an aside, your DIRS setting looks incorrect.
'DIRS': ['templates'],
If you want to include a myproject/templates directory, then change it to
'DIRS': [os.path.join(BASE_DIR, 'templates')]
For those interested I have finally found the issue to this problem. I had the authools module installed both in site_packages and locally in my project. On my local laptop, it seems the order of precedence was looking at my local django project first (where I had the module with the right template paths), whereas on AWS, the python path order listed site_packages first, thus looking into an unmodified version of authtools.
I have therefore removed the authtools version installed in my project and I am now using the original version installed in site_packages, while over-writting the authools template names in my app urls.py directly.
Thank you all for helping and putting me on the right track.

Django: conflicting models in (third-party) application

I integrated a third party app into my Django project, and only when I import it will I get this error message.
RuntimeError: Conflicting 'task' models in application 'django_q': <class 'django_q.models.Task'> and <class 'models.Task'>.
I'm puzzled because my app runs well withouth it so I wonder how it could be an error on my side. I'm only using the app in its most simple use case. My general question is then: how can I investigate ?
So the app is django-q, a task queue (github). I installed it and called it in its most simple usage, following the good documentation.
CACHE = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'cache_table',
}
}
Q_CLUSTER = {
'name': 'DjangORM_queue',
'workers': 4,
'timeout': 3600,
'retry': 4000,
# 'queue_limit': 50,
# 'bulk': 10,
'orm': 'default'
}
api.py:
# api.py
# not putting all imports or __init__.py
def myhook(task):
print task.result
import ipdb; ipdb.set_trace()
def mymethod(request, pk, **kwargs):
from django_q.tasks import async, result
async('models.MyModel.method', pk, hook='myhook', sync=True)
Now manage.py runserver is ok, until I call my api and it reaches tasks.async. Full stacktrace:
Traceback (most recent call last):
File "/home/[...]/django/core/handlers/base.py", line 132, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/.../my-project/searchapp/models/api.py", line 965, in mymethod
tasks.async('models.MyModel.mymethod', pk, hook='myhook', sync=True)
File "/home/[...]/django_q/tasks.py", line 43, in async
return _sync(pack)
File "/home/[...]/django_q/tasks.py", line 176, in _sync
cluster.worker(task_queue, result_queue, Value('f', -1))
File "/home/[...]/django_q/cluster.py", line 369, in worker
m = importlib.import_module(module)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/[...]/django_q/models.py", line 15, in <module>
class Task(models.Model):
File "/home/[...]/django/db/models/base.py", line 309, in __new__
new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
File "/home/[...]/django/apps/registry.py", line 221, in register_model
(model_name, app_label, app_models[model_name], model))
RuntimeError: Conflicting 'task' models in application 'django_q': <class 'django_q.models.Task'> and <class 'models.Task'>.
I first checked I don't have a model named Task, nor do my django installed apps. We don't.
I searched for a similar pb and found this SO answer, so I tried to tweak the imports of django-q, with no success (it doesn't mean I did it right though).
Is it a circular import (SO hint) ?
A Django bug report (which wasn't) is interesting also, I found comment 13 particarly (about double entries in sys.path and ways of import). My sys.path has [ my_project, …/site_packages/django_q, …/site_packages/] so I don't feel impacted by comment 13's description;
I couldn't reproduce the issue on a fresh django project;
I feel like trying another queuing system :/
Any hints on what could be wrong ?
Thanks !
ps: I could also point to my full repo
Too bad, I went with huey. It's simple and complete.
django-rq looks like a good solution too, with a django dashboard integration.

Django ImportError: cannot import name get_permission_codename

I am doing the tango with django tutorial. I am up to chapter 5 on working with models and I am setting up the admin website. I get this strange error:
ImportError: cannot import name get_permission_codename
This seems to go away when I remove the
admin.autodiscover()
from my project/urls.py. But I am concerned that I will need this down the road.
Here is the Traceback I get when I run the development server:
Environment:
Request Method: GET Request URL: http://127.0.0.1:8000/admin/
Django Version: 1.5.4 Python Version: 2.7.3 Installed Applications:
('django.contrib.auth', 'django.contrib.contenttypes',
'django.contrib.sessions', 'django.contrib.sites',
'django.contrib.messages', 'django.contrib.staticfiles',
'django.contrib.admin', 'rango') Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback: File
"/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py"
in get_response
103. resolver_match = resolver.resolve(request.path_info) File
"/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py"
in resolve
319. for pattern in self.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py"
in url_patterns
347. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File
"/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py"
in urlconf_module
342. self._urlconf_module = import_module(self.urlconf_name) File
"/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py" in
import_module
35. import(name) File "/home/gpanterov/MyProjects/django/tango_with_django_project/tango_with_django_project/urls.py"
in
6. admin.autodiscover() File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/init.py"
in autodiscover
29. import_module('%s.admin' % app) File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py" in
import_module
35. import(name) File "/usr/local/lib/python2.7/dist-packages/django/contrib/contenttypes/admin.py"
in
5. from django.contrib.admin.checks import InlineModelAdminChecks File
"/usr/local/lib/python2.7/dist-packages/django/contrib/admin/checks.py"
in
6. from django.contrib.admin.utils import get_fields_from_path, NotRelationField, flatten File
"/usr/local/lib/python2.7/dist-packages/django/contrib/admin/utils.py"
in
6. from django.contrib.auth import get_permission_codename
Exception Type: ImportError at /admin/ Exception Value: cannot import
name get_permission_codename
When I remove the admin.autodiscover() line, the development server runs and I am able to get to the admin panel, but when I log in with the superuser password I created earlier, I get the message "You don't have permission to edit anything." and I don't see any of the categories I created.
I got this error when downgrading django from latest version (1.8) to an old version (1.4) for testing.
The problem here is that git doesn't delete .pyc files when switching branches (because they are .gitignore'ed) and python only regenerates them when the corresponding .py file is newer than the .pyc file (see this question for details).
The solution is to delete all *.pyc files in django/contrib/admin and django/contrib/contenttypes directories.
cannot import name get_permission_codename
Make sure u have not install all the version of django in your system.
if there then remove all and install fresh django

Django debug toolbar ImproperlyConfigured: Error importing middleware debug_toolbar.middleware: "No module named toolbar.loader"

I installed and configured debug_toolbar as the instruction say.See Here, i could even run syncdb.But when i access the admin page i get this error:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/servers/basehttp.py", line 283, in run
self.result = application(self.environ, self.start_response)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/staticfiles/handlers.py", line 68, in __call__
return self.application(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 250, in __call__
self.load_middleware()
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 47, in load_middleware
raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e))
ImproperlyConfigured: Error importing middleware debug_toolbar.middleware: "No module named toolbar.loader"
And I can't access any other page.Same error.
I searched for a while and couldn't find any answer.What i did wrong here?
I will support the installation of debug_toolbar when you are inside on Virtualenv. Just make sure that its is activated in your settings.py and then do a :
pip install django-debug-toolbar
Do you have the latest version of debug toolbar?
In debug_toolbar/middleware.py the import (line 14) reads:
from debug_toolbar.toolbar.loader import DebugToolbar
See if that matches your debug_toolbar/middleware.py to start with.
It sounds like something is funky with your installation. Check that the directories are alright, and try importing the middleware from ./manage.py shell.
Then perhaps try deleting the debug_toolbar directories manually and reinstalling it with pip if all else fails.
If you are using virtualenv, make sure that you have the virtualenv activated where you have installed debug_toolbar.
http://django-debug-toolbar.readthedocs.org/en/1.2/configuration.html
'debug_toolbar' -> INSTALLED_APPS
'debug_toolbar.middleware.DebugToolbarMiddleware' -> MIDDLEWARE_CLASSES (at first position)
define STATIC_ROOT and ./manage.py collectstatic
DEBUG_TOOLBAR_PATCH_SETTINGS = False
INTERNAL_IPS = ('127.0.0.1',)