Django deployment - can't import app.urls - django

I just moved a django project to a deployment server from my dev server, and I'm having some issues deploying it. My apache config is as follows:
<Location "/">
Order allow,deny
Allow from all
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE project.settings
PythonDebug On
PythonPath "['/home/django/'] + sys.path"
</Location>
Django does work, since it renders the Django debug views, but I get the following error:
ImportError at /
No module named app.urls
And here is all the information Django gives me:
Request Method: GET
Request URL: http://myserver.com/
Django Version: 1.1.1
Python Version: 2.6.5
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.admindocs',
'project.app']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
Traceback:
File "/usr/lib64/python2.6/site-packages/django/core/handlers/base.py" in get_response
83. request.path_info)
File "/usr/lib64/python2.6/site-packages/django/core/urlresolvers.py" in resolve
218. sub_match = pattern.resolve(new_path)
File "/usr/lib64/python2.6/site-packages/django/core/urlresolvers.py" in resolve
216. for pattern in self.url_patterns:
File "/usr/lib64/python2.6/site-packages/django/core/urlresolvers.py" in _get_url_patterns
245. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/lib64/python2.6/site-packages/django/core/urlresolvers.py" in _get_urlconf_module
240. self._urlconf_module = import_module(self.urlconf_name)
File "/usr/lib64/python2.6/site-packages/django/utils/importlib.py" in import_module
35. __import__(name)
Exception Type: ImportError at /
Exception Value: No module named app.urls
Any ideas as to why I get an import error?

Add the project directory to sys.path.

My guess is that if you simply change your url configuration to reference "project.app.urls" instead of "app.urls", your problem will be fixed.
It seems that you've listed "project.app" in INSTALLED_APPS in your project's settings.py file, but you've referenced "app.urls" in your urls.py. You need to standardize and either always reference "app", and change your PythonPath to include the project directory, or always reference "project.app".

I would recommend to use virtualenv along with mod_python. Some instructions here: http://mydjangoblog.com/2009/03/30/django-mod_python-and-virtualenv/
It has the advantage of solving all your path problems, but also to allow to install extra modules (or even other versions of django) very easily.

Related

Virtualenv package issue on Heroku deploy (Django app)

