Ticket #5126: ticket5126_3.diff

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

New patch, pass instance via initial parameter in constructor

  • django/newforms/models.py

     
    6666        form.save_m2m = save_m2m
    6767    return instance
    6868
    69 def make_model_init(form, fields):
     69def make_model_init(form, model, fields):
    7070    """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:
     71    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
     72                 initial=None):
     73        from django.db import models
     74        if isinstance(initial, models.Model):
     75            instance, initial = initial, {}
     76            for f in model._meta.fields:
     77                if not f.editable:
    7778                    continue
    7879                if fields and f.name not in fields:
    7980                    continue
    8081                initial[f.name] = f.value_from_object(instance)
    81         form.__init__(self, **kwargs)
     82        form.__init__(self, data=data, files=files, auto_id=auto_id,
     83                      prefix=prefix, initial=initial)
    8284    return __init__
    8385
    8486def make_model_save(model, fields, fail_message):
     
    115117            field_list.append((f.name, formfield))
    116118    base_fields = SortedDictFromList(field_list)
    117119    return type(opts.object_name + 'Form', (form,),
    118         {'base_fields': base_fields, '_model': model, '__init__': make_model_init(form, fields),
     120        {'base_fields': base_fields, '_model': model,
     121         '__init__': make_model_init(form, model, fields),
    119122         'save': make_model_save(model, fields, 'created')})
    120123
    121124def form_for_instance(instance, form=BaseForm, fields=None, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)):
Back to Top