简体   繁体   中英

Python/Django: Trouble using Slug in URL

I'm building an application using Python 2.7 and Django 1.10 (my first one), and right now I'm having trouble to create the links using slugs for a product detail page.

When I manually type the product URL it works fine (/courses/analise-swot/). It reads the details.html page and builds it appropriately using the information from the database. Here are the errors I'm getting:

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.

Here is my code:

class where I create the slug in 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 method in models.py:

def get_absolute_url(self):
    return ('details', (), {'slug': self.slug})

entire 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'),

request in 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)

The get_absolute_url method should not return a tuple.

Define a get_absolute_url() method to tell Django how to calculate the canonical URL for an object. To callers, this method should appear to return a string that can be used to refer to the object over HTTP.


Something like the following will be more like it:

def get_absolute_url(self):
    return '/%s/' % self.slug

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM