未找到带有参数 '(")' 的 'new_entry' 的反向操作。尝试了 1 个模式:['new_entry'/int:topic_id>/']

问题描述 投票:0回答:1

我在运行程序时收到此错误。据说该错误发生在我的 topic.html 中,但我不确定我输入的内容是否错误,以致 topic_id 返回空字符串。

views.py 从 django.shortcuts 导入渲染,重定向

from .models import Topic
from .forms import TopicForm, EntryForm

在此创建您的观点。

def index(request):
"""The home page for Test log"""
return render(request, 'test_logs/index.html')

def topics(request):
"""Show all topics"""
topics = Topic.objects.order_by('date_added')
context = {'topics': topics}
return render(request, 'test_logs/topics.html', context)

def topic(request, topic_id):
"""Show a single topic and all its entries."""
topic = Topic.objects.get(id=topic_id)
entries = topic.entry_set.order_by('-date_added')
context = {'topic': topic, 'entries': entries}
return render(request, 'test_logs/topic.html', context)

def new_topic(request):
"""Add new topic"""
if request.method != 'POST':
\#No data submitted; create a blank form.
form = TopicForm()
else:
\# POST data submitted; process data.
 form = TopicForm(request.POST)
if form.is_valid():
form.save()
return redirect('test_logs:topics')

context = {'form': form}
return render(request, 'test_logs/new_topic.html', context)

def new_entry(request, topic_id):
"""Add a new entry for a particular topic"""
 topic = Topic.objects.get(id=topic_id)

if request.method != 'POST':
    # No data submitted; create a blank form.
    form = EntryForm()
else:
    # POST data submitted; process data.
    form = EntryForm(data=request.POST)
    if form.is_vaild():
        new_entry = form.save(commit=False)
        new_entry.topic = topic
        new_entry.save()
        return redirect('test_logs:topic', topic_id==topic_id)
        
context = {'topic': topic, 'form': form}
return render(request, 'test_logs/new_entry.html', context)

*new_entry.py*
 {% extends "test_logs/base.html" %}

{% block content %}

{{主题}}

添加新条目:

{% csrf_token %}
{{ form.as_div }}
add entry

{% endblock content %}

我希望在我的主题所在的页面上出现一个新链接,以允许用户在该主题中创建新条目。

*topic.html*
 {% extends 'test_logs/base.html' %}

{% block content %}

\<p\>Topic: {{ topic }}\</p\>

\<p\>Entries:\</p\>

\<p\>
 \<a href="{% url 'test_logs:new_entry' topic_id %}"\>add new entry\</a\>
\</p\>

\<ul\>
 {% for entry in entries %}
 \<li\>
   \<p\>{{ entry.date_added|date:'M d, Y H:i' }}\</p\>
   \<p\>{{ entry.text|linebreaks }}\</p\>
\</li\>
{% empty %}
\<li\>
   There are no entires for this topic yet.
\</li\>
 {% endfor %}
\</ul\>

{% endblock content %}
python django rendering
1个回答
0
投票

在视图代码中,

topic.html
的渲染方式如下:

context = {'topic': topic, 'entries': entries}
return render(request, 'test_logs/topic.html', context)

topic.html
尝试显示此链接时,就会出现问题:

<a href="{% url 'test_logs:new_entry' topic_id %}">add new entry</a>

上下文不包含任何名为

topic_id
的项目,因此它尝试为该变量使用空白字符串。

但是该视图的 url 定义

new_entry/int:topic_id>/
不允许
topic_id
为空。所以它找不到任何匹配的 url 定义。

也许您在 href 链接中指的是

topic.id
,而不是
topic_id

© www.soinside.com 2019 - 2024. All rights reserved.