I have deployed a Django project to Heroku, but I've run into an issue: there is a package, that's inside the virtualenv folder, that gives me an error.
This is the traceback
Environment:
Request Method: POST
Request URL: https://pin-a-voyage.herokuapp.com/login/
Django Version: 1.8
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'custom_user',
'django_markdown',
'parsley')
Installed Middleware:
('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',
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware')
Traceback:
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/app/blog/views.py" in login
147. auth_login(request, user)
File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/__init__.py" in login
117. user_logged_in.send(sender=user.__class__, request=request, user=user)
File "/app/.heroku/python/lib/python2.7/site-packages/django/dispatch/dispatcher.py" in send
201. response = receiver(signal=self, sender=sender, **named)
File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/models.py" in update_last_login
26. user.save(update_fields=['last_login'])
File "/app/custom_user/models.py" in save
62. new_image = resizeimage.resize_width(pil_image_obj, 300)
File "/app/.heroku/python/lib/python2.7/site-packages/resizeimage/resizeimage.py" in wrapper
31. validator(image, size)
File "/app/.heroku/python/lib/python2.7/site-packages/resizeimage/resizeimage.py" in _width_is_big_enough
47. raise ImageSizeError(image.size[0], width)
Exception Type: ImageSizeError at /login/
Exception Value: 'Image is too small, Image size : 300, Required size : 300'
In a nutshell: I upload a profile pic, but I run into this error, because I have modified the package on the virtualenv folder, but the virtualenv folder isn't pushed to Heroku.
Since the virtualenv folder has to be put in .gitignore when deploying to Heroku (isn't it?), how can I avoid this problem?
If you need to make local edits to a package ( but consider instead contributing or forking a new version ), then you may want to copy that package into your Django project and use it as if you would have written it yourself. I.e. As a regular Django app in your project.
In most cases one should not edit files in a virtual environment. This is because virtual environment holds packages installed with pip only in the local system. However the developer can edit code of the installed app if requirement cannot by achieved by using the options/attributes provided with the package.
You can push customized code of your installed app and can use it in your production environment by using overriding file with custom code. See reusable apps for an example.
First make sure updated requirements.txt is pushed to your production environment. From the stack trace /site-packages/resizeimage/ is causing you issues. If you are using PIL update requirements.txt to include pil and install PIL in your heroku server too.
then override the necessary files of your package. To do this you can create a directory with same name as of the pip package and then create a file with the same name of the one you have to edit. After this push this directory.

Django1.7 'RemovedInDjango19Warning' when using apache with mod_wsgi

i am using Django version 1.7 for an application,
everything was running good in my developpement PC (i was runnin it using manage.py runserver command.
now i am trying to move it to a production server.
in the production server, everything is still good when running the server using the manage.pycommand.
but accessing the application remotely (via apache2 & mod_wsgi), i get an RemovedInDjango19Warning Exception.
after looking for a solution all i could find is how to ignore theses warnings for manage.py which don't work for me and i don't know how to disable this warnings from wsgi ?
Traceback:
Environment:
Request Method: GET
Request URL: http://192.168.0.17/
Django Version: 1.7.1
Python Version: 3.4.3
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions',
'rest_framework',
'rest_framework_nested',
'django_gravatar',
'authentication',
'djcelery',
'job',
'seed',
'proxies',
'emails')
Installed Middleware:
('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')
Traceback:
File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py" in get_response
98. resolver_match = resolver.resolve(request.path_info)
File "/usr/local/lib/python3.4/dist-packages/django/core/urlresolvers.py" in resolve
343. for pattern in self.url_patterns:
File "/usr/local/lib/python3.4/dist-packages/django/core/urlresolvers.py" in url_patterns
372. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python3.4/dist-packages/django/core/urlresolvers.py" in urlconf_module
366. self._urlconf_module = import_module(self.urlconf_name)
File "/usr/lib/python3.4/importlib/__init__.py" in import_module
109. return _bootstrap._gcd_import(name[level:], package, level)
File "/var/www/cvc.ma/CapValue/urls.py" in <module>
6. url(r'^api/v1/auth/', include('authentication.urls')),
File "/usr/local/lib/python3.4/dist-packages/django/conf/urls/__init__.py" in include
28. urlconf_module = import_module(urlconf_module)
File "/usr/lib/python3.4/importlib/__init__.py" in import_module
109. return _bootstrap._gcd_import(name[level:], package, level)
File "/var/www/cvc.ma/authentication/urls.py" in <module>
2. from authentication.views import LoginView, LogoutView
File "/var/www/cvc.ma/authentication/views.py" in <module>
4. from rest_framework import permissions, viewsets, status, views
File "/usr/local/lib/python3.4/dist-packages/rest_framework/viewsets.py" in <module>
24. from rest_framework import views, generics, mixins
File "/usr/local/lib/python3.4/dist-packages/rest_framework/views.py" in <module>
11. from rest_framework.request import Request
File "/usr/local/lib/python3.4/dist-packages/rest_framework/request.py" in <module>
20. from rest_framework.settings import api_settings
File "/usr/local/lib/python3.4/dist-packages/rest_framework/settings.py" in <module>
22. from django.utils import importlib, six
File "/usr/local/lib/python3.4/dist-packages/django/utils/importlib.py" in <module>
10. RemovedInDjango19Warning, stacklevel=2)
Exception Type: RemovedInDjango19Warning at /
Exception Value: django.utils.importlib will be removed in Django 1.9.
It's happening because the django.utils.importlib module is removed in Django 1.9, in favor of the importlib in the standard library. Django Rest Framework still uses it.
You can disable the warning by following the instructions on the accepted answer of this question -- How to suppress the deprecation warnings in Django?
Finally, i ended up upgrading to Django1.9 and fixed the migration bugs.
If you just want to silence the warning in mod_wsgi, you may add a configuration directive such as:
WSGIPythonWarnings ignore::DeprecationWarning::
See this blog entry, the release notes (point 15) and the original issue.
In essence, mod_wsgi had no equivalent to the -W control option, so a directive was added. The default must have been kept at "log everything" to be consistent across different wsgi apps.

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

Apache Django mod_wsig - no modules named urls error

I have a simple admin django project and there I created another application called webadmin. Project structure is as follow:
tstprj
manage.py
tstprj
settings.py
urls.py
wsgi.py
init.py
webadmin
admin.py
urls.py
views.py
models.py
init.py
I have a separate wsgi file that I reference from apache conf:
# tstprj.wsgi
import os
import sys
sys.path.insert(0, '/var/www/tstprj')
os.environ['DJANGO_SETTINGS_MODULE'] = 'tstprj.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
and apache's virtual host - tstprj.conf:
<VirtualHost *:80>
WSGIScriptAlias / /home/pm/dev/tstprj.wsgi
ServerName <<my_ip_address>>
Alias /static /var/www/tstprj/static/
<Directory /var/www/tstprj/>
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
I get the error ImportError at / No module named urls.
The traceback:
Environment:
Request Method: GET
Request URL: http://<<my_ip_address>>/
Django Version: 1.6
Python Version: 2.7.3
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'webadmin')
Installed Middleware:
('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:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
101. resolver_match = resolver.resolve(request.path_info)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in resolve
318. for pattern in self.url_patterns:
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in url_patterns
346. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in urlconf_module
341. self._urlconf_module = import_module(self.urlconf_name)
File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py" in import_module
40. __import__(name)
File "/var/www/tstprj/tstprj/urls.py" in
11. url(r'^admin/webadmin', include('webadmin.urls')),
File "/usr/local/lib/python2.7/dist-packages/django/conf/urls/__init__.py" in include
26. urlconf_module = import_module(urlconf_module)
File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py" in import_module
40. __import__(name)
Exception Type: ImportError at /
Exception Value: No module named urls
And, of course, tstprj.urls:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/webadmin', include('webadmin.urls')),
url(r'^admin/', include(admin.site.urls)),
)
EDIT:
webadmin.urls
from django.conf.urls import *
from webadmin.views import *
urlpatterns = patterns('',
url(r'^/playlist/(?P<plid>(\d+))/song/add/$', addSong, name="addsong"),
url(r'^/playlist/(?P<plid>(\d+))/song/(?P<sgid>(\d+))/delete/$', deleteSong),
url(r'^/playlist/(?P<plid>(\d+))/up/$', moveUpSong),
url(r'^/playlist/(?P<plid>(\d+))/down/$', moveDownSong),
url(r'^/playlist/(?P<plid>(\d+))/top/$', moveTopSong),
url(r'^/playlist/(?P<plid>(\d+))/bottom/$', moveBottomSong),
url(r'^/playlist/(?P<plid>(\d+))/position/$', moveToPositionSong),
url(r'^/playlist/(?P<plid>(\d+))/deleteSelected/$', deleteSelectedSongs),
url(r'^/user/(?P<uid>(\d+))/deleteSelected/$', deleteSelectedStations),
url(r'^/user/(?P<uid>(\d+))/station/(?P<sid>(\d+))/playlist/deleteSelected/$', deleteSelectedPlaylists),
url(r'^/user/(?P<uid>(\d+))/station/(?P<sid>(\d+))/playlist/(?P<plid>(\d+))/delete/$', deletePlaylist),
url(r'^/user/(?P<uid>(\d+))/station/(?P<sid>(\d+))/playlist/add/$', addPlaylist, name="addplaylist"),
url(r'^/user/(?P<uid>(\d+))/playlist/all/$', playlist_list, name="playlist_list"),
url(r'^/user/(?P<uid>(\d+))/station/add/$', addStation, name="addStation"),
url(r'^/user/(?P<uid>(\d+))/station/(?P<sid>(\d+))/$', viewStation, name="viewStation"),
url(r'^/user/(?P<uid>(\d+))/station/(?P<sid>(\d+))/delete/$', deleteStation, name="deleteStation"),
)
What is the matter?
I'm not sure, but your apache configuration may be incomplete. I'm unsure the python version it calls is the one you want.
I normally set the python path, like this:
WSGIDaemonProcess process_name processes=2 threads=12 python-path=/home/pm/dev:home/pm/.../lib/python2.7
WSGIProcessGroup process_name
WSGIRestrictEmbedded On
WSGILazyInitialization On
WSGIScriptAlias / /home/pm/dev/tstprj.wsgi
The first line ensures that Python uses the libraries installed in "home/pm/.../lib/python2.7", and is able to reach "/home/pm/dev".
I'm unsure this answers this question, but maybe you can try it.
Of course you don't want this answer anymore! but:
Add project and App dirs to sys.path in wsgi.py of your project and it may find all of the modules in your project
import sys
sys.path.append('<Project_Directory>')
sys.path.append('<Project_Directory>/AppName')

Django App template Loader, can't find app templates

I have the following two apps located in my virtualenv: backend backoffice.
The backoffice app has templates under:
backoffice/templates
So when I login into the Django shell, I can to do the following:
>>>from django.template.loaders.app_directories import Loader
>>> list(l.get_template_sources('index.html'))
[u'/var/www/venv2.7/lib/python2.7/site-packages/django/contrib/auth/templates/index.html', u'/var/www/venv2.7/lib/python2.7/site-packages/backoffice/templates/index.html', u'/var/www/venv2.7/lib/python2.7/site-packages/django/contrib/admin/templates/index.html']
So it seems the template is correctly found (l.load_template_source(('index.html') is also working).
However, when I access my home page via the browser I get an error:
TemplateDoesNotExist at /
Can someone help me solve the puzzle? What am I missing?
update: full trackback
Request Method: GET
Request URL: http://192.168.211.140/
Django Version: 1.5.1
Python Version: 2.7.6
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'backoffice',
'backend',
'django.contrib.admin')
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')
Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
Using loader django.template.loaders.app_directories.Loader:
/var/www/backoffice/venv2.7/lib/python2.7/site-packages/django/contrib/auth/templates/index.html (File does not exist)
/var/www/backoffice/venv2.7/lib/python2.7/site-packages/django/contrib/admin/templates/index.html (File does not exist)
Traceback:
File "/var/www/backoffice/venv2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/var/www/backoffice/venv2.7/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
25. return view_func(request, *args, **kwargs)
File "/var/www/backoffice/venv2.7/lib/python2.7/site-packages/backoffice/views.py" in start_page
177. return render(request, 'index.html', context)
File "/var/www/backoffice/venv2.7/lib/python2.7/site-packages/django/shortcuts/__init__.py" in render
53. return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/var/www/backoffice/venv2.7/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
170. t = get_template(template_name)
File "/var/www/backoffice/venv2.7/lib/python2.7/site-packages/django/template/loader.py" in get_template
146. template, origin = find_template(template_name)
File "/var/www/backoffice/venv2.7/lib/python2.7/site-packages/django/template/loader.py" in find_template
139. raise TemplateDoesNotExist(name)
Exception Type: TemplateDoesNotExist at /
Exception Value: index.html
Ah, I want to cry, how can Django be so tricky ...
I just updated settings.INSTALLED_APPS:
# It was like this
INSTALLED_APPS = (
'django.contrib.auth',
...
'backoffice',
'backend',
'django.contrib.admin' #!!! NOT ALLOWED HERE
)
# This will workd
INSTALLED_APPS = (
'django.contrib.auth',
...
'django.contrib.admin' # ALLOWED HERE
'backoffice',
'backend',
)
The order of INSTALLED_APPS is important. However, a good standard practice to prevent collisions on template names when you use the app directory loader is to namespace your templates by the app name in its director structure, such that:
Your templates for app backoffice live in:
backoffice/templates/backoffice/
In implementation, you would be rendering the template "backoffice/index.html" which will never collide with a template in django.contrib.admin. This design pattern plays nice with pluggable apps. Should you ever release backoffice as a pluggable app, other users can override its templates in their main template directory by simply adding a backoffice directory.