首页 > 解决方案 > 如何根据 for 循环中的特定参数从主页链接到另一个详细信息页面?- 姜戈

问题描述

我正在学习 django,并且在一个项目期间,我一直坚持将 home.html 链接到特定的 details.html

我的代码如下:

网址.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home, name="home"),
    path('details/<statename>', views.details, name='details')
]

视图.py

from django.shortcuts import render

# This is the dictionary for all the attractions
attractions = [
  { 'attraction_name' : 'Niagra Falls', 'state' : 'New York'},
  { 'attraction_name' : 'Grand Canyon National Park', 'state' : 'Arizona'},
  { 'attraction_name' : 'Mall of America', 'state' : 'Minnesota'},
  { 'attraction_name' : 'Mount Rushmore', 'state' : 'South Dakota'},
  { 'attraction_name' : 'Times Square', 'state' : 'New York'},
  { 'attraction_name' : 'Walt Disney World', 'state' : 'Florida'}
]

def home(request):
  # The context is all of the variables we want passed into the template.
  context = {"attractions" : attractions}
  return render(request, 'tourist_attractions/home.html', context)

def details(request, statename):
  # We replace the dash with a space for later ease of use. The dash is there because of the slugify filter.
  context = {"attractions" : attractions, "statename" : statename.replace("-", " ")}
  return render(request, 'tourist_attractions/details.html', context)

home.html(我尝试使用 for 循环从home一个页面链接到另一个页面)details/<statename>



{% block content %}
<h1>This is a list of attractions in America!</h1>
<table>
  <tr>
    <th>Attraction</th>
    <th>State</th>
    <th>State details</th>
  </tr>
  {% for item in attractions|dictsort:"state" %}
  <tr>
    <td>{{ item.attraction_name }}</td> # included in the task
    <td>{{ item.state }}</td> # included in the task
    <td><a href="{% url 'details' statename=item.state %}">click here</a></td> # Not in the task but I assumed that after clicking each link, the link should lead the user to that details/<statename>

    <td>{{ item.attraction_name }}</td> 
    <td>{{ item.state }}</td> 
    <!--I would like the link to lead the user to that details/<statename> url-->
    <td><a href="{% url 'details' statename=item.state %}">click here</a></td> 
  </tr>
  {% endfor %}
</table>
{% endblock %}

后来,我创建details.html了其中的一个,如果我输入 urldetails/arizonadetails/new-york,则 url details/ 效果很好。

问题是当州名中有空格时,我无法单击从主页到详细信息页面的链接,例如,当我想查看“纽约”时代广场的更多详细信息时。我想知道如何正确地从家链接到详细信息/。

谢谢。

标签: pythondjango

解决方案


在 url 中有空格通常不能很好地工作。我建议您(并且常用的)是在您的状态模型中创建一个新字段,该字段将是一个从状态名称计算出来的 slug。Slugs 是由非 URL 证明字符串(如带空格的名称)构建的 URL 证明字符串。然后您可以将此新字段用作 URL 变量(而不是名称)。

为了计算 slug,我经常使用python-slugifyhttps ://github.com/un33k/python-slugify

假设您有一个带有state字段(包含州名)的州模型:

from django.db import models
from slugify import slugify

class State(models.Model):
    # Some fields
    state = models.CharField(max_length=30)

    @property
    def slug(self):
        return slugify(self.state)

然后在您的模板中,只需替换item.stateitem.slugURL 匹配。


推荐阅读