2

note : This is closely related to the answer in this question : django admin - add custom form fields that are not part of the model

In Django it is possible to create custom ModelForms that have "rouge" fields that don't pertain to a specific database field in any model.

In the following code example there is a custom field that called 'extra_field'. It appears in the admin page for it's model instance and it can be accessed in the save method but there does not appear to be a 'load' method.

How do I load the 'extra_field' with data before the admin page loads?

# admin.py
class YourModelForm(forms.ModelForm):
    extra_field = forms.CharField()

    def load(..., obj):
        # This method doesn't exist.
        # extra_field = obj.id * random()

    def save(self, commit=True):
        extra_field = self.cleaned_data.get('extra_field', None)
        return super(YourModelForm, self).save(commit=commit)

    class Meta:
        model = YourModel

class YourModelAdmin(admin.ModelAdmin):
    form = YourModelForm
    fieldsets = (
        (None, {
            'fields': ('name', 'description', 'extra_field',),
        }),
    )

source code by @vishnu

Community
  • 1
  • 1
Bigginn
  • 199
  • 1
  • 1
  • 12

1 Answers1

4

Override the form's __init__ method and set the initial property of the field:

class YourModelForm(forms.ModelForm):

    extra_field = forms.CharField()

    def __init__(self, *args, **kwargs):
        super(YourModelForm, self).__init__(*args, **kwargs)
        initial = '%s*rnd' % self.instance.pk if self.instance.pk else 'new'
        self.fields['extra_field'].initial = initial
catavaran
  • 44,703
  • 8
  • 98
  • 85