【问题标题】:Django Form ajax post with checkboxes带有复选框的 Django Form ajax 帖子
【发布时间】:2014-02-05 22:11:18
【问题描述】:

我正在尝试通过 AJAX 发布一个选中多个复选框的 Django 表单。选中一个复选框后,一切正常。选择多个时,它不会保存任何内容。我猜这是因为我在发送到服务器之前如何在 JS 中组织我的数据。

有问题的模型是:

class Room(models.Model):
    hotel = models.ForeignKey(Hotel)
    name = models.CharField(max_length=32)
    capacity = models.IntegerField(
        choices=((i, i) for i in range(1, 31)),
        default=3)
    taxes = models.ManyToManyField(
        Tax, related_name='room',
        blank=True, limit_choices_to={'hotel': F('hotel')})

创建或编辑房间的形式是:

class RoomForm(forms.ModelForm):
    name = forms.CharField(widget=forms.TextInput)

    class Meta():
        model = Room
        fields = ('name', 'capacity', 'taxes')
        widgets = {
            'capacity': forms.Select,
            'taxes': forms.CheckboxSelectMultiple,
        }

    def __init__(self, *args, **kwargs):
        super(RoomForm, self).__init__(*args, **kwargs)
        if 'initial' in kwargs:
            self.fields['taxes'].queryset = Tax.objects.filter(hotel=kwargs['initial']['hotel'])

我像这样通过 ajax 发布表单:

var elements = $('form').serializeArray();
var params = {}, i;
for (i in elements) {
    element = elements[i];
    if (element.name in params) {
        if (!(params[element.name] instanceof Array)) {
            params[element.name] = Array(params[element.name]);
        }
        params[element.name].push(element.value);
    } else {
        params[element.name] = element.value;
    }
}
params['csrfmiddlewaretoken'] = CSRF_TOKEN;

$.post(e.target.action, params, function(response) {
    callback(response);
});

选中并张贴一个税收复选框时,它可以完美运行。 However, when more than one tax is selected, django receives the request.POST like this:

{..., u'taxes[]': [u'269', u'268', u'156'], ...}

而不是这个:

{..., u'taxes': [u'269', u'268', u'156'], ...}

因此,表单已验证,但未保存任何税费... :(

另一个注意事项:我曾尝试在发布表单之前使用断点跳转,并且 params 对象没有 taxes[] 键,但它确实有一个 taxes 键。

【问题讨论】:

    标签: ajax django jquery django-forms


    【解决方案1】:

    好吧,经过许多小时的调试和搜索,这个答案 (https://stackoverflow.com/a/21016757/1580632) 帮助我解决了这个问题。简而言之,在 $.ajax 调用中,只需添加:

    $.ajax({
        ...
        traditional: true,
        ...
    }
    

    就是这样。

    【讨论】:

      猜你喜欢
      • 2017-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-12
      • 1970-01-01
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      相关资源
      最近更新 更多