Code Monkey home page Code Monkey logo

django-autoslug's People

Contributors

azmeuk avatar bertrandbordage avatar botpub avatar cclauss avatar cyberj avatar davidstockwell avatar dteskera avatar dubrzr avatar fabiocaccamo avatar fuzzylogic2000 avatar giff-h avatar hoylemd avatar ipmb avatar jayvdb avatar jezdez avatar justinmayer avatar kane-c avatar kangfend avatar kmike avatar kostko avatar mikeurbanski avatar neithere avatar nicoechaniz avatar philb61 avatar shanx avatar ulgens avatar vstoykov avatar willyhakim avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-autoslug's Issues

unique_with does not work with BooleanFields

I have a model which has a BooleanField that determines on which path a model should be visible:

class ExampleModel(models.Model):
    title = models.CharField(max_length=255)
    is_in_A = models.BooleanField()
    slug = AutoSlugField(unique_with='is_in_A', populate_from='title', always_update=True)

The unique_with in this field does not work when the is_in_A is False.

autoslug 1.9.4 python 3.7.3 django 2.2 import successfull but importlib fails

Hi,

I am trying to use an AutoSlugField in my django 2.2 application, the import in my INSTALLED_APPS settings.py raises no error but when using it in my app model i get a python3 import lib error.

Any ideas why this happens and how to fix it ?

Below is the code and output.

autoslug_error

pip freeze outputs django-autoslug==1.9.4

PS : this happens when running python manage.py makemigrations

Yours thankfully

Django 1.10 compatibility

autoslug.utils.get_uniqueness_lookups uses _meta.get_field_by_name, which is deprecated in Django 1.9 and removed in Django 1.10 (shows up when running Django 1.8 with the -Wall python flag):

.../python2.7/site-packages/autoslug/utils.py:119: RemovedInDjango110Warning: 'get_field_by_name is an unofficial API that has been deprecated. You may be able to replace it with 'get_field()'
    field_object, model, direct, m2m = instance._meta.get_field_by_name(field_name)

allow_unicode should not be popped off the kwargs

Currently, the django-autoslug sets self.allow_unicode to the kwargs value and it pops allow_unicode out the kwargs.

self.allow_unicode = kwargs.pop('allow_unicode', False)

Since SlugField has allow_unicode=False in its init kwargs, and then sets self.allow_unicode=allow_unicode, you get a situation where self.allow_unicode is always false.

The solution is to just remove the code where self.allow_unicode is set and the kwargs are popped off.

error when used model.save()

Hello,

i have the following:

from django.db import models
from autoslug import AutoSlugField
from autoslug.settings import slugify as default_slugify

class Cimas(models.Model):

  def slugify_sierra(self, value):
    return default_slugify(value.replace('/', '-'))

  c_nombre = models.CharField(
    max_length = 150,
  )
  c_sierra = models.CharField(
    max_length = 150,
    blank = True,
    null = True,
  )
  sierra_slug = AutoSlugField(
    max_length = 150,
    populate_from = 'c_sierra',
    slugify=slugify_sierra,
  )
  c_estado = models.CharField(
    choices = ESTADOS,
    max_length = 11,
    default = 'Desconocida',
  )

  --- more fields ---

When i edit a record slug filed is change correctly without error, but when a use Model.save() in shell or in a funcition i've got this error:

python3 manage.py shell
Python 3.6.3 (v3.6.3:2c5fed86e0, Oct  3 2017, 00:32:08)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.5.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from senderismo.models import Cimas

In [2]: cima = Cimas.objects.filter(c_nombre = "Zaria")[0]

In [3]: cima
Out[3]: <Cimas:   768 - Zaria (625 m) - estado: Pendiente - buzón: Con buzón>

In [4]: cima.c_sierra
Out[4]: 'Igorin/bianditz'

In [5]: cima.sierra_slug
Out[5]: 'igorin-bianditz'

