Flask-admin Chapter II: Use of wtforms and use of Queryselectfield in database scenarios instead of Selectfield

Source: Internet
Author: User

Overview

The Flask Admin can support custom views, and you can choose to inherit flask_admin for the more complex views involved . Baseview to define the structure of your expectations.

Each function of a custom view can be decorated with flask_admin.expose syntax sugar , which allows you to define the HTTP methods and external URLs that you expect to receive .

Flask Admin is a good package that makes custom views very convenient.

Custom views involve a variety of form actions, which are certainly stressful for friends who are not accustomed to writing front ends. However, lazy people have a lazy way, you can choose

The wtforms package provides form functionality, as well as the ability to inherit the templates provided by Flask Admin, which makes it easy to generate form pages.

and Flask Admin's official online is strongly recommended to inherit or directly use the template provided by Flask Admin. In this way, one can maintain a custom view and

Use Flask Admin's sqla yourself. The Modelview view style remains constant, and it is possible to re-use the ready-made stuff to release the workforce.

For want to inherit Flask admin template, you can see the flask admin specific rendering related logic at a glance, or quite intuitive.

For those who do not want to see the source code, it can be understood as the Flask Admin Package Directory templates/bootstrap3/admin (specifically bootstrap3 or BOOTSTRAP2 needs to be based on its own needs) The templates in the directory are inheritable,

Specifically want to inherit which to see their own needs.

How to use wtforms

The use of wtforms is quite simple, directly inherit form. The form class is available.

Here is an example of the following

 from wtforms Import form, fields, validators, widgets  from wtforms.ext.sqlalchemy.fields Import Queryselectfield class MyForm (form. Form):    = fields. TextField (label=u' script parameter ')    = fields. Integerfield (label=u' timeout time 'default=5)

The above defines a form that has two elements, args, and timeout, but does not see args and timeout when the page is specifically displayed. Instead, the script parameters and time-outs are replaced.

This is because the label is specified so that the form's corresponding element displays the value of the label.

Specifically in the Flask Admin application want to render the corresponding page, only need to use the following statement to be able to:

@expose ('/<your_url>', methods = ['GET','POST'])    defindex (self): form=MyForm (Request.Form)ifRequest.method = ='POST':            ifHelpers.validate_form_on_submit ( from):                #Do you logical        returnSelf.render ('admin/file/form.html', form = form)

The above is just a very concise related code, or very concise. Admin/file/form.html is directly using the template provided by the Flask Admin, which can be used directly.

Using the short lines of code above, you can render a complete form. For a simple application scenario, the above can be used to fully satisfy the requirements.

However, many times the form needs to have a drop-down list box, which requires querying data from the database to make a specific selection. In this case, the database needs to be involved, involving a multi-select list box

Flask Admin Multi-select list box elements are pretty simple to use.

choices = [(' Line', u'Linear Chart'), ('Pie', u'Pie chart'), ('column', u'Histogram'), ('Bar', u'Bar Chart')]chart_type= fields. Selectfield (label=u'type', choices=choices)

As with the args parameter of the form defined above and the timeout parameter, it is quite simple to use Selectfield.

Wtforms support for fetching data from the database

Fields. The data sources available to Selectfield can be not only predefined, but also queried from the database.

 for inch    = fields. Selectfield (label=u' release task ',                          = [validators.required ()], choices = tasks)

This makes it easy to query all the records from the database and select them as options in the drop-down list box.

Problems with the use of Selectfield

But strictly speaking, the above scenes are not very suitable for selectfield. The record in the drop-down list box will never change, even though the data in the task is constantly being updated during use.

The main reason is that a task is a static member of a form class and remains unchanged after it is defined. Therefore, even though the data in the task table is changing all the time, the results of tasks are fixed.

Using Queryselectfield

The solution is still there, that is, the use of Queryselectfield,queryselectfield is not in the Wtforms.fields file, so we do not know that it exists. and Wtforms's official website also recommended US

Using Selectfield support to fetch records from the database, which led us to think that we could use them, I ignored Queryselectfield.

Use of Queryselectfield

 fromWtforms.ext.sqlalchemy.fieldsImportQueryselectfieldclassMyForm (form. Form):defquery_factory ():return[R.name forRinchdb.session.query (Script). All ()]defget_pk (obj):returnobj name= Queryselectfield (label=u'Script Name', validators=[validators.required ()], query_factory=query_factory, GET_PK=GET_PK)

Queryselectfield is pretty simple to use, but it needs to provide two functions, query_factory and GET_PK. The two functions in the example above are based on the scenes I use to

Used, name is the primary key for the script table. Therefore, the above example can dynamically get the contents of the primary key in the script table. The contents of the drop-down list box follow the changes in the data in the script table. Just in line with our needs.

Conclusion

Flask Admin is pretty powerful, the more you will find a lot of unexpected things in the back. Insist on continuous learning, do not compromise!

Flask-admin Chapter II: Use of wtforms and use of Queryselectfield in database scenarios instead of Selectfield

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.