Skip to content

Instantly share code, notes, and snippets.

@maxicecilia
Created April 4, 2014 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxicecilia/9966521 to your computer and use it in GitHub Desktop.
Save maxicecilia/9966521 to your computer and use it in GitHub Desktop.
Add an extra query string to Django Grappelli's autolookup fields.
// Add this file to your admin class throught class Media.
(function($) {
// Add the extra querystring to the autolookup field.
function update_lookup_querystring(obj_id) {
id = $("#" + obj_id).val();
$("[id^=lookup_id_linea_set-]").each(function( index ) {
var original_href = $(this).attr('href').split('&')[0];
$(this).attr('href', original_href + '&' + obj_id + '=' + id);
});
}
// Call it somewhere.
$(document).ready(function() {
$(".grp-add-handler").click(function() {
update_lookup_querystring('client_id');
});
});
})(grp.jQuery);
class Foo(models.Model):
...
@staticmethod
def autocomplete_queryset(*args, **kwargs):
qs = Precio.objects.all()
if 'client_id' in kwargs:
qs = qs.filter(client__pk=kwargs['client_id'])
return qs
class YPAutocompleteLookup(AutocompleteLookup):
'''
patch grappelli's autocomplete to let us control the queryset
by creating a autocomplete_queryset function on the model
'''
def get_queryset(self):
'''
Send the extra querystring to your autocomplete_queryset.
Add args/kwargs to all your autocomplete_queryset methods or validate here.
'''
if hasattr(self.model, "autocomplete_queryset"):
qs = self.model.autocomplete_queryset(
id_cliente=self.request.GET.get('client_id', None))
else:
qs = self.model._default_manager.all()
qs = self.get_filtered_queryset(qs)
qs = self.get_searched_queryset(qs)
return qs.distinct()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment