我需要一些幫助才能讓add_page函數正常運行。我已經做了大部分的一部分,但是當我嘗試點擊,使新的一頁我無意中發現錯誤404,我的URL看起來像這樣:http://127.0.0.1:8000/rango/category//add_page探戈與Django練習8.3.1 - 添加頁面
編輯:可以鍛鍊這裏的說明:http://www.tangowithdjango.com/book17/chapters/forms.html#creating-an-add-pages-view-template-and-url-mapping
相關文件:
urls.py
from django.conf.urls import patterns, url
from rango import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='about'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/$', views.category, name='category'),
url(r'^add_category/$', views.add_category, name='add_category'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/add_page/$', views.add_page, name='add_page'),
)
add_page.html
<!DOCTYPE html>
<html>
<head>
<title>Rango</title>
</head>
<body>
<h1>Add page</h1><br/>
<form id="page_form" method="POST" action="/rango/category/{{category_name_slug}}/add_page/">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<input type="submit" name="submit" value="Create Page" />
</form>
</body>
</html>
views.py
def add_page(request, category_name_slug):
try:
cat = Category.objects.get(slug=category_name_slug)
except Category.DoesNotExist:
cat = None
# A HTTP POST?
if request.method == 'POST':
form = PageForm(request.POST)
if form.is_valid():
if cat:
page = form.save(commit=False)
page.category = cat
page.views = 0
page.save()
return category(request, category_name_slug)
else:
print form.errors
else:
form = PageForm()
context_dict = {'form':form, 'category': cat, 'category_name_slug': category_name_slug}
return render(request, 'rango/add_page.html', context_dict)
category.html
<!DOCTYPE html>
<html>
<head>
<title>Rango</title>
</head>
<body>
{%if category %} <!-- If category is defined we proceed to check pages -->
<h1>{{ category_name }}</h1>
{% if pages %}
<ul>
{% for page in pages %}
<li><a href="{{ page.url }}">{{ page.title }}</a></li>
{% endfor %}
</ul><br/>
<strong>Would you like to add more </strong>
<a href="/rango/category/{{ category_name_slug }}/add_page/">pages</a>
<strong>?</strong>
{% else %}
<strong>No pages currently in category. Would you like to </strong>
<a href="/rango/category/{{ category_name_slug }}/add_page/">make one</a>
<strong>?</strong>
{% endif %}
{% else %} <!-- If category is not defind an error message tells us so! -->
The specified category {{ category_name }} does not exist!
{% endif %}
</body>
</html>
我發現已經simmilar問題的線程,但它並沒有解決我的問題。任何幫助,將不勝感激,
亞歷
我仍然沒有找到修復,如果有人這樣做,我會很高興看到它 – narn