Ticket #5126: ticket5126_4.diff

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

Regenerated full patch

  • 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, model, fields):
     70    """Returns the __init__() method for a Form."""
     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:
     78                    continue
     79                if fields and f.name not in fields:
     80                    continue
     81                initial[f.name] = f.value_from_object(instance)
     82        form.__init__(self, data=data, files=files, auto_id=auto_id,
     83                      prefix=prefix, initial=initial)
     84    return __init__
     85
    5786def make_model_save(model, fields, fail_message):
    5887    "Returns the save() method for a Form."
    5988    def save(self, commit=True):
     
    88117            field_list.append((f.name, formfield))
    89118    base_fields = SortedDictFromList(field_list)
    90119    return type(opts.object_name + 'Form', (form,),
    91         {'base_fields': base_fields, '_model': model, 'save': make_model_save(model, fields, 'created')})
     120        {'base_fields': base_fields, '_model': model,
     121         '__init__': make_model_init(form, model, fields),
     122         'save': make_model_save(model, fields, 'created')})
    92123
    93124def form_for_instance(instance, form=BaseForm, fields=None, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)):
    94125    """
Back to Top