So, I filled in a multiple select box with values ββfrom an ajax request using Javascript. The problem is that the form object is actually empty, so when I want to check the form, it cannot get the value from the options field.
If I can get the identifier (s) from somewhere, I could send a new request and populate the verified object this way. I just can't figure out how ..
JScode is as follows:
function changeOptions() {
var id = $("#id_place").find(":selected").attr("value");
var selection = new Array();
$("#id_locations option:selected").each(function(i, selectedElement) {
selection.push($(selectedElement).val());
});
$.ajax({
type: "GET",
url: "../../../../../location/locationsByPlace.json?id=" + id,
success: function(locations) {
$("#id_locations").empty();
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;
}
}
$("#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", "");
});
}
Run codeHide resultPython:
class EventAdminForm(NodeAdminForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
self.obj = kwargs.pop('obj', None)
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)
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")
I need to find a way to either add values ββto a django field object (which is unlikely using JS) or get values ββby invoking an HTML form field using python