【问题标题】:django: unable to redirect to another view in djangodjango:无法重定向到 django 中的另一个视图
【发布时间】:2019-03-15 13:38:04
【问题描述】:

我正在尝试单击http://127.0.0.1:8000/main/electronics/switch/ 中的一个按钮来调用getCommodityCommentDetail 做某事,然后重定向到另一个页面commodityInfoPage

让我感到困惑的是,该页面始终在初始页面中显示相同的内容,尽管 url 已更改,例如到http://127.0.0.1:8000/main/comments/1/

经过测试,发现views.py中的commodityInfoPage没有被调用。我已经搜索了很长时间的解决方案,但都失败了。那么我该如何解决呢?

urls.py:

app_name = 'main'

urlpatterns = [
    # eg:127.0.0.1:8000/main/
    path('', views.index, name = 'index'),
    path('getCommodityInfo/', views.getCommodityInfo, name = 'getCommodityInfo'),
    path('getCommodityCommentDetail/', views.getCommodityCommentDetail, name="getCommodityCommentDetail"),
    path('<str:category>/<str:searchKey>/',views.commodityInfoPage, name = 'commodityInfoPage'),
    path('comments/<str:commodityId>/', views.commodityCommentPage,name = 'commodityCommentPage'),
]

view.py:

def getCommodityCommentDetail(request):
    if request.method=="POST":
        commodityId = request.POST.get("commodityId")
        # scrapy module is waiting implementation

        #
        return HttpResponseRedirect(reverse('main:commodityInfoPage',args=(commodityId)))

def commodityCommentPage(request, commodityId):
    print("enter commodityCommentPage")
    commentList = JDCommentDetail.objects.all()
    context = {'commentList':commentList}
    return render(request,'main/commodityCommentPage.html',context)

模板:

<form action="{% url 'main:getCommodityCommentDetail'%}" method="POST">
   {% csrf_token %}
   <input class="hidden" value="{{commodity.id}}" name="commodityId">
   <button type="submit" class="btn btn-default" >review</button>
</form>

【问题讨论】:

  • 注意args应该是一个元组或一个列表,即args=(commodityId,)
  • 我查看了源代码,但我不明白为什么args必须是元组或列表。你能告诉我为什么吗?link
  • 首先,请参阅examples in the docs - 他们使用列表。它应该是一个列表或一个元组,因为可以有多个 arg。您的代码目前可能对您有用,因为 commodityId 是单个字符串,例如"1"。如果你用args=("15")I think it will be treatedargs=["1", "5"] 一样进行测试(因为字符串是可迭代的),你会得到一个错误。

标签: python django django-urls


【解决方案1】:

问题在于comments/1/commodityInfoPage URL 模式匹配。

path('<str:category>/<str:searchKey>/',views.commodityInfoPage, name='commodityInfoPage'),

您可以通过更改 URL 模式以使其不会发生冲突来解决此问题,或者将commodityCommentPage URL 模式移动到commodityInfoPage 的上方。

path('comments/<str:commodityId>/', views.commodityCommentPage, name='commodityCommentPage'),
path('<str:category>/<str:searchKey>/', views.commodityInfoPage, name='commodityInfoPage'),

请注意,如果您对模式重新排序,如果类别为“cmets”,您将无法查看commodityInfoPage

【讨论】:

  • 谢谢!!!我已将路径更改为以下模式,并且可以正常工作。 path('commodityInfo/&lt;str:category&gt;/&lt;str:searchKey&gt;/',views.commodityInfoPage, name = 'commodityInfoPage'),
猜你喜欢
  • 2020-01-01
  • 1970-01-01
  • 2018-10-19
  • 2018-10-26
  • 1970-01-01
  • 2012-03-10
  • 1970-01-01
  • 2012-02-10
  • 2018-12-11
相关资源
最近更新 更多