Crowl
Crowl

Reputation: 37

Django/Ajax : How to filter a form field's queryset asynchronously?

In a given Django form view, I'd like to filter a field's queryset by an option a user has selected while viewing the form. And I'd like that to happen asynchronously. I've read that AJAX might be what I should use, but I know very little of JS, and I can't make much sense of the information I've read.

The way I see it, I'd like a user to be able to click on one or more checkboxes that would filter 'loot.item_name' by 'item.in_itemlist' or 'item.item_type' (automatically, using onChange or onUpdate or smth?). Would someone kindly give me some pointers? Cheers,

Here are my models:

models.py

class Itemlist(models.Model):
    name = models.CharField([...])

class Item(models.Model):
    name = models.CharField([...])
    item_type = models.CharField([...])
    in_itemlist = models.ForeignKey(Itemlist, [...])

class Loot(models.Model):
    item_name = models.ForeignKey(Item, [...])
    quantity = [...]

my view,

views.py

def create_loot(request):
    # LootForm is a simple ModelForm, with some crispy layout stuff.
    form = LootForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            form.save()
            [...]
    return render(request, 'loot_form.html', context={'form': form}

and the template,

loot_form.html

{% extends "base_generic.html" %}

{% block leftsidebar %}
   /* for each unique itemlist referenced in the items, */
   /* make a checkbox that once clicked, filters 'loot.item_name' by the selected option.*/
{% endblock leftsidebar %}

{% block content %}

  <h1 class="page-title">Add Loot</h1>
  <hr class="page-title-hr">

  {% csrf_token %}
  {% load crispy_forms_tags %}
  {% crispy form form.helper %}

{% endblock content %}

Upvotes: 0

Views: 711

Answers (1)

Prashant Gupta
Prashant Gupta

Reputation: 303

You can create Api based view for your Model

in JavaScript, you can call the the API end and get the data Ajax code can be something like below

$(document).ready(function () {
    setTimeout(function () {
      $(document).on('click', '#id', function () {
        $.get("./api/v2/end_point?state=" + state, function (data, status) {
          var inner_data = data[0].state_count;
          change_text.html(inner_data);
        });
      });
    }, 100);
})

Upvotes: 1

Related Questions