使用fcgi在子目录中的Django

时间:2013-02-28 22:46:00

标签: django apache subdirectory fastcgi bluehost

我试图避免以某种方式添加一个context_processor来将我的项目的基本URL添加到我在所有模板中使用的每个URL。

我的django项目位于一个子目录下(我们称之为foo),我的模板中的很多网址与此类似:

<a href='/somepath'>whatever</a>

这适用于托管在域根目录上的项目,但在这种情况下,因为我在子目录foo下,url实际上指向 www.example.com/somepath

有趣的是Admin网站运行正常。它的所有网址都指向 富/管理员/...

我怀疑我没有找到正确的术语来找到答案。

的.htaccess

AddHandler fcgid-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ foo.fcgi/$1 [L]

.fcgi

#!/usr/bin/python
import sys, os

# Current Path
cwd = os.path.join( os.path.dirname( os.path.abspath( __file__ ) ) )

# Activate current virtualenv
activate_this = os.path.join( cwd, 'bin', 'activate_this.py' )
execfile( activate_this, dict( __file__ = activate_this ) )

# Add a custom Python path.
sys.path.insert( 0, os.path.join( cwd, 'foo' ) )

os.environ['DJANGO_SETTINGS_MODULE'] = 'foo.settings'
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")

大多数网址我都可以使用{%url%}和FORCE_SCRIPT_NAME来正常工作,但对于网址,我在urls.py中没有条目反向(),我不确定是否应该只需在模板中使用FORCE_SCRIPT_NAME变量,或者有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

以下是我解决问题的方法。不确定这是否是最好的方法,但现在就可以了。

  1. 确保将FORCE_SCRIPT_NAME设置为您的子目录
  2. 在与settings.py
  3. 相同的目录中创建了context_processors.py
  4. 将context_processors.url_prefix添加到CONTEXT_PROCESSORS下的settings.py
  5. 模板中无法使用{%url%}标记的任何地方,只需添加{{URL_PREFIX}}
  6. context_processors.py

    from django.conf import settings # import the settings file
    
    def url_prefix(request):
        # return the value you want as a dictionnary. you may add multiple values in there.
        return {'URL_PREFIX': settings.FORCE_SCRIPT_NAME}
    

    settings.py

    CONTEXT_PROCESSORS = (
        ...,
        'context_processors.url_prefix',
    )
    
相关问题