You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django在线购物项目首页404错误,请求代码排查

Django项目首页404错误排查及修复

核心问题:根路径路由匹配失效

项目根目录urls.py中的路由正则写法错误,导致访问/时无法匹配到home视图。

错误代码(项目urls.py):

re_path(r'^/', include(website_urls)),

修复方案:

将上述代码替换为以下任意一种写法:

  • 使用re_path正则匹配根路径:
re_path(r'^', include(website_urls)),
  • 推荐使用Django 2.0+新增的path简化写法:
path('', include('website.urls')),

其他需修复的代码问题(避免后续功能异常)

1. 应用urls.py中logout路由格式错误

错误代码:

re_path(r'^logout/$/', Logout, name='logout'),

末尾多了一个冗余的/,修复后:

re_path(r'^logout/$', Logout, name='logout'),

2. 应用urls.py中placeorder路由语法错误

re_path需使用正则分组语法,不能混用path的路径转换器:
错误代码:

re_path(r'^placeorder/<str:i>/$', PlaceOrder, name='placeorder'),

修复为正则分组写法:

re_path(r'^placeorder/(?P<i>[^/]+)/$', PlaceOrder, name='placeorder'),

或改用path更简洁:

path('placeorder/<str:i>/', PlaceOrder, name='placeorder'),

3. views.py中的逻辑与语法错误

  • PlaceOrder函数:模型查询方法少写s,返回模板误用redirect:
    # 错误
    customer = Customer.object.get(id=i)
    return redirect(request, 'website/placeorder.html', {'form':form})
    # 修复后
    customer = Customer.objects.get(id=i)
    return render(request, 'website/placeorder.html', {'form':form})
    
  • RegisterPage函数:表单类名写错,render参数格式错误:
    # 错误
    customerform = CreatePostForm(request.POST)
    return render(request, 'website/register.html', {'form': form},{'customerform': customerform})
    # 修复后
    customerform = CreateCustomerForm(request.POST)
    return render(request, 'website/register.html', {'form': form, 'customerform': customerform})
    
  • LoginPage函数:else块缩进不规范:
    # 错误
    else:
         if request.method == 'POST':
    # 修复后
    else:
        if request.method == 'POST':
    

内容的提问来源于stack exchange,提问作者user21738139

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 16:28:09