python - Best practice: prepopulate SlugField in Django (without Admin module) -


in days of django possible prepopulate slugfield within model.

in admin module use

prepopulated_fields = {'slug':('title',),} 

i found snippet handles unique slugify doubt best way.

so best practise autogenerate slugfield without using admin module?

id use modelform integrade form in frontpage, should autogenerate unique slug url.

this cut , paste 1 of older (as in less coded) models. should show idea, little polish, should work.

from django.template.defaultfilters import slugify def get_nickname(self):     nick = self.name     vowels = ('a','e','i','o','u')     first_letter = nick[:1]     nick = nick[1:]      vowel in vowels: nick = nick.replace(vowel,'')     nick = first_letter + nick     if len(nick) > 8:         nick = nick[:7]     return nick  def save(self, force_insert=false, force_update=false, using=none):     if not self.nickname:         self.nickname = self.get_nickname() if len(self.name)>8 else self.name     self.slug = slugify(self.nickname)     slug_test = somemodel.objects.filter(slug=self.slug, id=self.id) # corrected use generic model name     if slug_test:         count = slug_test.count         self.slug = "{}{}".format(self.slug[:len(self.slug)-1], count)      super(somemodel, self).save() 

update: tighter code get_nick method ...

>>> name = 'alabama' >>> vowels = {'a', 'e', 'i', 'o', 'u'} >>> nick = name[0] + ''.join(l l in name[1:] if l not in vowels) >>> nick 'albm' 

fwiw: updated model, eliminating get_nickname method, , adding simple lambda top of save method:

vowels = {'a','e','i','o','u'} create_nick = lambda name: name[0] + ''.join(l l in name[1:] if l not in vowels)[:7] if not self.nickname:     self.nickname = create_nick(self.name) if len(self.name)>8 else self.name ... 

Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

css - Can I use the :after pseudo-element on an input field? -