Admin Hack: Quick lookup of GenericForeignKey id by ContentType

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
photo/models.py:

from common.models import City, State, Country, Region

class Photo(models.Model):
    # this could be a Region, Country, State, City, 
    object_type = models.ForeignKey(ContentType, null=True, blank=True)
    object_id = models.PositiveIntegerField(null=True, blank=True)
    content_object = generic.GenericForeignKey("object_type", "object_id")    


templates/admin/photo/photo/change_form.html:

{% extends "admin/change_form.html" %}

{% block extrahead %}{{ block.super }}
<script type="text/javascript" src="/site_media/js/jquery-1.2.6.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 == 'city' || type == 'state' || type == 'country' || 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 %}

Comments

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.