В настоящее время я работаю над учебником в книге "Python Cra sh".
Учебное пособие посвящено созданию веб-приложения "Журнал обучения" с Django. Идея приложения состоит в том, чтобы позволить пользователям: 1. создавать «Темы», о которых они узнали 2. добавлять «Записи» в эти Темы, описывая детали, которые они изучили, определяя c для этих тем
I в настоящее время я застрял при создании формы ввода и получаю сообщение об ошибке, когда я запускаю http://127.0.0.1: 8000 / new_entry / 1
NoReverseMatch at /new_entry/1
Reverse for 'topic' with arguments '('',)' not found. 1 pattern(s) tried: ['topics/(?P<topic_id>[0-9]+)/$']
Request Method: GET
Request URL: http://127.0.0.1:8000/new_entry/1
Django Version: 3.0.5
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'topic' with arguments '('',)' not found. 1 pattern(s) tried: ['topics/(?P<topic_id>[0-9]+)/$']
Exception Location: C:\Users\DR\Desktop\learning_log\ll_env\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677
Python Executable: C:\Users\DR\Desktop\learning_log\ll_env\Scripts\python.exe
Python Version: 3.8.2
Python Path:
['C:\\Users\\DR\\Desktop\\learning_log',
'C:\\Program '
'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8.752.0_x64__qbz5n2kfra8p0\\python38.zip',
'C:\\Program '
'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8.752.0_x64__qbz5n2kfra8p0\\DLLs',
'C:\\Program '
'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8.752.0_x64__qbz5n2kfra8p0\\lib',
'C:\\Users\\DR\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0',
'C:\\Users\\DR\\Desktop\\learning_log\\ll_env',
'C:\\Users\\DR\\Desktop\\learning_log\\ll_env\\lib\\site-packages']
Server time: Wed, 15 Apr 2020 19:46:06 +0000
Файл forms.py:
from django import forms
from .models import Topic, Entry
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['text']
labels = {'text': ''}
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
fields = ['text']
labels = {'text': ''}
widgets = {'text': forms.Textarea(attrs={'cols': 80})}
Файл urls.py:
from django.urls import path
from . import views
app_name = "learning_logs"
urlpatterns = [
# --snip--
# Page for adding new entry
path('new_entry/<int:topic_id>', views.new_entry, name='new_entry'),
]
И views.py:
from django.shortcuts import render, redirect
from .models import Topic
from .forms import TopicForm, EntryForm
#--snip
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 redirect('learning_logs:topic', topic_id=topic_id)
# Display a blank or invalid form.
context = {'topic': topic, 'form': form}
return render(request, 'learning_logs/new_entry.html', context)
И, наконец, new_entry. html:
{% extends "learning_logs/base.html" %}
{% block content %}
<p><a href="{% url 'learning_logs:topic' topic_id %}">{{ topic }}</a></p>
<p>Add a new entry:</p>
<form action="{% url 'learning_logs:new_entry' topic.id %}" method='post'>
{% csrf_token %}
{{ form.as_p }}
<button name="submit">Add entry</button>
</form>
{% endblock content %}
И топи c. html:
{% extends "learning_logs/base.html" %}
{% block content %}
<p>Topic: {{ topic }}</p>
<p>Entries:</p>
<p>
<a href="{% url 'learning_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 entries for this topic yet.</li>
{% endfor %}
</ul>
{% endblock content %}
Любая помощь будет высоко ценится!