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.
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
Asked: 2023-06-24 15:08:07 +0000
Seen: 7 times
Last updated: Jun 24 '23
What is the meaning of the error message "duplicate key value violates unique constraint" in Django?
How can I eliminate the dividing line between rows in a table using Ant Design?
How to create a Cloudwatch Log Group in Terraform with a KMS key?
If my data doesn't have an ID property, what alternative key options do I have?
What is the process for combining dictionaries that contain other dictionaries?
Which integer hash functions that can take an integer hash key are considered to be effective?
How can I establish a connection to the host using VSCode and the private key?