How to set default values in TabularInline formset in Django admin

前端 未结 3 1970
礼貌的吻别
礼貌的吻别 2021-02-05 22:58

How to set first default rows/values in django admin\'s inline?

    class Employee(models.Model):
        username = models.CharField(_(\'Username\'), max_length         


        
3条回答
  •  悲&欢浪女
    2021-02-05 23:35

    To provide a static default for all instances in the inline, I found a simpler solution that just sets it in a form:

    class DetailsForm(django_forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.fields['label'] = 'first_name'
    
    
    class DetailsInline(admin.TabularInline):
        form = DetailsForm
        # ...
    

    I think this doesn't work for the OP's particular case because each form has a different value for the 'label' field, but I hope it can be useful for anyone coming to this page in the future.

提交回复
热议问题