Django admin: Prefill data when clicking the add-another button next to a ForeignKey dropdown
Django allows you to replace a request's GET dict (which it uses to pre-populate the admin form).
Django will automatically fill values from URL GET parameters if you are sending field values of model form in the URL.
For example, considering
"http://myhost/admin/app/model/add/?name=testname"
, it will prefill the name
field of the form in the admin add-view template with the value 'testname'
.
But, if you are sending any id in your URL, you need to modify the GET parameters by overriding the add_view
function.
Taken from stackoverflow answer
class ArticleAdmin(admin.ModelAdmin):
// ...
def add_view(self, request, form_url='', extra_context=None):
source_id = request.GET.get('source',None)
if source_id != None:
source = FeedPost.objects.get(id=source_id)
// any extra processing can go here...
g = request.GET.copy()
g.update({
'title':source.title,
'contents':source.description + u"... \n\n[" + source.url + "]",
})
request.GET = g
return super(ArticleAdmin, self).add_view(request, form_url, extra_context)
It just an example.DO it with Your model and fields :)