Получить идентификатор опции из формы с множественным выбором, заполненной javascript

Поэтому я заполнил поле множественного выбора значениями из запроса ajax, используя Javascript. Проблема в том, что объект формы на самом деле пуст, поэтому, когда я хочу проверить форму, он не может получить значение из поля параметра.

Если бы я мог получить идентификаторы откуда-нибудь, я мог бы отправить новый запрос и заполнить проверенный объект таким образом. Я просто не могу узнать, как..

JScode выглядит так:

function changeOptions() {
  var id = $("#id_place").find(":selected").attr("value"); //get the ID of the place
  var selection = new Array();
  $("#id_locations option:selected").each(function(i, selectedElement) {
    selection.push($(selectedElement).val()); //get which locations were originally selected
  });
  $.ajax({
    type: "GET",
    url: "../../../../../location/locationsByPlace.json?id=" + id, //see locationsByPlace.json in location/views.py
    success: function(locations) {
      $("#id_locations").empty(); //empty the location select field
      var selected = false;
      for (var i = 0; i < locations.length; i++) {
        for (var j = 0; j < selection.length; j++) {
          if (selection[j] == locations[i].id) {
            selected = true;
            break;
          }
        }
        //add the right locations for the given place
        $("#id_locations").append($("<option />")
          .val(locations[i].id)
          .text(locations[i].name)
          .attr("selected", (selected ? "selected" : ""))
        );
        selected = false;
      }
    }
  });
}

function allLocationsToggled() {
  var all_locations = $("#id_all_locations").attr("checked");
  if (all_locations) {
    $("#id_locations").attr("disabled", true);
  } else {
    $("#id_locations").attr("disabled", false);
  }

  $("#id_locations option").each(function() {
    $(this).attr("selected", "");
  });
}

Python:

class EventAdminForm(NodeAdminForm):
def __init__(self, *args, **kwargs):
    self.request = kwargs.pop('request', None)
    self.obj = kwargs.pop('obj', None)

    #the super(...).__init__ doesn't have 'request' or 'obj', we need to pop them before calling the super. (We added those arguments in the getForm method of EventAdmin)
    super(EventAdminForm, self).__init__(*args, **kwargs)

    if(self.request.user.is_superuser):
    choices = []
    deleted  = DataState.objects.get(pk=DataState.DELETED)
    closed  = DataState.objects.get(pk=DataState.CLOSED)

    qs = Place.objects.all().exclude(data_state=closed).exclude(data_state=deleted)

    for p in qs:        
        choices.append((p.pk,p.name,))

    self.fields['place'] = forms.ChoiceField(choices = choices)

        # leave the locationchoices array empty so the fill can be done by JS
    locationchoices = []
    self.fields['locations'] = forms.MultipleChoiceField(choices = locationchoices)

def clean(self):
    cleaned_data  = super(EventAdminForm, self).clean()
    all_locations = cleaned_data.get("all_locations")
    locations   = cleaned_data.get("locations")
    try:
        place  = Place.objects.get(pk=cleaned_data.get('place'))
        cleaned_data['place'] = place
    except:
        raise forms.ValidationError('You have to choose a correct place!')
    if not all_locations and (locations == None or len(locations) == 0):
        raise forms.ValidationError('The event must have a location! '
                'Select one or more locations from the list or choose "All locations".')
    for l in cleaned_data['locations']:
            if(l.place.id != cleaned_data['place'].id):
                raise forms.ValidationError("The locations you specified do not match the place")

Мне нужно найти способ либо добавить значения к объекту поля django (что маловероятно при использовании JS), либо получить значения, вызвав поле формы HTML с помощью python

0 ответов

Другие вопросы по тегам