0

在我的在线商店 django 项目中,我想创建一个子页面,显示页面中列出的产品的详细信息。

urls.py我创建了两个页面的网址,如下所示:

path('wwqm', views.water_quality_sensor  , name='wwqm'),
path('wwqm/<str:water_sensor_title>', views.water_sensor_item, name='water_sensor_item'),

在这种情况下,一堆项目显示在wwqm. 用户点击一个产品,water_sensor_item应该加载。

我知道这并不重要,但这里是views.py

def water_quality_sensor(request):

    queryset_list = Water_quality_sensor.objects.order_by('-product_name').filter(is_published=True)

    context = {
                'water_quality_sensor': queryset_list,
            }

    return render(request, 'products/water_quality_sensor.html', context)

def water_sensor_item(request, water_sensor_title):

    water_sensors =  get_object_or_404(Water_quality_sensor, title=water_sensor_title)
    context = {
        'water_sensors': water_sensors
    }
    return render(request, 'products/water_sensor_item.html' , context)

我尝试根据传递给其视图(产品标题)的参数为每个项目构建 url。

在我的模板中,我尝试创建如下链接:

<a href="{% url 'water_sensor_item' w_q_sensor.title %}" class="card hoverable mb-4 text-dark" >

我的产品标题之一是3725。当我在主页中单击该产品时,出现以下错误:

Django Version: 3.1.2  
Exception Type: NoReverseMatch  
Exception Value:     Reverse for 'water_quality_sensor' not found. 'water_quality_sensor' is not a valid view function or pattern name.

我究竟做错了什么?

4

1 回答 1

1

在你的 urls.py

path('wwqm', views.water_quality_sensor  , name='wwqm'),

你用了名字wwqm。但它看起来像在你的模板中的某个地方(很可能是 water_sensor_item.html),你有类似的东西:

<a href="{% url 'water_quality_sensor' %}"

将其更改为wwqm或更改名称urls.py

更新 最好<str:title><int:pk> 在您的网址中使用,以避免在两个产品中使用相同的名称。pk是独一无二的。

在你的urls.py

path('wwqm/<str:water_sensor_title><int:pk>', views.water_sensor_item, name='water_sensor_item'),          # add <int:pk>

在您的模板中:

# since url is taking both title and pk arguments, you need to provide both of them. 
<a href="{% url 'water_sensor_item' title= w_q_sensor.title pk=w_q_sensor.pk %}" class="card hoverable mb-4 text-dark" >

在你看来:

def water_sensor_item(request, water_sensor_title, pk): # added pk

    water_sensors =  get_object_or_404(Water_quality_sensor, pk=pk) # use pk to get the object
    context = {
        'water_sensors': water_sensors
    }
    return render(request, 'products/water_sensor_item.html' , context)
于 2020-12-07T06:11:15.413 回答