📅  最后修改于: 2023-12-03 15:35:00.743000             🧑  作者: Mango
If you're a Django developer, you're probably familiar with the concept of URLs. They're the addresses that map to specific views in your web application.
But have you heard of slug URLs? They're a specific type of URL that can make your application more user-friendly and search-engine friendly.
In this guide, we'll cover everything you need to know about slug URLs in Django, including:
Slug URLs are a type of URL that use human-readable text instead of a unique identifier or database ID. For example, instead of a URL like https://example.com/product/1234/
, you might have a URL like https://example.com/product/awesome-product/
.
The "awesome-product" part of the URL is known as the slug. Slugs are typically generated from the title or name of the content being displayed, and they're meant to be more user-friendly and search engine friendly.
There are several reasons you might want to use slug URLs in your Django application:
To generate a slug in Django, you can use the slugify()
function from the django.utils.text
module. This function takes a string and converts it to a URL-friendly slug.
from django.utils.text import slugify
title = "Awesome Product"
slug = slugify(title)
print(slug) # "awesome-product"
You can also use the slugify()
function in your Django models to generate slugs automatically. For example:
from django.db import models
from django.utils.text import slugify
class Product(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save(*args, **kwargs)
In this example, the slug
field will automatically be generated based on the title
field.
Once you've generated a slug, you can use it in your Django views and templates to generate URLs.
In your views, you can use the reverse()
function with the slug as an argument to generate a URL.
from django.urls import reverse
def product_detail(request, slug):
product = Product.objects.get(slug=slug)
# ...
url = reverse("product_detail", args=[product.slug])
# url will be "/product/awesome-product/"
In your templates, you can use the url
template tag with the slug as an argument to generate a URL.
<a href="{% url "product_detail" product.slug %}">{{ product.title }}</a>
Here are some best practices for using slug URLs in your Django project:
By following these best practices, you can ensure that your slug URLs are user-friendly, search-engine friendly, and consistent.