Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Intermediate fields in Django | Python
Next article icon

Add the slug field inside Django Model

Last Updated : 11 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The slug field within Django models is a pivotal step for improving the structure and readability of URLs in web applications. This addition allows developers to automatically generate URL-friendly slugs based on titles, enhancing user experience and search engine optimization (SEO). By implementing this feature, you can create cleaner, more meaningful, and SEO-friendly URLs for your content, which is essential for attracting and retaining website visitors.

Slug field in Django

Let’s assume our blog has a post with the title ‘The Django book by Geeksforgeeks’ with primary key id= 2. We might refer to this post with 

www.geeksforgeeks.org/posts/2. 

Or, we can reference the title like

 www.geeksforgeeks.org/posts/The Django book by Geeksforgeeks. 

But the problem is spaces are not valid in URLs, they need to be replaced by %20 which is ugly, making it the following 

www.geeksforgeeks.org/posts/The%20Django%20book%20by%20geeksforgeeks 

But it is not solving meaningful URL. Another option can be

 www.geeksforgeeks.org/posts/the-django-book-by-geeksforgeeks

So, the slug is now the-django-book-by-geeksforgeeks. All letters are down cased and spaces are replaced by hyphens –

Adding Slug field in Django Models

The slug field, represented as models.SlugField in Django models, is used to store a URL-friendly version of a text-based field, such as a title. Its primary purpose is to create cleaner, more readable, and search engine-friendly URLs for your content.

Python3




STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
  
class Post(models.Model):
title = models.CharField(max_length = 250)
slug = models.SlugField(max_length = 250, null = True, blank = True)
text = models.TextField()
published_at = models.DateTimeField(auto_now_add = True)
updated = models.DateTimeField(auto_now = True)
  
status = models.CharField(max_length = 10, choices = STATUS_CHOICES,
                                                    default ='draft')
  
  
class Meta:
    ordering = ('-published_at', )
  
def __str__(self):
    return self.title
 
 

Adding Slugify to our Project

Now we need to find a way to convert the title into a slug automatically. We want this script to be triggered every time a new instance of Post model is created. For this purpose, we will use signals.

Note: Add new file util.py in the same directory where settings.py file is saved. 

Python3




import string, random
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.utils.text import slugify
  
def random_string_generator(size = 10, chars = string.ascii_lowercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))
  
def unique_slug_generator(instance, new_slug = None):
    if new_slug is not None:
        slug = new_slug
    else:
        slug = slugify(instance.title)
    Klass = instance.__class__
    max_length = Klass._meta.get_field('slug').max_length
    slug = slug[:max_length]
    qs_exists = Klass.objects.filter(slug = slug).exists()
      
    if qs_exists:
        new_slug = "{slug}-{randstr}".format(
            slug = slug[:max_length-5], randstr = random_string_generator(size = 4))
              
        return unique_slug_generator(instance, new_slug = new_slug)
    return slug
 
 

Signals in Django

In many cases when there is a modification in a model’s instance we need to execute some action. Django provides us with an elegant way to handle these situations. The signals are utilities that allow associating events with actions. We can develop a function that will run when a signal calls it. 

In models.py file of posts app where Post Model was defined, add this in the same file: 

Python3




@receiver(pre_save, sender=Post)
def pre_save_receiver(sender, instance, *args, **kwargs):
   if not instance.slug:
       instance.slug = unique_slug_generator(instance)
 
 

The pre_save_receiver function should be placed separately outside the Post model.

Modify URL with Slug

To modify your urls.py file to use the slug field in your Django model for generating URLs, you can create URL patterns that include the slug as a parameter. Here’s an example of how to do this:

Python3




from django.urls import path
from . import views
  
urlpatterns = [
    path('posts/<slug:slug>/', views.post_detail, name='post_detail'),
    # Other URL patterns
]
 
 

Modify Views

This `detail` view function in Django takes a `slug` parameter from the URL and searches for a post with a matching slug in a case-insensitive manner. If a post is found, it retrieves and renders the post’s details using the ‘details.html’ template. If no matching post is found, it returns an “Post Not Found” response to inform users of the absence of the requested content.

Note: In urls.py edit detail path with path(‘posts/’, detail). In views.py edit the detail function with 

Python3




def detail(request, slug):
    # Filter posts based on the slug (case-insensitive)
    q = Post.objects.filter(slug__iexact=slug)
  
    if q.exists():
        # If a post with the given slug exists, retrieve the first matching post
        q = q.first()
    else:
        # If no post is found, return an "Post Not Found" response
        return HttpResponse('<h1>Post Not Found</h1>')
  
    # Create a context dictionary containing the retrieved post
    context = {'post': q}
  
    # Render the 'details.html' template with the context
    return render(request, 'posts/details.html', context)
 
 

The last step is to add the link in HTML file <a href=”/posts/{{ a.slug }}” class=”btn btn-primary”>View</a>. Now we are ready to go to 127.0.0.1:8000/posts/title-you-have-added and it will show you the page details.html.



Next Article
Intermediate fields in Django | Python

I

ishwarjangid
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

  • Django Models
    A Django model is the built-in feature that Django uses to create tables, their fields, and various constraints. In short, Django Models is the SQL Database one uses with Django. SQL (Structured Query Language) is complex and involves a lot of different queries for creating, deleting, updating, or a
    10 min read
  • Django ORM - Inserting, Updating & Deleting Data
    Django lets us interact with its database models, i.e. add, delete, modify, and query objects, using a database-abstraction API called ORM(Object Relational Mapper). This article discusses all the functional operations we can perform using Django ORM. Prerequisite: Django models Django ORM Django's
    3 min read
  • Django Basic App Model - Makemigrations and Migrate
    In this article, we will create a basic model of an app and also learn about what are migrations in Django and migrate in Django also develop some basic understanding related to them in Python. Makemigrations and Migrations in DjangoMakemigrations and migrate are commands that are used to interact w
    5 min read
  • Add the slug field inside Django Model
    The slug field within Django models is a pivotal step for improving the structure and readability of URLs in web applications. This addition allows developers to automatically generate URL-friendly slugs based on titles, enhancing user experience and search engine optimization (SEO). By implementing
    4 min read
  • Intermediate fields in Django | Python
    Prerequisite: Django models, Relational fields in DjangoIn Django, a many-to-many relationship exists between two models A and B, when one instance of A is related to multiple instances of B, and vice versa. For example - In a shop management system, an Item and a Customer share a many-to-many relat
    2 min read
  • Python | Uploading images in Django
    In most websites, we often deal with media data such as images, files, etc. In Django, we can deal with the images with the help of the model field which is ImageField. In this article, we have created the app image_app in a sample project named image_upload. The very first step is to add the below
    5 min read
  • Change Object Display Name using __str__ function - Django Models | Python
    How to Change Display Name of an Object in Django admin interface? Whenever an instance of model is created in Django, it displays the object as ModelName Object(1). This article will explore how to make changes to your Django model using def __str__(self) to change the display name in the model. Ob
    2 min read
  • Custom Field Validations in Django Models
    This article revolves around how to add custom validation to a particular field. For example to add validation of an email to a CharField by specifying a particular format. There can be multiple ways on how to achieve custom validation. In this article, we are going to show it from the model itself
    3 min read
  • Meta Class in Models - Django
    Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source. D
    3 min read
  • How to use Django Field Choices ?
    Django Field Choices. According to documentation Field Choices are a sequence consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) ...]) to use as choices for some field. For example, consider a field semester which can have options as { 1, 2, 3, 4, 5, 6 } only. Choices limits t
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences