def model_to_dict(instance, fields=None, exclude=None):
 from django.db.models.fields.related import ManyToManyField
 opts = instance._meta
 data = {}
 for f in (opts.fields + opts.many_to_many):
  if (not f.editable):
   continue
  if (fields and (not (f.name in fields))):
   continue
  if (exclude and (f.name in exclude)):
   continue
  if isinstance(f, ManyToManyField):
   if (instance.pk is None):
    data[f.name] = []
   else:
    data[f.name] = list(f.value_from_object(instance).values_list(u'pk', flat=True))
  else:
   data[f.name] = f.value_from_object(instance)
 return data

def model_to_dict ( instance , fields = None , exclude = None ) : from django . db . models . fields . related import ManyToManyField opts = instance . _meta data = { } for f in ( opts . fields + opts . many_to_many ) : if ( not f . editable ) : continue if ( fields and ( not ( f . name in fields ) ) ) : continue if ( exclude and ( f . name in exclude ) ) : continue if isinstance ( f , ManyToManyField ) : if ( instance . pk is None ) : data [ f . name ] = [ ] else : data [ f . name ] = list ( f . value_from_object ( instance ) . values_list ( u'pk' , flat = True ) ) else : data [ f . name ] = f . value_from_object ( instance ) return data
returns a dict containing the data in instance suitable for passing as a forms initial keyword argument .