当前位置: 动力学知识库 > 问答 > 编程问答 >

Django - Adding a prefix when using reverse()

问题描述:

Is it possible to have a prefix when using the reverse function?

for example:

I have reverse('foo') that point to www.bla.com/foo

but the URL needs to be www.bla.com/bla2/foo

So the bla2 would be the prefix

Thank you

网友答案:

If '/bla2' is the mount point for your Django application, with a correctly setup WSGI server you should not need to do anything to add it. This is because the WSGI server should already be sending through SCRIPT_NAME set as '/bla2' and Django should insert that automatically at the front of URLs constructed using reverse().

Can you explain what WSGI server you are using and/or whether you have it hosted behind a proxy front end that is publishing the site at a different URL mount point to the backend.

If you do have this situation where a front end is proxying as '/bla2', but the backend has it mounted at '/'. Then the Django setting you need to specify to force the backend to use '/bla2' and so insert the correct prefix is FORCE_SCRIPT_NAME.

  • https://docs.djangoproject.com/en/dev/ref/settings/#force-script-name

Note that this affects the whole site.

网友答案:

if you need www.bla.com/bla2/foo then your foo url should be pointing to www.bla.com/bla2/foo not www.bla.com/foo

Other way to perform that, is creating a final url, something like this:

final_url = prefix + reverse('foo')

Note: reverse('foo') will output /foo/ not www.bla.com/foo

分享给朋友:
您可能感兴趣的文章:
随机阅读: