Ajax data manipulation when transmitting to Django CBV

Viewed 92

I'm using django-autocomplete-light with the select2 "select multiple" widget for a M2M form. I have it set up to enable "Create New" when the input is not found. However, my model has additional required fields beyond the initial input of the "select multiple" widget. I am trying to create a way to prompt the user for the additional fields when trying to create, and then sending that data through ajax to my django view. Right now, if I pre-supply the other required fields within my view, the user can create a new object with the name that they've entered (and clicked "Create New") for, and the other fields will be determined in my view. This shows me that the code is working, but ideally I'd like to prompt the user for the additional data. I have created a prompt, however I cannot the correct syntax for transmitting the data.

As an example, pretend I have a model with required fields "Name" and "Location". On the Select2 widget, the user types a "Name" which doesn't exist as an object, and clicks "Create New". Now, I'd like the script to prompt them for the location, then transmit that in as a get_or_create parameter.

Code below:

**views.py**
class Videoautocomplete(autocomplete.Select2QuerySetView):
     create_field = 'name'
     def create_object(self, text):
        """Create an object given a text."""
        object = Model.objects.all()[0]
        return self.get_queryset().get_or_create(name=text, location=object.location)[0]
    def get_queryset(self):
        """This is the code for the initial search within the select2 field"""
        qs = Model.objects.order_by('name')
        if self.q:
            qs = qs.filter(name__icontains=self.q)
        return qs
**select2.js**
$(this).on('select2:selecting', function (e) {
            var data = e.params.args.data;

            if (data.create_id !== true)
                return;

            e.preventDefault();

            var select = $(this);

            $.ajax({
                url: $(this).attr('data-autocomplete-light-url'),
                type: 'POST',
                dataType: 'json',
                
                beforeSend: function(xhr, settings) {
                    xhr.setRequestHeader("X-CSRFToken", document.csrftoken);
                    """Below is prompting the user for the location, and assigning it to the variable location"""
                    var location = prompt("Please enter the location", "");
                },
                """How do I add the contents of the variable Location into the data below?"""
                data: {
                    text: data.id,
                    forward: yl.getForwards($(this))
                },

                success: function(data, textStatus, jqXHR ) {
                    select.append(
                        $('<option>', {value: data.id, text: data.text, selected: true})
                    );
                    select.trigger('change');
                    select.select2('close');
                }
            });
        });

If I intercept the transmitted JSON object as a string (using "test" as the input), I get this:

{"id":"test","text":"Create \"test\"","create_id":true}

I need to figure out how to inject the Location variable into that object, but I can't figure out the syntax. Any help?

0 Answers
Related