Search code examples
djangojquery-uidjango-formsdjango-widget

Django form wont submit because of autocomplete widget field


I want to fill a text input in my form using an autocomplete widget that I have created using jquery ui. Everything works exactly how I want to, except when the form is submitted.

The problem is that when I submit the form, the text input is automatically reseted (I don't know why) and after that, the page reloads saying that the field is required (just validation working how it's supposed to). Of course, if it didn't reset the field everything would go fine.

I dont know if my select event of the autocomplete is working fine, here is the code:

 select : function (e, ui) {
   // I create a new attribute to store de database primary key of this option. This is
   // usefull later on.
   $('#%(input_id)s').attr('itemid', ui.item.real_value);

   // I set the input text value's.
   $('#%(input_id)s').val(ui.item.label);
 }

Here is the full code of the autocomplete:

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" %(attrs)s/>
        <script type="text/javascript">
            $("#%(input_id)s").autocomplete({
               %(options)s 
            });
        </script>
    ''' % {
           'attrs' : flatatt(final_attrs),
           'options' :  options, 
           'input_id' : final_attrs['id']
    })

Tip: If I write some text without selecting it from the autocomplete, it still fails.

Another tip: If I set the field as optional it arrives to the view empty.

What should I do to make this work when I submit the form??? I have spent hours trying to make this work. How can I make the form to recognise that I have allready filled that field?

Here is the code of the form:

test = forms.CharField(label = "autotest", widget = AutocompleteTextInputWidget('/myjsonservice'))

This is the rendered html:

<input type="text"  autocomplete="off" id="id_test"/>
        <script type="text/javascript">
            $("#id_test").autocomplete({

            delay : 0,
            minLength : 0,
            source : function (request, response) {
                if ($(this).data('xhr')) {
                    $(this).data('xhr').abort();
                }
                $(this).data('xhr', $.ajax({
                    url : "/myjsonservice",
                    dataType : "json",
                    data : {term : request.term},
                    beforeSend : function(xhr, settings) {
                        $('#id_test').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) {
                $('#id_test').attr('itemid', ui.item.real_value);
                $('#id_test').val(ui.item.label);
            }

            });
        </script>

Solution

  • 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!!!