├── .gitignore ├── .travis.yml ├── Makefile ├── README.rst ├── docs ├── Makefile ├── architecture.rst ├── conf.py ├── index.rst ├── installation.rst ├── make.bat └── usage.rst ├── manage.py ├── setup.py ├── sluggable ├── __init__.py ├── fields.py ├── models.py ├── settings.py ├── tests │ ├── __init__.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── settings.py │ └── tests.py ├── utils.py └── views.py └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | *.pot 3 | *.pyc 4 | local_settings.py 5 | .coverage 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | language: python 3 | python: 3.8 4 | 5 | install: pip install tox 6 | script: tox 7 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | pep8: 2 | flake8 sluggable --ignore=E501,E127,E128,E124 3 | 4 | test: 5 | coverage run --branch --source=sluggable manage.py test sluggable 6 | coverage report --omit=sluggable/test* 7 | 8 | release: 9 | python setup.py sdist register upload -s 10 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | django-sluggable 2 | ================ 3 | 4 | .. image:: https://secure.travis-ci.org/thoas/django-sluggable.png?branch=master 5 | :alt: Build Status 6 | :target: http://travis-ci.org/thoas/django-sluggable 7 | 8 | 9 | django-sluggable is a library to manage your slugs and redirect old slugs 10 | to a new one. With this library, you will have the plain history of your operations. 11 | 12 | Installation 13 | ------------ 14 | 15 | To install it, simply :: 16 | 17 | pip install django-sluggable 18 | 19 | Documentation 20 | ------------- 21 | 22 | For documentation, usage, and examples, see: 23 | http://django-sluggable.readthedocs.org 24 | 25 | Inspiration 26 | ----------- 27 | 28 | Some code are from django-autoslug_ and old codebase of Ulule by twidi_. 29 | 30 | A big thanks to them. 31 | 32 | .. _django-autoslug: https://pypi.python.org/pypi/django-autoslug 33 | .. _twidi: https://github.com/twidi 34 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 16 | 17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 18 | 19 | help: 20 | @echo "Please use \`make ' where is one of" 21 | @echo " html to make standalone HTML files" 22 | @echo " dirhtml to make HTML files named index.html in directories" 23 | @echo " singlehtml to make a single large HTML file" 24 | @echo " pickle to make pickle files" 25 | @echo " json to make JSON files" 26 | @echo " htmlhelp to make HTML files and a HTML help project" 27 | @echo " qthelp to make HTML files and a qthelp project" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 31 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 32 | @echo " text to make text files" 33 | @echo " man to make manual pages" 34 | @echo " texinfo to make Texinfo files" 35 | @echo " info to make Texinfo files and run them through makeinfo" 36 | @echo " gettext to make PO message catalogs" 37 | @echo " changes to make an overview of all changed/added/deprecated items" 38 | @echo " linkcheck to check all external links for integrity" 39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 40 | 41 | clean: 42 | -rm -rf $(BUILDDIR)/* 43 | 44 | html: 45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 48 | 49 | dirhtml: 50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 51 | @echo 52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 53 | 54 | singlehtml: 55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 56 | @echo 57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 58 | 59 | pickle: 60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 61 | @echo 62 | @echo "Build finished; now you can process the pickle files." 63 | 64 | json: 65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 66 | @echo 67 | @echo "Build finished; now you can process the JSON files." 68 | 69 | htmlhelp: 70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 71 | @echo 72 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 73 | ".hhp project file in $(BUILDDIR)/htmlhelp." 74 | 75 | qthelp: 76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 77 | @echo 78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/django-sluggable.qhcp" 81 | @echo "To view the help file:" 82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django-sluggable.qhc" 83 | 84 | devhelp: 85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 86 | @echo 87 | @echo "Build finished." 88 | @echo "To view the help file:" 89 | @echo "# mkdir -p $$HOME/.local/share/devhelp/django-sluggable" 90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django-sluggable" 91 | @echo "# devhelp" 92 | 93 | epub: 94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 95 | @echo 96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 97 | 98 | latex: 99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 100 | @echo 101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 103 | "(use \`make latexpdf' here to do that automatically)." 104 | 105 | latexpdf: 106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 107 | @echo "Running LaTeX files through pdflatex..." 108 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 110 | 111 | text: 112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 113 | @echo 114 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 115 | 116 | man: 117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 118 | @echo 119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 120 | 121 | texinfo: 122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 123 | @echo 124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 125 | @echo "Run \`make' in that directory to run these through makeinfo" \ 126 | "(use \`make info' here to do that automatically)." 127 | 128 | info: 129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 130 | @echo "Running Texinfo files through makeinfo..." 131 | make -C $(BUILDDIR)/texinfo info 132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 133 | 134 | gettext: 135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 136 | @echo 137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 138 | 139 | changes: 140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 141 | @echo 142 | @echo "The overview file is in $(BUILDDIR)/changes." 143 | 144 | linkcheck: 145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 146 | @echo 147 | @echo "Link check complete; look for any errors in the above output " \ 148 | "or in $(BUILDDIR)/linkcheck/output.txt." 149 | 150 | doctest: 151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 152 | @echo "Testing of doctests in the sources finished, look at the " \ 153 | "results in $(BUILDDIR)/doctest/output.txt." 154 | -------------------------------------------------------------------------------- /docs/architecture.rst: -------------------------------------------------------------------------------- 1 | .. _ref-architecture: 2 | 3 | ============ 4 | Architecture 5 | ============ 6 | 7 | ... 8 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # django-sluggable documentation build configuration file, created by 4 | # sphinx-quickstart on Sat Jan 5 22:37:19 2013. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | #sys.path.insert(0, os.path.abspath('.')) 20 | 21 | # -- General configuration ----------------------------------------------------- 22 | 23 | # If your documentation needs a minimal Sphinx version, state it here. 24 | #needs_sphinx = '1.0' 25 | 26 | # Add any Sphinx extension module names here, as strings. They can be extensions 27 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 28 | extensions = [] 29 | 30 | # Add any paths that contain templates here, relative to this directory. 31 | templates_path = ['_templates'] 32 | 33 | # The suffix of source filenames. 34 | source_suffix = '.rst' 35 | 36 | # The encoding of source files. 37 | #source_encoding = 'utf-8-sig' 38 | 39 | # The master toctree document. 40 | master_doc = 'index' 41 | 42 | # General information about the project. 43 | project = u'django-sluggable' 44 | copyright = u'2013, 2012, Florent Messa and contributors' 45 | 46 | # The version info for the project you're documenting, acts as replacement for 47 | # |version| and |release|, also used in various other places throughout the 48 | # built documents. 49 | # 50 | try: 51 | from sluggable import __version__ 52 | # The short X.Y version. 53 | version = '.'.join(__version__.split('.')[:2]) 54 | # The full version, including alpha/beta/rc tags. 55 | release = __version__ 56 | except ImportError: 57 | version = release = 'dev' 58 | 59 | # The language for content autogenerated by Sphinx. Refer to documentation 60 | # for a list of supported languages. 61 | #language = None 62 | 63 | # There are two options for replacing |today|: either, you set today to some 64 | # non-false value, then it is used: 65 | #today = '' 66 | # Else, today_fmt is used as the format for a strftime call. 67 | #today_fmt = '%B %d, %Y' 68 | 69 | # List of patterns, relative to source directory, that match files and 70 | # directories to ignore when looking for source files. 71 | exclude_patterns = ['_build'] 72 | 73 | # The reST default role (used for this markup: `text`) to use for all documents. 74 | #default_role = None 75 | 76 | # If true, '()' will be appended to :func: etc. cross-reference text. 77 | #add_function_parentheses = True 78 | 79 | # If true, the current module name will be prepended to all description 80 | # unit titles (such as .. function::). 81 | #add_module_names = True 82 | 83 | # If true, sectionauthor and moduleauthor directives will be shown in the 84 | # output. They are ignored by default. 85 | #show_authors = False 86 | 87 | # The name of the Pygments (syntax highlighting) style to use. 88 | pygments_style = 'sphinx' 89 | 90 | # A list of ignored prefixes for module index sorting. 91 | #modindex_common_prefix = [] 92 | 93 | 94 | # -- Options for HTML output --------------------------------------------------- 95 | 96 | # The theme to use for HTML and HTML Help pages. See the documentation for 97 | # a list of builtin themes. 98 | html_theme = 'default' 99 | 100 | # Theme options are theme-specific and customize the look and feel of a theme 101 | # further. For a list of options available for each theme, see the 102 | # documentation. 103 | #html_theme_options = {} 104 | 105 | # Add any paths that contain custom themes here, relative to this directory. 106 | #html_theme_path = [] 107 | 108 | # The name for this set of Sphinx documents. If None, it defaults to 109 | # " v documentation". 110 | #html_title = None 111 | 112 | # A shorter title for the navigation bar. Default is the same as html_title. 113 | #html_short_title = None 114 | 115 | # The name of an image file (relative to this directory) to place at the top 116 | # of the sidebar. 117 | #html_logo = None 118 | 119 | # The name of an image file (within the static path) to use as favicon of the 120 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 121 | # pixels large. 122 | #html_favicon = None 123 | 124 | # Add any paths that contain custom static files (such as style sheets) here, 125 | # relative to this directory. They are copied after the builtin static files, 126 | # so a file named "default.css" will overwrite the builtin "default.css". 127 | html_static_path = ['_static'] 128 | 129 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 130 | # using the given strftime format. 131 | #html_last_updated_fmt = '%b %d, %Y' 132 | 133 | # If true, SmartyPants will be used to convert quotes and dashes to 134 | # typographically correct entities. 135 | #html_use_smartypants = True 136 | 137 | # Custom sidebar templates, maps document names to template names. 138 | #html_sidebars = {} 139 | 140 | # Additional templates that should be rendered to pages, maps page names to 141 | # template names. 142 | #html_additional_pages = {} 143 | 144 | # If false, no module index is generated. 145 | #html_domain_indices = True 146 | 147 | # If false, no index is generated. 148 | #html_use_index = True 149 | 150 | # If true, the index is split into individual pages for each letter. 151 | #html_split_index = False 152 | 153 | # If true, links to the reST sources are added to the pages. 154 | #html_show_sourcelink = True 155 | 156 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 157 | #html_show_sphinx = True 158 | 159 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 160 | #html_show_copyright = True 161 | 162 | # If true, an OpenSearch description file will be output, and all pages will 163 | # contain a tag referring to it. The value of this option must be the 164 | # base URL from which the finished HTML is served. 165 | #html_use_opensearch = '' 166 | 167 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 168 | #html_file_suffix = None 169 | 170 | # Output file base name for HTML help builder. 171 | htmlhelp_basename = 'django-sluggabledoc' 172 | 173 | 174 | # -- Options for LaTeX output -------------------------------------------------- 175 | 176 | latex_elements = { 177 | # The paper size ('letterpaper' or 'a4paper'). 178 | #'papersize': 'letterpaper', 179 | 180 | # The font size ('10pt', '11pt' or '12pt'). 181 | #'pointsize': '10pt', 182 | 183 | # Additional stuff for the LaTeX preamble. 184 | #'preamble': '', 185 | } 186 | 187 | # Grouping the document tree into LaTeX files. List of tuples 188 | # (source start file, target name, title, author, documentclass [howto/manual]). 189 | latex_documents = [ 190 | ('index', 'django-sluggable.tex', u'django-sluggable Documentation', 191 | u'2012, Florent Messa and contributors', 'manual'), 192 | ] 193 | 194 | # The name of an image file (relative to this directory) to place at the top of 195 | # the title page. 196 | #latex_logo = None 197 | 198 | # For "manual" documents, if this is true, then toplevel headings are parts, 199 | # not chapters. 200 | #latex_use_parts = False 201 | 202 | # If true, show page references after internal links. 203 | #latex_show_pagerefs = False 204 | 205 | # If true, show URL addresses after external links. 206 | #latex_show_urls = False 207 | 208 | # Documents to append as an appendix to all manuals. 209 | #latex_appendices = [] 210 | 211 | # If false, no module index is generated. 212 | #latex_domain_indices = True 213 | 214 | 215 | # -- Options for manual page output -------------------------------------------- 216 | 217 | # One entry per manual page. List of tuples 218 | # (source start file, name, description, authors, manual section). 219 | man_pages = [ 220 | ('index', 'django-sluggable', u'django-sluggable Documentation', 221 | [u'2012, Florent Messa and contributors'], 1) 222 | ] 223 | 224 | # If true, show URL addresses after external links. 225 | #man_show_urls = False 226 | 227 | 228 | # -- Options for Texinfo output ------------------------------------------------ 229 | 230 | # Grouping the document tree into Texinfo files. List of tuples 231 | # (source start file, target name, title, author, 232 | # dir menu entry, description, category) 233 | texinfo_documents = [ 234 | ('index', 'django-sluggable', u'django-sluggable Documentation', 235 | u'2012, Florent Messa and contributors', 'django-sluggable', 'One line description of project.', 236 | 'Miscellaneous'), 237 | ] 238 | 239 | # Documents to append as an appendix to all manuals. 240 | #texinfo_appendices = [] 241 | 242 | # If false, no module index is generated. 243 | #texinfo_domain_indices = True 244 | 245 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 246 | #texinfo_show_urls = 'footnote' 247 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | Introduction 2 | ------------ 3 | 4 | django-sluggable is a library to manage your slugs and redirect old slugs 5 | to a new one. With this library, you will have the plain history of your operations. 6 | 7 | You can report bugs and discuss features on the `issues page `_. 8 | 9 | Reference 10 | --------- 11 | 12 | For further details see the reference documentation: 13 | 14 | .. toctree:: 15 | :maxdepth: 2 16 | 17 | installation 18 | usage 19 | architecture 20 | 21 | 22 | Indices and tables 23 | ================== 24 | 25 | * :ref:`genindex` 26 | * :ref:`modindex` 27 | * :ref:`search` 28 | 29 | Issues 30 | ------ 31 | 32 | For any bug reports and feature requests, please use the 33 | `Github issue tracker`_. 34 | 35 | .. _`Github issue tracker`: https://github.com/thoas/django-sluggable/issues 36 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | .. _ref-installation: 2 | 3 | ============ 4 | Installation 5 | ============ 6 | 7 | Either check out django-sluggable from GitHub_ or to pull a release off PyPI_ :: 8 | 9 | pip install django-sluggable 10 | 11 | .. _GitHub: http://github.com/thoas/django-sluggable 12 | .. _PyPI: http://pypi.python.org/pypi/django-sluggable 13 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. linkcheck to check all external links for integrity 37 | echo. doctest to run all doctests embedded in the documentation if enabled 38 | goto end 39 | ) 40 | 41 | if "%1" == "clean" ( 42 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 43 | del /q /s %BUILDDIR%\* 44 | goto end 45 | ) 46 | 47 | if "%1" == "html" ( 48 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 49 | if errorlevel 1 exit /b 1 50 | echo. 51 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 52 | goto end 53 | ) 54 | 55 | if "%1" == "dirhtml" ( 56 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 57 | if errorlevel 1 exit /b 1 58 | echo. 59 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 60 | goto end 61 | ) 62 | 63 | if "%1" == "singlehtml" ( 64 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 68 | goto end 69 | ) 70 | 71 | if "%1" == "pickle" ( 72 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished; now you can process the pickle files. 76 | goto end 77 | ) 78 | 79 | if "%1" == "json" ( 80 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished; now you can process the JSON files. 84 | goto end 85 | ) 86 | 87 | if "%1" == "htmlhelp" ( 88 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can run HTML Help Workshop with the ^ 92 | .hhp project file in %BUILDDIR%/htmlhelp. 93 | goto end 94 | ) 95 | 96 | if "%1" == "qthelp" ( 97 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 98 | if errorlevel 1 exit /b 1 99 | echo. 100 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 101 | .qhcp project file in %BUILDDIR%/qthelp, like this: 102 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\django-sluggable.qhcp 103 | echo.To view the help file: 104 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\django-sluggable.ghc 105 | goto end 106 | ) 107 | 108 | if "%1" == "devhelp" ( 109 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 110 | if errorlevel 1 exit /b 1 111 | echo. 112 | echo.Build finished. 113 | goto end 114 | ) 115 | 116 | if "%1" == "epub" ( 117 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 118 | if errorlevel 1 exit /b 1 119 | echo. 120 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 121 | goto end 122 | ) 123 | 124 | if "%1" == "latex" ( 125 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 129 | goto end 130 | ) 131 | 132 | if "%1" == "text" ( 133 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The text files are in %BUILDDIR%/text. 137 | goto end 138 | ) 139 | 140 | if "%1" == "man" ( 141 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 145 | goto end 146 | ) 147 | 148 | if "%1" == "texinfo" ( 149 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 150 | if errorlevel 1 exit /b 1 151 | echo. 152 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 153 | goto end 154 | ) 155 | 156 | if "%1" == "gettext" ( 157 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 158 | if errorlevel 1 exit /b 1 159 | echo. 160 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 161 | goto end 162 | ) 163 | 164 | if "%1" == "changes" ( 165 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 166 | if errorlevel 1 exit /b 1 167 | echo. 168 | echo.The overview file is in %BUILDDIR%/changes. 169 | goto end 170 | ) 171 | 172 | if "%1" == "linkcheck" ( 173 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 174 | if errorlevel 1 exit /b 1 175 | echo. 176 | echo.Link check complete; look for any errors in the above output ^ 177 | or in %BUILDDIR%/linkcheck/output.txt. 178 | goto end 179 | ) 180 | 181 | if "%1" == "doctest" ( 182 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 183 | if errorlevel 1 exit /b 1 184 | echo. 185 | echo.Testing of doctests in the sources finished, look at the ^ 186 | results in %BUILDDIR%/doctest/output.txt. 187 | goto end 188 | ) 189 | 190 | :end 191 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | .. _ref-usage: 2 | 3 | ===== 4 | Usage 5 | ===== 6 | 7 | Integrated in an application 8 | ---------------------------- 9 | 10 | To use `django-sluggable`_ we will provide a basic application in this section. 11 | 12 | Consider having the following ``models.py``:: 13 | 14 | # users/models.py 15 | 16 | class User(models.Model): 17 | username = models.CharField(max_length=150) 18 | 19 | Now you want urls like ``/users/`` but also keeping your SEO when 20 | a specific user is changing his username: we want a permanent redirection 21 | between the old username and the new one. 22 | 23 | 24 | In ``models.py``, we will define a decider model which will store all usernames:: 25 | 26 | # users/models.py 27 | from sluggable.models import Slug 28 | 29 | 30 | class UserSlug(Slug): 31 | class Meta: 32 | abstract = False 33 | 34 | In the case of our ``User`` class the slug is basically the username of the user, 35 | so we will change the type of the ``username`` field. 36 | 37 | :: 38 | 39 | # users/models.py 40 | from sluggable.fields import SluggableField 41 | 42 | 43 | class User(models.Model): 44 | username = SluggableField(decider=UserSlug) 45 | 46 | def __unicode__(self): 47 | return self.username 48 | 49 | 50 | Now you have your sluggable model, let's play with the API, 51 | by adding our first member in the console:: 52 | 53 | In [1]: from users.models import User, UserSlug 54 | In [2]: user = User.objects.create(username="thoas") 55 | 56 | When you are creating a new ``User`` it will also create a linked model by 57 | using the `contenttypes`_ framework of Django:: 58 | 59 | In [3]: user_slug = UserSlug.objects.get(slug="thoas") 60 | In [4]: user_slug.redirect 61 | False 62 | 63 | With this ``UserSlug`` you can now track every username changes by your users. 64 | 65 | Remember your first created user right? We will change its username:: 66 | 67 | In [5]: user.username = 'oleiade' 68 | In [6]: user.save() 69 | 70 | You new username is now your primary username and you will be able to provide 71 | a permanent redirection between the old one and new one:: 72 | 73 | In [7]: user_slug = UserSlug.objects.get(slug="oleiade") 74 | In [8]: user_slug.redirect 75 | False 76 | In [9]: old_slug = UserSlug.objects.get(slug="thoas") 77 | In [10]: old_slug.redirect 78 | True 79 | 80 | If you are accessing an old slug, you can also retrieve the current one at any 81 | time:: 82 | 83 | In [11]: old_slug.current 84 | 85 | 86 | If you do not have a ``Slug`` instance, no problem you can use the default manager 87 | for that:: 88 | 89 | In [12]: Slug.objects.get_current(user) 90 | 91 | 92 | Work with class-based views 93 | --------------------------- 94 | 95 | Now you know how to manipulate your users, we will add real world 96 | examples in an real application. 97 | 98 | Let's begin with the ``views.py`` file. 99 | 100 | In this section, we will only use `Class-based views`_ so if you are not 101 | familiar with them, go check them they are awesome:: 102 | 103 | # users/views.py 104 | from django.views import generic 105 | 106 | from users.models import User 107 | 108 | 109 | class UserDetailView(generic.Detail): 110 | model = UserSlug 111 | context_object_name = 'slug' 112 | slug_field = 'username' 113 | template_name = 'users/detail.html' 114 | 115 | 116 | # users/urls.py 117 | from users import views 118 | 119 | 120 | urlpatterns = patterns('', 121 | url(r'^users/(?P\w+)/$', 122 | views.UserDetailView.as_view(), 123 | name='user_detail'), 124 | ) 125 | 126 | 127 | So we have defined a pretty standard view to show an user with its username, 128 | so boring duh? 129 | 130 | The interesting part is the redirection provided by `django-sluggable`_, let's 131 | rewrite ``UserDetailView.get``:: 132 | 133 | # users/views.py 134 | from django.views import generic 135 | from django.shorcuts import redirect 136 | 137 | from users.models import User 138 | 139 | 140 | class UserDetailView(generic.Detail): 141 | model = UserSlug 142 | context_object_name = 'user' 143 | slug_field = 'username' 144 | template_name = 'users/detail.html' 145 | 146 | def get(self, request, *args, **kwargs): 147 | obj = self.get_object() 148 | 149 | # The slug retrieved is a redirection to a new one 150 | if obj.redirect: 151 | 152 | # Retrieve the current slug used 153 | current = obj.current 154 | 155 | return redirect('user_detail', username=current.slug) 156 | 157 | # Retrieve the real object affected to the slug 158 | self.object = obj.content_object 159 | 160 | context = self.get_context_data(object=self.object) 161 | 162 | return self.render_to_response(context) 163 | 164 | 165 | Wait? ``UserDetailView.get`` is big. 166 | 167 | .. image:: http://ragefaces.s3.amazonaws.com/503e3b03ae7c700dcb000057/1e6b90eb5b4fd404356004c534bfa613.png 168 | 169 | Let's rewrite it with `django-multiurl`_ to dispatch our slug management between 170 | multiple views. 171 | 172 | With this new method, we don't have to rewrite ``UserDetailView.get`` anymore:: 173 | 174 | # users/views.py 175 | 176 | from django.views import generic 177 | 178 | from users.models import User, UserSlug 179 | 180 | class UserDetailView(generic.Detail): 181 | model = User 182 | context_object_name = 'slug' 183 | slug_field = 'username' 184 | template_name = 'users/detail.html' 185 | 186 | 187 | class UserRedirectView(generic.RedirectView): 188 | permanent = True 189 | 190 | def get_redirect_url(self, username): 191 | slug = get_object_or_404(UserSlug.objects.filter(redirect=True), slug=username) 192 | 193 | return reverse('user_detail', args=(slug.current.slug,)) 194 | 195 | But we have to rewrite our ``urls.py`` file to use `django-multiurl`_:: 196 | 197 | # users/urls.py 198 | 199 | from multiurl import multiurl, ContinueResolving 200 | 201 | from django.http import Http404 202 | 203 | from users import views 204 | 205 | urlpatterns = patterns('', 206 | multiurl( 207 | url(r'^users/(?P\w+)/$', 208 | views.UserDetailView.as_view(), 209 | name='user_detail'), 210 | url(r'^users/(?P\w+)/$', 211 | views.UserRedirectView.as_view(), 212 | name='user_redirect'), 213 | catch = (Http404, ContinueResolving) 214 | ) 215 | ) 216 | 217 | .. image:: http://ragefaces.s3.amazonaws.com/5041ed6dae7c704f08000007/85cbfbcb8f496826ca8867bd28e0d3b9.png 218 | 219 | 220 | Hidden features 221 | --------------- 222 | 223 | How know if the slug has changed?:: 224 | 225 | In [1]: user = User.objects.create(username="thoas") 226 | In [2]: user.slug_changed 227 | False 228 | In [3]: user.slug = 'oleiade' 229 | In [4]: user.slug_changed 230 | True 231 | 232 | How to know if a slug is available or not?:: 233 | 234 | In [1]: user = User.objects.create(username="thoas") 235 | In [2]: UserSlug.objects.is_slug_available('thoas') 236 | False 237 | In [3]: user.slug = 'oleiade' 238 | In [4]: user.save() 239 | In [5]: UserSlug.objects.is_slug_available('thoas') 240 | False 241 | 242 | If you are providing an optional ``obj`` parameter which has the slug:: 243 | 244 | In [6]: UserSlug.objects.is_slug_available('thoas', obj=user) 245 | True 246 | 247 | Restore previous slug and remove redirections:: 248 | 249 | In [7]: UserSlug.objects.update_slug(user, 'thoas', erase_redirects=True) 250 | 251 | .. _`contenttypes`: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/ 252 | .. _`django-sluggable`: https://github.com/thoas/django-sluggable 253 | .. _`Class-based views`: https://docs.djangoproject.com/en/dev/topics/class-based-views/ 254 | .. _`django-multiurl`: https://github.com/jacobian/django-multiurl 255 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sluggable.tests.settings') 7 | os.environ.setdefault('DJANGO_CONFIGURATION', 'Test') 8 | 9 | from django.core.management import execute_from_command_line 10 | 11 | execute_from_command_line(sys.argv) 12 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import os 3 | from setuptools import setup, find_packages 4 | 5 | version = __import__("sluggable").__version__ 6 | 7 | root = os.path.abspath(os.path.dirname(__file__)) 8 | 9 | with open(os.path.join(root, "README.rst")) as f: 10 | README = f.read() 11 | 12 | setup( 13 | name="django-sluggable", 14 | version=version, 15 | description="Slug your multiple models and manage redirections", 16 | long_description=README, 17 | author="Florent Messa", 18 | author_email="florent.messa@gmail.com", 19 | url="http://github.com/thoas/django-sluggable", 20 | packages=find_packages(), 21 | zip_safe=False, 22 | include_package_data=True, 23 | classifiers=[ 24 | "Environment :: Web Environment", 25 | "Intended Audience :: Developers", 26 | "License :: OSI Approved :: MIT License", 27 | "Operating System :: OS Independent", 28 | "Programming Language :: Python", 29 | "Programming Language :: Python :: 3", 30 | "Programming Language :: Python :: 3.8", 31 | "Programming Language :: Python :: 3.9", 32 | "Topic :: Utilities", 33 | ], 34 | ) 35 | -------------------------------------------------------------------------------- /sluggable/__init__.py: -------------------------------------------------------------------------------- 1 | version = (0, 7, 0) 2 | 3 | __version__ = ".".join(map(str, version)) 4 | -------------------------------------------------------------------------------- /sluggable/fields.py: -------------------------------------------------------------------------------- 1 | from django.db.models import signals 2 | from django.db import models 3 | 4 | from . import settings, utils 5 | 6 | 7 | class SluggableObjectDescriptor(object): 8 | def __init__(self, field_with_rel): 9 | self.field = field_with_rel 10 | self.changed = False 11 | 12 | def __get__(self, instance, instance_type=None): 13 | if not instance: 14 | return self 15 | val = instance.__dict__.get(self.field.attname, None) 16 | 17 | if val is None: 18 | # If NULL is an allowed value, return it. 19 | if self.field.null: 20 | return None 21 | 22 | return val 23 | 24 | def __set__(self, instance, value): 25 | instance.__dict__[self.field.attname] = value 26 | 27 | setattr(instance, "%s_changed" % self.field.attname, True) 28 | 29 | 30 | class SluggableField(models.SlugField): 31 | descriptor_class = SluggableObjectDescriptor 32 | 33 | def __init__(self, *args, **kwargs): 34 | self.decider = kwargs.pop("decider", None) 35 | self.populate_from = kwargs.pop("populate_from", None) 36 | self.always_update = kwargs.pop("always_update", False) 37 | self.index_sep = kwargs.pop("sep", settings.SLUGGABLE_SEPARATOR) 38 | self.manager = kwargs.pop("manager", None) 39 | self.slugify = kwargs.pop("slugify", settings.slugify) 40 | assert hasattr(self.slugify, "__call__") 41 | 42 | super(SluggableField, self).__init__(*args, **kwargs) 43 | 44 | def contribute_to_class(self, cls, name): 45 | super(SluggableField, self).contribute_to_class(cls, name) 46 | 47 | signals.post_init.connect(self.instance_post_init, sender=cls) 48 | signals.pre_save.connect(self.instance_pre_save, sender=cls) 49 | signals.post_save.connect(self.instance_post_save, sender=cls) 50 | signals.post_delete.connect(self.instance_post_delete, sender=cls) 51 | 52 | if self.decider: 53 | if not hasattr(self.decider, "sluggable_models"): 54 | self.decider.sluggable_models = [] 55 | 56 | self.decider.sluggable_models.append(cls) 57 | 58 | setattr(cls, self.name, self.descriptor_class(self)) 59 | setattr(cls, "%s_changed" % self.name, True) 60 | 61 | def instance_post_init(self, instance, *args, **kwargs): 62 | if instance.pk: 63 | setattr(instance, "%s_changed" % self.name, False) 64 | 65 | def instance_pre_save(self, instance, *args, **kwargs): 66 | original_value = value = self.value_from_object(instance) 67 | 68 | if self.always_update or (self.populate_from and not value): 69 | value = utils.get_prepopulated_value(instance, self.populate_from) 70 | 71 | if value and ( 72 | original_value != value 73 | or getattr(instance, "%s_changed" % self.name, False) 74 | ): 75 | slug = utils.crop_slug(self.slugify(value), self.max_length) 76 | 77 | slug = self.decider.objects.generate_unique_slug( 78 | instance, slug, self.max_length, self.index_sep 79 | ) 80 | 81 | setattr(instance, self.name, slug) 82 | 83 | return slug 84 | 85 | return None 86 | 87 | def instance_post_save(self, instance, **kwargs): 88 | if getattr(instance, "%s_changed" % self.name, False) and ( 89 | not self.null or self.null and getattr(instance, self.name) 90 | ): 91 | self.decider.objects.update_slug( 92 | instance, 93 | getattr(instance, self.name), 94 | created=kwargs.get("created", False), 95 | ) 96 | 97 | setattr(instance, "%s_changed" % self.name, False) 98 | 99 | def instance_post_delete(self, instance, **kwargs): 100 | self.decider.objects.filter_by_obj(instance).delete() 101 | 102 | def get_prep_lookup(self, lookup_type, value): 103 | if hasattr(value, "value"): 104 | value = value.value 105 | 106 | return super(SluggableField, self).get_prep_lookup(lookup_type, value) 107 | 108 | def get_prep_value(self, value): 109 | if value is None: 110 | return None 111 | 112 | return value 113 | -------------------------------------------------------------------------------- /sluggable/models.py: -------------------------------------------------------------------------------- 1 | import django 2 | 3 | from django.db import models 4 | from django.contrib.contenttypes.models import ContentType 5 | from django.contrib.contenttypes.fields import GenericForeignKey 6 | 7 | try: 8 | from django.utils.translation import gettext_lazy as _ 9 | except ImportError: 10 | from django.utils.translation import gettext_lazy as _ # noqa 11 | 12 | from django.db.models.query import QuerySet 13 | from django.core.exceptions import ObjectDoesNotExist 14 | 15 | 16 | from .utils import get_obj_id, generate_unique_slug 17 | from . import settings 18 | 19 | 20 | class SlugQuerySet(QuerySet): 21 | def filter_by_obj(self, obj, **kwargs): 22 | content_type = kwargs.pop( 23 | "content_type", ContentType.objects.get_for_model(obj) 24 | ) 25 | 26 | return self.filter_by_obj_id(obj.pk, content_type=content_type, **kwargs) 27 | 28 | def filter_by_obj_id(self, obj_id, content_type, **kwargs): 29 | kwargs["content_type_id"] = get_obj_id(content_type) 30 | kwargs["object_id"] = obj_id 31 | 32 | return self._filter_or_exclude( 33 | kwargs.pop("exclude", False), 34 | (), 35 | kwargs, 36 | ) 37 | 38 | def filter_by_model(self, klass, **kwargs): 39 | content_type = kwargs.pop( 40 | "content_type", ContentType.objects.get_for_model(klass) 41 | ) 42 | 43 | return self.filter(content_type_id=get_obj_id(content_type), **kwargs) 44 | 45 | 46 | class SlugManager(models.Manager): 47 | def get_queryset(self): 48 | return SlugQuerySet(self.model) 49 | 50 | if django.VERSION < (1, 6): 51 | get_query_set = get_queryset 52 | 53 | def filter_by_obj(self, *args, **kwargs): 54 | return self.get_queryset().filter_by_obj(*args, **kwargs) 55 | 56 | def filter_by_obj_id(self, *args, **kwargs): 57 | return self.get_queryset().filter_by_obj_id(*args, **kwargs) 58 | 59 | def filter_by_model(self, *args, **kwargs): 60 | return self.get_queryset().filter_by_model(*args, **kwargs) 61 | 62 | def get_current(self, obj, content_type=None): 63 | if isinstance(obj, models.Model): 64 | obj_id = obj.pk 65 | 66 | if not content_type: 67 | content_type = ContentType.objects.get_for_model(obj) 68 | else: 69 | obj_id = obj 70 | 71 | try: 72 | return self.filter_by_obj_id( 73 | obj_id, content_type=content_type, redirect=False 74 | ).get() 75 | except ObjectDoesNotExist: 76 | return None 77 | 78 | def is_slug_available(self, slug, obj=None): 79 | if slug in self.model.forbidden_slugs(): 80 | return False 81 | 82 | if settings.SLUGGABLE_CASE_SENSITIVE: 83 | qs = self.filter(slug=slug) 84 | else: 85 | qs = self.filter(slug__iexact=slug) 86 | 87 | if obj is not None: 88 | qs = qs.filter_by_obj(obj, exclude=True) 89 | 90 | if qs.exists(): 91 | return False 92 | 93 | return True 94 | 95 | def generate_unique_slug(self, instance, slug, max_length, index_sep): 96 | 97 | qs = self.filter_by_obj(instance, exclude=True) 98 | 99 | return generate_unique_slug(qs, instance, slug, max_length, "slug", index_sep) 100 | 101 | def update_slug(self, instance, slug, erase_redirects=False, created=False): 102 | content_type = ContentType.objects.get_for_model(instance) 103 | 104 | pk = instance.pk 105 | 106 | update = False 107 | affected = True 108 | filters = { 109 | "content_type": content_type, 110 | "object_id": pk, 111 | "redirect": False, 112 | "slug": slug, 113 | } 114 | 115 | if not created: 116 | try: 117 | current = self.get(**filters) 118 | new = False 119 | update = current.slug != slug 120 | except self.model.DoesNotExist: 121 | new = True 122 | update = True 123 | 124 | if created or update: 125 | if not created: 126 | base_qs = self.filter(content_type=content_type, object_id=pk) 127 | 128 | qs = base_qs.exclude(slug=slug) 129 | 130 | if not new and erase_redirects: 131 | qs.delete() 132 | else: 133 | qs.update(redirect=True) 134 | 135 | affected = base_qs.filter(slug=slug).update(redirect=False) 136 | 137 | if not affected or created: 138 | slug = self.model(**filters) 139 | slug.save() 140 | 141 | 142 | class Slug(models.Model): 143 | content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT) 144 | object_id = models.PositiveIntegerField() 145 | content_object = GenericForeignKey("content_type", "object_id") 146 | 147 | slug = models.CharField( 148 | max_length=255, verbose_name=_("URL"), db_index=True, unique=True 149 | ) 150 | redirect = models.BooleanField(default=False, verbose_name=_("Redirection")) 151 | 152 | created = models.DateTimeField(auto_now_add=True) 153 | 154 | objects = SlugManager() 155 | 156 | class Meta: 157 | abstract = True 158 | 159 | def __str__(self): 160 | return _("%s for %s") % (self.slug, self.content_object) 161 | 162 | @classmethod 163 | def forbidden_slugs(self): 164 | return [] 165 | 166 | @property 167 | def current(self): 168 | if not self.redirect: 169 | return self 170 | 171 | klass = self.__class__ 172 | 173 | return klass.objects.get_current( 174 | self.object_id, content_type=self.content_type_id 175 | ) 176 | -------------------------------------------------------------------------------- /sluggable/settings.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | 3 | # use custom slugifying function if any 4 | slugify = getattr(settings, "SLUGGABLE_SLUGIFY_FUNCTION", None) 5 | 6 | if not slugify: 7 | try: 8 | # i18n-friendly approach 9 | from unidecode import unidecode 10 | 11 | slugify = lambda s: unidecode(s).replace(" ", "-") 12 | except ImportError: 13 | try: 14 | # Cyrillic transliteration (primarily Russian) 15 | from pytils.translit import slugify 16 | except ImportError: 17 | # fall back to Django's default method 18 | slugify = "django.template.defaultfilters.slugify" 19 | 20 | # find callable by string 21 | if isinstance(slugify, str): 22 | try: 23 | from django.core.urlresolvers import get_callable 24 | except ImportError: 25 | from django.urls.resolvers import get_callable 26 | 27 | slugify = get_callable(slugify) 28 | 29 | 30 | SLUGGABLE_SEPARATOR = getattr(settings, "SLUGGABLE_SEPARATOR", "-") 31 | 32 | SLUGGABLE_CASE_SENSITIVE = getattr(settings, "SLUGGABLE_CASE_SENSITIVE", False) 33 | -------------------------------------------------------------------------------- /sluggable/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thoas/django-sluggable/ab01785412e25ab8c6db48ead7188e6245fb82a0/sluggable/tests/__init__.py -------------------------------------------------------------------------------- /sluggable/tests/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.0.1 on 2019-12-30 03:14 2 | 3 | from django.db import migrations, models 4 | import django.db.models.deletion 5 | import sluggable.fields 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | initial = True 11 | 12 | dependencies = [ 13 | ('contenttypes', '0002_remove_content_type_name'), 14 | ] 15 | 16 | operations = [ 17 | migrations.CreateModel( 18 | name='Answer', 19 | fields=[ 20 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 21 | ('slug', sluggable.fields.SluggableField(null=True)), 22 | ], 23 | ), 24 | migrations.CreateModel( 25 | name='Poll', 26 | fields=[ 27 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 28 | ('question', models.CharField(max_length=200)), 29 | ('pub_date', models.DateTimeField(auto_now_add=True, verbose_name='date published')), 30 | ('slug', sluggable.fields.SluggableField()), 31 | ], 32 | ), 33 | migrations.CreateModel( 34 | name='User', 35 | fields=[ 36 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 37 | ('username', sluggable.fields.SluggableField(unique=True)), 38 | ], 39 | ), 40 | migrations.CreateModel( 41 | name='UserSlug', 42 | fields=[ 43 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 44 | ('object_id', models.PositiveIntegerField()), 45 | ('slug', models.CharField(db_index=True, max_length=255, unique=True, verbose_name='URL')), 46 | ('redirect', models.BooleanField(default=False, verbose_name='Redirection')), 47 | ('created', models.DateTimeField(auto_now_add=True)), 48 | ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='contenttypes.ContentType')), 49 | ], 50 | options={ 51 | 'abstract': False, 52 | }, 53 | ), 54 | migrations.CreateModel( 55 | name='PollSlug', 56 | fields=[ 57 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 58 | ('object_id', models.PositiveIntegerField()), 59 | ('slug', models.CharField(db_index=True, max_length=255, unique=True, verbose_name='URL')), 60 | ('redirect', models.BooleanField(default=False, verbose_name='Redirection')), 61 | ('created', models.DateTimeField(auto_now_add=True)), 62 | ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='contenttypes.ContentType')), 63 | ], 64 | options={ 65 | 'abstract': False, 66 | }, 67 | ), 68 | migrations.CreateModel( 69 | name='AnswerSlug', 70 | fields=[ 71 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 72 | ('object_id', models.PositiveIntegerField()), 73 | ('slug', models.CharField(db_index=True, max_length=255, unique=True, verbose_name='URL')), 74 | ('redirect', models.BooleanField(default=False, verbose_name='Redirection')), 75 | ('created', models.DateTimeField(auto_now_add=True)), 76 | ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='contenttypes.ContentType')), 77 | ], 78 | options={ 79 | 'abstract': False, 80 | }, 81 | ), 82 | ] 83 | -------------------------------------------------------------------------------- /sluggable/tests/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thoas/django-sluggable/ab01785412e25ab8c6db48ead7188e6245fb82a0/sluggable/tests/migrations/__init__.py -------------------------------------------------------------------------------- /sluggable/tests/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | from sluggable.models import Slug 4 | from sluggable.fields import SluggableField 5 | 6 | 7 | class PollSlug(Slug): 8 | class Meta: 9 | abstract = False 10 | 11 | 12 | class Poll(models.Model): 13 | question = models.CharField(max_length=200) 14 | pub_date = models.DateTimeField("date published", auto_now_add=True) 15 | slug = SluggableField(populate_from="question", decider=PollSlug) 16 | 17 | def __str__(self): 18 | return self.question 19 | 20 | 21 | class UserSlug(Slug): 22 | class Meta: 23 | abstract = False 24 | 25 | 26 | class User(models.Model): 27 | username = SluggableField(decider=UserSlug, unique=True) 28 | 29 | 30 | class AnswerSlug(Slug): 31 | class Meta: 32 | abstract = False 33 | 34 | 35 | class Answer(models.Model): 36 | slug = SluggableField(null=True, decider=AnswerSlug) 37 | -------------------------------------------------------------------------------- /sluggable/tests/settings.py: -------------------------------------------------------------------------------- 1 | DATABASES = { 2 | "default": { 3 | "ENGINE": "django.db.backends.sqlite3", 4 | "NAME": ":memory:", 5 | } 6 | } 7 | 8 | SITE_ID = 1 9 | DEBUG = True 10 | 11 | INSTALLED_APPS = [ 12 | "django.contrib.auth", 13 | "django.contrib.contenttypes", 14 | "django.contrib.sessions", 15 | "django.contrib.sites", 16 | "sluggable", 17 | "sluggable.tests", 18 | ] 19 | 20 | SECRET_KEY = "blabla" 21 | 22 | MIDDLEWARE = [ 23 | "django.contrib.sessions.middleware.SessionMiddleware", 24 | "django.middleware.common.CommonMiddleware", 25 | "django.middleware.csrf.CsrfViewMiddleware", 26 | "django.contrib.auth.middleware.AuthenticationMiddleware", 27 | "django.contrib.messages.middleware.MessageMiddleware", 28 | "django.middleware.clickjacking.XFrameOptionsMiddleware", 29 | ] 30 | 31 | SLUGGABLE_SLUGIFY_FUNCTION = "django.template.defaultfilters.slugify" 32 | 33 | DEFAULT_AUTO_FIELD = "django.db.models.AutoField" 34 | -------------------------------------------------------------------------------- /sluggable/tests/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | from .models import Answer, AnswerSlug, Poll, PollSlug, UserSlug, User 4 | 5 | 6 | class SluggableTests(TestCase): 7 | def test_sluggable_models_for_decider(self): 8 | self.assertEqual(PollSlug.sluggable_models, [Poll]) 9 | 10 | def test_slug_without_populate_from(self): 11 | with self.assertNumQueries(4): 12 | user = User.objects.create(username="thoas") 13 | 14 | self.assertEqual(UserSlug.objects.count(), 1) 15 | 16 | user.username = "oleiade" 17 | user.save() 18 | 19 | self.assertEqual(UserSlug.objects.count(), 2) 20 | 21 | current = UserSlug.objects.get_current(user) 22 | 23 | self.assertEqual(current.slug, "oleiade") 24 | 25 | user.username = "thoas" 26 | user.save() 27 | 28 | current = UserSlug.objects.get_current(user) 29 | 30 | self.assertEqual(current.slug, "thoas") 31 | 32 | self.assertEqual(UserSlug.objects.filter(redirect=True).count(), 1) 33 | 34 | user = User.objects.create(username="thoas") 35 | 36 | self.assertEqual(user.username, "thoas-2") 37 | 38 | old = User.objects.get(username="thoas") 39 | old.delete() 40 | 41 | user.username = "thoas" 42 | user.save() 43 | 44 | self.assertEqual(user.username, "thoas") 45 | 46 | def test_changed(self): 47 | poll = Poll.objects.create(question="Quick test") 48 | 49 | self.assertFalse(poll.slug_changed) 50 | 51 | poll = Poll.objects.get(slug="quick-test") 52 | 53 | self.assertFalse(poll.slug_changed) 54 | 55 | poll = Poll(question="Quick test") 56 | 57 | self.assertTrue(poll.slug_changed) 58 | 59 | poll.save() 60 | 61 | self.assertEqual(poll.slug, "quick-test-2") 62 | 63 | def test_simple_add(self): 64 | poll = Poll.objects.create(question="Quick test") 65 | 66 | self.assertEqual(poll.slug, "quick-test") 67 | 68 | self.assertEqual(PollSlug.objects.count(), 1) 69 | 70 | slug = PollSlug.objects.get(slug="quick-test") 71 | 72 | self.assertEqual(slug.slug, "quick-test") 73 | 74 | self.assertFalse(slug.redirect) 75 | 76 | self.assertEqual(slug.content_object, poll) 77 | 78 | def test_simple_when_slugfield_is_nullable(self): 79 | answer = Answer.objects.create() 80 | 81 | self.assertIsNone(answer.slug) 82 | 83 | self.assertEqual(AnswerSlug.objects.count(), 0) 84 | 85 | def test_simple_add_when_slugfield_is_nullable(self): 86 | answer = Answer.objects.create() 87 | 88 | answer.slug = "answer" 89 | answer.save() 90 | 91 | self.assertEqual(answer.slug, "answer") 92 | 93 | self.assertEqual(AnswerSlug.objects.count(), 1) 94 | 95 | slug = AnswerSlug.objects.get(slug="answer") 96 | 97 | self.assertEqual(slug.slug, "answer") 98 | 99 | self.assertFalse(slug.redirect) 100 | 101 | self.assertEqual(slug.content_object, answer) 102 | 103 | def test_redirect(self): 104 | poll = Poll.objects.create(question="Quick test") 105 | poll.question = "Another test" 106 | poll.save() 107 | 108 | self.assertEqual(poll.slug, "quick-test") 109 | 110 | poll.slug = "quick-test-2" 111 | poll.save() 112 | 113 | self.assertEqual(PollSlug.objects.count(), 2) 114 | 115 | slug = PollSlug.objects.get(slug="quick-test-2") 116 | 117 | self.assertFalse(slug.redirect) 118 | 119 | old = PollSlug.objects.get(slug="quick-test") 120 | 121 | self.assertTrue(old.redirect) 122 | 123 | current = PollSlug.objects.get_current(poll) 124 | 125 | self.assertEqual(old.current, slug) 126 | 127 | self.assertFalse(current is None) 128 | 129 | self.assertFalse(current.redirect) 130 | 131 | def test_redirect_restore_previous_slug(self): 132 | poll = Poll.objects.create(question="Quick test") 133 | poll.question = "Another test" 134 | poll.save() 135 | 136 | poll.slug = "quick-test-2" 137 | poll.save() 138 | 139 | self.assertEqual(PollSlug.objects.count(), 2) 140 | 141 | poll.slug = "quick-test" 142 | poll.save() 143 | 144 | self.assertEqual(PollSlug.objects.count(), 2) 145 | 146 | slug = PollSlug.objects.get(slug="quick-test") 147 | self.assertFalse(slug.redirect) 148 | 149 | self.assertEqual(PollSlug.objects.filter(redirect=False).count(), 1) 150 | 151 | current = PollSlug.objects.get_current(poll) 152 | 153 | self.assertEqual(current.slug, "quick-test") 154 | 155 | def test_is_slug_available(self): 156 | poll = Poll.objects.create(question="Quick test") 157 | 158 | self.assertFalse(PollSlug.objects.is_slug_available("quick-test")) 159 | 160 | self.assertTrue(PollSlug.objects.is_slug_available("quick-test", obj=poll)) 161 | 162 | def test_delete(self): 163 | poll = Poll.objects.create(question="Quick test") 164 | 165 | self.assertEqual(PollSlug.objects.count(), 1) 166 | 167 | poll.delete() 168 | 169 | self.assertEqual(PollSlug.objects.count(), 0) 170 | -------------------------------------------------------------------------------- /sluggable/utils.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | from django.db import models 4 | 5 | 6 | def get_obj_id(obj): 7 | obj_id = obj 8 | 9 | if isinstance(obj, models.Model): 10 | obj_id = obj.pk 11 | 12 | return obj_id 13 | 14 | 15 | def get_prepopulated_value(instance, populate_from): 16 | """ 17 | Returns preliminary value based on `populate_from`. 18 | """ 19 | if hasattr(populate_from, "__call__"): 20 | return populate_from(instance) 21 | 22 | attr = getattr(instance, populate_from) 23 | return callable(attr) and attr() or attr 24 | 25 | 26 | def crop_slug(slug, max_length): 27 | if max_length < len(slug): 28 | return slug[:max_length] 29 | 30 | return slug 31 | 32 | 33 | def generate_unique_slug(qs, instance, slug, max_length, field_name, index_sep): 34 | """ 35 | Generates unique slug by adding a number to given value until no model 36 | instance can be found with such slug. If ``unique_with`` (a tuple of field 37 | names) was specified for the field, all these fields are included together 38 | in the query when looking for a "rival" model instance. 39 | """ 40 | 41 | original_slug = slug = crop_slug(slug, max_length) 42 | 43 | index = 1 44 | 45 | # keep changing the slug until it is unique 46 | while True: 47 | # find instances with same slug 48 | rivals = qs.filter(**{field_name: slug}).exclude(pk=instance.pk) 49 | 50 | if not rivals: 51 | # the slug is unique, no model uses it 52 | return slug 53 | 54 | # the slug is not unique; change once more 55 | index += 1 56 | 57 | # ensure the resulting string is not too long 58 | tail_length = len(index_sep) + len(str(index)) 59 | combined_length = len(original_slug) + tail_length 60 | if max_length < combined_length: 61 | original_slug = original_slug[: max_length - tail_length] 62 | 63 | # re-generate the slug 64 | data = dict(slug=original_slug, sep=index_sep, index=index) 65 | 66 | slug = "%(slug)s%(sep)s%(index)d" % data 67 | 68 | return slug 69 | -------------------------------------------------------------------------------- /sluggable/views.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thoas/django-sluggable/ab01785412e25ab8c6db48ead7188e6245fb82a0/sluggable/views.py -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | 3 | envlist = 4 | {py38}-django{32} 5 | 6 | [testenv] 7 | 8 | basepython = 9 | py38: python3.8 10 | 11 | deps = 12 | coverage 13 | {py38}-django32: Django>=3.2 14 | 15 | setenv = 16 | PYTHONPATH = {toxinidir} 17 | 18 | whitelist_externals = 19 | make 20 | 21 | changedir = {toxinidir} 22 | 23 | commands = 24 | make test 25 | --------------------------------------------------------------------------------