我正在尝试制作非常有意义的网址,但我想我做错了。
这有效:
from django.conf.urls.defaults import patterns, url
from places.views import explore_view
urlpatterns = patterns('',
url(r'', explore_view, name='explore'),
)
这不是:
from django.conf.urls.defaults import patterns, url
from places.views import explore_view
urlpatterns = patterns('',
url(r'(?P<countryorcategory>[0-9A-Za-z._%+-]+)', explore_view, name='explore'),
)
我收到此错误:
使用参数'()'和关键字参数'{}'反向'explore' 没找到。
以下是explore_view的代码:
def explore_view(request, countryorcategory=None):
"""
This is the explore view - to view places sugeested by ambassadors
"""
user = request.user
page = request.GET.get("page", 1)
per_page = request.GET.get("per_page", 20)
category_id = request.GET.get("category_id", None)
attrs = request.GET
lat = safe_attr(attrs, "lat", "float", None)
lon = safe_attr(attrs, "lon", "float", None)
q = request.GET.get('q', None)
if q and not lat or lon:
cache_key = 'GoogleGeocode-{}'.format(hashlib.md5(q.encode('UTF-8', 'replace')).hexdigest())
latlon = cache.get(cache_key)
if not latlon:
latlon = geocode(q)
if latlon:
cache.set(cache_key, latlon)
if latlon:
lat = latlon['lat']
lon = latlon['lng']
if not q:
q = ''
category_names = getattr(settings, "EXPLORE_CATEGORIES", [])
categories = [Category.objects.get(name=cat_name).serialize() for cat_name in category_names]
more = True
places = Place.objects.explore_places(user, category_id=category_id, lat=lat, lon=lon, page=page, per_page=20)
if len(places) != per_page:
more = False
return render_to_response('explore/main.html', {'places': places, 'categories': categories, 'category_id': category_id, 'lat': lat, 'lon': lon, 'more': more, 'q': q}, RequestContext(request))
答案 0 :(得分:14)
这一行:
url(r'(?P<countryorcategory>[0-9A-Za-z._%+-]+)', explore_view, name='explore')
...定义了一个在模板中使用参数countryorcategory
的网址。您需要在模板中为您的网址添加以下任一参数:
{% url 'explore' argument %}
{% url 'explore' countryorcategory=argument %}
如果要继续使用具有相同名称的非参数URL,您可以定义具有相同名称但具有不同模式的其他URL 。例如:
urlpatterns = patterns('',
url(r'(?P<countryorcategory>[0-9A-Za-z._%+-]+)', explore_view, name='explore'),
url(r'', explore_view, name='explore'),
)
然后{% url 'explore' %}
应该有或没有参数。
答案 1 :(得分:2)
对我来说,我忘记了路线的命名空间。而不是
{% url 'login' %}
我应该写
{% url 'accounts:login' %}
使用此配置:
# root URLs
url(r'^accounts/', include('myproject.accounts.accounts.urls', namespace='accounts'))
# accounts URLs
url(r'^login$', views.login, name='login')
答案 2 :(得分:1)
我假设你正在使用这样的模板:
{% url 'explore' argument %}
此错误可能意味着argument
未设置为任何内容。