【问题标题】:Django url parsing errorDjango url 解析错误
【发布时间】:2015-07-22 14:05:18
【问题描述】:

好的, 我有两种不同的观点,都在项目站点范围内。

urls.py

url(r'^accounts/login/$', 'taxo.views.login'),
url(r'^accounts/invalid/$', 'taxo.views.invalid'),
...

taxo/views.py

def login(request):
    c = {}
    c.update(csrf(request))
    return render_to_response('login.html', c)
def invalid(request):
    return render_to_response('invalid.html',{'title':'invalid'})

模板/login.html

<form action="/accounts/auth/" method="post">{% csrf_token %}
   <label for="username">User name</label>
   <input type="text" name="username" value="" id="username">
   <label for="password">Password</label>
   <input type="password" name="password" value="" id="password">
   <input type="submit" value="login" />
</form>

模板/invalid.html

<form style="float: right" action="accounts/login/" method="post">
  {% csrf_token %}
  {{form}}
  <input type="submit" value="Login" class="search"/>
</form>

使用上面的代码,我得到了 Page not Found 错误

Page not found (404)
Request Method: POST
Request URL: http://127.0.0.1:8000/accounts/invalid/accounts/login/

Django 将请求的 url 解析为相对于当前页面的 url。当我用{% url %} 标记替换操作时。我在 /accounts/invalid/ 处遇到 NoReverseMatch 错误

我该如何正确地做到这一点?

【问题讨论】:

  • 看起来你将两个 url 端点连接到 1 个 url

标签: django django-urls


【解决方案1】:

试试这个:

<form style="float: right" action="/accounts/login/" method="post">
  {% csrf_token %}
  {{form}}
  <input type="submit" value="Login" class="search"/>
</form>

【讨论】:

  • 我做到了,但在 /accounts/invalid/ Reverse 处得到了 - NoReverseMatch,用于“/accounts/login/”,但未找到参数“()”和关键字参数“{}”。尝试了 0 个模式:[] 代替。
【解决方案2】:

原因如下:

Request URL: http://127.0.0.1:8000/accounts/invalid/accounts/login/
正则表达式末尾的

$ 表示斜杠后没有任何内容:

url(r'^accounts/login/$', 'taxo.views.login', name='login'),
url(r'^accounts/invalid/$', 'taxo.views.invalid', name='invalid'),

因此您可以使用这些网址:

http://127.0.0.1:8000/accounts/login/
http://127.0.0.1:8000/accounts/invalid/

编辑: 为什么模板重定向中的一个 URL 以斜杠开头而一个没有?试试这个:

<form style="float: right" action="{% url 'login' %}" method="post">

【讨论】:

  • 当我尝试的时候。我得到了 NoReverseMatch 异常:没有找到带有参数 '()' 和关键字参数 '{}' 的 '/accounts/login/' 的反向。尝试了 0 个模式:[]
  • 评论无法显示代码,所以我编辑了答案。检查 urls.py 和模板中的更改 - 它更优雅。
猜你喜欢
  • 2014-07-20
  • 2015-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-22
  • 1970-01-01
相关资源
最近更新 更多