[Django]-Change model admin form default value

5๐Ÿ‘

โœ…

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

To change the initial value of the form field, you can either redefine the 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 form in the django admin is easy!

class BAdmin(admin.ModelAdmin):
    form = BForm

admin.site.register(B, BAdmin)
๐Ÿ‘คAlasdair

1๐Ÿ‘

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)
๐Ÿ‘คjai

1๐Ÿ‘

From this answer, the easiest way Iโ€™ve found is to override the function get_changeform_initial_data.

Hereโ€™s how I applied it to my project.

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

By overriding the get_changeform_initial_data function in the admin class Iโ€™m able to set the step order for each new object thatโ€™s created in 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()
        }
๐Ÿ‘คFistOfFury

Leave a comment