Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django reverse returns different values when called from WSGI or shell

I have deployed a Django project on an Apache server using mod_wsgi, using a prefix URL /mysite, i.e. my Apache configuration contains

WSGIScriptAlias /mysite /var/www/mysite/mysite/wsgi.py

When reverse('myview') (from django.core.urlresolvers) is called from the web server process, it returns the expected URL /mysite/myview, i.e. including the prefix URL.

However, when reverse('myview') is called from a script (e.g. a cronjob), not through the web server process, only /myview is returned without the desired prefix URL. My example script looks like this:

import sys
import os
import django

sys.path.append('/var/www/mysite')
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
django.setup()

from django.core.urlresolvers import reverse
print reverse('myview') # prints '/myview'

Is there a way to include the prefix URL when running outside of the web server context, so that the same reverse('myview') code can be run from both contexts and returns the same value?

like image 932
Jens Wetzl Avatar asked Jul 10 '26 06:07

Jens Wetzl


1 Answers

Django only expects a SCRIPT_NAME in the context of a web request. It is retrieved from the WSGI environment or the FORCE_SCRIPT_NAME setting and set for the duration of the request.

To manually set a script name, use set_script_prefix():

from django.core.urlresolvers import set_script_prefix

set_script_prefix('/mysite')

Note that this is 1) a private, undocumented function, and 2) stored in a thread-local variable.

like image 106
knbk Avatar answered Jul 14 '26 00:07

knbk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!