Django 2.0 - Amigavel Urls

Asked

Viewed 635 times

0

I’m studying Django 2.0.2, and I’m having difficulties in URL friendly together with Slugfield in the models.py class, but I don’t know how to define def get_absolute_url(self): correctly. I can access directly through the URL. Missing now set the function in the models class to work. Could anyone help me? Below 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 at Django’s documentation, but I still don’t understand: URL dispatcher.

1 answer

1


Just a little adjustment in re_path, add the ^ to indicate regex start and mark regex string with r:

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

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

py.models

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.