【问题标题】:How to ignore or redirect a http request in Django?如何在 Django 中忽略或重定向 http 请求?
【发布时间】:2018-01-12 18:39:56
【问题描述】:

我在后端使用 Angular 4 前端和 Python Django。 如果我点击详细信息按钮,我会在我的组件中运行 openDetail 方法

openDetail(id:number){
    this.router.navigate(['/motor/detail', {"id": id}])
  }

浏览器打开带有 URL http://localhost:8000/motor/detail;id=21 的详细信息组件。完美的。重要的是要知道,我只需要 id 就可以在我的详细信息组件中使用它们。

但是如果我刷新页面,我会遇到 404 错误。 --> The current path, motor/detail;id=21, didn't match any of these. 嗯,这个也清楚了,跳到后端了。

ma​​in - urls.py

#... some other urls...
url(r'^motor/', include('motorControll.urls')),

电机 - urls.py

url(r'^$', views.index, name="index"),
url(r'^overview/$', views.MotorMapping.as_view({'get': 'getAllData'})),
url(r'^detail/$', views.index, name="index"),
url(r'^detail/(?P<id>\d+)/$', views.MotorMapping.as_view({'get': 'getById'})),
url(r'^detail/save/$', views.MotorMapping.as_view({'post': 'save'})),

如何忽略此调用或重定向到索引页面? 我需要 id,因为下一步,在加载详细信息页面后,通过此 url http://localhost:8000/motor/detail/21 加载详细信息,它返回包含所有数据的 JSON。

【问题讨论】:

  • 为什么你的网址中有;。是不是笔误?
  • 其实不是。它来自 Angular 教程 angular.io/guide/router#heroes-list-optionally-selecting-a-hero 我希望我理解的内容正确 :) --> 向下滚动一点,它在蓝色框中 Matrix URL notation
  • 我建议您使用查询参数而不是矩阵 URL 表示法。它真的是休息的标准,除了角度之外,你也很容易使用

标签: python django angular django-rest-framework


【解决方案1】:

您在motors.urls 中的URL 映射已针对URL /motor/detail/21 正确配置——因此它可以工作。但它没有为/motor/detail;id=21 之类的 URL 配置。

如果您向motors.url 添加了另一条路由,以便/motor/detail;id=21 可以正常工作——类似于url(r'^detail;id=(?P&lt;id&gt;\d+)$', views.MotorMapping.as_view({'get': 'getById'})),,那么该URL 将返回原始JSON,所以这不是您想要的。

相反,实际的解决方案更复杂——您希望将 URL 路由到您的单页应用程序,而不是 Django,并让 Angular 负责从 Django Rest Framework 加载数据。

【讨论】:

    猜你喜欢
    • 2017-03-29
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 2018-10-03
    • 2021-10-01
    • 2017-01-17
    相关资源
    最近更新 更多