Django

Code

Changeset 4387

Show
Ignore:
Timestamp:
01/22/07 00:10:47 (2 years ago)
Author:
adrian
Message:

newforms: Added formfield_callback argument to form_for_model and form_for_instance. The admin reworking will need this hook.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/django/newforms/models.py

    r4300 r4387  
    4848    return save 
    4949 
    50 def form_for_model(model, form=BaseForm): 
     50def form_for_model(model, form=BaseForm, formfield_callback=lambda f: f.formfield()): 
    5151    """ 
    5252    Returns a Form class for the given Django model class. 
    5353 
    5454    Provide ``form`` if you want to use a custom BaseForm subclass. 
     55 
     56    Provide ``formfield_callback`` if you want to define different logic for 
     57    determining the formfield for a given database field. It's a callable that 
     58    takes a database Field instance and returns a form Field instance. 
    5559    """ 
    5660    opts = model._meta 
    5761    field_list = [] 
    5862    for f in opts.fields + opts.many_to_many: 
    59         formfield = f.formfield(
     63        formfield = formfield_callback(f
    6064        if formfield: 
    6165            field_list.append((f.name, formfield)) 
     
    6367    return type(opts.object_name + 'Form', (form,), {'fields': fields, '_model': model, 'save': model_save}) 
    6468 
    65 def form_for_instance(instance, form=BaseForm): 
     69def form_for_instance(instance, form=BaseForm, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)): 
    6670    """ 
    6771    Returns a Form class for the given Django model instance. 
    6872 
    6973    Provide ``form`` if you want to use a custom BaseForm subclass. 
     74 
     75    Provide ``formfield_callback`` if you want to define different logic for 
     76    determining the formfield for a given database field. It's a callable that 
     77    takes a database Field instance, plus **kwargs, and returns a form Field 
     78    instance with the given kwargs (i.e. 'initial'). 
    7079    """ 
    7180    model = instance.__class__ 
     
    7483    for f in opts.fields + opts.many_to_many: 
    7584        current_value = f.value_from_object(instance) 
    76         formfield = f.formfield(initial=current_value) 
     85        formfield = formfield_callback(f, initial=current_value) 
    7786        if formfield: 
    7887            field_list.append((f.name, formfield))