【问题标题】:TemplateSyntaxError during Template rendering模板渲染期间的 TemplateSyntaxError
【发布时间】:2023-03-06 07:51:01
【问题描述】:

这里是 Python/Django 初学者 - 我收到此错误:

使用参数 '('',)' 和关键字参数 '{}' 反转 'topic' 未找到。尝试了 1 种模式:['topics/(?P\d+)/$']

尝试加载我的模板时。 这是我的模板:

{% extends "learning_logs/base.html" %}

{% block content %}

<p>Topics</p>

<ul>
{% for topic in topics %}
  <li>
    <a href="{% url 'learning_logs:topic' topic_id %}">{{ topic }}</a>
  </li>
{% empty %}
  <li>No topics for now</li>
{% endfor %}
</ul>

{% endblock content %}

这是我的观点.py

from django.shortcuts import render
from .models import Topic

# Create your views here.
def index(request):
    '''Home page for learning log'''
    return render(request, 'learning_logs/index.html')

def topics(request):
    '''Show all topics'''
    topics = Topic.objects.order_by('date_added')
    context = {'topics': topics}
    return render(request, 'learning_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, 'learning_logs/topic.html', context)

我已经有一段时间了,在这里阅读了一些以前的答案,但它们都与 auth/login 不起作用有关。还尝试按照一些答案的建议删除 url 后的 '' ,但它没有用。我正在使用 Python Crash Course: A Hands-On, Project-Based Introduction to Programming 作为我的教程。

任何帮助将不胜感激。

最后,这是我的 urls.py 代码 从 django.conf.urls 导入 url 从 。导入视图

urlpatterns = [
    # Home page
    url(r'^$', views.index, name='index'),  
    url(r'^topics/$', views.topics, name='topics'), 
    url(r'^topics/(?P<topic_id>\d+)/$', views.topics, name='topic'),

【问题讨论】:

    标签: python django python-3.x django-templates django-views


    【解决方案1】:

    根据报错,url标签中有参数传入,但为空:

    带参数的“主题”反转'('',)'...

    这是因为topic_id 变量没有定义。你应该改用topic.id

    <a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a>
    

    【讨论】:

    • @Alezandah 您应该通过单击复选符号来接受此答案,以表明您的问题已解决......并感谢 alex 的努力;)
    猜你喜欢
    • 2017-05-21
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 2020-06-08
    • 2017-01-31
    相关资源
    最近更新 更多