Skip to content

Instantly share code, notes, and snippets.

@dstegelman
Last active April 29, 2020 18:26
Show Gist options
  • Save dstegelman/9394645 to your computer and use it in GitHub Desktop.
Save dstegelman/9394645 to your computer and use it in GitHub Desktop.
Adding Lookups to Django Generic Foreign Keys with Tabular Inlines
from itertools import chain
from django.utils.safestring import mark_safe
from django import forms
from django.contrib.contenttypes.models import ContentType
from django.forms import ModelForm
from django.contrib.admin.widgets import ForeignKeyRawIdWidget
from django.db.models.fields.related import ManyToOneRel
from django.contrib.admin.sites import site
class ContentTypeSelect(forms.Select):
def __init__(self, lookup_id, attrs=None, choices=()):
self.lookup_id = lookup_id
super(ContentTypeSelect, self).__init__(attrs, choices)
def render(self, name, value, attrs=None, choices=()):
output = super(ContentTypeSelect, self).render(name, value, attrs, choices)
choices = chain(self.choices, choices)
choiceoutput = ' var %s_choice_urls = {' % (attrs['id'].replace('-', ''),)
for choice in choices:
try:
ctype = ContentType.objects.get(pk=int(choice[0]))
choiceoutput += ' \'%s\' : \'../../../%s/%s/?t=%s\',' % ( str(choice[0]),
ctype.app_label, ctype.model, ctype.model_class()._meta.pk.name)
except:
pass
choiceoutput += '};'
output += ('<script type="text/javascript">'
'(function($) {'
'%(choiceoutput)s'
' $(\'#%(id)s\').change(function() {'
' $(\'#%(fk_id)s\').attr(\'href\',%(change_id)s_choice_urls[$(this).val()]);'
' });'
'})(django.jQuery);'
'</script>' % {'choiceoutput': choiceoutput,
'id': attrs['id'],
'change_id': attrs['id'].replace('-', ''),
'fk_id': "lookup_%sobject_id" % attrs['id'].replace('content_type', '')
})
return mark_safe(u''.join(output))
class AdminRatingForm(ModelForm):
def __init__(self, *args, **kwargs):
super(AdminRatingForm, self).__init__(*args, **kwargs)
try:
model = self.instance.content_type.model_class()
model_key = model._meta.pk.name
except:
model = Article
model_key = 'id'
self.fields['object_id'].widget = ForeignKeyRawIdWidget(rel=ManyToOneRel(model, model_key), admin_site=site)
self.fields['content_type'].widget.widget = ContentTypeSelect('lookup_id_object_id',
self.fields['content_type'].widget.widget.attrs,
self.fields['content_type'].widget.widget.choices)
class Meta:
model = ReleatedResource
class GenericItemInline(admin.TabularInline):
model = ReleatedResource
form = AdminRatingForm
{% extends "admin/change_form.html" %}
{% block extrahead %}{{ block.super }}
<script type="text/javascript" src="/static/js/lib/jquery/jquery-1.6.1.min.js"></script>
<script>
$(document).ready(function(){
$(".object_id").append("<div id='lookup_box'></div>");
$("#id_object_type").change(function () {
var type = $("#id_object_type option:selected").text();
var good_choice = true;
if (type == 'sermon' || type == 'devotional' || type == 'article' || type == 'region') {
var link_root = '../../../common/';
$("#lookup_box").html("<a onclick='return showRelatedObjectLookupPopup(this);' id='lookup_id_object_id' class='related-lookup' href='../../../common/region/'>lookup</a>");
$("#lookup_id_object_id").text("Lookup " + type);
$("#lookup_id_object_id").attr('href', link_root + type + '/');
} else {
$("#lookup_box").html("<span class='related-lookup' style='color: red;'>Invalid Choice! - Pick City, State, Country or Region</span>");
}
})
.change();
});
</script>
{% endblock %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment