Manipulate Forms in Admin

linkaiyi
Follow

example to save certain inline

def save_related(self):
    current_user = self.form_obj.instance
    print(current_user.id)
    current_user.save()
    for formset in self.formsets:
        for f in formset:
            if f.__class__.__name__ == 'UserSettingForm':
                instance = f.save(commit=False)
                if current_user.user_ownsettings:
                    data = instance.__dict__.copy()
                    del data['_state']
                    del data['id']
                    data['user_id'] = current_user.id
                    UserSetting.objects.filter(id=current_user.user_ownsettings.id).update(**data)
        self.formsets.remove(formset)
    super(UserAdmin, self).save_related()

force to save inlines even no changes

from django.contrib import admin
from django.forms.models import BaseInlineFormSet, ModelForm

class AlwaysChangedModelForm(ModelForm):
    def has_changed(self):
        """ Should returns True if data differs from initial. 
        By always returning true even unchanged inlines will get validated and saved."""
        return True

class CheckerInline(admin.StackedInline):
    """ Base class for checker inlines """
    extra = 0
    form = AlwaysChangedModelForm

pythonic multiline string

use '''''' to enclose multiline string
EMAIL = '''line1
        line2
        line3'''

pythonic way to make case switch

use dictionary:

result = {
  'a': lambda x: x * 5,
  'b': lambda x: x + 7,
  'c': lambda x: x - 2
}[value](x)
Object has 0 attachments

Was this article helpful?

This article is viewed 39 times!

0 Comments

Leave a Comment

Support