Login

Instance partial update

Author:
dballanc
Posted:
September 9, 2007
Language:
Python
Version:
.96
Tags:
forms model partial updating
Score:
7 (after 7 ratings)

If you're like me, you've got a models with a lot of fields/foreignkeys and often only want to edit a portion of the model in a form. Add this method to your custom form class and use it in place of the save() method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"""
Add this method to a custom form to use as an alternative
to the save method.  When passed an object instance, the it
will set values on the model corresponding to matching
field names on the form.  

Example:

myobject = MyObject.objects.get(pk=1) 
form = MyForm(request.POST) 
    if form.is_valid(): 
        form.update_instance(myobject)
"""
def update_instance(self,instance,commit=True):
    for f in instance._meta.fields:
        if f.attname in self.fields:
            setattr(instance,f.attname,self.cleaned_data[f.attname])
    if commit:
        try: 
            instance.save()
        except: 
            return False
    return instance

More like this

  1. Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 5 months, 1 week ago
  2. Crispy Form by sourabhsinha396 6 months ago
  3. ReadOnlySelect by mkoistinen 6 months, 2 weeks ago
  4. Verify events sent to your webhook endpoints by santos22 7 months, 1 week ago
  5. Django Language Middleware by agusmakmun 7 months, 3 weeks ago

Comments

Please login first before commenting.