Reputation: 43
There's a link in custom view that points to Django-admin change form of specific model instance. The goal is to change values of some form fields before form rendering, like it's possible to prepopulate fields in add form by adding parameters (ModelFieldName=value) to add form URL. How to change values in change form fields before rendering? Maybe, I must create my ModelForm, change fields values in it and assign to form variable of ModelAdmin? If so, how to change values of ModelForm fields?
Upvotes: 1
Views: 5573
Reputation: 33420
I just figured that ModelAdmin.add_view uses request.GET to set initial in django/contrib/admin/options.py line 900.
So to prepopulate the "name" field of the someapp.somemodel add form with 'bar', just open: /admin/someapp/somemodel/add/?name=bar
Now if you want a similar behaviour in the change form, override get_object method as such:
def get_object(self, request, object_id):
obj = super(YourModelAdmin, self).get_object(request, object_id)
for key, value in request.GET.items():
setattr(obj, key, value)
return obj
Now open /admin/someapp/somemodel/1/?name=bar and the field "name" will have value "bar" in the form.
This is tested hack.
Upvotes: 1