Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-Admin Stores NULL in Database Instead of empty string ('')

Title says it all. Using flask-admin and would like to store an empty string in my database instead of NULL but when I leave a field blank in flask-admin it enters NULL in the database. If I type '' into the flask-admin view, the database stores that as "''" in the database.

I am NOT asking about how to display an empty string in the flask-admin view as a lot of other people have asked about. I am asking what I should type into the flask-admin view or what code I should change in order to store an empty string in my database from the flask-admin view.

The reason I need to do this is parts of my code validates the table column at issue for '' (an empty string). Example: db.tablename.query.filter_by(complete=''). One option is to change all my validation to db.tablename.query.filter_by(complete=None), but I would like to keep all my code consistent in validating for '' and it would be a lot to change all the validation lines to None so it would be most helpful if I knew how to set a table cell to a blank string from the flask-admin view.

Using python3.6

like image 342
user10213377 Avatar asked Nov 24 '25 08:11

user10213377


1 Answers

To override this behaviour you can create a new field class:

import wtforms.fields

class StringField(wtforms.fields.StringField):
    def process_data(self, value):
        self.data = value or ''

process_data method receives and stores form data. If it receives None it will store it as ''. To use this logic in your view add this class to the form_overrides attribute:

class MyView(ModelView):
    form_overrides = {
        'my_field': StringField,
    }
like image 51
Sergey Shubin Avatar answered Nov 27 '25 01:11

Sergey Shubin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!