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)
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)
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()
}
- [Django]-How to restrict access for staff users to see only their information in Django admin page?
- [Django]-Django ping google http error
- [Django]-Tastypie โ where to restrict fields that may be updated by PATCH?
- [Django]-Inverted logic in Django ModelForm
- [Django]-How to display multiple lines of text in django admin?