首页 > 解决方案 > /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'),
]

感谢您的时间

标签: django

解决方案


你的问题可能在这里:

如果有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,但它可能不存在?只需遵循模板中的逻辑


推荐阅读