models: prevent too long error on Origin.slug (#54047)

This commit is contained in:
Benjamin Dauvergne 2021-08-24 10:02:54 +02:00
parent d5f8c07b97
commit bd8a6e32b6
2 changed files with 36 additions and 3 deletions

View File

@ -0,0 +1,25 @@
# Generated by Django 2.2.19 on 2021-08-24 07:57
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('fargo', '0001_squashed_0017_auto_20180331_1532'),
]
operations = [
migrations.AlterField(
model_name='origin',
name='label',
field=models.TextField(verbose_name='Label'),
),
migrations.AlterField(
model_name='origin',
name='slug',
field=models.SlugField(max_length=256, verbose_name='Slug'),
),
]

View File

@ -16,6 +16,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import base64
import hashlib
import subprocess
import os
import re
@ -42,14 +43,21 @@ from jsonfield import JSONField
from . import utils, managers
def slug_truncate(label, length=256):
slug = slugify(label)
if len(slug) < length:
return slug
return slug[: length - 5] + '-%4s' % hashlib.md5(label.encode()).hexdigest()[:4]
@python_2_unicode_compatible
class Origin(models.Model):
label = models.CharField(_('Label'), max_length=80)
slug = models.SlugField(_('Slug'))
label = models.TextField(_('Label'))
slug = models.SlugField(_('Slug'), max_length=256)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.label)
self.slug = slug_truncate(self.label)
return super(Origin, self).save(*args, **kwargs)
def __str__(self):