I want to create a slug field stored in database.
I searched and I found http://flask.pocoo.org/snippets/5/ but I'm having trouble integrating the code in my app.
This is my modele.py
:
from unicodedata import normalize
def slugfy(text, encoding=None,
permitted_chars='abcdefghijklmnopqrstuvwxyz0123456789-'):
if isinstance(text, str):
text = text.decode(encoding or 'ascii')
clean_text = text.strip().replace(' ', '-').lower()
while '--' in clean_text:
clean_text = clean_text.replace('--', '-')
ascii_text = normalize('NFKD', clean_text).encode('ascii', 'ignore')
strict_text = map(lambda x: x if x in permitted_chars else '', ascii_text)
return ''.join(strict_text)
class Chanteur(db.Model):
id = db.Column(db.Integer, primary_key = True)
nom = db.Column(db.String(200), index = True, unique = True)
slug = db.Column(db.String(255))
chanteurs = db.relationship('Chanson', backref = 'chanteur', lazy = 'dynamic')
def __repr__(self):
return '<Chanteur %r>' % (self.nom)
def __setattr__(self, key, value):
super(Chanteur, self).__setattr__(key, value)
if key == 'nom':
self.slug = slugfy(self.nom)
class Chanson(db.Model):
id = db.Column(db.Integer, primary_key = True)
titre = db.Column(db.String(255))
chanteur_id = db.Column(db.Integer, db.ForeignKey('chanteur.id'))
def __repr__(self):
return '<Chanson %r>' % (self.titre)
It is not working: when I add a new objet (chanteur) the slug field is empty