Search code examples
djangopython-3.xdjango-formsdjango-widgetdjango-ajax-selects

How to render default values in django-ajax_select field


I am using ajax_select for my m2m and foreign key fields, its working fine but it is not rendering default value of that field, it is rending empty value ("|"). I am not using ajax_select in my admin panel, so when I open that form in admin panel, fields are having default values already. That means their is no problem in default values but in ajax_select field.

What it is rending now :

<input type="hidden" name="colours" id="id_colours" value="|" data-ajax-select="autocompleteselectmultiple" data-plugin-options="{&quot;source&quot;: &quot;/ajax_select/ajax_lookup/colours&quot;, &quot;html&quot;: true}" data-changed="true">

What I wanted is:

<input type="hidden" name="colours" id="id_colours" value="|8|" data-ajax-select="autocompleteselectmultiple" data-plugin-options="{&quot;source&quot;: &quot;/ajax_select/ajax_lookup/colours&quot;, &quot;html&quot;: true}" data-changed="true">

If at least default value initialized in name=colour, I can show help text that default value is White.

As I searched at documentation of ajax_select but nothing found related to it, does anyone know how to render default values in ajax_select field.

Is this problem occurring with me only or ajax_select doesn't have this default value feature ?


Solution

  • This can be achieved by overriding the get_form() method as :

    def get_form(self,form_class=None):
        form = super().get_form(form_class)
        form['colours'].initial = '8'
        return form
    

    Now default value is set manually and also working in ajax_select.