简体   繁体   English

python 速成课程学习日志项目没有反向匹配错误

[英]No Reverse Match error for python crash course learning logs project

I am following the book Python Crash Course and am trying to do the Learning Logs app for Django.我正在关注 Python Crash Course 这本书,并正在尝试为 Django 做学习日志应用程序。 Everything was going well except when I tried to add entry forms for users on chapter 19. I am encountering the error一切都很顺利,除非我尝试在第 19 章为用户添加条目 forms。我遇到了错误

Reverse for 'new_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['new_entry/(?P<topic_id>[0-9]+)/$']

My models.py look like this:我的 models.py 看起来像这样:

from django.db import models

# Create your models here.
class Topic(models.Model):
    """A topic the user is learning about"""
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        """Return a string representation of the model."""
        return self.text

class Entry(models.Model):
    """Something specific learned about a topic"""
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'entries'

    def __str__(self):
        """Return a string representation of the model."""
        return self.text[:50] + "..."

My urls.py:

"""Defines url patterns for learning_logs"""

from django.urls import path

from . import views

urlpatterns = [
    # Homepage
    path('', views.index, name='index'),
    path('topics/', views.topics, name='topics'),
    #Detail page for single topic
    path('topics/<int:topic_id>/', views.topic, name='topic'),
    #page for adding a new topic
    path('new_topic', views.new_topic, name='new_topic'),
    #page for adding a new entry
    path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'),
]

my views.py:我的意见.py:

from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse

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


def index(request):
    """The homepage 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)

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

    context = {'form': form}
    return render(request, 'learning_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_valid():
            new_entry = form.save(commit=False)
            new_entry.topic = topic
            new_entry.save()
            return HttpResponseRedirect(reverse('topic', args=[topic_id]))

    context = {'topic': topic, 'form': form, 'topic_id':topic_id}
    return render(request, 'learning_logs/new_entry.html', context)

my new_entry.html:我的 new_entry.html:

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

{% block content %}

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

<p>Add a new entry:</p>

<form action="{% url 'new_entry' topic.id %}" method='post'>
    {% csrf_token %}
    {{ form.as_p }}
    <button name='submit'>add entry</button>
</form>

{% endblock content %}

my base.html:我的基地.html:

<p>
    <a href="{% url 'index' %}">Learning Log</a> -
    <a href="{% url 'topics' %}">Topics</a>
</p>

{% block content %}{% endblock content %}

index.html:索引.html:

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

{% block content %}
<p>Learning Log helps you keep track of your learning, for any topic you're learning about. </p>
{% endblock content %}

my topics.html:我的主题。html:

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

{% block content %}
<p>Topics</p>

<ul>
    {% for topic in topics %}
        <li>
            <a href="{% url 'topic' topic.id %}">{{ topic }}</a>
        </li>
    {% empty %}
        <li>No topics have been added yet.</li>
    {% endfor %}
</ul>

<a href="{% url 'new_topic' %}">Add a new topic</a>

{% endblock content %}

my new_topic.html:我的 new_topic.html:

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

{% block content %}
<p>Topics</p>

<ul>
    {% for topic in topics %}
        <li>
            <a href="{% url 'topic' topic.id %}">{{ topic }}</a>
        </li>
    {% empty %}
        <li>No topics have been added yet.</li>
    {% endfor %}
</ul>

<a href="{% url 'new_topic' %}">Add a new topic</a>

{% endblock content %}

my topic.html:我的主题。html:

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

{% block content %}

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

<p>Entries:</p>
<p>
    <a href="{% url '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 entries for this topic yet.
    </li>
{% endfor %}
</ul>

{% endblock content %}

I'm not sure what's going on.我不确定发生了什么事。 I DID read on the existing threads and followed some suggestions stating that I needed to add 'topic_id':topic on context or provide arguments, and so on, but nothing seems to work.我确实阅读了现有线程并遵循了一些建议,说明我需要在上下文中添加'topic_id':topic或提供 arguments 等等,但似乎没有任何效果。 If you would be kind enough to give me an idea of what's going on I would appreciate it.如果您愿意让我了解正在发生的事情,我将不胜感激。

Try to change this line as:尝试将此行更改为:

<form action="{% url 'new_entry' topic_id=topic.id %}" method='post'>

In your topic.html you have:在你的topic.html你有:

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

But you have never passed any topic_id in the context, although you have passed the topic so you can change it to:但是您从未在上下文中传递过任何 topic_id,尽管您已经传递了主题,因此您可以将其更改为:

<a href="{% url 'new_entry' topic.id %}">add new entry</a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM