Django NoReverseMatch带单参数

2024-05-23 18:05:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正试图从一个只有一个参数的模板调用url。当尝试解析{%url'rep'object.person.id%}时,我得到一个NoReverseMatch异常,并显示以下文本

Reverse for 'rep' with arguments '(400034,)' and keyword arguments '{}' not found. 2 pattern(s) tried: [u'replist/$(\\d+)/$', u'$(\\d+)/$']

似乎它找到了正确的模式,而争论正是我所期待的,但它只是因为某些原因而不匹配。有人看到什么东西向他们扑来吗?我已经把头撞在墙上好几个小时了,我觉得这将是一个愚蠢的错误

应用程序的所有代码都可以在下面找到

URL.py:

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.replist, name='main'),
    url(r'^(\d+)/$', views.rep, name='rep'),
]

views.py:

from django.shortcuts import render_to_response, render

import time
import urllib2
import json
import unicodedata

def replist(request):
    poli_link = "https://www.govtrack.us/api/v2/role?current=true"

    req = urllib2.Request(poli_link)
    response = urllib2.urlopen(req)
    html = response.read()

    reps = json.loads(html)

    return render_to_response("replist/rep_list.html", dict(reps=reps))

def rep(request, repid ):
    return render_to_response("replist/rep.html", dict(rep=rep) )

rep_list.html:

{% extends "replist/bbase.html" %}

{% load taglookup %}

{% block content %}
    <style type="text/css">
        .main { margin-left: 25px; margin-right: 25px; float: left; width: 75%; margin-top: 30px; }
        .sidebar { float: left; margin-top: 30px; }
        .time { font-size: 0.8em; margin-top: 2px; }
        .body { font-size: 1.1em; margin-top: 2px; }
        .commentlink { text-align: right; }
        .step-links a { font-size: 0.89em; }
        .title {
            font-size: 1.4em; margin-top: 20px; border-bottom: 1px solid #ccc;
            padding-left: 4px; margin-left: 5px;
        }
        .messages { margin-left: 20px; }
        .pagination { margin-top: 20px; margin-left: -20px; }
    </style>
    <div class="main">
    {% for object in reps|get_item:"objects" %}
    <a href="{% url 'rep' object.person.id %}">{{object.person.name}}</a><br>
    {% endfor %}
    </div>
{% endblock %}

Tags: marginimporturlsizeobjectresponsetophtml
2条回答

需要纠正的事项:

url(r'^(\d+)/$', views.rep, name='rep'),

应该是

url(r'^(?P<repid>\d+)/$', views.rep, name='rep'),

views.py

def rep(request, repid ):
    return render_to_response("replist/rep.html", dict(rep=rep) )

应该是

def rep(request, repid):
    # get rep from db and render to template
    return render(request, "replist/rep.html", {'rep': rep})
[u'replist/$(\\d+)/$', u'$(\\d+)/$']

$匹配字符串的结尾。显然,在字符串结束后,您无法匹配任何内容。您需要删除项目的URLconf中与include()一起使用的正则表达式中的尾随$

相关问题 更多 >