找到NoReverseMatch

2024-05-20 16:25:21 发布

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

我使用的是django 1.7和python 3.4 我试图实现跟踪和取消跟踪到我的网站用户,但我卡住了。 网址.py你知道吗

url(r'^user/', include('myuserprofile.urls'),),

你知道吗myuserprofile.url.py你知道吗

urlpatterns = patterns('',
                       url(r'^(?P<slug>[^/]+)/$', 'myuserprofile.views.profile', name='profile'),
                       url(r'^(?P<slug>[^/]+)/follow/$', 'myuserprofile.views.follow', name='follow'),
                       url(r'^(?P<slug>[^/]+)/unfollow/$', 'myuserprofile.views.unfollow', name='unfollow'),

你知道吗视图.py你知道吗

@login_required
def follow(request):
    myuser = request.user.id
    if request.method == 'POST':
        to_user = MyUser.objects.get(id=request.POST['to_user'])
        rel, created = Relationship.objects.get_or_create(
            from_user=myuser.myuserprofile,
            to_user=to_user,
            defaults={'status': 'following'}
        )
else:
        return HttpResponseRedirect(reverse('/'))

            if not created:
                rel.status = 'following'
                rel.save()

模板部分是这样的:

<form action="{% if relationship.status == 'F' %}{% url 'unfollow' %}{% else %}{% url 'follow' %}{% endif %}" method="POST">

找不到参数为“()”且关键字参数为“{}”的“follow”的反转。尝试了1个模式:['user/(?P[^/]+)/跟/$']


Tags: tonamepyurlifrequeststatuspost
3条回答

你需要使用namespaced URL。 在您的例子中,URL unfollow应该被引用为<app_name>:unfollow。你知道吗

URL namespaces allow you to uniquely reverse named URL patterns even if different applications use the same URL names. It’s a good practice for third-party apps to always use namespaced URLs (as we did in the tutorial). Similarly, it also allows you to reverse URLs if multiple instances of an application are deployed. In other words, since multiple instances of a single application will share named URLs, namespaces provide a way to tell these named URLs apart

看看这个Here

你必须使用URL namespaces

这是我的

民意测验/网址.py你知道吗

from django.conf.urls import patterns, url

from . import views

urlpatterns = patterns('',
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
    ...
)

所以我们有类似的用途

{% url 'polls:index' %}

您应该添加要跟随/取消跟随的用户的用户名:

{% url 'follow' user_to_follow.username %}

urls.py更改为:

urlpatterns = patterns('myuserprofile.views',
         url(r'^(?P<username>[^/]+)/$', 'profile', name='profile'),
         url(r'^(?P<username>[^/]+)/follow/$', 'follow', name='follow'),
         url(r'^(?P<username>[^/]+)/unfollow/$', 'unfollow', name='unfollow'),
)

视图的签名应该接受username参数:

@login_required
def follow(request, username):
    myuser = request.user.id
    if request.method == 'POST':
        to_user = MyUser.objects.get(username=username)
        ...

相关问题 更多 >