SlugField (source code) is a field for storing URL slugs in a relational database. SlugField is a column defined by the Django ORM.
SlugField
is actually defined within the
django.db.models.fields
module but is typically imported from
django.db.models
rather than including the fields
module reference.
gadget-board is a Django, Django REST Framework (DRF) and Angular web application that is open source under the Apache2 license.
gadget-board / web / gadgets / models.py
from django.db import models
from django.contrib.postgres.fields import JSONField
from django.template.defaultfilters import slugify
from authentication.models import Account
class Gadget(models.Model):
name = models.CharField(max_length=40, unique=True)
slug = models.SlugField(null=True, blank=True)
description = models.TextField()
users_can_upload = models.ManyToManyField(Account)
image_name = models.CharField(max_length=140, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
@property
def image_url(self):
if self.image_name != "":
return "backend/static/media/{}".format(self.image_name)
else:
return "backend/static/dashboard_icon_big.png"
def __str__(self):
return self.name
def save(self, *args, **kwargs):
if not self.id:
self.slug = slugify(self.name)
super(Gadget, self).save(*args, **kwargs)
class GadgetData(models.Model):
gadget = models.ForeignKey(Gadget, db_index=True, on_delete=models.DO_NOTHING) # Add index on filtered fields
data = JSONField()
added_by = models.ForeignKey(Account, on_delete=models.DO_NOTHING)
timestamp = models.DateTimeField(null=True, blank=True, db_index=True) # Add index on filtered fields
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '{} {} {}'.format(self.gadget, self.timestamp, self.added_by)
wagtail (project website) is a fantastic Django-based CMS with code that is open source under the BSD 3-Clause "New" or "Revised" License.
wagtail / wagtail / core / models.py
import json
import logging
from collections import defaultdict
from io import StringIO
from urllib.parse import urlparse
from warnings import warn
from django.conf import settings
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.core import checks
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.core.handlers.base import BaseHandler
from django.core.handlers.wsgi import WSGIRequest
from django.db import models, transaction
from django.db.models import Case, Q, Value, When
from django.db.models.functions import Concat, Substr
from django.http import Http404
from django.template.response import TemplateResponse
from django.urls import reverse
from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.text import capfirst, slugify
from django.utils.translation import ugettext_lazy as _
from modelcluster.models import (
ClusterableModel, get_all_child_m2m_relations, get_all_child_relations)
from treebeard.mp_tree import MP_Node
from wagtail.core.query import PageQuerySet, TreeQuerySet
from wagtail.core.signals import page_published, page_unpublished
from wagtail.core.sites import get_site_for_hostname
from wagtail.core.url_routing import RouteResult
from wagtail.core.utils import WAGTAIL_APPEND_SLASH, camelcase_to_underscore, resolve_model_string
from wagtail.search import index
from wagtail.utils.deprecation import RemovedInWagtail29Warning
## ... code abbreviated to get to the SlugField example ...
class AbstractPage(MP_Node):
"""
Abstract superclass for Page. According to Django's inheritance rules, managers set on
abstract models are inherited by subclasses, but managers set on concrete models that are extended
via multi-table inheritance are not. We therefore need to attach PageManager to an abstract
superclass to ensure that it is retained by subclasses of Page.
"""
objects = PageManager()
class Meta:
abstract = True
class Page(AbstractPage, index.Indexed, ClusterableModel, metaclass=PageBase):
title = models.CharField(
verbose_name=_('title'),
max_length=255,
help_text=_("The page title as you'd like it to be seen by the public")
)
# to reflect title of a current draft in the admin UI
draft_title = models.CharField(
max_length=255,
editable=False
)
slug = models.SlugField(
verbose_name=_('slug'),
allow_unicode=True,
max_length=255,
help_text=_("The name of the page as it will appear in URLs e.g http://domain.com/blog/[my-slug]/")
)
content_type = models.ForeignKey(
'contenttypes.ContentType',
verbose_name=_('content type'),
related_name='pages',
on_delete=models.SET(get_default_page_content_type)
)
live = models.BooleanField(verbose_name=_('live'), default=True, editable=False)
has_unpublished_changes = models.BooleanField(
verbose_name=_('has unpublished changes'),
default=False,
editable=False
)
url_path = models.TextField(verbose_name=_('URL path'), blank=True, editable=False)
owner = models.ForeignKey(
settings.AUTH_USER_MODEL,
verbose_name=_('owner'),
null=True,
blank=True,
editable=True,
on_delete=models.SET_NULL,
related_name='owned_pages'
)
## ... code file continues here without further SlugField examples ...
django-debug-toolbar (source code and PyPI page) provides a way to create, store, manage and use tags in a Django project. The code for django-taggit is open source and maintained by the collaborative developer community group Jazzband.
django-taggit / taggit / migrations / 0001_initial.py
# 0001_initial.py
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("contenttypes", "0001_initial")]
operations = [
migrations.CreateModel(
name="Tag",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
help_text="",
verbose_name="ID",
),
),
(
"name",
models.CharField(
help_text="", unique=True, max_length=100, verbose_name="Name"
),
),
(
"slug",
models.SlugField(
help_text="", unique=True, max_length=100, verbose_name="Slug"
),
),
],
options={"verbose_name": "Tag", "verbose_name_plural": "Tags"},
bases=(models.Model,),
),
migrations.CreateModel(
name="TaggedItem",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
help_text="",
verbose_name="ID",
),
),
(
"object_id",
models.IntegerField(
help_text="", verbose_name="Object id", db_index=True
),
),
(
"content_type",
models.ForeignKey(
related_name="taggit_taggeditem_tagged_items",
verbose_name="Content type",
to="contenttypes.ContentType",
help_text="",
on_delete=models.CASCADE,
),
),
(
"tag",
models.ForeignKey(
related_name="taggit_taggeditem_items",
to="taggit.Tag",
help_text="",
on_delete=models.CASCADE,
),
),
],
options={
"verbose_name": "Tagged Item",
"verbose_name_plural": "Tagged Items",
},
bases=(models.Model,),
),
]