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

Slugfield django что это

  • автор:

Django Slug Tutorial

In this tutorial we will add slugs to a Django website. As noted in the official docs: «Slug is a newspaper term. A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs.»

To give a concrete example, assume you had a Newspaper website (such as we’ll build in this tutorial). For a story titled «Hello World,» the URL would be example.com/hello-world assuming the site was called example.com .

Despite their ubiquity, slugs can be somewhat challenging to implement the first time around, at least in my experience. Therefore we will implement everything from scratch so you can see how the pieces all fit together. If you are already comfortable implementing ListView and DetailView you can jump right to the Slug section.

Set Up

To start let’s navigate into a directory for our code. This can be hosted anywhere on your computer but an easy-to-find location is the Desktop in a directory called newspaper .

To pay homage to Django’s origin at a newspaper, we’ll create a basic Newspaper website with Articles. If you need help installing Python, Django, and all the rest (see here for in-depth instructions).

On your command line create and activate a virtual environment, install Django, create a new project called django_project , set up the initial database via migrate , and then start the local web server with runserver .

Don’t forget to include that period . at the end of the startproject command! It is an optional step that avoid Django creating an additional directory otherwise.

Navigate to http://127.0.0.1:8000/ in your web browser to see the Django welcome page which confirms everything is configured properly.

Django welcome page

Articles app

Since the focus of this tutorial is on slugs I’m going to simply give the commands and code to wire up this Articles app. Full explanations can be found in my book Django for Beginners!

Let’s start by creating an app called articles . Stop the local server with Control+c and use the startapp command to create this new app.

Then update INSTALLED_APPS within our django_project/settings.py file to notify Django about the app.

Article Model

Create the database model which will have a title and body . We’ll also set __str__ and a get_absolute_url which are Django best practices.

Now create a migrations file for this change, then add it to our database via migrate .

Django Admin

The Django admin is a convenient way to play around with models so we’ll use it. But first, create a superuser account.

And then update articles/admin.py to display our app within the admin.

Start up the server again with python manage.py runserver and navigate to the admin at http://127.0.0.1:8000/admin. Log in with your superuser account.

Admin Homepage

Click on the «+ Add» next to the Articles section and add an entry.

Admin Article

In addition to a model we’ll eventually need a URL, view, and template to display an Article page. I like to move to URLs next after models although the order doesn’t matter: we need all four before we can display a single page. The first step is to add the articles app to our project-level django_project/urls.py file.

Next in your text editor create the app-level articles/urls.py file. We’ll have a ListView to list all articles and a DetailView for individual articles.

Note that we’re referencing two views that have yet to be created: ArticleListView and ArticleDetailView . We’ll add them in the next section.

Views

For each view we specify the related model and appropriate not-yet-created template.

Templates

Finally, we come to the last step: templates. By default Django will look within each app for a templates directory. That structure in our case would be articles/templates/template.html .

Type Control+c on the command line and create the new templates directory.

Then in your text editor add the two new templates: articles/templates/article_list.html and articles/templates/article_detail.html .

For our list page we loop over object_list which is provided by ListView . And we add an a href by using the get_absolute_url method added to the model.

The detail view outputs our two fields— title and body —using the object default provided by DetailView. You can, and probably should, rename both object_list in the ListView and object in the DetailView to be more descriptive.

Make sure the server is running— python manage.py runserver —and check out both our pages in your web browser.

The list of all articles is available at http://127.0.0.1:8000/ .

ListView

And the detail view for our single article is at http://127.0.0.1:8000/1 .

DetailView

Slugs

Finally we come to slugs. Ultimately we want our article title to be reflected in the URL. In other words, «A Day in the Life» should have the URL of http://127.0.0.1:8000/a-day-in-the-life .

There are only two steps required: updating our articles/models.py file and articles/urls.py . Ready? Let’s go.

In our model, we can add Django’s built-in SlugField. But we must also—and this is the part that typically trips people up—update get_absolute_url as well. That’s where we pass in the value used in our URL. Currently it passes in the id for the article an args , so 1 for our first article. We need to change that over to a keyword argument, kwargs , for our slug .

Moving along let’s add a migration file since we’ve updated our model.

