python - Create Django slug method -
i started using django time , stuck trying work slug. know are, it's dificult me define simple slug , display on browser.
here scenario: i've models.py containing class book 3 fields: name, price , autor. want retunr slug string name , autor hyphens (-) , lowercase letters.
my question how achieve this. using model, views , html. i've got till now. don't know how displayed on browser(localhost:8000/book_name
)
class book(models.model): name = models.charfield(max_length=100) price = models.integerfield(default=0) autor = models.charfield(max_length=100) slug = models.slugfield(unique=true) @models.permalink def get_absolute_url(self): return 'app:book', (self.slug,)
from django.template.defaultfilters import slugify
add following model:
def save(self,*args,**kwargs): self.slug = slugify(self.name) return super(book,self).save(*args,**kwargs)
then can use slug in urls:
url(r'mybooks/(?p<slug>[-\w]+)/$', views.bookdetailview.as_view(),name='book_details'),
views:
from django.views import generic class bookdetailview(generic.detailview): template_name = "templates/book_detail.html"
Comments
Post a Comment