python - 将多个 id 传递到 url Django

标签 python html django

您好,我正在尝试将用户发送回 html 文件,但是当我在 View 函数中使用以下代码时:

def delete_topic(request, topic_id):
    """ Delete Topic """
    topic = Topic.objects.get(id=topic_id)
    topic.delete()
    return HttpResponseRedirect(reverse('blogging_logs:topics'))

它给了我一个 NoReverseMatch 错误,我似乎不明白为什么。我注意到我的主题 View 函数需要category_id,但我不知道如何传递多个id。

enter image description here

这是我的主题 View

def topics(request, category_id):
    """Show all topics for a single category"""
    category = Category.objects.get(id=category_id)  # get category that was requested
    topics = category.topic_set.all()  # get all topics associated with category that was requested
    context = {'category': category, 'topics': topics}
    return render(request, 'blogging_logs/category.html', context)

这是使用delete_topics def 的html 页面。 topic.html

{% block content %}
<h3>{{ topic }}</h3>
  {% for entry in entries %}
      <p>{{ entry.text|linebreaks }}</p>
    {% empty %}
      <li>No entry entered yet!</li>
    {% endfor %}

    <a href="{% url 'blogging_logs:entry' topic.id %}"> Add entry </a>
    <a href="{% url 'blogging_logs:delete_topic' topic.id %}">Delete Topic</a>
{% endblock content %}

我尝试将第二个 ID (category.id) 添加到 topic.html 中的 URL (delete_topic),但出现错误。我假设我的错误是它没有获取将用户发送回主题页面所需的类别 ID。

最佳答案

首先,您不需要多个 ID,只需要类别 ID。

其次,您需要将其添加到Python代码中而不是模板中:

 return HttpResponseRedirect(reverse('blogging_logs:topics', args=(topic.category_id)))

关于python - 将多个 id 传递到 url Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52028942/

相关文章:

os.environ 变量的 Python 3.6 Lambda 代码错误

html - 蜜 jar 字段破坏整个页面

CSS:没有边距黑客的等高div

python - 比 locals() 或 dict(foo=foo) 更好的东西用于将上下文导出到模板引擎

python - Django 获取外键整个对象而不仅仅是 id(主键)

python - 期待 ValueError : too many values to unpack but getting TypeError: 'bool' object is not iterable

python - 我该如何将StringVar()放入StringVar()中?

python - Unicode解码错误: 'ascii' codec can't decode byte 0x96 in position 0

html - 当下拉列表更改其内容时,带下拉列表的表不会在 IE 7 中调整大小

django - 在 Gunicorn 超时时转储 Django 堆栈跟踪