Ack! What is this?! It turns out we already have data in our database, our single Article, so we can’t just willy-nilly add a new field on. Django is helpfully telling us that we either need to a one-off default of null or add it ourself. Hmmm.

For this very reason, it is generally good advice to always add new fields with either null=True or with a default value.

Let’s take the easy approach of setting null=True for now. So type 2 on the command line. Then add this to our slug field.

Try to create a migrations file again and it will work.

Go ahead and migrate the database as well to apply the change.

But if you think about it, what we’ve done is create a null value for our slug . We have to go into the admin to set it properly. Start up the local server, python manage.py runserver , and go to the Article page in the Admin. The Slug field is empty.

Empty Slug

Manually add in our desired value a-day-in-the-life and click «Save.»

Add Slug

Ok, last step is to update articles/urls.py so that we display the slug keyword argument in the URL itself. Luckily that just means swapping out <int:pk> for <slug:slug> .

And we’re done! Go to the list view page at http://127.0.0.1:8000/ and click on the link for our article.

Slug URL

And there it is with our slug as the URL! Beautiful.

Unique and Null

Moving forward, do we really want to allow a null value for a slug? Probably not as it will break our site! Another consideration is: what happens if there are identical slugs? How will that resolve itself? The short answer is: not well.

Therefore let’s change our slug field so that null is not allowed and unique values are required.

Make migration/migrate. Need empty for past entry.

Select 2 since we can manually handle the existing row ourself, and in fact, already have. Then migrate the database.

PrePopulated Fields

Manually adding a slug field each time quickly becomes tedious. So we can use a prepopulated_field in the admin to automate the process for us.

Update articles/admin.py as follows:

Now head over to the admin and add a new article. You’ll note that as you type in the Title field, the Slug field is automatically populated. Pretty neat!

Signals, Lifecycle Hooks, Save, and Forms/Serializers

In the real world, it’s unlikely to simply provide admin access to a user. You could, but at scale it’s definitely not a good idea. And even on a small scale, most non-technical users will find a web interface more appealing.

So. how to auto-populate the slug field when creating a new Article. It turns out Django has a built-in tool for this called slugify!

But how to use slugify ? In practice, it’s common to see this done with a Signal. But I would argue—as would Django Fellow Carlton Gibson—that this is not a good use of signals because we know both the sender and receiver here. There’s no mystery. We discuss the proper use of signals at length in our Django Chat Podcast episode on the topic.

An alternative to signals is to use a lifecycle hook via something like the django-lifecycle package. Lifecycle hooks are an alternative to Signals that provide similar functionality with less indirection.

Another common way to see this implemented is by overriding the Article model’s save method. This also «works» but is not the best solution. Here is one way to do that.

The best solution, in my opinion, is to create the slug in the form itself. This can be done by overriding the form’s clean method so that cleaned_data has the slug, or JavaScript can be used to auto-populate the field as is done in the Django admin itself. If you’re using an API, the same approach can be applied to the serializer.

This solution does not rely on a custom signal and handles the slug before it touches the database. In the words of Carlton Gibson, who suggested this approach to me, win-win-win.

Words of Caution

A quick word of caution on using slugs in a large website. Despite requiring an Article to be unique it is almost inevitable to have naming conflicts using slugs. However slugs do seem to have good SEO properties. A good compromise is to combine a slug with a UUID or a username. The ultimate URL would therefore be << uuid >>/<< slug >> or << username >>/<< slug >> . If you look at Github, for example, they use the pattern of username + slug for each repo which is why my Django for Beginners source code is located at https://github.com/wsvincent/djangoforbeginners . While you could also use an id + a slug, using ids is often a security concern and should be avoided for production websites.

© LearnDjango | Django is a registered trademark of the Django Software Foundation.

How to Create Django SEO Friendly URL using Slugs/SlugField

Search engine optimization (SEO) is a very important aspect of any web application especially if you are hoping to get a handful of traffic from search engines such as Google.

There are many components/parts involved in building a search engine optimized website and of them is search engine friendly URLs also known as keyword-rich URLS / user-friendly URLs / slug URLs.

