Django 2.0 - Urls Amigavel

0

I'm studying Django 2.0.2, and I'm having trouble with friendly URL along with SlugField in the models.py class, but I can not set def get_absolute_url(self): correctly. I can access the URL directly. It is now necessary to define the function in the models class to work. can anybody help me? Below is the url of my app.

from django.urls import include, path, re_path
from simplemooc.courses import views

app_name='courses'

urlpatterns = [
    path('', views.index, name='index'),
    re_path('(?P<slug>[\w-]+)/$', views.details, name='details'), 
]

I also looked in the Django documentation, but I still did not understand: URL Dispatcher

a>.

    
asked by anonymous 20.02.2018 / 23:09

1 answer

1

Only a small setting in re_path , add ^ to indicate start of regex and mark the regex string with r :

re_path(r'^(?P<slug>[\w-]+)/$', views.details, name='details'), 

In your model, you can use reverse to return the URL in the get_absolute_url() method:

models.py

from django.urls import reverse
from django.db import models

class ModelName(models.Model):
    slug = models.SlugField()
    # outros campos...

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

Where details is the name of your URL.

    
21.02.2018 / 20:20