我在 django 的模板中生成反向 url 时遇到了问题。几个小时以来,我一直在尝试解决它,但我不知道问题可能是什么。URL 反转在模型和视图中效果很好:
# like this in models.py
@models.permalink
def get_absolute_url(self):
return ('entry', (), {
'entry_id': self.entry.id,
})
# or this in views.py
return HttpResponseRedirect(reverse('entry',args=(entry_id,)))
但是当我试图在模板中制作它时,会出现这样的错误:
NoReverseMatch at /entry/1/
Reverse for ''add_comment'' with arguments '(1L,)' 和关键字参数 '{}' 未找到。
我的文件结构如下所示:
project/
├── frontend
│ ├── models.py
│ ├── urls.py
│ └── views.py
├── settings.py
├── templates
│ ├── add_comment.html
│ └── entry.html
├── utils
│ └── with_template.py
└── wsgi.py
我的 urls.py:
from project.frontend.views import *
from django.conf.urls import patterns, include, url
urlpatterns = patterns('project.frontend.views',
url(r'^entry/(?P<entry_id>\d+)/', 'entry', name="entry"),
(r'^entry_list/', 'entry_list'),
然后entry_list.html:
{% extends "base.html" %}
{% block content %}
{% for entry in entries %}
{% url 'entry' entry.id %}
{% endfor %}
{% endblock %}
在views.py中我有:
@with_template
def entry(request, entry_id):
entry = Entry.objects.get(id=entry_id)
entry.comments = entry.get_comments()
return locals()
其中 with_template 跟随装饰器(但我不认为这是一种情况):
class TheWrapper(object):
def __init__(self, default_template_name):
self.default_template_name = default_template_name
def __call__(self, func):
def decorated_func(request, *args, **kwargs):
extra_context = kwargs.pop('extra_context', {})
dictionary = {}
ret = func(request, *args, **kwargs)
if isinstance(ret, HttpResponse):
return ret
dictionary.update(ret)
dictionary.update(extra_context)
return render_to_response(dictionary.get('template_name',
self.default_template_name),
context_instance=RequestContext(request),
dictionary=dictionary)
update_wrapper(decorated_func, func)
return decorated_func
if not callable(arg):
return TheWrapper(arg)
else:
default_template_name = ''.join([ arg.__name__, '.html'])
return TheWrapper(default_template_name)(arg)
您有什么想法,可能会导致问题吗?非常感谢提前!
编辑: 我刚刚做了一个实验。我评论了我能留下的所有东西:urls.py
# -*- coding: UTF-8 -*-
from justmetyou.frontend.views import *
from django.conf.urls import patterns, include, url
urlpatterns = patterns('justmetyou.frontend.views',
url(r'^entry/(?P<entry_id>\d+)/', 'entry', name="entry"),
)
视图.py
# -*- coding: UTF-8 -*-
from justmetyou.frontend.models import *
from django.shortcuts import render_to_response, get_object_or_404
def entry(request, entry_id):
entry = Entry.objects.get(id=entry_id)
return render_to_response('entry.html', {'entry':entry})
entry.html
{% extends "base.html" %}
{% block content %}
{% url 'entry' 1 %}
{% endblock %}
什么都没有改变。我总是遇到同样的错误。所以现在我更加困惑了,因为在这个简单的代码中一切看起来都很好。你认为这可能是像服务器这样的外部东西或像这样的东西......?我没有任何想法...