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

Django中request.GET.get返回None求助:超市网站获取商品数量失败

解决request.GET.get返回None的问题

问题根源

  1. URL路由匹配错误:你的meat_series路由使用re_path(r'^meat_series/', ...),正则表达式未以$结尾,导致任何以meat_series/开头的URL(如meat_series/price/)都会被匹配到meat_series视图,而非price视图。请求根本没到达price函数,自然拿不到GET参数。
  2. 表单action路径错误:表单使用相对路径price/,提交后URL变为/web/meat_series/price/?apple=1,偏离了price视图的正确路由/web/price/。

解决方案

1. 修正URL路由配置

将meat_series的路由改为精确匹配:

from django.urls import path, re_path
from . import views
app_name = 'web'
urlpatterns = [
    path('', views.index, name='index'),
    re_path(r'^login/', views.login_request, name='login'),
    re_path(r'^register/', views.register_request, name='register'),
    # 修正为精确匹配,添加$结尾
    re_path(r'^meat_series/$', views.meat_series, name='meat_series'),
    # 更推荐使用path(默认精确匹配):
    # path('meat_series/', views.meat_series, name='meat_series'),
    path('logout/', views.logout_request, name='logout'),
    path('price/', views.price, name='price')
]

2. 修正表单的action路径

使用Django的url模板标签生成正确的绝对路径,避免相对路径问题:

{% block content %}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
{% for ser in meat_ser %}
<div style="position:sticky ;" class= "row" >
<div class="col-sm-6">
<div class="card mb-3 " style="width: 18rem;">
<img style="height: 250px;margin: 0%;" id='photo'src="{{ser.photo}}" class="card-img-top" alt="...">
        
<div class="card-body">
<h5 class="card-title">{{ser.Name}}</h5>
<p class="card-text"></p>

<!-- 使用url标签生成正确的action路径 -->
<form action="{% url 'web:price' %}" method="GET">
<label for="quantity">Quality:</label>
<!-- 修正label的for属性,关联input的id -->
<input type="number" name="{{ser.Name}}" id="quantity">
<input type="submit" value="Buy">
</form>

验证修改效果

提交表单后,URL应变为http://127.0.0.1:8000/web/price/?apple=1,此时price视图中的request.GET.get('apple')可正确获取值1。也可添加调试代码确认:

def price(request):
    print(request.GET)  # 控制台会输出<QueryDict: {'apple': ['1']}>
    a = request.GET.get('apple')
    return render(request, 'price.html', {'a': a})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 00:25:26