Ticket #5126: ticket5126_2.diff

File ticket5126_2.diff, 2.4 KB (added by Christopher Lenz <cmlenz@…>, 17 years ago)

Another patch with an added init_from_instance function

  • django/newforms/models.py

     
    1313from widgets import Select, SelectMultiple, MultipleHiddenInput
    1414
    1515__all__ = (
    16     'save_instance', 'form_for_model', 'form_for_instance', 'form_for_fields',
    17     'ModelChoiceField', 'ModelMultipleChoiceField'
     16    'init_from_instance', 'save_instance', 'form_for_model',
     17    'form_for_instance', 'form_for_fields', 'ModelChoiceField',
     18    'ModelMultipleChoiceField'
    1819)
    1920
     21def init_from_instance(form, instance, fields=None):
     22    """
     23    Populates the initial data of Form ``form`` from model instance
     24    ``instance``.
     25    """
     26    opts = instance.__class__._meta
     27    for f in opts.fields:
     28        if fields and f.name not in fields:
     29            continue
     30        form.initial[f.name] = f.value_from_object(instance)
     31
    2032def save_instance(form, instance, fields=None, fail_message='saved', commit=True):
    2133    """
    2234    Saves bound Form ``form``'s cleaned_data into model instance ``instance``.
     
    5466        form.save_m2m = save_m2m
    5567    return instance
    5668
     69def make_model_init(form, fields):
     70    """Returns the __init__() method for a Form."""
     71    def __init__(self, instance=None, **kwargs):
     72        if instance:
     73            opts = instance.__class__._meta
     74            initial = kwargs.setdefault('initial', {})
     75            for f in opts.fields:
     76                if not f.editable or f.name in initial:
     77                    continue
     78                if fields and f.name not in fields:
     79                    continue
     80                initial[f.name] = f.value_from_object(instance)
     81        form.__init__(self, **kwargs)
     82    return __init__
     83
    5784def make_model_save(model, fields, fail_message):
    5885    "Returns the save() method for a Form."
    5986    def save(self, commit=True):
     
    88115            field_list.append((f.name, formfield))
    89116    base_fields = SortedDictFromList(field_list)
    90117    return type(opts.object_name + 'Form', (form,),
    91         {'base_fields': base_fields, '_model': model, 'save': make_model_save(model, fields, 'created')})
     118        {'base_fields': base_fields, '_model': model, '__init__': make_model_init(form, fields),
     119         'save': make_model_save(model, fields, 'created')})
    92120
    93121def form_for_instance(instance, form=BaseForm, fields=None, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)):
    94122    """
Back to Top