[Django]-Django form wont submit because of autocomplete widget field

3đź‘Ť

âś…

Finally found the answer, the problem was that the “name” attribute wasn’t rendered. Hence, the field could’t get to the view as part of the request.

The final code of the autocomplete widget ended up like this:

class AutocompleteTextInputWidget (forms.TextInput):

    def media(self):
        js = ("/js/autocomplete.js", "pepe.js")

    def __init__(self, source, options={}, attrs={}):
        self.options = None
        self.attrs = {'autocomplete': 'off'}
        self.source = source
        self.minLength = 1
        self.delay = 0
        if len(options) > 0:
            self.options = JSONEncoder().encode(options)

        self.attrs.update(attrs)

    def render(self, name, value=None, attrs=None):
        final_attrs = self.build_attrs(attrs)       
        options = ''

        if value:
            final_attrs['value'] = escape(value)

        if isinstance(self.source, list) or isinstance(self.source, tuple):
            # Crea un Json con las opciones.
            source = '[' 
            for i in range(0, len(self.source)):
                if i > 0:
                    source += ', '
                source += '"' + self.source[i] + '"'
            source += ']'

            options = u'''
                delay : %(delay)d,
                minLength : %(minlength)s,
                source : %(source)s
            '''  % {
                   'delay' : self.delay,
                   'minlength' : self.minLength,
                   'source' : source
            }

        elif isinstance(self.source, str):
            options = u'''
                delay : %(delay)d,
                minLength : %(minlength)s,
                source : function (request, response) {
                    if ($(this).data('xhr')) {
                        $(this).data('xhr').abort();
                    }
                    $(this).data('xhr', $.ajax({
                        url : "%(source_url)s",
                        dataType : "json",
                        data : {term : request.term},
                        beforeSend : function(xhr, settings) {
                            $('#%(input_id)s').removeAttr('itemid');
                        },
                        success : function(data) {
                            if (data != 'CACHE_MISS') {
                                response($.map(data, function(item) {
                                    return {
                                        label : item[1],
                                        value: item[1],
                                        real_value : item[0]
                                    };
                                }));
                            }
                        },
                    }))
                },
                select : function (e, ui) {
                    $('#%(input_id)s').attr('itemid', ui.item.real_value);
                    $('#%(input_id)s').val(ui.item.label);
                }
            ''' % {
                   'delay' : self.delay,
                   'minlength' : self.delay,
                   'source_url' : self.source,
                   'input_id' : final_attrs['id'],
            }
        if not self.attrs.has_key('id'):
            final_attrs['id'] = 'id_%s' % name    

        return mark_safe(u''' 
            <input type="text" name="%(name)s" %(attrs)s/>
            <script type="text/javascript">
                $("#%(input_id)s").autocomplete({
                   %(options)s 
                });
            </script>
        ''' % {
               'attrs' : flatatt(final_attrs),
               'options' :  options, 
               'input_id' : final_attrs['id'],
               'name' : name
        })
  1. If someone knows how to improve this messy code it would be nice.
  2. If someone knows about a nice widget documentation for django 1.4 (Other than the oficial, which sucks by the way) it would be nice too.

Bye, good coding everyone!!!

👤danielrvt

Leave a comment