0
我正在使用Python 2.7和Django 1.10(我的第一個)構建一個應用程序,現在我無法使用產品詳細信息頁面的slugs創建鏈接。Python/Django:在URL中使用Slug時遇到問題
當我手動輸入產品URL時,它工作正常(/ courses/analise-swot /)。它讀取details.html頁面並使用數據庫中的信息進行適當構建。下面是我收到的錯誤:
Page not found (404)
Request Method: GET
Request URL:
Using the URLconf defined in simplemooc.urls, Django tried these URL patterns, in this order:
^ ^$ [name='home']
^ ^contato/ [name='contato']
^courses/ ^$ [name='cursos']
^courses/ ^(?P<slug>[A-Za-z0-9_\-]+)/$ [name='details']
^admin/
^media\/(?P<path>.*)$
The current URL, courses/(u'details',(), {u'slug': u'analise-swot'}), didn't match any of these.
這裏是我的代碼:
類,我創建models.py的毛坯:在models.py
class Course(models.Model):
name = models.CharField('Nome', max_length=100)
slug = models.SlugField('Atalho', max_length=100, unique=True)
get_absolute_url方法:
def get_absolute_url(self):
return ('details',(), {'slug': self.slug})
整個urls.py:
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^$', views.cursos, name='cursos'),
url(r'^(?P<slug>[A-Za-z0-9_\-]+)/$', views.details, name='details'),
請求在views.py:
def details(request, slug):
courses = get_object_or_404(Course, slug=slug)
context = {
'course': courses
}
template_name = 'courses/details.html'
return render(request, template_name, context)
非常感謝!你的建議奏效了!我這樣寫: def get_absolute_url(self): return「/ courses /%s /」%self.slug –