Change admin admin form value

I have a typical model inheritance in my project:

class A(models.Model): boolean_field = models.BooleanField(default=True) class B(A): some_other_field = models.CharField() 

I want to override the default boolean_field in class B , how can I do this?

I think this can be a complex task at the database level, so maybe at least I can just override this default value in Django admin (I mean in the ModelAdmin form for class B ).

+2
source share
3 answers

As you think, the easiest way is to change the model form used for model B in the django admin.

To change the initial value of a form field, you can override this field or override the __init__ method.

 class BForm(forms.ModelForm): # either redefine the boolean field boolean_field = models.BooleanField(initial=False) class Meta: model = B # or override the __init__ method and set initial=False # this is a bit more complicated but less repetitive def __init__(self, *args, **kwargs): super(BForm, self).__init__(*args, **kwargs) self.fields['boolean_field'].initial = False 

Using your custom model in django admin is easy!

 class BAdmin(admin.ModelAdmin): form = BForm admin.site.register(B, BAdmin) 
+5
source
 class A(models.Model): boolean_field = models.BooleanField(default=True) def __unicode__(self): return self. boolean_field class B(): some_other_field = models.CharField() default_fiel_from_bool = models.ForeignKey(A) 
+1
source

From this answer, the easiest way is to override the get_changeform_initial_data function.

This is how I applied it to my project.

In this example, I have an ORM class named Step and an Admin class named StepAdmin . The get_latest_step_order function gets the step_order from the last object in the table.

By overriding the get_changeform_initial_data strong> function in the admin class, I can set the step order for each new object created on the admin screen.

 class Step(models.Model): step_name = models.CharField(max_length=200) step_status = models.ForeignKey(StepStatus, null=True) step_order = models.IntegerField() def get_latest_step_order(): return Step.objects.latest('step_order').step_order+1 class StepAdmin(admin.ModelAdmin): fields = ["step_name","step_status","step_order"] def get_changeform_initial_data(self, request): return { 'step_order': get_latest_step_order() } 
0
source

Source: https://habr.com/ru/post/1385917/


All Articles