Home Django return choices with AjaxView
Reply: 0

Django return choices with AjaxView

user2205
1#
user2205 Published in April 19, 2018, 10:00 am

I am using two ChoiceFields in my form. The available choices in the second one depend on the one in the first one.
I created an on change event in my template:

$("#id_department").change(function(){
  console.log($(this).val())
  var department = $(this).val();
  $.ajax({
    type: "POST",
    url : "{% url "load-choices" %}",
    data : {"department" : department},
    success: function(data){
      console.log(data)
      $("#id_usage").append(data);

    },
  });
});

which points to my view:

class LoadChoices(View):
    def post(self, request, *args, **kwargs):
        usages = {
            "new": _("New Device is created"),
            "room": _("Room is changed"),
            "owner": _("person currently lending is changed"),
            "reminder": _("Reminder that device is still owned"),
            "overdue": _("Reminder that device is overdue"),
            "trashed": _("Device is trashed")
        }
        department = request.POST["department"]
        used = MailTemplate.objects.values_list('usage', flat=True).filter(department = department)
        valid = [x for x in usages if not any(y in x for y in used)]
        return(HttpResponse(valid))

usages are the available choices, used are the choices that I do not want to include in the dropdown and valid are the choices I want to show in the dropdown. Normally, if I was in the edit view, I would just assign validto the field. But as this is the ajax view, as far as I understand it, I have to return valid.
But if I try to do that as shown above, the template receives a string like roomownernewremindertrashedoverdue and the dropdown choices do not change, they stay at their initial values that are determined when the form is loaded. (valid, when printed from the ajax view, has this format: [u'room', u'owner', u'new', u'reminder', u'trashed', u'overdue'].)
Now, for my question: How do I have to format/return these choices and how do I have to pass them to the ChoiceField, if not with append?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.460225 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO