Where to store field data and how to provide access to it?
Forms
have Fields
, Fields
have a value
. However, they only get a value
after the form has been submitted.
- How should I store this value? Should I give every field a value attribute,
field.value
,- leave it as
None
prior to posting, and fill it in afterwords? - Omit it completely, and dynamically add it?
- Store it on the form instead, like
form.data['field']
. - Create a a wrapper class
FieldWithData
to avoid any inconsistent states (if you have an object of this type, you know it has data) and allows me to set the data in the initializer rather than accessing attributes directly (although I guess this isn't so different from using a setter)
- leave it as
- How should I provide access to the field data through the
Form
object? Options:form.fields['nam开发者_C百科e'].value
(how it's presently being stored internally)form.data['field']
(create a proxy "data" class that retrieves the real data off the field, or re-arrange the internals to actually store the data like this)form.field.value
- looks fairly nice, but then I'd have two references to the same field, one asform.field
and one asform.fields['field']
which I need internally so that I can iterate over them
Too many design decisions. Driving me nuts. This is what sucks about solo'ing a project.
It really depends on how you interact with the structures in question. Do you manipulate Form
and Field
objects prior to assigning them values? Do you need to frequently iterate over all the given Fields
? Do you need Form
once it's been submitted? Etc.
I'd suggest writing some/all of the code that uses Form
and figure out how you want to interact with Form
data, and what your ideal interface would look like.
I would keep a form's definition and the form's values from submission separate. I.e. I would not have a value
attribute on the Field(Definition) objects.
To work with submitted values, I would probably use a dict. You could let the Form class handle the creation of this dict:
# assuming my_form is a Form object and request represents the HTTP request
form_values = my_form.values_from_request(request)
print(form_values["Name"])
The values_from_request
method would iterate through the Form's Field(Definition)s to get the submitted data from the HTTP request. The method could also do stuff like validation and data type conversion.
精彩评论