How do I set the default value of a relationship field in flask_admin based on the url parameter?
Asked Answered
T

2

5

Let's say I have the following models declared:

class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    addresses = db.relationship('Address', backref='person',
                                lazy='dynamic')

class Address(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(50))
    person_id = db.Column(db.Integer, db.ForeignKey('person.id'))

And I would like to create a view where the user can view and add details to the Person object. I want to have a button to add an address that goes something like:

<a href='{{ url_for('address.create_view',person=get_value(model,'id'))}}' class='btn'>Add</a>

Now my problem is how do set the person_id to the value that was sent? Ideally I would like to hide the person dropdown widget and turn it into a hiddenfield with the value sent. But I would settle for just selecting the correct person from the person drop down list in the address form.

Thank you.

Thirtythree answered 10/10, 2016 at 5:19 Comment(0)
P
11

You can override the create_form method of your ModelView:

class PersonView(ModelView):
    def create_form(self):
        form = super(PersonView, self).create_form()
        person_id = request.args.get('person_id')
        if person_id and not form.person_id.data:
            form.person_id.data = person_id
        return form
Preteritive answered 2/3, 2018 at 16:37 Comment(0)
U
-2

You can add an extra column to your view and add a formatter for this column. For example:

class PersonView(ModelView):
    column_list = ('id', 'name', 'action')
    column_formatters = {'action': format_action}

# define the formatter
def format_action(view, context, model, name):
    person_id = model.id
    return "your html with person ID: %s" % person_id

please read the doc

Unguentum answered 21/11, 2016 at 10:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.