Slugfield django что это
Перейти к содержимому

Slugfield django что это

SlugField — Модели Django

Слаг — это, по сути, короткая метка для чего-либо, содержащая только буквы, цифры, символы подчеркивания или дефисы. Обычно они используются в URL-адресах. Например, в типичном URL-адресе записи в блоге:

Here, the last data add-the-slug-field-inside-django-model is the slug.

SlugField :

SlugField in Django is like a CharField, where you can specify max_length attribute also. If max_length is not specified, Django will use a default length of 50. It also implies setting Field.db_index to True.It is often useful to automatically prepopulate a SlugField based on the value of some other value.It uses validate_slug or validate_unicode_slug for validation.

Синтаксис

У SlugField есть следующие необязательные аргументы:

The maximum length (in characters) of the field. The max_length is enforced at the database level and in Django’s validation using MaxLengthValidator.

Если True, поле принимает буквы Unicode в дополнение к буквам ASCII. По умолчанию False.

Описание SlugField модели Django

Illustration of SlugField using an Example. Consider a project named geeksforgeeks having an app named geeks .

What is a "slug" in Django?

When I read Django code I often see in models what is called a «slug». I am not quite sure what this is, but I do know it has something to do with URLs. How and when is this slug-thing supposed to be used?

(I have read its definition in this glossary.)

13 Answers 13

A «slug» is a way of generating a valid URL, generally using data already obtained. For instance, a slug uses the title of an article to generate a URL. I advise to generate the slug by means of a function, given the title (or another piece of data), rather than setting it manually.

Now let’s pretend that we have a Django model such as:

How would you reference this object with a URL and with a meaningful name? You could for instance use Article.id so the URL would look like this:

Or, you might want to reference the title like this:

Since spaces aren’t valid in URLs, they must be replaced by %20 , which results in:

Both attempts are not resulting in very meaningful, easy-to-read URL. This is better:

In this example, the-46-year-old-virgin is a slug: it is created from the title by down-casing all letters, and replacing spaces by hyphens — .

Also see the URL of this very web page for another example.

If I may provide some historical context :

The term «slug» has to do with casting metal—lead, in this case—out of which the press fonts were made. Every paper then had its fonts factory regularly re-melted and recast in fresh molds, since after many prints they became worn out. Apprentices like me started their career there, and went all the way to the top (not anymore).

Typographs had to compose the text of an article in a backward manner with lead characters stacked in a wise. So at printing time the letters would be straight on the paper. All typographs could read the newspaper mirrored as fast as the printed one. Therefore the slugs, (like snails) also the slow stories (the last to be fixed) were many on the bench waiting, solely identified by their fist letters, mostly the whole title generally more readable. Some «hot» news were waiting there on the bench, for possible last minute correction, (Evening paper) before last assembly and definitive printing.

Django emerged from the offices of the Lawrence journal in Kansas. Where probably some printing jargon still lingers. A-django-enthusiast-&-friendly-old-slug-boy-from-France.

The term ‘slug’ comes from the world of newspaper production.

It’s an informal name given to a story during the production process. As the story winds its path from the beat reporter (assuming these even exist any more?) through to editor through to the «printing presses», this is the name it is referenced by, e.g., «Have you fixed those errors in the ‘kate-and-william’ story?».

Some systems (such as Django) use the slug as part of the URL to locate the story, an example being www.mysite.com/archives/kate-and-william .

Even Stack Overflow itself does this, with the GEB-ish (a) self-referential https://stackoverflow.com/questions/427102/what-is-a-slug-in-django/427201#427201 , although you can replace the slug with blahblah and it will still find it okay.

It may even date back earlier than that, since screenplays had «slug lines» at the start of each scene, which basically sets the background for that scene (where, when, and so on). It’s very similar in that it’s a precis or preamble of what follows.

On a Linotype machine, a slug was a single line piece of metal which was created from the individual letter forms. By making a single slug for the whole line, this greatly improved on the old character-by-character compositing.

Although the following is pure conjecture, an early meaning of slug was for a counterfeit coin (which would have to be pressed somehow). I could envisage that usage being transformed to the printing term (since the slug had to be pressed using the original characters) and from there, changing from the ‘piece of metal’ definition to the ‘story summary’ definition. From there, it’s a short step from proper printing to the online world.

(a) «Godel Escher, Bach», by one Douglas Hofstadter, which I (at least) consider one of the great modern intellectual works. You should also check out his other work, «Metamagical Themas».

Создание ЧПУ используя slug во фреймворке Python Django

Создание человеко понятных URL в Python Django со slug

Slug — это тип поля в Django для создания понятных URL на латинице. С помощью его мы можем автоматически конвертировать нашу запись, например с заголовком:

В этой статье будет рассмотрен пример автоматического создания такой возможности.

Навигация по посту

Создание модели

В модели обязательно должно находится текстовое поле, на которое будет создаваться slug. В основном это тег "<title>" или "<h1>". Для примера моя модель в models.py выглядит так:

Если не указать максимальную длину поля для SlugField, то оно будет равно 50. По умолчанию, для SlugField создается не кластерный индекс так как "db_index=True".

При этом вы не сможете создать ЧПУ на основе полей: DateTimeField, ForeignKey, OneToOneField, ManyToManyField.

Если есть вероятность того, что поле для создания slug может дублироваться — лучше установить требование к уникальности так как по умолчанию этого не делается:

Не забудьте выполнить миграцию:

Создание первого приложения во фреймворке Python Django 3

Регистрация в admin.py

В файле admin.py мы регистрируем нашу модель для отображения в панели администрирования через атрибут 'prepopulated_fields'. Мой 'slug' будет основан на 'title':

Теперь, при заполнении заголовка в панели администрирования будет срабатывать JavaScript конвертирующий кириллицу в ASCII.

Создание ЧПУ в Django 3 с использованием prepopulated_fields

Повторное редактирование заголовка у созданной новости не будет изменять slug.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *