Created
April 4, 2014 01:48
-
-
Save maxicecilia/9966521 to your computer and use it in GitHub Desktop.
Add an extra query string to Django Grappelli's autolookup fields.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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