NoReverseMatch at / Reverse for 'user-profile' for 'user-profile' 找不到参数 '(,)'。尝试了 1 种模式:['配置文



请有人帮忙,我是Django的新手,不知道如何在我的代码中绕过这一点。我遵循了一个教程,它与Django建立了一个聊天室。一切都很好,但后来我想修改它,并在用户的个人资料页面上显示用户写的帖子,这样其他人就可以看到它,但我却在/找不到参数为"(",("的"用户配置文件"的反转。尝试了1种模式:['配置文件/(?P[^/]+(/$']

这是我的View文件;

from django.shortcuts import render, redirect
from django.http import HttpResponse
#from django.urls import reverse
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login, logout
from django.db.models import Q
from .models import Message, Room, Topic
from .forms import RoomForm
def userProfile(request, pk):
user = User.objects.get(id=pk)
rooms = user.room_set.all()
context = {'user': user, 'rooms': rooms}
return render(request, 'base/profile.html', context)

这是我的网址:

from django.urls import path
from . import views 
urlpatterns=[
path('', views.home, name="home"),
path('room/<str:pk>/', views.room, name="room"),
path('profile/<str:pk>/', views.userProfile, name='user-profile'),
]

'模板呈现过程中出错'在模板C:\Users\Nonesi\Desktop\StudyBudy\base\templates\base\feed_component.html中,第9行出现错误这是我的模板:

<div>
{% for room in rooms %}
<div>
{% if request.user == room.host %}
<a href="{% url 'update-room' room.id %}">Edit</a>
<a href="{% url 'delete-room' room.id %}">Delete</a>
{% endif %}

<a href="{% url 'user-profile' room.host.id %} ">@{{room.host.username}}</a>
<h5>{{room.id}} -- <a href="{% url 'room' room.id %}">{{room.name}}</a></h5>
<small>{{room.topic.name}}</small>
</div>
<hr>
{% endfor %}        
</div>

您可以尝试:

<div>
{% for room in rooms %}
<div>
{% if request.user == room.host %}
<a href="{% url 'update-room' room.id %}">Edit</a>
<a href="{% url 'delete-room' room.id %}">Delete</a>
{% endif %}
{% if room.host.id %}

<a href="{% url 'user-profile' room.host.id %} ">@{{room.host.username}}</a>
{% endif %}

<h5>{{room.id}} -- <a href="{% url 'room' room.id %}">{{room.name}}</a></h5>
<small>{{room.topic.name}}</small>
</div>
<hr>
{% endfor %}        
</div>

只有在对象存在的情况下才显示配置文件的url,这样就不会触发反向匹配错误,当然这也需要改进后端代码。

<a href="{% url 'user-profile' request.user.id %}">@{{room.host.username}}</a>    

最新更新