In [6]: cima.c_estado
Out[6]: 'Pendiente'

In [7]: cima.c_estado = "Hecha"

In [8]: cima.c_estado
Out[8]: 'Hecha'

In [9]: cima.save()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-ef79aeddcd43> in <module>
----> 1 cima.save()

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/base.py in save(self, force_insert, force_update, using, update_fields)
    739
    740         self.save_base(using=using, force_insert=force_insert,
--> 741                        force_update=force_update, update_fields=update_fields)
    742     save.alters_data = True
    743

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/base.py in save_base(self, raw, force_insert, force_update, using, update_fields)
    777             updated = self._save_table(
    778                 raw, cls, force_insert or parent_inserted,
--> 779                 force_update, using, update_fields,
    780             )
    781         # Store the database on which the object was saved

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/base.py in _save_table(self, raw, cls, force_insert, force_update, using, update_fields)
    846             base_qs = cls._base_manager.using(using)
    847             values = [(f, None, (getattr(self, f.attname) if raw else f.pre_save(self, False)))
--> 848                       for f in non_pks]
    849             forced_update = update_fields or force_update
    850             updated = self._do_update(base_qs, using, pk_val, values, update_fields,

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/base.py in <listcomp>(.0)
    846             base_qs = cls._base_manager.using(using)
    847             values = [(f, None, (getattr(self, f.attname) if raw else f.pre_save(self, False)))
--> 848                       for f in non_pks]
    849             forced_update = update_fields or force_update
    850             updated = self._do_update(base_qs, using, pk_val, values, update_fields,

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/autoslug/fields.py in pre_save(self, instance, add)
    274         slug = None
    275         if value:
--> 276             slug = self.slugify(value)
    277         if not slug:
    278             slug = None

TypeError: slugify_sierra() missing 1 required positional argument: 'value'

What am i doing wrong ?

What i want to do is change some Cimas fileds (not slug filed) from a function

Verison: django-autoslug 1.9.8

NOTE: sorry for my bad English.

Thank you.

Uniqueness Manager is always overridden

If you override the de manager that check for uniqueness, it will always be overridden bij de Default manager in case of empty result-set (ie. in case the value is unique according to the manager).

Error is at:
https://github.com/justinmayer/django-autoslug/blob/master/autoslug/utils.py#L64

The check is if not manager, which should be if manager is None. By doing if not manager, the results of if not QuerySet<[]> will make the AutoSlugField use the fallback of defaultmanager.

Populate with two fields

Hi, I have a question, ¿May I populate AutpSlugField with more than one field? I mean, if I want to generate slug with this model:

class Article(models.Model):
name = models.CharField()
created_at = models.DateField()
slug = AutoSlugField(populate_from=('title', 'created_at'))

This will generate the next slug: 'article-name-2016-08-04'

u"Key 'slug' not found in 'CategoryForm'"

Dear sir. I just install django-autoslug but when i start add new item on admin panel an error occurred with info:

KeyError at /admin/blog/category/add/

u"Key 'slug' not found in 'CategoryForm'"

Request Method: GET
Request URL: http://localhost:8000/admin/blog/category/add/
Django Version: 1.8.6
Exception Type: KeyError
Exception Value:

u"Key 'slug' not found in 'CategoryForm'"

Please help me.
Many thanks

Is django-autoslug dead?

Hi,

I have noticed, as many others, that this package isn't moving forward.

As mentioned in #16 @neithere doesn't have the time to maintain the project. Also mentioned is a movement of the project to jazzband, which I can see here: jazzband/help#38
But, as far I can see in that issue, the move isn't completed yet. #12 tells the same story.

Cookiecutter-django are started considering abandon django-autoslug (cookiecutter/cookiecutter-django#1111), and I have the same thoughts as well. If the community isn't able to help develop and maintain the project - I have to either abandon it or clone the project and try to get a movement of the community. A thing I really would not like.

@neithere and others - are there anything we as community can do the help the movement of the project to jazzband?

Function to generate unique slug can generate an excessive number of DB query

The code that generates the unique slug is querying the database indefinitely until it finds the unique value.

In the case of common words, this causes excessive number of db calls. It would be nice if it was possible to specify the maximum number of tries. A uuid value can be used to generate the slug after index exceeds that number.

Lambda functions no longer work with Django migrations

To use a function (like slugifying someone's full name, which requires an instance of the model), in the past you could use a Lambda function. However, trying to do an (unrelated) migration on that model now raises an error:

"ValueError: Cannot serialize function: lambda"

Migration error 'function' object has no attribute 'slugify'

Hey here is what was generated with django migrations
from slugify import slugify
...
('slug', autoslug.fields.AutoSlugField(always_update=True, blank=True, editable=False, null=True, populate_from=b'name', slugify=slugify.slugify.slugify, unique=True)),

AttributeError: 'function' object has no attribute 'slugify'

I get this when trying to migrate.

No python 2.7 pypi release

I was getting this setup.py error on version 0.9.1:

    from _version_helper import __version__

ImportError: No module named _version_helper

Looking at the releases I figure this was a packaging error that got fixed in 0.9.2.
Unfortunately 0.9.2 is not available as a Python 2.7 package, just as a Py3 wheel.

Import "autoslug" could not be resolved

I have installed django-autoslug 1.9.9 but when I try to Import it in my models.py file it brings up the error Import "autoslug" could not be resolved. I'm using Python 3.12.2 and Django 5.0.3. All my other installed libraries are working fine except this one.

AutoSlugField with two charfields

Hi,

is possible to crate a slug with two foreignkey? For example

class Match(models.Model):
    home = models.ForeignKey(
        'groups_manager.Group',
        verbose_name=_('Home Team'),
        related_name='home_player_set'
    )
    away = models.ForeignKey(
        'groups_manager.Group',
        verbose_name=_('Away Team'),
        related_name='away_player_set')

   slug = AutoSlugField(populate_from='home + away')

Autoslug does not create unique slugs with `bulk_create`

Add this test to AutoSlugFieldTestCase and see it raise an exception:

    def test_uniqueness_slug_with_bulk_create(self):
        ModelWithUniqueSlug.objects.bulk_create([
            ModelWithUniqueSlug(name='test'),
            ModelWithUniqueSlug(name='test'),
        ])
        a, b = list(ModelWithUniqueSlug.objects.all())
        assert a.slug != b.slug

slug doesn't work peoperly in Farsi even with allow_unicode=True

hi
so i'm using AutoSlugField for a website that is in Farsi language (similar to arabic alphabet)
and i set the allow_unicode to True
but it still dosen't work and just returns the name of the model as slug

this is my field:
slug = AutoSlugField(verbose_name=_("slug"), populate_from="title", unique=True, allow_unicode=True)

worth noting that it works fine when i use an english word as title
the problem is with using Farsi words

Add modeltranslation support

Steps to reproduce the problem:

  • more languages, for example: en, it, fr
  • default language: en
  • modeltranslation installed
  • model with a name field and a slug field populated from name
  • name and slug fields are marked for translation in translation.py
  • in the admin populate the name field for all languages using the different values and save it

Current result:
All slug values are always (for all languages) the slugified version of name in the default language:

slug_en populated from name_en
slug_it populated from name_en
slug_fr populated from name_en

Expected result:
Each slug value should be the slugified version of name for the corresponding language:

slug_en populated from name_en
slug_it populated from name_it
slug_fr populated from name_fr

Dirty solution overriding model save method:

#requires always_update = False
def save(self, *args, **kwargs):
    
    for lang_code, lang_verbose in settings.LANGUAGES:
        lang_code = lang_code.replace('-', '_')
        
        setattr(self, 'slug_%s' % lang_code, slugify( getattr(self, 'name_%s' % lang_code, u'') ))
        
    super( NameSlugModel, self ).save( *args, **kwargs )

Unique atribute double sense.

I got an strange requests and i do not know how to solve my problem. I need to generate uniq slugs in my model, but i also need my column be not uniq. Is there way to generate uniq slug without uniq column in database(postgres)?

AssertionError: slug is defined before trying to ensure uniqueness

I have the exact same issue as described on Bitbucket: https://bitbucket.org/neithere/django-autoslug/issues/45/slug-is-defined-before-trying-to-ensure.

Here is my code (Django 1.10.3 and Python 3.5.2):

class Query(models.Model):
    text = models.CharField(max_length=512, unique=True, db_index=True)
    slug = AutoSlugField(populate_from='text', db_index=True, unique=True, always_update=True)
    # ...

The problem occurs when I try to save Query model with unsluggable data in the text field:

>>> Query.objects.get_or_create(text="???????")
***\lib\site-packages\autoslug\fields.py in pre_save(self, instance, add)
    270
    271         if not self.blank:
--> 272             assert slug, 'slug is defined before trying to ensure uniqueness'
    273
    274         if slug:

AssertionError: slug is defined before trying to ensure uniqueness

The source of the problem is following code in autoslug/utils.py (Note: I have unidecode installed):

# ...

# Use Django's default method over decoded string
    def slugify(value):
        return django_slugify(unidecode(value))

# ...

Django slugify function fails to create slug from text ??????? and autoslug fails on AssertionError.

I don't know how should autoslug behave in these situations but it would be great to provide nicer error (e.g. raise ValueError("Sorry but it is not possible to create slug from...")).

To @egregors: Try to install unidecode: pip install unidecode. Standard slugify function in Django doesn't work on all non-ascii data:

In [1]: from django.template.defaultfilters import slugify

In [2]: slugify('Привет!')
Out[2]: ''

vs:

In [4]: from unidecode import unidecode

In [5]: unidecode('Привет!')
Out[5]: 'Privet!'

Autoslug will use unidecode automatically, see this code: https://github.com/neithere/django-autoslug/blob/master/autoslug/utils.py#L19-L20.

How to force update / refresh the slug field?

Hi,

I did a model for blog posts and I want to update the slug until the "published" value is False. After that the post owner can update the title but the slug will stay the same. My initial idea was to put this logic inside the save method but I didn't found the "refresh" method from AutoSlugField. How can I solve this?

Regards,
Douglas

How to increase maximum length of AutoSlug field

I have tried adding max_length=255 to AutoSlugField but it is not getting reflected in forms, still getting a fixed length of 50, makemigrations then migrate is not applying new value, how to fix ?

License has viral clauses in it

https://github.com/neithere/django-autoslug/blob/master/COPYING.LESSER

I should have looked closer, I didn't realize this was an LGPL package. This can really hurt projects if someone alleges the delicate and ambiguous clauses of the LGPL a triggered a derivative work.

As a solo-founder, I can't afford to defend a legal accusation of creating a derivative, nor the time to explain why pages of ambiguous legal terminology can really cause a nightmare down the road. It's strongly advised not to cargocult legal documents without vetting them first.

Unless you have an explicit need to have people's projects using this project to be cannibalized to being a derivative of this project, it's advisable to pick a license like MIT/BSD/ISC that doesn't include the machinery to make such a thing a possibility.

I am removing all traces of this project from my code. And have to rewrite refs on https://github.com/develtech/django-slugify-processor as well.

max_length is not defined in migration

After having added a slug field with max_length = 100 to a model and run manage.py makemigrations, if you open the migration file you can see that max_length is not defined, then the field max_length will be set to 50.

Support for Django 2.0 ?

Hi,

i have the problem when upgrade to Django 2.0

from django.core.urlresolvers import get_callable
ImportError: No module named 'django.core.urlresolvers'

slug that has a dash at the end initially is changed with next model save

When the field to populate the slug from is a long string (>50) with a dash, underscore or blank at the 50th position, the initial slug will end with a dash or underscore. With the first model save after the initial one, the dash is removed.

This was introduced by a change in Django's slugify with version 3.
django/django@0382ecf

Because the slugify is used before the slug is cropped, the dash or underscore at the end is initially saved.

slug = self.slugify(value)

return slug[:field.max_length]

I added a test showing the problem (and opened a PR by accident earlier, sorry). The test is here:https://github.com/fuzzylogic2000/django-autoslug/blob/a96382f61751912b1a7e2ae755625b5e5a0077d7/autoslug/tests/tests.py#L275

I would like to fix this. How would you prefer that I do that?
My favourite solition is to use the slugify function a second time, directly after the cropping. That would not only solve this in this case, but also when there are other future changes.
Another solution would be to rstrip the dash or underscore.

Doesn't work with Django 3.1

Hi,

I tried django-autoslug==1.9.7 with django==3.1rc1 and got this error:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/mmalysh/Dev/my-project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/Users/mmalysh/Dev/my-project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 377, in execute
    django.setup()
  File "/Users/mmalysh/Dev/my-project/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/mmalysh/Dev/my-project/venv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate
    app_config.import_models()
  File "/Users/mmalysh/Dev/my-project/venv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models
    self.models_module = import_module(models_module_name)
  File "/Users/mmalysh/.pyenv/versions/3.7.7/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/Users/mmalysh/Dev/my-project/src/apps/stats/models.py", line 6, in <module>
    from autoslug import AutoSlugField
  File "/Users/mmalysh/Dev/my-project/venv/lib/python3.7/site-packages/autoslug/__init__.py", line 12, in <module>
    from autoslug.fields import AutoSlugField
  File "/Users/mmalysh/Dev/my-project/venv/lib/python3.7/site-packages/autoslug/fields.py", line 30, in <module>
    from autoslug.settings import slugify, autoslug_modeltranslation_enable
  File "/Users/mmalysh/Dev/my-project/venv/lib/python3.7/site-packages/autoslug/settings.py", line 71, in <module>
    slugify = get_callable(slugify_function_path)
  File "/Users/mmalysh/Dev/my-project/venv/lib/python3.7/site-packages/django/urls/utils.py", line 28, in get_callable
    mod = import_module(mod_name)
  File "/Users/mmalysh/.pyenv/versions/3.7.7/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "/Users/mmalysh/Dev/my-project/venv/lib/python3.7/site-packages/autoslug/utils.py", line 17, in <module>
    from django.db.models.fields import FieldDoesNotExist, DateField
ImportError: cannot import name 'FieldDoesNotExist' from 'django.db.models.fields' (/Users/mmalysh/Dev/my-project/venv/lib/python3.7/site-packages/django/db/models/fields/__init__.py)

Here is a release note related to the error:

The compatibility import of django.core.exceptions.FieldDoesNotExist in django.db.models.fields is removed.

Django release notes: https://docs.djangoproject.com/en/3.1/releases/3.1/

ModuleNotFoundError: No module named 'django.core.urlresolvers' on python 3.6.3

File "/Users/sadafnoor/.pyenv/versions/evaly3.6.3/lib/python3.6/site-packages/autoslug/__init__.py", line 11, in <module>
    from autoslug.fields import AutoSlugField
  File "/Users/sadafnoor/.pyenv/versions/evaly3.6.3/lib/python3.6/site-packages/autoslug/fields.py", line 29, in <module>
    from autoslug.settings import slugify, autoslug_modeltranslation_enable
  File "/Users/sadafnoor/.pyenv/versions/evaly3.6.3/lib/python3.6/site-packages/autoslug/settings.py", line 61, in <module>
    from django.core.urlresolvers import get_callable
ModuleNotFoundError: No module named 'django.core.urlresolvers'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.