Answer the question
In order to leave comments, you need to log in
How to automatically generate a slug from a Russian word?
there is a simple model:
class ModelZavet(models.Model):
mz_name = models.CharField('Название для сайта', max_length=200)
mz_slug = models.SlugField('URL', max_length=70, db_index=True)
mz_num = models.PositiveSmallIntegerField('Порядок', default=1)
mz_descriptions = models.TextField('Описание', blank=True)
prepopulated_fields = {'mz_slug': ('mz_name',)}
def save(self, *args, **kwargs):
if not self.id:
self.mz_slug = slugify(self.mz_name)
super(ModelZavet, self).save(*args, **kwargs)
Answer the question
In order to leave comments, you need to log in
write your own slugify with Russian support, or, before that, make a transliteration of mz_name
from autoslug import AutoSlugField # AutoSlugField needs to be additionally installed (pip install django-autoslug) - adds slug fields
from uuslug import uuslug # needs to be additionally installed (pip install django-uuslug) - translates URLs to Latin
class ModelZavet(models.Model):
...
mz_slug = AutoSlugField('URL', max_length=70, db_index=True, unique=True, populate_form=lambda instance: instance.mz_name, slugify=lambda value: value.replace(' ', '-'))
. ..
def save(self, *args, **kwargs):
self.mz_slug = uuslug(self.mz_slug, instance=self)
super(ModelZavet, self).save(*args, **kwargs)
# populate_form -> takes title title
# slugify=lambda value: value.replace(' ', '-') -> replace spaces with dashes
! In order to avoid problems when performing migration -> replace lambda functions with regular functions and write them before the model
def instance_ mz_slug(instance):
return instance.mz_name
def slugify_value(value):
return value.replace(' ', '-' ) #should
be like this:
class ModelZavet(models.Model):
...
mz_slug = AutoSlugField('URL', max_length=70, db_index=True, unique=True, verbose_name='URLs',
populate_from= instance_ mz_slug, slugify= slugify_value)
...
! If admin.py says
prepopulated_fields = {'mz_slug': ('mz_name',)} -> need to be removed or commented out
! There is no need to specify anything else
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question