Make primary key fields editable in Flask-Admin

I am using Flask-Admin for my Flask based project. In it I have some models (using peewee) where the primary key is user configured, for example username

for User

. However, Flask-Admin does not show these fields in page creation / editing models.

Now, when I try to create a new user, the Save button gives an error peewee.UserDoesNotExist

, and the Save and Add button says "Record was created successfully" twice, but doesn't actually do anything.

I extended the method save()

to automatically generate username from name if canceled, but the problem persisted even when I removed the override.

Code...

This is what my User model looks like:

# import peewee as pw

class User(BaseModel, UserMixin):
    username = pw.CharField(32, primary_key=True)
    password = pw.CharField(512, null=True)
    name = pw.CharField(64)

    # ... other fields not shown ... #

    def save(self, *args, **kwargs):
        # Set the username if field is blank
        if self.username == 'auto' or not self.username:
            self.username = self.name.replace(' ', '').lower()
        # Do the real save
        super(User, self).save(*args, **kwargs)

      

Here is my admin code:

# from flask_admin.contrib.peewee.view import ModelView

class AdminModelUser(ModelView):
    can_create = True
    column_list = ('username', 'name', 'group', 'active')

admin.add_view(AdminModelUser(User, name='Users', category='Accounts'))

      

Trying things

I later tried to override the method get_form()

to directly use wtfpeewee

and allow pk, for example:

# from wtfpeewee.orm import model_form
class AdminModelUser(ModelView):
    ...        
    def get_form(self):
        return model_form(User, allow_pk=True)

      

The field is now visible, but saving still doesn't work. When I edit the username of an existing user, the administrator says, "The entry was successfully saved," but it is not saved. And when I try to create a new user, I still get the error peewee.UserDoesNotExist

.

I am guessing that I made the override in the wrong place, with the fields being displayed on the form but not in the save methods. I couldn't find any mention of this in the docs: does anyone know how to do this?

+3


source to share


1 answer


If you have a non-integer primary key, you must call save()

with force_insert=True

to add a new row.



http://docs.peewee-orm.com/en/latest/peewee/models.html#non-integer-primary-keys-composite-keys-and-other-tricks

+2


source







All Articles