6👍
✅
I managed to figure it out. Thankfully, Django allows you to replace a request
‘s GET
dict (which it uses to pre-populate the admin form). The following worked for me:
class ArticleAdmin(admin.ModelAdmin):
# ...
def add_view(self, request, form_url='', extra_context=None):
source_id = request.GET.get('source', None)
if source_id is not 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)
This way, I obtain the source
object from a URL parameter, do what I want with them, and pre-populate the form.
2👍
You can override method add_view
of ModelAdmin
instance. Add getting an object there, set object’s pk
to None
and provide that object as an instance
to the form. Object with pk == None
will be always inserted as a new object in the database on form’s save()
Source:stackexchange.com