Ticket #3186: django_newforms_from_db_helper2.patch

File django_newforms_from_db_helper2.patch, 1.2 KB (added by dave@…, 18 years ago)

Patch implementing the "seed from db object" helper (with obvious syntax errors fixed this time)

  • django/newforms/models.py

     
    55
    66from forms import BaseForm, DeclarativeFieldsMetaclass, SortedDictFromList
    77
    8 __all__ = ('form_for_model', 'form_for_fields')
     8__all__ = ('form_for_model', 'form_for_fields', 'form_with_db_data')
    99
    1010def create(self, save=True):
    1111    "Creates and returns model instance according to self.clean_data."
     
    3636    "Returns a Form class for the given list of Django database field instances."
    3737    fields = SortedDictFromList([(f.name, f.formfield()) for f in field_list])
    3838    return type('FormForFields', (BaseForm,), {'fields': fields})
     39
     40def form_with_db_data(obj, form, **kwargs):
     41    """Return an instance of the given Form class whose fields are
     42    pre-filled with data from the given SQL object."""
     43
     44    data = {}
     45    for field in form.fields.keys():
     46        data[field] = getattr(obj, field, None)
     47    f = form(data=data, **kwargs)
     48    # Force the form to ignore errors, as we want this prefilled form
     49    # returned to the user, not immediately rolled back into the
     50    # database.
     51    f.ignore_errors = True
     52    return f
Back to Top