简体   繁体   中英

How to use slug in URL with generic view?

How can I view a single article by it's headline like so: news/article_name ?

I managed to make it work with numbers ( <int:pk> in urls then access it in template using {% url 'article' article.id %} ) so news/1 actually worked. Instead of using numbers I want to use headlines and can't figure out how.

models.py

class Article(models.Model):
headline = models.CharField(max_length=200)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField()

def __str__(self):
    return self.headline

urls.py

path('<slug:headline>/', views.DetailView.as_view(), name='article'),

views.py

class ArticleView(generic.DetailView):
    model = Article
    template_name = 'news/index.html'
    context_object_name = 'article'
    local_context = {**context, **{'show_comments':False}}

somewhere in article template

<p><a href="{% url 'article' %}">Read more</a></p>

When you used the primary key you had to include that in the URL tag.

{% url 'article' article.id %}

In the same way, you have to include the headline in the URL tag.

{% url 'article' article.headline %}

Note that it might be better to include a separate slug field instead of using headline , so that you get URLs like /news/man-bites-dog instead of /news/Man%20Bites%20Dog

class Article(models.Model):
    headline = models.CharField(max_length=200)
    slug = models.SlugField()

Then you would change the url tag to:

{% url 'article' article.slug %}

Your slug should be a SlugField() . You can use the utility slugify() to generate a url-friendly string based on your headline.

class Article(models.Model):
    headline = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200)
    ... your other fields ...

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

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