简体   繁体   中英

django slug works for one word but when it's more than one words it collapses

With a small word like "cool" it works but if it's like "not cool" then it doesn't work because slug makes it not-cool.

path('<slug>/', views.series_pg, name='series_detail'),
#MODELS.PY    
class Series(models.Model):
    name = models.CharField(max_length=128, unique=True)
    genre = models.CharField(max_length=128, default=1)
    tv_or_movie = models.CharField(max_length=128, default=1)
    period = models.CharField(max_length=128, default=1)
    descritpion = models.TextField()
    slug = models.SlugField(unique=True)



    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return "/%s/" %self.slug

#VIEWS.PY
def series_pg(request, slug):
    series = Series.objects.get(name=slug)

If slug changes the original word then it doesn't work

EDIT:

My error is

DoesNotExist at /office/ Series matching query does not exist.

I added "The Office" but slug makes it office

Django slug field works like if you give value not cool then it's slugify this to not-cool .

In your views.py you want to filter by name . Say in the name it has the value not cool but in slugfield, you keep the value not-cool . Then you try to filter it out by .get(name=slug) that means .get(not cool=not-cool) . So the queryset doesn't return any matching object and doesn't match with the URL.

You can do it

def series_pg(request, slug):
    series = Series.objects.get(slug=slug)

"A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They're generally used in URLs."

-Django Documentation

What context are you using the Slug Field? It will convert spaces like "not cool" to "not-cool" because that's its purpose.

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