【发布时间】:2022-07-04 22:38:35
【问题描述】:
请有人帮忙,我是 Django 新手,不知道如何在我的代码中解决这个问题。我正在关注一个教程,它用 Django 构建了一个聊天室。一切正常,但后来我想修改它并在他们的个人资料页面上显示用户写的帖子,以便其他人可以看到它,但是我收到了这个错误'NoReverseMatch at / 未找到带有参数 '('',)' 的 'user-profile' 的反向操作。尝试了 1 种模式:['profile/(?P[^/]+)/$']
这是我的视图文件;
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>
【问题讨论】:
-
这是典型的错误消息,如果您的情况下 url 的参数为空,请检查 room.id 是否为空
-
感谢您的贡献伙伴