No User matches the given query. Page Not found 404?

馋奶兔 提交于 2021-02-11 14:59:53

问题


In my blog website I want to open another user's profile on clicking one of the links. But it keeps on showing 404 error saying No user matches the given query.

Here's that link in a base.html

<a href="{% url 'blogapp:userprofile' username=view.kwargs.username %}">{{ view.kwargs.username }}</a>

Here's my urls.py pattern for the function-

path('userprofile/<str:username>/',views.userprofile,name='userprofile'),

Here's my function views.py

@login_required
def userprofile(request,username):
    user = get_object_or_404(User,username='username')

    return render(request,'blogapp/userprofile.html',{'user':user})

here's my template file

{% extends 'blogapp/base.html' %}

{% block content %}

          <div class="row">
            <img  src="{{ user.profile.image.url }}">
          <div class="details">
            <h2>{{ user.username }}</h2>
            <p>{{ user.email }}</p>
          </div>
          </div>
          <p style="margin-top: 10px; margin-left: 138px;">{{ user.profile.description }}</p>
          <hr>


{% endblock %}

{{ view.kwargs.username }} gives the perfect username that I search for. But problem is somewhere in the userprofile view. It goes to the perfect route http://127.0.0.1:8000/userprofile/username/ but it still shows a 404 error.


回答1:


In your views you are passing username as a string, whereas it should be a variable that's being passed inside the userprofile function.

@login_required
def userprofile(request,username):
    user = get_object_or_404(User,username=username)

    return render(request,'blogapp/userprofile.html',{'user':user})



回答2:


@login_required
def userprofile(request,username):
    user = get_object_or_404(User,username='username')

    return render(request,'blogapp/userprofile.html',{'user':user})

Shoudld be this

@login_required
def userprofile(request,username):
    user = get_object_or_404(User,username=username)

    return render(request,'blogapp/userprofile.html',{'user':user})

Username on line 2 is being treated as a string instead of variable.



来源:https://stackoverflow.com/questions/57538717/no-user-matches-the-given-query-page-not-found-404

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!