|
| 1 | +title: django.db.models SlugField Example Code |
| 2 | +category: page |
| 3 | +slug: django-db-models-slugfield-examples |
| 4 | +sortorder: 50157 |
| 5 | +toc: False |
| 6 | +sidebartitle: django.db.models SlugField |
| 7 | +meta: Python code examples for the Django ORM's SlugField class, found within the django.db.models module of the Django project. |
| 8 | + |
| 9 | + |
| 10 | +[SlugField](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.SlugField) |
| 11 | +([source code](https://github.com/django/django/blob/master/django/db/models/fields/__init__.py)) |
| 12 | +is a field for storing |
| 13 | +[URL slugs](https://stackoverflow.com/questions/427102/what-is-a-slug-in-django) |
| 14 | +in a [relational database](/databases.html). SlugField is a column |
| 15 | +defined by the [Django ORM](/django-orm.html). |
| 16 | + |
| 17 | +`SlugField` is actually defined within the |
| 18 | +[django.db.models.fields](https://github.com/django/django/blob/master/django/db/models/fields/__init__.py) |
| 19 | +module but is typically imported from |
| 20 | +[django.db.models](https://github.com/django/django/tree/master/django/db/models) |
| 21 | +rather than including the `fields` module reference. |
| 22 | + |
| 23 | + |
| 24 | +## Example 1 from gadget-board |
| 25 | +[gadget-board](https://github.com/mik4el/gadget-board) is a |
| 26 | +[Django](/django.html), |
| 27 | +[Django REST Framework (DRF)](/django-rest-framework-drf.html) and |
| 28 | +[Angular](/angular.html) web application that is open source under the |
| 29 | +[Apache2 license](https://github.com/mik4el/gadget-board/blob/master/LICENSE). |
| 30 | + |
| 31 | +[**gadget-board / web / gadgets / models.py**](https://github.com/mik4el/gadget-board/blob/master/web/gadgets/models.py) |
| 32 | + |
| 33 | +```python |
| 34 | +~~from django.db import models |
| 35 | +from django.contrib.postgres.fields import JSONField |
| 36 | +from django.template.defaultfilters import slugify |
| 37 | +from authentication.models import Account |
| 38 | + |
| 39 | + |
| 40 | +class Gadget(models.Model): |
| 41 | + name = models.CharField(max_length=40, unique=True) |
| 42 | +~~ slug = models.SlugField(null=True, blank=True) |
| 43 | + description = models.TextField() |
| 44 | + users_can_upload = models.ManyToManyField(Account) |
| 45 | + image_name = models.CharField(max_length=140, blank=True) |
| 46 | + created_at = models.DateTimeField(auto_now_add=True) |
| 47 | + updated_at = models.DateTimeField(auto_now=True) |
| 48 | + |
| 49 | + @property |
| 50 | + def image_url(self): |
| 51 | + if self.image_name != "": |
| 52 | + return "backend/static/media/{}".format(self.image_name) |
| 53 | + else: |
| 54 | + return "backend/static/dashboard_icon_big.png" |
| 55 | + |
| 56 | + def __str__(self): |
| 57 | + return self.name |
| 58 | + |
| 59 | +~~ def save(self, *args, **kwargs): |
| 60 | +~~ if not self.id: |
| 61 | +~~ self.slug = slugify(self.name) |
| 62 | +~~ |
| 63 | +~~ super(Gadget, self).save(*args, **kwargs) |
| 64 | + |
| 65 | + |
| 66 | +class GadgetData(models.Model): |
| 67 | + gadget = models.ForeignKey(Gadget, db_index=True, on_delete=models.DO_NOTHING) # Add index on filtered fields |
| 68 | + data = JSONField() |
| 69 | + added_by = models.ForeignKey(Account, on_delete=models.DO_NOTHING) |
| 70 | + timestamp = models.DateTimeField(null=True, blank=True, db_index=True) # Add index on filtered fields |
| 71 | + created_at = models.DateTimeField(auto_now_add=True) |
| 72 | + |
| 73 | + def __str__(self): |
| 74 | + return '{} {} {}'.format(self.gadget, self.timestamp, self.added_by) |
| 75 | + |
| 76 | +``` |
| 77 | + |
| 78 | + |
| 79 | +## Example 2 from wagtail |
| 80 | +[wagtail](https://github.com/wagtail/wagtail) |
| 81 | +([project website](https://wagtail.io/)) is a fantastic |
| 82 | +[Django](/django.html)-based CMS with code that is open source |
| 83 | +under the |
| 84 | +[BSD 3-Clause "New" or "Revised" License](https://github.com/wagtail/wagtail/blob/master/LICENSE). |
| 85 | + |
| 86 | +[**wagtail / wagtail / core / models.py**](https://github.com/wagtail/wagtail/blob/master/wagtail/core/models.py) |
| 87 | + |
| 88 | +```python |
| 89 | +import json |
| 90 | +import logging |
| 91 | +from collections import defaultdict |
| 92 | +from io import StringIO |
| 93 | +from urllib.parse import urlparse |
| 94 | +from warnings import warn |
| 95 | + |
| 96 | +from django.conf import settings |
| 97 | +from django.contrib.auth.models import Group, Permission |
| 98 | +from django.contrib.contenttypes.models import ContentType |
| 99 | +from django.core import checks |
| 100 | +from django.core.cache import cache |
| 101 | +from django.core.exceptions import ValidationError |
| 102 | +from django.core.handlers.base import BaseHandler |
| 103 | +from django.core.handlers.wsgi import WSGIRequest |
| 104 | +~~from django.db import models, transaction |
| 105 | +from django.db.models import Case, Q, Value, When |
| 106 | +from django.db.models.functions import Concat, Substr |
| 107 | +from django.http import Http404 |
| 108 | +from django.template.response import TemplateResponse |
| 109 | +from django.urls import reverse |
| 110 | +from django.utils import timezone |
| 111 | +from django.utils.functional import cached_property |
| 112 | +from django.utils.text import capfirst, slugify |
| 113 | +from django.utils.translation import ugettext_lazy as _ |
| 114 | +from modelcluster.models import ( |
| 115 | + ClusterableModel, get_all_child_m2m_relations, get_all_child_relations) |
| 116 | +from treebeard.mp_tree import MP_Node |
| 117 | + |
| 118 | +from wagtail.core.query import PageQuerySet, TreeQuerySet |
| 119 | +from wagtail.core.signals import page_published, page_unpublished |
| 120 | +from wagtail.core.sites import get_site_for_hostname |
| 121 | +from wagtail.core.url_routing import RouteResult |
| 122 | +from wagtail.core.utils import WAGTAIL_APPEND_SLASH, camelcase_to_underscore, resolve_model_string |
| 123 | +from wagtail.search import index |
| 124 | +from wagtail.utils.deprecation import RemovedInWagtail29Warning |
| 125 | + |
| 126 | + |
| 127 | +## ... code abbreviated to get to the SlugField example ... |
| 128 | +class AbstractPage(MP_Node): |
| 129 | + """ |
| 130 | + Abstract superclass for Page. According to Django's inheritance rules, managers set on |
| 131 | + abstract models are inherited by subclasses, but managers set on concrete models that are extended |
| 132 | + via multi-table inheritance are not. We therefore need to attach PageManager to an abstract |
| 133 | + superclass to ensure that it is retained by subclasses of Page. |
| 134 | + """ |
| 135 | + objects = PageManager() |
| 136 | + |
| 137 | + class Meta: |
| 138 | + abstract = True |
| 139 | + |
| 140 | + |
| 141 | +class Page(AbstractPage, index.Indexed, ClusterableModel, metaclass=PageBase): |
| 142 | + title = models.CharField( |
| 143 | + verbose_name=_('title'), |
| 144 | + max_length=255, |
| 145 | + help_text=_("The page title as you'd like it to be seen by the public") |
| 146 | + ) |
| 147 | + # to reflect title of a current draft in the admin UI |
| 148 | + draft_title = models.CharField( |
| 149 | + max_length=255, |
| 150 | + editable=False |
| 151 | + ) |
| 152 | +~~ slug = models.SlugField( |
| 153 | +~~ verbose_name=_('slug'), |
| 154 | +~~ allow_unicode=True, |
| 155 | +~~ max_length=255, |
| 156 | +~~ help_text=_("The name of the page as it will appear in URLs e.g http://domain.com/blog/[my-slug]/") |
| 157 | +~~ ) |
| 158 | + content_type = models.ForeignKey( |
| 159 | + 'contenttypes.ContentType', |
| 160 | + verbose_name=_('content type'), |
| 161 | + related_name='pages', |
| 162 | + on_delete=models.SET(get_default_page_content_type) |
| 163 | + ) |
| 164 | + live = models.BooleanField(verbose_name=_('live'), default=True, editable=False) |
| 165 | + has_unpublished_changes = models.BooleanField( |
| 166 | + verbose_name=_('has unpublished changes'), |
| 167 | + default=False, |
| 168 | + editable=False |
| 169 | + ) |
| 170 | + url_path = models.TextField(verbose_name=_('URL path'), blank=True, editable=False) |
| 171 | + owner = models.ForeignKey( |
| 172 | + settings.AUTH_USER_MODEL, |
| 173 | + verbose_name=_('owner'), |
| 174 | + null=True, |
| 175 | + blank=True, |
| 176 | + editable=True, |
| 177 | + on_delete=models.SET_NULL, |
| 178 | + related_name='owned_pages' |
| 179 | + ) |
| 180 | + |
| 181 | +## ... code file continues here without further SlugField examples ... |
| 182 | +``` |
| 183 | + |
| 184 | + |
| 185 | +## Example 3 from django-taggit |
| 186 | +[django-debug-toolbar](https://github.com/jazzband/django-debug-toolbar) |
| 187 | +([source code](https://github.com/jazzband/django-debug-toolbar) and |
| 188 | +[PyPI page](https://pypi.org/project/django-taggit/)) provides a way |
| 189 | +to create, store, manage and use tags in a [Django](/django.html) project. |
| 190 | +The code for django-taggit is |
| 191 | +[open source](https://github.com/jazzband/django-taggit/blob/master/LICENSE) |
| 192 | +and maintained by the collaborative developer community group |
| 193 | +[Jazzband](https://jazzband.co/). |
| 194 | + |
| 195 | +[**django-taggit / taggit / migrations / 0001_initial.py**](https://github.com/jazzband/django-taggit/blob/master/taggit/migrations/0001_initial.py) |
| 196 | + |
| 197 | +```python |
| 198 | +# 0001_initial.py |
| 199 | +~~from django.db import migrations, models |
| 200 | + |
| 201 | + |
| 202 | +class Migration(migrations.Migration): |
| 203 | + |
| 204 | + dependencies = [("contenttypes", "0001_initial")] |
| 205 | + |
| 206 | + operations = [ |
| 207 | + migrations.CreateModel( |
| 208 | + name="Tag", |
| 209 | + fields=[ |
| 210 | + ( |
| 211 | + "id", |
| 212 | + models.AutoField( |
| 213 | + auto_created=True, |
| 214 | + primary_key=True, |
| 215 | + serialize=False, |
| 216 | + help_text="", |
| 217 | + verbose_name="ID", |
| 218 | + ), |
| 219 | + ), |
| 220 | + ( |
| 221 | + "name", |
| 222 | + models.CharField( |
| 223 | + help_text="", unique=True, max_length=100, verbose_name="Name" |
| 224 | + ), |
| 225 | + ), |
| 226 | +~~ ( |
| 227 | +~~ "slug", |
| 228 | +~~ models.SlugField( |
| 229 | +~~ help_text="", unique=True, max_length=100, verbose_name="Slug" |
| 230 | +~~ ), |
| 231 | +~~ ), |
| 232 | + ], |
| 233 | + options={"verbose_name": "Tag", "verbose_name_plural": "Tags"}, |
| 234 | + bases=(models.Model,), |
| 235 | + ), |
| 236 | + migrations.CreateModel( |
| 237 | + name="TaggedItem", |
| 238 | + fields=[ |
| 239 | + ( |
| 240 | + "id", |
| 241 | + models.AutoField( |
| 242 | + auto_created=True, |
| 243 | + primary_key=True, |
| 244 | + serialize=False, |
| 245 | + help_text="", |
| 246 | + verbose_name="ID", |
| 247 | + ), |
| 248 | + ), |
| 249 | + ( |
| 250 | + "object_id", |
| 251 | + models.IntegerField( |
| 252 | + help_text="", verbose_name="Object id", db_index=True |
| 253 | + ), |
| 254 | + ), |
| 255 | + ( |
| 256 | + "content_type", |
| 257 | + models.ForeignKey( |
| 258 | + related_name="taggit_taggeditem_tagged_items", |
| 259 | + verbose_name="Content type", |
| 260 | + to="contenttypes.ContentType", |
| 261 | + help_text="", |
| 262 | + on_delete=models.CASCADE, |
| 263 | + ), |
| 264 | + ), |
| 265 | + ( |
| 266 | + "tag", |
| 267 | + models.ForeignKey( |
| 268 | + related_name="taggit_taggeditem_items", |
| 269 | + to="taggit.Tag", |
| 270 | + help_text="", |
| 271 | + on_delete=models.CASCADE, |
| 272 | + ), |
| 273 | + ), |
| 274 | + ], |
| 275 | + options={ |
| 276 | + "verbose_name": "Tagged Item", |
| 277 | + "verbose_name_plural": "Tagged Items", |
| 278 | + }, |
| 279 | + bases=(models.Model,), |
| 280 | + ), |
| 281 | + ] |
| 282 | + |
| 283 | +``` |
| 284 | + |
0 commit comments