首页 > 解决方案 > django:无法重定向到 django 中的另一个视图

问题描述

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

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

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

网址.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'),
]

视图.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>

标签: pythondjangodjango-urls

解决方案


问题是comments/1/commodityInfoPageURL 模式匹配。

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

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

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

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


推荐阅读