Skip to content

Instantly share code, notes, and snippets.

@un-def
Last active November 23, 2015 08:38
Show Gist options
  • Save un-def/bff93a026baf75b8b90b to your computer and use it in GitHub Desktop.
Save un-def/bff93a026baf75b8b90b to your computer and use it in GitHub Desktop.
Django InstanceLinkWidget
from django import forms
from django.utils.safestring import mark_safe
from django.core.urlresolvers import reverse
class InstanceLinkWidget(forms.Widget):
def __init__(self, obj, attrs=None):
self.obj = obj
super(InstanceLinkWidget, self).__init__(attrs)
def render(self, name, value, attrs=None):
if self.obj.pk:
url = reverse('admin:{0}_{1}_change'.format(
self.obj._meta.app_label,
self.obj._meta.model_name),
args=(self.obj.pk,))
return mark_safe(u'<a href="{0}">{1}</a>'.format(url, self.obj))
else:
return mark_safe(u'---')
def value_from_datadict(self, data, files, name):
return unicode(self.obj.pk)
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['anothermodel'].widget = InstanceLinkWidget(self.instance.anothermodel)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment