I'm in the process of moving a django site over to a new server. On the old server, the django site was accessed like mysite.com/ , but now, we would like to access it via mysite.com/mysite, and let mysite.com handle something else. I have made the following changes to apache like so:
WSGIDaemonProcess mysite processes=2 threads=15 display-name=%{GROUP}
WSGIProcessGroup mysite
WSGIScriptAlias /mysite /srv/www/django.wsgi
#WSGIScriptAlias /mysite /srv/www/django.wsgi #previous config
<Directory /srv/www/mysite/mysite >
Order allow,deny
Allow from all
</Directory>
Alias /site_media "/srv/www/mysite/site_media/"
Alias /admin_media "/srv/www/mysite/admin_media/"
This seems to work fine- pointing the browser at mysite.com/unity/admin allows me to access the admin page correctly, and view the respective apps correct. However, anything that uses a custom template seems to be half-baked. For instance, there's an entry in a template below like so:
{% ifcodable cl.model %}<li>Coding Report</li>{% endifcodable %}
This will redirect the page to
http://mysite.com/report/texas/texas
As opposed to
http://mysite.com/mysite/report/texas/texas
I'm not sure if the template is set up incorrectly or if it has something to do with the new alias. My urls.py looks like so:
from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
.....
(r'^report/([a-zA-Z]+?)/([a-zA-Z]+?)/(overall|\d+)/{0,1}$', 'mysite.k.views.performance'),
(r'^report/(.+?)/(.+?)/{0,1}$', 'mysite.k.views.report'),
.....
My django.wsgi file looks like so:
import os,sys
sys.path.append('/srv/www/mysite')
sys.path.append('/srv/www/mysite/mysite')
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
I don't know what the proper thing would be to do to correct the problem. I'm fairly new to django, so if there is a wicked simple solution I apologize. Any advice would be greatly appreciated!
The problem is that your url begins with /report in the href attribute. Beginning with a / means that it should be relative to the root of your domain. I believe what you need to change is how the Django sites framework is configured, and it looks like this question has the answer.
Also, you should probably use the url tag in your templates instead of hardcoding the urls in your anchor tags.
Related
I'm trying to do the Django tutorial. Part 1 went OK (i.stack.imgur.com/US5GN.jpg)
However, once I activate the admin site the root I get (i.stack.imgur.com/EXfE4.jpg). Edit (as S.O. doesn't yet allow me to post images; thanks, cberner):
Page not found (404)
Request Method: GET
Request URL: http://dj1.net/
Using the URLconf defined in dj1_net.urls, Django tried these URL patterns, in this order:
^admin/
The current URL, , didn't match any of these.
dj1.net is my test domain (editing /etc/hosts), and while dj1.net/admin/ now works as expected, I don't know why dj1.net/ throws this error once I uncomment (as instructed) the line
url(r'^admin/', include(admin.site.urls)),
under mysite/urls.py (in my case dj1_net/urls.py). It seems to me everything should work as before unless the GET request is against /admin/.
My stack: a Debian 6.0 VPS with Apache and mod_wsgi. I want to avoid Django's built-in server: if I can't deploy it for real, I'd rather know earlier rather than later. In fact, for easy PHP support I'm very interested in an Apache-based solution.
For further reference, here is my /etc/apache2/sites-available/dj1.net:
<VirtualHost *:80>
ServerName dj1.net
DocumentRoot /var/www/dj1_net
Alias /static/ /var/www/dj1_net/static/
Alias /media/ /var/www/dj1_net/media/
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
WSGIScriptAlias / /var/www/dj1_net/django.wsgi
WSGIProcessGroup dj1_net
WSGIDaemonProcess dj1_net processes=2 threads=16 maximum-requests=1000 display-name=apache-dj1_net-wsgi
</VirtualHost>
Finally, here is /var/www/dj1_net/django.wsgi:
import sys
import os
import os.path
sys.path.append(os.path.dirname(__file__))
os.environ['DJANGO_SETTINGS_MODULE'] = 'dj1_net.settings'
from django.core.handlers.wsgi import WSGIHandler
application = WSGIHandler()
Just to be upfront, I know close to nil about Apache server configuration and WSGI. I do, however, want to make this set-up work before embarking in Django. I followed a mix of the official instructions and this post, since I frankly couldn't make get Django to work applying either instructions verbatim. I'm afraid the bottom of the problem must lie there...
Any tips will be greatly appreciated.
Cheers!
S.P.
Second edit. Here is dj1_net/urls.py (thanks, scytale):
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'dj1_net.views.home', name='home'),
# url(r'^dj1_net/', include('dj1_net.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
You don't have a url defined for the root of your site. You'll need to add one, for example:
url(r'^$', 'dj1_net.views.my_view_function'),
That would go after the line that defines the admin URL.
I wish to have multiple django installations. One at / (which is working fine) and one at /adam. The one at slash adam is redirected by apache correctly, until you try and visit an app. E.g. /admin works but /adam/admin does not work. I get the error:
Page not found (404)
Request Method: GET
Request URL: http://[CENSORED]/adam/
Using the URLconf defined in bms.urls, Django tried these URL patterns, in this order:
^admin/doc/
^admin/
The current URL, , didn't match any of these.
Notice the empty commas. The apache virtual host is:
<VirtualHost *:80>
ServerName [CENSORED]
DocumentRoot /home/user/bms
Alias /static/admin/ /usr/local/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/contrib/admin/media/
<Directory /home/user/bms/apache>
Order allow,deny
Allow from all
</Directory>
<Directory /home/ajt1g09/bms/apache>
Order allow,deny
Allow from all
</Directory>
WSGIDaemonProcess bms user=user group=user processes=2 threads=25 python-path=/usr/local/lib/python2.7/site-packages
WSGIProcessGroup bms
WSGIScriptAliasMatch ^/adam(.*) /home/ajt1g09/bms/apache/django.wsgi
WSGIScriptAlias / /home/user/bms/apache/django.wsgi
</VirtualHost>
And the django.wsgi file in ajt1g09/bms/apache:
import os
import sys
path = '/home/ajt1g09/bms'
if path not in sys.path:
sys.path.append(path)
sys.path.append('/usr/local/lib/python2.7/site-packages')
sys.path.append('/home/ajt1g09')
os.environ['DJANGO_SETTINGS_MODULE'] = 'bms.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
And finally, the urls.py file in ajt1g09/bms (clearly showing /admin is there):
from django.conf.urls.defaults import
patterns, include, url
#Uncomment the next two lines to enable the admin: from django.contrib
import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'bms.views.home', name='home'),
# url(r'^bms/', include('bms.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)), )
I have no idea what the problem is.
You shouldn't be using:
WSGIScriptAliasMatch ^/adam(.*) /home/ajt1g09/bms/apache/django.wsgi
Just use:
WSGIScriptAlias /adam /home/ajt1g09/bms/apache/django.wsgi
The WSGIScriptAliasMatch will not work as written because you haven't re substituted the matched part from back into last argument. Ie.,
WSGIScriptAliasMatch ^/adam(.*) /home/ajt1g09/bms/apache/django.wsgi$1
You should though simply not be using WSGIScriptAliasMatch. That is for advanced use cases only and requires you be very careful in using it because how you use it can impact what SCRIPT_NAME/PATH_INFO are set to when passed to application and it is those that urls.py matching is based off.
So after a few hours of irritation i finally got my django site up and running! The only problem i have now is that all the stylesheets/images are linked incorrectly. Or, well, they are linked correctly but django wont give me the files, kind of.
This is how it's set up:
views.py:
from django.shortcuts import render_to_response
def home(request):
return render_to_response('index.html')
urls.py:
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',
# Examples:
url(r'^$', 'mysite.views.home', name='home'),
)
and that brings up index.html, but none of the other files are shown, like images, stylesheets etc. How do I solve this? I have a feeling it's really easy!? I tried googling, but couldn't find anything.
Thanks in advance,
qwerty
It sounds like what you're looking for is the ability to serve static files.
Basically, you'll need to add a folder somewhere in your project to save the media to. Then, you'll need to edit your urls.py and settings.py files to accommodate access to your new static media directory.
urls.py
urlpatterns = patterns('',
# Examples:
url(r'^$', 'mysite.views.home', name='home'),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root':
settings.STATIC_ROOT}),
)
settings.py
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
# Should be the location where you put your static folder.
# Should be different for testing and production environments.
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'media')
# This is assuming that your settings.py file is in path/to/project/ and your
# static files are in path/to/project/media/
Then in your template you can do this:
< img src="/static/my_image.jpg" / >
Or whatever you want. This will work for javascript, css and image files.
Expanding on Shamanu4's comment: what you're asking for is how static files are served. For development purposes, you can use the static file server.
Long term, though, this is not an optimal solution. The easy way is to segregate all your static files and serve them directly through your web browser via a different path. In Apache, this static file path can be inside your Django path if you configure the static path first.
If you need high performance, though, the Django team recommends that you use a lightweight, speed-optimized server (such as lighttpd) to serve static files and another server with WSGI support (such as Apache) to serve Django.
In the Django project I have at work, I have Django served from /djangoprojname/ and static files served from /djangoprojname/static/. On disk, the static directory is at the same level as my Django project's directory. both of which are in a Mercurial repository. Within static/, I have css/, js/, and img/, and within those directories, I have one directory per app, named the same as the app. This keeps things from getting messy.
My django.conf (in /etc/httpd/conf.d on Fedora or RHEL) looks something like:
WSGIDaemonProcess djangoprojname threads=15
WSGISocketPrefix /var/run/wsgi/wsgi
Alias /djangoprojname/static/ /var/www/djangoprojname/static/
Alias /djangoprojname/admin/media/ /usr/lib/python2.6/site-packages/django/contrib/admin/media/
WSGIScriptAlias /djangoprojname /var/www/djangoprojname/django.wsgi
WSGIProcessGroup djangoprojname
<Directory /var/www/djangoprojname>
Order deny,allow
Allow from all
</Directory>
<Directory /usr/lib/python2.6/site-packages/django/contrib/admin/media>
Order deny,allow
Allow from all
</Directory>
For development, I added this to the end of my project's urls.py:
# Only serve static media if in development (runserver) mode.
if settings.IS_DEV:
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT,
'show_indexes': True}),
)
settings.IS_DEV is set in my settings.py to True if this is running on a development server. manage.py is modified to set an environment variable if runserver is used, and settings.py checks for this variable. MEDIA_ROOT is set to the path to the static directory.
You are probably having problem with MEDIA_ROOT and MEDIA_URL in your settings.py. Please refer to http://docs.djangoproject.com/en/1.3/ref/settings/#media-root
Below are the relevant configuration files, also at http://dpaste.com/97213/ .
The apache config is currently working, because accessing 'example.com/' shows me the index.html file I have placed at the document root.
I'd like to serve Django/apps at the prefix '/d', so 'example.com/d/' would load the default app, 'example.com/d/app3' would load another, as configured in urls.py.
Serving Django, I'm using the suggested mod_wsgi, on Linux.
Currently, I can access the Ticket app at 'example.com/d', but when the #login_required decorator tries to send me to the login page, I get sent to 'example.com/accounts/login', rather than the expected 'example.com/d/accounts/login'.
Since the default app loads correctly, I'm not sure what I'm doing wrong here, or if this is a bug in Django when generating the urls.
Any suggestions?
EDIT:
As a note, if I change the apache config line:
WSGIScriptAlias /d /home/blah/django_projects/Tickets/apache/django.wsgi
to
WSGIScriptAlias / /home/blah/django_projects/Tickets/apache/django.wsgi
The application, commenting, and logging in all work fine. Even going to 'example.com/admin' loads the admin, although I've left the admin media broken, so no stylesheets are loaded.
--- Configs Follow:
#
# /home/blah/django_projects/Ticket/urls.py
#
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^', include('ticket.urls')),
(r'^admin/', include(admin.site.urls)),
(r'^comments/', include('django.contrib.comments.urls')),
)
#
# /home/blah/django_projects/Ticket/apache/django.wsgi
#
import os, sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
sys.path.append('/home/blah/django_projects')
sys.path.append('/home/blah/django_projects/Tickets')
os.environ['DJANGO_SETTINGS_MODULE'] = 'Tickets.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
#
# /etc/apache2/sites-available/django_tickets_wsgi (apache conf)
#
NameVirtualHost *
<VirtualHost *>
Alias /media /home/blah/django_projects/Tickets/media
WSGIScriptAlias /d /home/blah/django_projects/Tickets/apache/django.wsgi
WSGIDaemonProcess exmaple_com user=blah group=blah processes=1 threads=10
WSGIProcessGroup example_com
ServerAdmin localhost#example.com
ServerName example.com
DocumentRoot /var/www/
<Directory /var/www/>
Options -Indexes FollowSymLinks -MultiViews -Includes
AllowOverride None
Order allow,deny
allow from all
</Directory>
ErrorLog /var/log/apache2/error.log
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn
CustomLog /var/log/apache2/access.log combined
ServerSignature Off
</VirtualHost>
This is a possible duplicate of Django Apache Redirect Problem, as that answer solved this problem.
I only eventually stumbled on that answer by opening almost all of the 'related questions' here, just out of desperation. From my perspective, I think my question has some valuable "search friendly" words.
EDIT: The answer: (via alex vasi)
Things to try:
Change current domain to "yourdomain.tld/cflow" in the "sites" framework. It's easy to do using django admin or dumpdata/loaddata manage.py commands.
Looks like your site is using login_required decorator. In that particular case you can add to settings.py:
LOGIN_URL = '/[prefix]/accounts/login/'
In your urls.py rename urlpatterns to base_urlpatterns; then add the followinig definition at the end of the same file:
urlpatterns = patterns('',
'^', include(base_urlpatterns), # iff you wish to maintain the un-prefixed URL's too
'^your_prefix/', include(base_urlpatterns),
)
I have set up a Django application that uses images. I think I have set up the media settings MEDIA_ROOT and MEDIA_URL correctly. However the images don't show up. Do you know what can be the problem?
Let consider this example:
The image files are under /home/www/media/app/photos and we are trying to request http://example.com/photos/123.jpg
Should I use these settings?
MEDIA\_ROOT = /home/www/media
MEDIA_URL = http://example.com/app
UPDATE: Forgot to mention that I'm using built-in development server.
FOR DEVELOPMENT ONLY
You can setup a static media server for use with their development server by doing this in your urls.py file. I have attached the code showing how I use it (along with the forced DEBUG conditionals.)
from django.conf import settings
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'views.index'),
# Accounts
(r'^accounts/login/$', 'views.user_login'),
(r'^accounts/logout/$', 'views.user_logout'),
# Contrib Modules
(r'^admin/(.*)', admin.site.root),
)
if settings.DEBUG :
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)
I place my MEDIA_ROOT in a subdirectory of html/media and link to it as such in settings.py
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'html/media/').replace('\\','/')
After development is finished, the project gets deployed to the web server where static media files are then served by Apache using directives.
Serving static content from Django is discouraged from the developer themselves (if I'm not wrong, it only works when in debug mode). You should use a dedicated web server, instead.
If you really need to do that, anyway, read the documentation on how to serve static files.
This is the correct way of showing image files with ImageField. Imagine we have a user profile picture:
models.py:
UserProfile:
profilePic= models.ImageField( upload_to='PATH_TO_UPLOAD', blank=True, null=True)
settings.py:
MEDIA_ROOT = 'FULL_PATH_OF_MEDIA'
MEDIA_URL = 'URL_OF_MEDIA'
urls.py:
urlpatterns = [
.
.
.
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
PATH_TO_UPLOAD is the path which user upload data goes. This is sub-directory of FULL_PATH_OF_MEDIA, which means the uploaded file will have
FULL_PATH_OF_MEDIA/PATH_TO_UPLOAD
full path.Now this content can be accessed at this url:
SITE_NAME/URL_OF_MEDIA/PATH_TO_UPLOAD
I also recommend reading this on static_files vs media_files
doc
You can just add those lines to your urls.py
from django.urls import re_path
from django.views.static import serve
urlpatterns = [
...
re_path(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
]
I suspect you are getting the Django 404 page. Try directly accessing one of your images and see if that's happening.
If so, your need to configure your web server to not send requests within your media hierarchy to Django but to instead serve them directly. Here is a snip from my Apache conf file. The first section tells Apache to send everything to Django. The second section has "SetHandler None" which says "handle stuff under /media in the normal way."
See http://docs.djangoproject.com/en/dev/howto/deployment/modpython/ for all the exciting details.
Partial httpd.conf file for PrinceOfPinot.com (AKA pop):
<Location "/">
SetHandler python-program
PythonAutoReload Off
PythonDebug Off
PythonPath "['/var/www/production/pop', '/usr/local/lib/python2.5/site-packages/django'] + sys.path"
SetEnv DJANGO_SETTINGS_MODULE settings
PythonHandler django.core.handlers.modpython
</Location>
<Location "/media">
SetHandler None
AddOutputFilterByType DEFLATE text/html text/css application/x-javascript
</Location>
I'm aware that the original question is with the dev server, but for anyone else who is looking for a production environment answer:
https://docs.djangoproject.com/en/1.8/howto/static-files/deployment/ provides a guide on how to have django serve files in a production environment. From the tone of the guide, it does seem to imply that it is best to have a separate web server to handle the files or use mod_wsgi with Apache