Ask Your Question
0

How can the initial value of a new foreign key be set in the Django admin?

asked 2023-06-24 15:08:07 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-06-24 15:21:02 +0000

pufferfish gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-24 15:08:07 +0000

Seen: 7 times

Last updated: Jun 24 '23