首页 > 解决方案 > 将域路径添加到 django html 模板

问题描述

我正在为一个结合了 nginx 反向代理和女服务员的 django 应用程序提供服务。在 nginx 配置中,应用程序通过一个位置链接:

location /app/ {
            proxy_pass http://localhost:8686/;
    }

当应用程序通过waitress端口 8686 运行时。

现在,如果我访问 domain.com/app,我的索引页面会正确提供。虽然,我的 django html 模板包含以下链接:

 <p> You are not logged in.</p> <a href="/accounts/login"><button>Login</button></a>

当我按下那个按钮时,我得到

domain.com/accounts/login

但应该是

domain.com/app/accounts/login

我想知道如何更改代码,使其独立于应用程序链接的位置工作。

urls.py网址中包含这样的内容:

urlpatterns:  = [...,
    path('accounts/', include('django.contrib.auth.urls'))]

标签: djangowaitress

解决方案


在中定义 url urls.py(很可能您已经这样做了),然后reverse在模板中使用:

<a href="{% url 'foo:bar' %}"><button>Login</button></a>

然后在 nginx 中重写 URL 以使您的应用认为您正在访问/accounts/login而不是/app/accounts/login

location /app/ {
    rewrite ^/app(.*)$ $1 last;
    proxy_pass http://localhost:8686/;
}

文件:

  1. https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#std:templatetag-url
  2. https://www.nginx.com/blog/creating-nginx-rewrite-rules/

推荐阅读