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
SlugField is used for storing basically storing URL paths after a particular URL. To know more about how to properly add a SlugField to Django Project, refer this article – Add the slug field inside Django Model Now let’s check it in admin server. We have created an instance of GeeksModel.
A new folder named migrations would be created in geeks directory with a file named 0001_initial.py Thus, an geeks_field SlugField is created when you run migrations on the project. How to use SlugField ? SlugField is used for storing basically storing URL paths after a particular URL.
Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to SlugField will enable it to store empty values for that table in relational database. Here are the field options and attributes that an SlugField can use.
Flask-RESTful provides an easy way to control what data you actually render in your response. With the fields module, you can use whatever objects (ORM models/custom classes/etc.) you want in your resource. fields also lets you format and filter the response so you don’t have to worry about exposing internal data structures.
To persist the slug in the database, I use the following approach (employing the very helpful python-slugify
library):
from slugify import slugify # among other things
class Song(db.Model):
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(255))
slug = db.Column(db.String(255))
def __init__(self, *args, **kwargs):
if not 'slug' in kwargs:
kwargs['slug'] = slugify(kwargs.get('title', ''))
super().__init__(*args, **kwargs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With