从填充了javascript的多选表单中获取选项ID

时间:2015-04-22 03:36:46

标签: javascript python-2.7 django-1.5

所以我用ajax请求使用Javascript填充了一个multichoicefield。 问题是表单对象实际上是空的,所以当我想验证表单时,它无法从选项字段中获取值。

如果我可以从某个地方获取ID(' s),我可以发送一个新查询并填充这样的验证对象。我只是不知道如何......

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", "");
  });
}
&#13;
&#13;
&#13;

的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不太可能)或通过使用python调用HTML表单字段来获取值

0 个答案:

没有答案