我正在使用书籍" Tango with Django "。使用相对网址时出现问题。
很快
这个:<a href="{% url 'rango:add_page' rango:category.slug %}">Add a Page</a>
结果为:http://127.0.0.1:8000/rango/category//add_page/
rango / views.py 中的功能:
def show_category(request,category_name_slug):
context_dict= {}
try:
category=Category.objects.get(slug=category_name_slug)
pages = Page.objects.filter(category=category)
context_dict['pages']=pages
context_dict['category']=category
except Category.DoesNotExist:
context_dict['category']= None
context_dict['pages'] = None
return render(request,'rango/category.html',context_dict)
def add_page(request,category_name_slug):
try:
category = Category.objects.get(slug=category_name_slug)
except Category.DoesNotExist:
category = None
form=PageForm()
if request.method=='POST':
form = PageForm(request.POST)
if form.is_valid():
if category:
page = form.save(commit=False)
page.category = category
page.views = 0
page.save()
return show_category(request, category_name_slug)
else:
print(form.errors)
context_dict = {'form': form, 'category': category}
return render(request,'rango/add_page.html',context_dict)
rango / urls.py :
from django.conf.urls import url
from rango import views
app_name = 'rango'
urlpatterns =[
url(r'^$',views.index ,name='index'),
url(r'^about/$',views.about , name = 'about'),
url(r'^add_category/$',views.add_category,name='add_category'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/?$',views.show_category,name='show_category'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/add_page/?$', views.add_page, name='add_page'),
]
尝试使用 rango 命名空间,如:'rango:add_page'
,
和
<a href="/rango/category/{{ category_name_slug }}/add_page/">Add a Page</a>
和
<a href="/rango/category/{{ category.slug }}/add_page/">Add a Page</a>
,但它没有帮助我。