Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

slug field on flask

Tags:

python

flask

slug

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

like image 288
anouar Avatar asked May 14 '14 14:05

anouar


People also ask

What is slugfield in Django?

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.

How to create Geeks_field slugfield?

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.

What are slugfield options and attributes?

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.

What is fields in flask-RESTful?

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.


Video Answer


1 Answers

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)
like image 179
Berislav Lopac Avatar answered Oct 02 '22 11:10

Berislav Lopac