danyhiol
danyhiol

Reputation: 669

Create Django slug method

I just started using Django for some time now and i stuck trying to work with slug. I know what they are, but it's dificult for me to define a simple slug and display it on my browser.

Here is the scenario: i've a models.py containing a class book with 3 fields: name, price and Autor. I want to retunr a slug string for name and autor with only hyphens (-) and lowercase letters.

My question is how to achieve this. Using only the model, the views and the html. This is what i've got till now. But don't know how to get it displayed on my 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,)

Upvotes: 2

Views: 337

Answers (2)

Aviah Laor
Aviah Laor

Reputation: 3658

from django.template.defaultfilters import slugify

Add the following to your model:

def save(self,*args,**kwargs):

  self.slug = slugify(self.name)
  return super(Book,self).save(*args,**kwargs)

Then you can use the slug in your 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"

Upvotes: 2

the_unknown_spirit
the_unknown_spirit

Reputation: 2586

You may add this to your models.py file:

def save(self , *args , **kwargs):
    if not self.slug:
        self.slug=slugify(self.name)
        super(Book, self).save(*args, **kwargs)

It worked for me.

Upvotes: 0

Related Questions