问题
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