This module provides SelectField integration with SQLAlchemy ORM models, similar to those in the Django extension.
These fields are provided to make it easier to use data from ORM objects in your forms.
def enabled_categories():
return Category.query.filter_by(enabled=True)
class BlogPostEdit(Form):
title = StringField()
blog = QuerySelectField(get_label='title')
category = QuerySelectField(query_factory=enabled_categories, allow_blank=True)
def edit_blog_post(request, id):
post = Post.query.get(id)
form = BlogPostEdit(obj=post)
# Since we didn't provide a query_factory for the 'blog' field, we need
# to set a dynamic one in the view.
form.blog.query = Blog.query.filter(Blog.author == request.user).order_by(Blog.name)
Will display a select drop-down field to choose between ORM results in a sqlalchemy Query. The data property actually will store/keep an ORM model instance, not the ID. Submitting a choice which is not in the query will result in a validation error.
This field only works for queries on models whose primary key column(s) have a consistent string representation. This means it mostly only works for those composed of string, unicode, and integer types. For the most part, the primary keys will be auto-detected from the model, alternately pass a one-argument callable to get_pk which can return a unique comparable key.
The query property on the field can be set from within a view to assign a query per-instance to the field. If the property is not set, the query_factory callable passed to the field constructor will be called to obtain a query.
Specify get_label to customize the label associated with each option. If a string, this is the name of an attribute on the model object to use as the label text. If a one-argument callable, this callable will be passed model instance and expected to return the label text. Otherwise, the model object’s __str__ or __unicode__ will be used.
If allow_blank is set to True, then a blank choice will be added to the top of the list. Selecting this choice will result in the data property being None. The label for this blank choice can be set by specifying the blank_text parameter.
Very similar to QuerySelectField with the difference that this will display a multiple select. The data property will hold a list with ORM model instances and will be an empty list when no value is selected.
If any of the items in the data list or submitted form data cannot be found in the query, this will result in a validation error.
It is possible to generate forms from SQLAlchemy models similarly to how it can be done for Django ORM models.
Create a wtforms Form for a given SQLAlchemy model class:
from wtalchemy.orm import model_form
from myapp.models import User
UserForm = model_form(User)
Parameters: |
|
---|