1 | initial version |
There are a few ways to set the initial value of a new foreign key in the Django admin:
class MyModel(models.Model):
my_fk = models.ForeignKey(MyOtherModel, default=1)
This will set the initial value of my_fk
to the object with pk=1
in MyOtherModel
.
# in admin.py
class MyModelAdminForm(forms.ModelForm):
my_fk = forms.ModelChoiceField(queryset=MyOtherModel.objects.all(), initial=1)
class MyModelAdmin(admin.ModelAdmin):
form = MyModelAdminForm
This will create a custom form field for my_fk
in the admin form that will be initialized with the object with pk=1
in MyOtherModel
.
save_model
method in the admin model to set the initial value of the foreign key before saving the object. For example:# in admin.py
class MyModelAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.my_fk = MyOtherModel.objects.get(pk=1)
super().save_model(request, obj, form, change)
This will set the initial value of my_fk
to the object with pk=1
in MyOtherModel
before saving the object.