Ajax形式的Django Manytomanyfield

我实现了一个Ajax CRUD . 我的模型有一个ManyToMany字段(类别) . 如果我只为这个字段选择一个项目,那么一切都会很好,但是如果选择多个项目,它会显示无效的错误 . 请告诉我该怎么办 .

model.py:

class BusienssCategory(models.Model):
   title = models.CharField(max_length=20, unique=True)
   slug = models.SlugField(unique=True)
   description = models.CharField(max_length=45)

   def __str__(self):
      return self.title

class BusienssProfile(models.Model):
   title = models.CharField(max_length=20)
   description = models.CharField(max_length=40)
   category = select2.fields.ManyToManyField(BusienssCategory)
   image = models.ImageField(upload_to=upload_image_path, null=True, 
   blank=True)

   def __str__(self):
      return self.title

form.py:

class BusinessForm(forms.ModelForm):

class Meta:
    model = BusienssProfile
    fields = ('title', 'category',  'shortDescription')

view.py:

def save_business_form(request, form, template_name):
  data = dict()
  form = BusinessForm(request.POST, request.FILES)
  if request.method == 'POST':
    if form.is_valid():
        form.save()
        data['form_is_valid'] = True
        businesses = BusienssProfile.objects.all()
        data['html_business_list'] = render_to_string('business/business_profile/partial_business_list.html', {
            'businesses': businesses
        })
    else:
        data['form_is_valid'] = False
        context = {'form': form}
        data['html_form'] = render_to_string(template_name, context, 
        request=request)
  return JsonResponse(data)

ajax.js:

var saveForm = function() {

    var form = $(this);
    var data = new FormData($('form').get(0));
    var categories = $("#id_category").val();
    var featured = $('#id_featured').prop('checked');
    var active = $('#id_active').prop('checked');

    data.append("image", $("#id_image")[0].files[0]);
    data.append("title",$("#id_title").val());
    data.append("category", categories);
    data.append("description",$("#id_Description").val());

$.ajax({
  url: form.attr("action"),
  data: data,
  processData: false,
  contentType: false,
  type: form.attr("method"),
  dataType: 'json',
  success: function (data) {
    if (data.form_is_valid) {
            Command: toastr["success"]("The profile has been 
            deleted.", "Success");           
    }
    else {
      Command: toastr["error"]("Something has gone wrong!", "Failure")
    }
  },
error: function(XMLHttpRequest, textStatus, errorThrown, url) {
                alert("Status: " + textStatus);
                alert("Error: " + errorThrown);

            }
});
return false;
};

我已经在没有Ajax的情况下测试了表单,并且没有显示任何错误 . 我认为Multiselect回报值必定是错误的 .

回答(1)

2 years ago

最后,我通过同时使用serializeArray和FormData解决了这个问题 . 我使用Formdata来处理图像字段,使用serializeArray来序列化manytomanyField(和其他字段) . 这是我最后的js文件:

var saveForm = function() {

    var form = $(this);
    serialData = form.serializeArray();
    // We need to use FormData to upload image or file 
    var data = new FormData($('form').get(0));
    data.append("image", $("#id_image")[0].files[0]);
    var other_data = form.serializeArray();
        $.each(other_data,function(key,input){
        data.append(input.name,input.value);
    });

 $.ajax({
    url: form.attr("action"),
    data: data,
    type: form.attr("method"),
    dataType: 'json',
    cache: false,
    processData: false,
    contentType: false,
    success: function (data) {
    ...
    }
   return false;
   };