我在django中的模板中生成反向网址时遇到了问题。我试图解决它几个小时,我不知道问题可能是什么。 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,)))
但是当我试图在模板中制作时,我遇到了这样的错误:
> / entry / 1 /的NoReverseMatch 使用参数'(1L,)'和关键字参数'{}'找不到''add_comment''的反向。
我的文件结构如下:
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"),
)
views.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 %}
没有任何改变。我总是得到同样的错误。 所以现在我更加困惑,因为在这个简单的代码中,一切看起来都很好。你认为这可能是像服务器或smth这样的外部问题吗?我什么都不知道......
答案 0 :(得分:2)