Luckily for us, Django comes inbuilt with a SlugField Model Field that allows us to easily generate search engine friendly strings that can be used in our URL patterns for easy creation of pretty URLs or search engine-friendly URLs.

A slug is the part of a URL which identifies a particular page on a website in an easy to read form. A slug usually contains only letters, numbers, underscores or hyphens. They’re generally used in URLs.”

Take a look at these two URLs below for an article title: “How to Code”

You would agree with me that the second URL looks pretty and it conveys a meaning which is related to the content of our article.

In this article, I will be showing you how to SEO friendly URL patterns in Django that looks like the second URL above.

I will be assuming you are familiar with Django installation and setup, so I won’t be talking about how to do that.

To get started, create a virtual environment, install Django, create a Django project and create a Django app called “blog” or whatever you want.

For my own example, I will be creating a Django App called “blog” which I will use to create a simple blog App which has an SEO-friendly URL.

Example App

My Blog App will consist of an Article Model, a view and a URL Pattern.

In blog/models.py

In blog/views.py

In blog/urls.py

Follow the steps below to create your pretty URLs.

Use SlugField in the Model

There is a special model Field type in Django for slugs: SlugField.

Create a field named slug with type: SlugField.

In blog/models.py

Before saving the instance of a blog article, we convert the title to a slug with the slugify Django command, which basically replaces spaces by hyphens and also removes symbols if present.

As SlugField inherits from CharField, it comes with the attribute max_length which handles the maximum length of the string it contains at the database level.

If we use a SlugField without specifying its max_length attribute, it gets the value of 50 by default, which can lead to problems when we generate the string from a bigger max_length field.

So the trick is to make the title and the slug use the same max_length or make the slug field use a lesser max_lenght.

In blog/urls.py

In blog/views.py

OR

You can use a function-based view and pass in the post slug and post PK into the view.

In the above example, I am fetching the blog post using the “pk” which is a unique number attached to each data added into your database, fetching data via the “pk” is more reliable and I love using this approach.

In this case, the slug is just being used in the URL and nowhere else, the slug has nothing to do with fetching the article from our database.

If you follow the above steps, you should have a pretty URL for your articles right now.

Before you go, don’t forget to share this article on your social media profiles, someone might find it useful.

What is a slug in Django and How To Use It?

What is a slug in Django and How To Use It?

If you are working with Django or a similar web framework, you might have come across the term slug , slugField or slugify . What do these terms mean, why are slugs useful and how to use them properly? Where does the term slug come from?

A slug is a human-readable, unique label for a piece of data — usually an article or post. It’s most commonly used in urls, so it should contain no special characters.

In this tutorial I’ll quickly walk you through the “why”s and “how”s of Django slugs and also reveal the secret: what does an url identifier have to do with those slimy little creatures?

What is a slug?

Slug is just a regular string, with some restrictions: as it is very often used to build nice, human readable urls, it should not contain any special characters, that would be encoded when passed to the browser as an url.

Why Are Slugs Important

Accessibility — Human-readable URLs

Which one is better to look at:

It is just a much nicer user experience to see meaningful, intelligible urls on a website.

Search Engine Optimization

Having human human readable URLs does help with technical SEO, as it is a basic requirement by search engines. Excerpt from Google’s SEO guidelines:

A site’s URL structure should be as simple as possible. Consider organizing your content so that URLs are constructed logically and in a manner that is most intelligible to humans (when possible, readable words rather than long ID numbers). For example, if you’re searching for information about aviation, a URL like http://en.wikipedia.org/wiki/Aviation will help you decide whether to click that link. A URL like http://www.example.com/index.php?id_sezione=360&sid=3a5ebc944f41daa6f849f730f1, is much less appealing to users.

Consider using punctuation in your URLs. The URL http://www.example.com/green-dress.html is much more useful to us than http://www.example.com/greendress.html. We recommend that you use hyphens (-) instead of underscores (_) in your URLs.

So, if you have a Django app, that has some Article records in the database, then — from an SEO point-of-view — you are better off, if you look them up by some kind of meaningful identifier, then using just the auto-generated pk or uuid value.

Permalinks

