menu

Widgets

PRO Only

AjaxModelSelect and AjaxMultipleModelSelect provides autocomplete widgets for the django-material. Unlike other implementations, they not requires a separate autocomplete view registered. Instead, the autocomplete widgets sends HTTP OPTIONS request to the same view. So the same user permissions check would be applied, and the same form could be utilized to form autocomplete suggestions list.

Function based view integration sample:

from django.http import JsonResponse, QueryDict
from material.forms import AjaxModelSelect, get_ajax_suggestions

class AddressForm(forms.ModelForm):
    class Meta:
        model = Address
        fields = ['city', 'street', 'flat']
        widgets = {
            'city': AjaxModelSelect(lookups=['name__icontains'])
        }

 def address(request):
     form = AddressForm(request.POST or None)

     if request.method == 'OPTIONS':
         options = QueryDict(request.body, encoding=request.encoding)
         field = form.base_fields.get(options.get('field'))
         query = options.get('query')

         if field is None or query is None:
             return JsonResponse({'error': 'Field or Query is missing'}, status=400)
         return JsonResponse({
             'suggestions': get_ajax_suggestions(field, query)
         })
     elif form.is_valid():
         form.save()
         return redirect('success')

     return render(request, 'address.html', {'form': form})

Class based view integration sample:

from material.forms import FormAjaxCompleteMixin

class AddressFormView(FormAjaxCompleteMixin, generic.CreateView):
    model = Address
    form_class = AddressForm

API

class material.forms.AjaxModelSelect(*args, **kwargs)

A widget for ModelChoiceField with ajax based autocomplete.

To get AJAX results, GET requests with the additional X-Requested-Content=Autocomplete http header are performed to the same url as the form view.

Expected response is json like:

{
    suggestions: [
        { value: 'Chicago Blackhawks', data: { id: 1 } },
        { value: 'Chicago Bulls', data: { id: 2 } }
    ]
]
Parameters:lookups – list of field to query a model

Example:

class AddressForm(forms.Form):
    city = forms.ModelChoiceField(
        queryset=models.City.objects.all(),
        widget=AjaxModelSelect(loopups=['name__icontains'])
    )
class material.forms.AjaxMultipleModelSelect(*args, **kwargs)

A widget for ModelMultipleChoiceField with ajax based autocomplete.

class material.forms.FormAjaxCompleteMixin
material.forms.get_ajax_suggestions(field, query, max_results=25)

Default AJAX suggestion implementation