When selecting a foreignkey in the django admin change form I am trying to add an href that can view the record next to the plus that adds the record.
What I’ve tried just to get the href to render is I’ve copied out the admins def render into my own custom widgets file and added it to and subclassed it:
widgets.py
class RelatedFieldWidgetWrapperLink(RelatedFieldWidgetWrapper):
def render(self, name, value, *args, **kwargs):
rel_to = self.rel.to
info = (rel_to._meta.app_label, rel_to._meta.object_name.lower())
try:
related_url = reverse('admin:%s_%s_add' % info, current_app=self.admin_site.name)
except NoReverseMatch:
info = (self.admin_site.root_path, rel_to._meta.app_label, rel_to._meta.object_name.lower())
related_url = '%s%s/%s/add/' % info
self.widget.choices = self.choices
output = [self.widget.render(name, value, *args, **kwargs)]
if self.can_add_related:
# TODO: "id_" is hard-coded here. This should instead use the correct
# API to determine the ID dynamically.
output.append(u'<a href="%s" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % \
(related_url, name))
output.append(u'<img src="%simg/admin/icon_addlink.gif" width="10" height="10" alt="%s"/></a>' % (settings.ADMIN_MEDIA_PREFIX, _('Add Another')))
output.append(u'<a href="%s" class="testing" id="add_id_%s" onclick="#"> ' % \
(related_url, name))
return mark_safe(u''.join(output))
and in admin.py
formfield_overrides = {models.ForeignKey:{'widget':RelatedFieldWidgetWrapperLink}}
however I get thefollowing error:
TypeError
init() takes at least 4 arguments (1 given)
Has anyone run into this problem before?
The
RelatedFieldWidgetWrapperwidget, and your subclass, are not meant to be used as the widget informfield_overrides. The__init__methods have different function signatures, hence theTypeError.If you look at the code in
django.contrib.admin.options, you can see that theRelatedFieldWidgetWrapperwidget is instantiated in the model admin’sformfield_for_dbfieldmethod, so that it can be passed the argumentsrel,admin_siteandcan_add_related.I think you may have to override your model admin class’
formfield_for_dbfieldmethod, and use your customRelatedFieldWidgetWrapperLinkwidget there.Other approaches
You may find it cleaner to override the
formfield_for_foreignkeymethod thanformfield_for_dbfield.You may be able to subclass the
Selectwidget, and add your link in it’s render method. Your custom select widget would then be wrapped by theRelatedFieldWidgetWrapper. However, I am not sure whether you can produce theview_urlinside the scope of therendermethod.