使用ImageField在Ajax中序列化(窗体)

时间:2018-07-06 20:43:34

标签: javascript ajax django django-rest-framework

我的模型中有一个forms.ImageField,名为Post。创建实例时,我会通过Ajax进行操作,同时使用data=$(this).serialize()将序列化的数据发布到我的PostCreateAPIView中,该数据是Django REST Framework的通用API CreateView,但是此方法仅序列化数据,并且忽略我的图片。

这是我的代码:

我的CreateAPIView:

class PostCreateAPIView(generics.CreateAPIView):
    serializer_class    = PostModelCreateSerializer     
    permission_classes  = [permissions.IsAuthenticated] 
    def perform_create(self, serializer):               
        print(self)
        serializer.save(user = self.request.user)

我的表格:

class PostModelCreateForm(forms.ModelForm):

    content = forms.CharField(
                    label="",
                    help_text="",#text to help
                    widget=forms.Textarea( attrs={
                    'cols'          : "50", #size
                    'rows'          : "6", #size
                    'placeholder'   : 'Votre publication', 
                    'style'         : 'resize : none' 
                    }))

    group = forms.ChoiceField(choices=USER_GROUPS, label='')

    class Meta:
        model   = Post #we define the model
        fields  = [
        "content",
        "group",
        "photo"
        ]

$(document.body).on("submit", ".post_form_class",function(event){
      event.preventDefault();
      this_ = $(this);
      var formData  = this_.serialize();
      $.ajax({
         method   : "POST",
         url      : createPostUrl,
         data     : formData,
         success  : function(data){
           
         },
         error    : function(data){
           
         }
       });

  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id = 'post-form' class="post_form_class" method="POST" action="" enctype="multipart/form-data">
  <input type='hidden' name='csrfmiddlewaretoken' value='6bgEU7jPVxXskBGJzP7KzSj9mz75k2dpSqG9Fn1kfghUeWQPTKCbm8JJc5za0ecl' />
  <p></p>        

<div id="div_id_content" class="form-group"> <div class="controls "> <textarea name="content" cols="50" rows="6" placeholder="Votre publication" style="resize : none" class="textarea form-control" required id="id_content">
</textarea> </div> </div> <div id="div_id_group" class="form-group"> <label for="id_group" class="control-label  requiredField">
                Group<span class="asteriskField">*</span> </label> <div class="controls "> <select name="group" class="select form-control" id="id_group"> <option value="1" selected>Département juridique</option> <option value="2">Département ingénieurs</option> <option value="3">Département Commerce</option> <option value="4">Nouveau</option>

</select> </div> </div> <div id="div_id_photo" class="form-group"> <label for="id_photo" class="control-label ">
                Photo
            </label> <div class="controls "> <input type="file" name="photo" class="clearablefileinput" id="id_photo" /> </div> </div>

    <div class="row">

      <div class='col-sm-2 '>
        <input class="btn btn-primary submit_form" id="submit_form" type="submit" value="Publier"/>
      </div>

      <div class='col-sm-1 col-sm-offset-8 '>
        <span class='post-chars-left' > </span>
      </div>

    </div>

</form>

NB:我已经尝试过formData = new FormData(this_);,但出现此错误:

  

TypeError:FormData.constructor的参数1未实现接口HTMLFormElement

1 个答案:

答案 0 :(得分:0)

感谢卢卡,这是答案:

$(document.body).on("submit", ".post_form_class",function(event){
    event.preventDefault();

    var formData  = new FormData(this);
    $.ajax({
        method   : "POST",
        url      : createPostUrl,
        data     : formData,
        processData:false,
        contentType:false,
        success  : function(data){
        location.reload(true); 
        },
        error    : function(data){
            console.log("ERROR:CH0x2 while fetching after creation form submit");
            console.log("data :",data.status, data.statusText);
        }
    });

 });