In theory, you could have the article’s title directly included in the url and use that to look up the article, but the main problem with that approach would be that if you happen to update the title, that would mean the url also changes. You probably do not want that, as that would mean that all the external links to the page would be broken. From an SEO point-of-view that’s catastrophic. It would also mean that you need to update all your internal links as well. On top of that all users who might have bookmarked the page will probably be greeted with a 404 error page, as their bookmark would bring them to the old url.

For these reasons, it is considered good practice to keep webpages accessible on a permanent, unchanging link — a permalink.

How to Generate a Slug?

One possible (and actually the most commonly used) strategy to generate a slug for — let’s say — a blog post, is something like this:

  1. Take the title of the blog post
  2. Turn the whole title into lowercase
  3. Replace all whitespace characters with a hyphen ( — ). Note: Multiple consequent whitespace characters should also be replaced with one single hyphen: hello world should become hello-world not hello—-world
  4. Remove all other special characters (only letters, numbers and hyphens are allowed)

For example: the title of this article is What is a slug in Django? . The generated slug — as you can see in the url — is what-is-a-slug-in-django

Let’s see how to do that in Django!

Slugs in Django — the SlugField

Django comes with a model field that’s aimed specifically at storing slugs. It’s called SlugField and actually it’s just a Charfield with some extra validation, that makes sure that there are no invalid characters in the string.

Let’s see how to use it in practice:

How to Add SlugField to a Django Model

Let’s say you have an article model with a title:

You can simply add the slug field like this:

Populating Slug Fields

Adding the field to your model does not do much good in itself, somehow you will need to populate these fields with values.

Auto-Populating in Admin

One way to generate values for you slug field is to add it to the prepopulated_fields in the admin class.

For example, for the Article model defined above, we can define an admin class like this:

This will add a bit of javascript to the article admin page, that automatically generates a slug from the title. This is done only on creation, but not on update (in most cases we do not want to change the url, even if the title changes — see the section about permalinks)

If you go with this solution, the admin users will have the ability to change the generated slug manually.

As this is only a piece of client side code on the admin page, if the article is created programmatically, you will have to take care of the slug generation, otherwise it will remain empty.

Generating Slug Fields on Save

Another valid approach is to do the slug generation behind the scenes. You can override your Article model’s save method to generate a slug and populate the field with it.

To generate the slug value, we will use Django’s slugify utility.

Update your models file, like this:

The problem with this code is that it always regenerates the slug, whenever the title changes. We only want to do that on creation. (permalinks — remember?).

This issue is easily fixed, by checking the slug, and updating it only if it’s empty. The modified code looks like this:

Ensure Uniqueness

This is looking good so far, but what happens if an admin creates two articles the would have the same slug? How would Django know which one to find?

To ensure that for each slug there is always only one record in the articles table in the database, we can add some constraints on the Article model’s slug field: we want it to be unique and we do not want to allow null values.

The model’s code now looks like this:

This ensures that no duplicate values are allowed for the slug column in the database. If you try to create a second one with an existing value, you will get an error.

Depending on the database backend, most likely the lookups will also be a bit faster, as the db engine will be able to use an index on the unique key.

Lookup

The lookup itself, is pretty simple, assuming that you are using django.views.generic.DetailView as the base class for your ArticleView class, you can just define the urls for your articles with slug as a keyword argument:

Bonus: Where Does the Term “slug” Came From?

This all make sense, but why are they called slugs? As you made this far, here’s some fun trivia:

Actually, this term comes from newspaper publishing lingo — in the news room articles were referred to by a short, unique a name, to save time and avoid confusion.

The expression originated from printing/typesetting jargon. From the New York Times:

The term slug derives from the days of hot-metal printing, when printers set type by hand in a small form called a stick. Later huge Linotype machines turned molten lead into casts of letters, lines, sentences and paragraphs. A line of lead in both eras was known as a slug.

References

About the Author

Csongor Jozsa

Csongor Jozsa

Main author and editor at pythonin1minute.com. He's been working as a Software Developer/Security Engineer since 2005. Currently Lead Engineer at MBA.

Ezoic

report this ad

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.)

Slug
A short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs. For example, in a typical blog entry URL:

https://www.djangoproject.com/weblog/2008/apr/12/spring/ the last bit (spring) is the slug.

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».

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

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