django - /rubies/users/1/ 的 NoReverseMatch:找不到带有参数“(1,”)的“故事”的反向
问题描述
NoReverseMatch 在 /rubies/users/1/
未找到带有参数“(1,”)的“故事”的反向。尝试了 1 种模式:['rubies/users/(?P[0-9]+)/stories/(?P[0-9]+)/$']
我的故事页面遇到了同样的问题,其中错误
找不到带有参数'(1,'')'的'用户'的反向
上来了。很高兴,有人帮我解决了这个问题。但是,我无法找到解决方案,即使它实际上是相同的。
用户.html
{% extends "rubies/base.html" %}
{% block content %}
<ul class="list-group">
<li class="list-group-item">
Name: {{ user.username }}
</li>
<li class="list-group-item">
<ul>
Stories:
{% if story_id %}
{% for story in user.story.all %}
<li>
<a href="{% url 'rubies:story' user.id story.id %}">{{ story.title }}</a>
</li>
{% endfor %}
{% else %}
{% if current_user == story.author.id %}
<h2 class="bg-warning">You have not written any stories yet.</h2>
<a href="{% url 'rubies:story' user.id story.id %}">
<span class="fas fa-plus-circle" aria-hidden="true"></span>
</a>
{% else %}
<h2 class="bg-warning"> {{ story.author.username }} has not written any stories yet. </h2>
{% endif %}
{% endif %}
</ul>
</li>
</ul>
{% endblock %}
用户视图
def user_view(request, user_id):
if user_id is not None:
user = get_object_or_404(User, pk=user_id)
else:
user = User()
context = {
'user_id': user_id,
'name': user.name,
'surname': user.surname,
'username': user.username,
'password': user.password,
'email': user.email
}
return render(request, 'rubies/user.html', context)
网址.py
from django.urls import path
from rubies import views
from django.contrib.auth import views as auth_views
app_name = 'rubies'
urlpatterns = [
path('', views.index_view, name='index'),
path('register/', views.register_view, name='register'),
path('login/', auth_views.LoginView.as_view(), name='login'),
path('users/<int:user_id>/', views.user_view, name='user'),
path('users/<int:user_id>/stories/<int:story_id>/', views.story_view, name='story'),
path('users/<int:user_id>/new_story/', views.story_view, name='new_story'),
]
感谢您的时间
解决方案
你的问题可能在这里:
如果有story_id,这里的代码就会运行
<ul>
Stories:
{% if story_id %}
....
如果没有story_id,这里的代码就会运行
{% else %}
<a href="{% url 'rubies:story' user.id story.id %}">
<span class="fas fa-plus-circle" aria-hidden="true"></span>
{% endif %}
</ul>
在 else 中,您尝试创建一个带有story.id的 url,但它可能不存在?只需遵循模板中的逻辑
推荐阅读
- firebase - 为什么我在尝试创建受众时遇到错误?
- java - 在输入之间迭代时如何对 tjavaflex 组件中插入的行求和?
- sql - 需要所有匹配的值和不匹配的连接
- c++ - 存储向量的值
> 单独容器上的元素 - postgresql - laravel:插入数据库后如何返回多列?
- node.js - 模拟时钟偏差场景
- django - 如何 order_by ini views.py Django by user.first_name
- r - 如何在 sparklyr 中创建垃圾箱?
- sql - SQL Date 仅显示日期而不显示 YYYY MM DD
- ios - Swift 4.2 Make bottom of tableView move up when keyboard shows