即使 url 模式正确,也获得 NoReverseMatch?

Posted

技术标签:

【中文标题】即使 url 模式正确,也获得 NoReverseMatch?【英文标题】:Getting NoReverseMatch even though url patterns are correct? 【发布时间】:2021-01-24 04:28:52 【问题描述】:

我已经学习 Django 一个月了,如果我做了一些愚蠢的事情,我深表歉意,但是,当我尝试在 url '/profile 下呈现“个人资料”页面时,我收到了 NoReverseMatch Reverse for 'profile' with arguments '('',)' not found. 1 pattern(s) tried: ['profile/(?P<use>[^/]+)$'] 错误/[a user's name]',我很确定我所有的路径/模式都是正确的??这是我的代码,有人可以帮我吗?我所有其他 url 模式都可以正常工作。这条路径之前也很好用,我只是将“user”变量重命名为“use”,就发生了这种情况。

urls.py:

urlpatterns = [
    path("", views.index, name="index"),
    path("login", views.login_view, name="login"),
    path("logout", views.logout_view, name="logout"),
    path("register", views.register, name="register"),
    path("profile/<str:use>", views.profile, name="profile"),
    path("following", views.following, name="following"),

    #api
    path('', include(router.urls)),
]

views.py:

def profile(request, use):
    currentuser = str(request.user)
    followers = []
    following = []
    for follow in Follow.objects.filter(following=use):
        followers.append(follow.person)
    for item in Follow.objects.filter(person=use):
        following.append(item.following)
    follower_count = len(followers)
    following_count = len(following)
    try:
        Follow.objects.get(person=currentuser, following=use)
        followed = True
    except:
        followed = False
    post_list = Post.objects.filter(user=use)
    dates = []
    for post in post_list:
        dates.append(post.timestamp)
    dates.sort(key = lambda date: datetime.strptime(date, '%B %d, %Y, %I:%M %p'), reverse=True)
    formattedlist = []
    for date in dates:
        postobject = Post.objects.get(timestamp=date)
        formattedlist.append(postobject)
    paginatorlist = Paginator(formattedlist, 10)
    now_page_content = paginatorlist.page(1)
    nowpage = 1
    if request.method == "POST":
        # Update the database
        followbutton = request.POST.get("button")
        button = request.POST.get("nav-button")
        pagenum = request.POST.get("pg")
        if followbutton:
            if followbutton == "Follow":
                followid = Follow.objects.all().count() + 1
                person = currentuser
                following = use
                newfollow = Follow(followid, person, following)
                newfollow.save()
                return HttpResponseRedirect(f"/profile/use")
            else:
                deletefollow = Follow.objects.get(person=currentuser, following=use)
                deletefollow.delete()
                return HttpResponseRedirect(f"/profile/use")
        else:
            currentpage = paginatorlist.page(pagenum)
            if button == 'Previous':
                if pagenum == '1':
                    return render(request, "network/profile.html", 
                        "formattedlist": now_page_content, "currentnumber": nowpage, "message":'No previous page', "use": use, "currentuser": currentuser, "follower_count": follower_count, "following_count": following_count, "followed": followed,
                    )
                else:
                    nowpage = int(pagenum)-1
                    now_page_content = paginatorlist.page(nowpage)
                    return render(request, "network/profile.html", 
                        "formattedlist": now_page_content, "currentnumber": nowpage, "use": use, "currentuser": currentuser, "follower_count": follower_count, "following_count": following_count, "followed": followed,
                    )
            else:
                if currentpage.has_next() == False:
                    return render(request, "network/profile.html", 
                        "formattedlist": currentpage, "currentnumber": pagenum, "message":'No next page', "use": use, "currentuser": currentuser, "follower_count": follower_count, "following_count": following_count, "list": formattedlist, "followed": followed,
                    )
                else:
                    nowpage = int(pagenum)+1
                    now_page_content = paginatorlist.page(nowpage)
                    return render(request, "network/profile.html", 
                        "formattedlist": now_page_content, "currentnumber": nowpage, "use": use, "currentuser": currentuser, "follower_count": follower_count, "following_count": following_count, "followed": followed,
                    )
    return render(request, "network/profile.html", 
        "use": use, "currentuser": currentuser, "follower_count": follower_count, "following_count": following_count, "followed": followed, "formattedlist": now_page_content, "currentnumber": nowpage,
    )

network/profile.html

    % extends "network/layout.html" %
    % block body %
        <script src="http://127.0.0.1:8000/static/network/network.js"></script>
        <div>
            <h2 class="profiletext">use's profile page</h2>
            use
            % if message %
                <h6 style="color: red; margin-left: 10px">message</h6>
            % endif %
            <h5 class="profiletext">Follows: follower_count // Following: following_count</h5>
            % if use != currentuser %
                <form method="POST" class="profiletext" action="% url 'profile' use %">
                    % csrf_token %
                    % if followed == False %
                        <input type="submit" value="Follow" name="button">
                    % else %
                        <input type="submit" value="Unfollow" name="button">
                    % endif %
                </form>
            % endif %
        </div>
            % for post in formattedlist %
            <div class="post">
                <h5><a href="% url 'profile' post.use %">post.use</a></h5>
                <h6 style="font-weight: 60" class="edit"><a>Edit</a></h6>
                <h4 class="content" style="font-size: 16px;">post.content</h4>
                <h6 style="color: #d3d3d3; font-weight: 50">post.timestamp</h6>
                <h1 class="hidden">post.id</h1>
                % if user.is_authenticated %
                    <img src="https://cdn.shopify.com/s/files/1/0649/0603/products/bigo-0002-GH-8-bit-heart_grande.jpeg?v=1410449344">
                    <h2 class="likes">TODO</h2>
                % endif %
            </div>
        % endfor %
        <div>
            <form class="pagination" method="POST" action="% url 'profile' use %">
                % csrf_token %
                <input type="submit" value="Previous" class="page-link" name="nav-button"> 
                <input type="submit" value="Next" class="page-link" name="nav-button" >
                <input type="text" value=currentnumber class="pagenumber" name="pg">
            </form>
        </div>
    % endblock %

【问题讨论】:

【参考方案1】:

我假设您没有从 Post 模型更改 user 外键。所以,我猜你的错误来自这一行:

<h5><a href="% url 'profile' post.use %">post.use</a></h5>

所以,应该是这样的:

<h5><a href="% url 'profile' post.user %"> post.user </a></h5>

【讨论】:

以上是关于即使 url 模式正确,也获得 NoReverseMatch?的主要内容,如果未能解决你的问题,请参考以下文章

Spring Security - 即使凭据正确,身份验证也不起作用

AWS CORS 问题:即使在获得 200 状态代码后,Ajax 响应也会出现错误

NoReverse 匹配 "" Reverse for "" 参数 '()' 和关键字参数 ''

92. NoReverse Linked List 2

即使标题正确,POST 调用也会返回 CORS 错误

即使在从服务器获得响应后,失败函数也会得到回调