Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are a few ways to set the initial value of a new foreign key in the Django admin:

  1. Using a default value: You can set the default value of the foreign key field to the desired value in the model definition. For example:
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.

  1. Using a form field: You can create a custom form field for the foreign key in the admin form and set its initial value to the desired value. For example:
# 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.

  1. Using a custom save method: You can override the 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.