[PYTHON] Benefits of using slugfield in Django's model

Django is good! : relaxed:

thumbs up! about it. There was an article that mentioned what slug looks like in Django, but why should you use the slug feature in Django? How is it written? There seems to be no article that touches on that point, so I decided to write it.

What is slug? : rolling_eyes:

In conclusion, the reason for using slug is for SEO measures, but let's first explain about slug.

In the glossary in the Django Document, slug is explained as follows.

Slug A short label attached to an element, consisting of the English alphabet, numbers, underscores, and hyphens, usually used in URLs. For example, in the URL of a common blog entry: https://www.djangoproject.com/weblog/2008/apr/12/spring/ The string (spring) at the end is the slug. Glossary

I think it's okay to recognize that you want to add a specific wording to the end of the URL.

So what are the benefits of using slug with Django? : thinking:

As one of Google's official guidelines has the following title and wording, Google prefers simple URLs! It's also a guy who can predict the contents of the page from the address! It is recommended to have certain rules for URLs.

Keep the URL structure of your site as simple as possible. Classify your content so that you can construct URLs in a logical and human-understandable way (using meaningful words instead of IDs when possible). For example, if you're looking for information about an aircraft, a URL like http://en.wikipedia.org/wiki/Aviation will tell you if it's what you need just by looking at it. I can do it. http://www.example.com/index.php?id_sezione=360&sid=3a5ebc944f Keep the simple URL structure (https://support.google.com/webmasters/answer/76329?hl=ja)

There are other guidelines for SEO measures (whether each browser is supported, whether HTTPS is implemented, etc.), but as one element, make the URL simple and clear what page you are viewing. That is an important factor in taking SEO measures.

In other words https://www.djangoproject.com/articles/1 than, https://www.djangoproject.com/articles/1/introduction It can be said that a shape like this is preferable.

When building a blog with Django, you can use it as a description of the content of the article by providing a slug instead of ending the article id. It's built into Django from the beginning, so it's better to use it as an SEO measure.

How to write a slug in Django? : pencil2:

For example, when writing a model for an article, write as follows.

models.py


from django.db import models
from django.template.defaultfilters import slugify # new
from django.urls import reverse

class Article(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField()
    slug = models.SlugField(null=False, unique=True)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('article_detail', kwargs={'slug': self.slug})

    def save(self, *args, **kwargs): # new
        if not self.slug:
            self.slug = slugify(self.title)
        return super().save(*args, **kwargs)

As with CharField, you can also specify max_length, which will be 50 characters if max_length is not specified. Implicitly set Field.db_index to True.

views.py


from django.views.generic import ListView, DetailView

from .models import Article

class ArticleListView(ListView):
    model = Article
    template_name = 'article_list.html'


class ArticleDetailView(DetailView):
    model = Article
    template_name = 'article_detail.html'

urls.py


from django.urls import path

from .views import ArticleListView, ArticleDetailView

urlpatterns = [
    path('<slug:slug>', ArticleDetailView.as_view(), name='article_detail'), # new
    path('', ArticleListView.as_view(), name='article_list'),
]

admin.py


from django.contrib import admin

from .models import Article

class ArticleAdmin(admin.ModelAdmin):
    list_display = ('title', 'body',)
    prepopulated_fields = {'slug': ('title',)} # new

admin.site.register(Article, ArticleAdmin)

article_list.html


<h1>Articles</h1>
{% for article in object_list %}
  <ul>
    <li><a href="{{ article.get_absolute_url }}">{{ article.title }}</a></li>
  </ul>
{% endfor %}

article_detail.html


<div>
  <h2>{{ object.title }</h2>
  <p>{{ object.body }}</p>
</div>

Recommended Posts

Benefits of using slugfield in Django's model
Benefits of refining Django's Model
Benefits and examples of using RabbitMq
Limit Views using Django's Permission model
Image recognition model using deep learning in 2016
Sum of variables in a mathematical model
What is on_delete used in django's model?
Meaning of using DI framework in Python
Make any key the primary key in Django's model
Make inferences using scikit-learn's trained model in PySpark
Summary of Excel operations using OpenPyXL in Python
[Python] Implementation of clustering using a mixed Gaussian model
Specify the lighting Model of SCN Material in Pythonista
Maximum likelihood estimation implementation of topic model in python
Basics of I / O screen using tkinter in python3
A list of stumbling blocks in Django's image upload
Model using convolutional neural network in natural language processing
Two-dimensional visualization of document vectors using Word2Vec trained model
Variational Bayesian inference implementation of topic model in python
Ssh connection memo using ProxyCommand of ssh_config in Python
Model changes in Django
Example of using lambda
Implementation of VGG16 using Keras created without using a trained model
Prediction model of human body movement using one coin sensor
I tried refactoring the CNN model of TensorFlow using TF-Slim
A memo of writing a basic function in Python using recursion
Create an easy-to-use follow model in Django using ManyToManyField through