Django noreversematch用于基于类的视图

时间:2014-02-20 22:35:35

标签: django

我有这个观点:

class ProfileView(UpdateView):
    template_name = 'home/profile.html'
    form_class = UserForm
    success_url = '/'

    def get_object(self, *args, **kwargs):
        return self.request.user

和urls.py

urlpatterns = patterns('',
    url(r'^$', views.HomeView.as_view(), name="index"),
    url(r'^me/$', login_required(views.ProfileView.as_view()), name="me"),
)

main urls.py

urlpatterns = patterns('',
    # Examples:
    url(r'^$', include('demo.apps.home.urls', namespace="home")),
)

当我尝试在模板中反转它时:

<a href="{% url 'home:me' %}">My Profile</a>

我收到NoReverseMatch错误:

Reverse for 'me' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'$me']

2 个答案:

答案 0 :(得分:1)

您的主urls.py仅包含demo.apps.home.urls 空网址(因为^$匹配的内容)。您需要删除至少最终的$

urlpatterns = patterns('',
    # Examples:
    url(r'^', include('demo.apps.home.urls', namespace="home")),
)

答案 1 :(得分:0)

如果使用命名空间包含url,则必须在url标记(或反向函数)中使用命名空间:

<a href="{% url 'home:me' %}">My Profile</a>