赞
踩
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})}
# Page for adding a new topic.
re_path('^new_topic/$', views.new_topic, name='new_topic'),
# Page for adding a new entry.
re_path('^new_entry/(?P<topic_id>\d+)/$', views.new_entry, name='new_entry'),
from django.shortcuts import render from django.http import HttpResponseRedirect, Http404 from django.urls import reverse from .models import Topic, Entry from .forms import TopicForm, EntryForm def new_topic(request): """Add a 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 HttpResponseRedirect(reverse('learning_logs: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(): form.save() return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic_id])) # context = {'topic': topic, 'form': form, 'topic_id': topic_id} context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context)
<a href="{% url 'learning_logs:new_topic'%}">Add a new Topic:</a>
<a href="{% url 'learning_logs:new_entry' topic.id %}">Add a new Entry:</a>
Reverse for ‘new_entry’ with no arguments not found. 1 pattern(s) tried: [‘new_entry/(?P<topic_id>\d+)/$’]
分析:反解析‘new_entry’时候未找到没有参数的‘new_entry’,因为views.py中的new_entry(request, topic_id)函数有另外的参数topic_id,说明在调用的时候没有将topic_id的参数传给views.py中的函数,也没有传给urls.py中的re_path()函数。
解决:错误是在topic.html中,在向topic.html中添加new_entry页面链接的时候,未把topic_id参数传递给new_entry的re_path()函数和new_entry(request, topic_id)函数。
错误代码如下:
<a href="{% url 'learning_logs:new_entry'%}">Add a new Entry:</a>
修改后:
<a href="{% url 'learning_logs:new_entry' topic.id %}">Add a new Entry:</a>
进入topic页面点击Add a new Entry链接时候,出现找不到页面的情况:
分析:页面的链接不对
解决:错误是在topic.html中,在%和}多了一个空格,导致超链接解析错误。
错误代码如下:
<a href="{% url 'learning_logs:new_entry' topic.id % }">Add a new Entry:</a>
修改后:
<a href="{% url 'learning_logs:new_entry' topic.id %}">Add a new Entry:</a>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。