How do you load a custom field in django

折月煮酒 提交于 2019-12-24 11:54:14

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/28956332/how-do-you-load-a-custom-field-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!