-
-
Save andergmartins/9452777 to your computer and use it in GitHub Desktop.
Fix a wrong class name
This file contains 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
# WARNING: This is just a workaround. Consider it as a very | |
# temporary solution if you really need this feature. | |
from django.utils.safestring import mark_safe | |
from django_select2.util import convert_to_js_arr | |
TEMPORARY_ID = 0 | |
def selector(): | |
return """ | |
$input = $('.select2-%s').nextAll('input:not([id*="__prefix__"])'); | |
""" % TEMPORARY_ID | |
def render_js_script(inner_code): | |
code = """ | |
%s | |
if ($input.length != 0) { | |
%s | |
}""" % (selector(), inner_code) | |
return u""" | |
<script type="text/javascript"> | |
jQuery(function ($) { | |
%s else { | |
setTimeout(function() { | |
$('.add-row a').click(function () { | |
%s | |
}); | |
}, 500); | |
} | |
}); | |
</script>""" % (code, code) | |
class FixedSelect2WidgetMixin(object): | |
def render_js_code(self, id_, *args): | |
if id_: | |
return render_js_script(self.render_inner_js_code(id_, *args)) | |
return u'' | |
def render(self, name, value, attrs=None, choices=()): | |
global TEMPORARY_ID | |
s = """ | |
<span class="select2-%s"></span> | |
<script> | |
jQuery(function ($) { | |
%s | |
}); | |
</script> | |
""" % (TEMPORARY_ID, selector()) | |
s += super(FixedSelect2WidgetMixin, self).render( | |
name, value, attrs=attrs, choices=choices) | |
id_ = attrs.get('id', None) | |
s = s.replace("$('#%s')" % id_, '$input') | |
s = s.replace('$("#%s")' % id_, '$input') | |
s = s.replace("'%s'" % id_, '$input[0].id') | |
TEMPORARY_ID += 1 | |
return mark_safe(s) | |
# Now, redefine each widget class you need by adding the mixin | |
# as the first inherited class. | |
from django_select2 import AutoHeavySelect2Widget, AutoHeavySelect2MultipleWidget | |
class AutoHeavySelect2Widget(FixedSelect2WidgetMixin, AutoHeavySelect2Widget): | |
pass | |
class AutoHeavySelect2MultipleWidget(FixedSelect2WidgetMixin, AutoHeavySelect2MultipleWidget): | |
def render_inner_js_code(self, id_, name, value, *args): | |
js = '' | |
if value: | |
js += u"$('#%s').val(django_select2.convertArrToStr(%s));" \ | |
% (id_, convert_to_js_arr(value, id_)) | |
js += u"django_select2.initMultipleHidden($('#%s'));" % id_ | |
js += super(FixedSelect2WidgetMixin, self).render_inner_js_code( | |
id_, name, value, *args) | |
return js |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi man, your solution is good, but create two fields and first is broken
this block hide first broken field
nemovitost-formset ... formset id
s2id_id_nemovitosti .. base from formset prefix
$("#nemovitost-formset a").click(function(e){