Django-尽管位于urls.py中,但找不到播放器URL

时间:2018-12-04 16:12:20

标签: python django django-urls

最近几天,我一直在构建Django Web应用程序,以允许用户在MLB Statistics数据库上进行查询。我的某些Web应用程序运行良好,但是我尝试实现搜索功能并遇到URL映射问题。我试图从此继续,而是致力于使数据库显示基于他们所单击的播放器的链接的信息,但是我遇到了同样的问题,URL根据播放器的player_id是动态的。这部分仅使用以player_id作为其主键的People模型。

当前,我有一个“ allPlayers.html”,其中列出了数据库中的每个播放器以及将播放器的player_id发送到url的链接,如下所示:

allPlayers.html

{% extends "base_template.html" %}

{% block content %}
  <h1>MLB Stats All Players</h1>
  <p>Currently, there are : {{ num_players }} players listed in the database.</p>
  <table style="width:100%">
      <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th></th>
      </tr>
      {% for player in players %}
        <tr>
            <td>{{ player.name_first }}</td>
            <td>{{ player.name_last }}</td>
            <td>More on <a href="player/{{ player.player_id }}/">{{ player.name_first }} {{ player.name_last }}</a></td>
        </tr>
      {% endfor %}
  </table>

{% endblock %}

以及“ allPlayers.html”的相应视图:

def allplayers(request):
    """View function for allPlayers page of site."""

    # Generate counts of people object
    num_players = People.objects.count()
    players = People.objects.all()

    context = {
        'num_players': num_players,
        'players': players,
    }

    # Render the HTML template allPlayers.html w/ data in context variable
    return render(request, 'allPlayers.html', context=context)

如上所述,我已经成功地在Web应用程序上创建了一个页面,该页面列出了数据库中的每个播放器以及一个链接,并注意到我正在尝试通过player_id发送<a href='players/{{ player.player_id }}>。目前,allPlayers部分可以正常工作。但是,当我添加以下playerInfo.html和相应的视图时,事情就没那么简单了:

playerInfo.html

{% extends "base_template.html" %}

{% block content %}
  {% if results %}
    {% for player in results %}
      <p>{{ player.name_first }} {{ player.name_last }}</p>
    {% endfor %}
  {% endif %}
{% endblock %}

视图:

def player(request, pk=None):
    if pk is not None:
      print('Hello world')
      print('pk :', pk)
      #instance = get_object_or_404(People, player_id=pk)
      results = People.object.filter(player_id=pk)
      context = {
        "results": results
      }
      return render(request, "playerInfo.html", context)
    else:
        print('Hello')
        return render(request, 'playerInfo.html')

我的想法是,前面提到的包含{{ player.player_id }}的链接将与以下URL匹配,并将player_id的值放在pk中,如下所示,使用<int:pk>语法而不是正则表达式:

投票/urls.py

urlpatterns = [
    path('', views.index, name='index'),
    path('allPlayers', views.allplayers, name='allplayers'),
    path('allTeams', views.allteams, name='allteams'),
    path('search/', views.search, name='search'),
    path('player/<int:pk>/', views.player, name='player'),
]

但是,一旦导航到“ allPlayers”页面并单击播放器的链接之一,例如Hank Aaron(拥有player_id aaronha01),我就会得到以下找不到页面(404)错误:

Using the URLconf defined in baseballdb.urls, Django tried these URL patterns, in this order:

polls/ [name='index']
polls/ allPlayers [name='allplayers']
polls/ allTeams [name='allteams']
polls/ search/ [name='search']
polls/ player/<int:pk>/ [name='player']
admin/
The current path, polls/player/aaronha01/, didn't match any of these.

我已经为此烦恼了很多。如果有人提出任何建议,并且可以为我指出错误的思考方向或为我提供解决方案的方向,我们将不胜感激!谢谢。

2 个答案:

答案 0 :(得分:1)

您的<int:pk>中的path()(需要一个整数)与您的player_id(一个类似'aaronha01'的字符串)之间不匹配。

您可以在任何地方使用pk,并使用/player/17/之类的网址:

path('player/<int:pk>/', views.player, name='player'),

def player(request, pk):
    instance = get_object_or_404(People, pk=pk)
    context = {
        "instance": instance,
    }
    return render(request, "playerInfo.html", context)

# Use pk in template when constructing URL
<td>More on <a href="/player/{{ player.pk }}/">{{ player.name_first }} {{ player.name_last }}</a></td>

或者您可以在任何地方使用player_id,并使用/player/aaronha01/之类的网址。

path('player/<slug:player_id>/', views.player, name='player'),

def player(request, player_id):
    instance = get_object_or_404(People, player_id=player_id)
    context = {
        "instance": instance,
    }
    return render(request, "playerInfo.html", context)

# Use player_id in template when constructing URL
<td>More on <a href="/player/{{ player.player_id }}/">{{ player.name_first }} {{ player.name_last }}</a></td>

作为下一个改进,您可以开始使用{% url %}标记,这样就不再需要对URL进行硬编码了。

<a href="{% url "polls:player" player.player_id %}">

在上面,我假设您在app_name='polls'中有polls/urls.py,并且您已决定在网址格式中使用player_id而不是pk

答案 1 :(得分:1)

path('player/<int:pk>/'意味着仅有效的整数pk会匹配。如果您的pk不是int且类似有效的slug-请改用path('player/<slug:pk>/'

docs:https://docs.djangoproject.com/en/2.1/topics/http/urls/#path-converters

我的建议是使用{{ player.get_absolute_url }}{% url 'player' player.id %}而不是手动构建url。

缺少斜杠表示“从这里开始”,而不是从网站根目录开始: https://webmasters.stackexchange.com/questions/56840/what-is-the-purpose-of-leading-slash-in-html-urls