Ajax图像上传-无法上传.pic没有与其关联的文件

时间:2018-08-27 16:23:34

标签: python django django-forms

我正在尝试使用Ajax上传图像。表单接受用户的输入,提交后,帖子应加载到div中,而无需刷新页面,并保存在模型中。我无法在视图中接收文件,并且在使用带有ajax的表单数据时也收到状态代码被禁止的csrf令牌错误。图片是从管理端添加后上传并显示的。

这是我在home.html中的表格

    <form action="" method="POST" class="my-ajax-form" enctype="multipart/form-data" >
                {% csrf_token %}
                Post Title:<br>
                <input type="text" name="title" id="titles"><br>
                Post Text:<br>
                <input type="text" name="text" id="text"><br>
                Image:
                <input id="image" type="file" name="image"><br>

                <input type="submit" value="submit" class="btn btn-primary" name="" id="submit">
            </form>

models.py:

    class Post(models.Model):
    user= models.ForeignKey(User, on_delete=models.CASCADE)
    heading = models.CharField(max_length=200, null=False)
    text = models.TextField(null=False)
    created_date=models.DateTimeField(default=timezone.now)
    pic = models.ImageField(upload_to='image', blank='True')

     def __str__(self):
       return self.heading



     def getuser(self):
       return self.user.username

     def total_likes(self):
       return Like.objects.filter(post=self).count()



   class Like(models.Model):
   user = models.ForeignKey(User,on_delete=models.CASCADE)
   post = models.ForeignKey(Post,on_delete=models.CASCADE)

     def __str__(self):
       return self.post.heading

plugin.js:

    var $myForm = $('.my-ajax-form');


  $('#submit').click(function(event){
    event.preventDefault();

   $.ajax({
        method:'POST',
        url: 'save/',
        data:{
        title : $('#titles').val(),
        text : $('#text').val(),

        csrfmiddlewaretoken: 
    $('input[name=csrfmiddlewaretoken]').val()
             },
        datatype:'json',
        success: function(data) {
        console.log("Post Added!");
        console.log('DATA: ',data)
        datas=$.parseJSON(data)

        console.log('author: ', datas.text)
         $('#postlist').prepend('<form class="like_form"><div 
   class="postcard"><p>Author: '+ datas.author+'</p><p>Created Date: 
  '+datas.created+'</p><p>Title: '+datas.title+'</p> 
    <p>'+datas.text+'</p><p><img src="'+datas.image +'" width="300px"> 
 </p>   
  <div class="like-section">'+' '+datas.total_likes+' ' +' Likes<form 
  action="like/" method="POST" ><input type="submit"  
   name="'+datas.postpk+'" value="Like" class="btn btn-primary like"/> 
   </form></form>')
      },
    error: function(xhr,errmsg,err) {
      console.log("There was an error. Try again please!");
     console.log(xhr.status + ": " + xhr.responseText);
    }
          });
   });


formdata = new FormData();
$("#image").on("change", function() {
    var file = this.files[0];
    if (formdata) {
        formdata.append("image", file);


        $.ajax({
            url: 'save/',
            type: "POST",

            data: {
            form_data: formdata,
              csrfmiddlewaretoken: 
    $('input[name=csrfmiddlewaretoken]').val()
            },
            processData: false,

            success:function(){
            console.log('SUCCESS');
            },
             error: function(rs,e){
        console.log(rs, e.responseText);
        console.log('ERROR');
  },
         });
    }
  });

views.py:

    def savepost(request):
if request.method=='POST':

        titles = request.POST['title']
        texts = request.POST['text']
        image = request.FILES.get('image')
        print(image)
        response_data={}
        post = Post(user=request.user, heading=titles, text=texts, pic=image)
        post.save()

        likes=Like.objects.filter(post=post)
        response_data['result'] = 'Create post successful!'
        response_data['postpk'] = post.pk
        response_data['text'] = post.text
        response_data['total_likes'] = str(post.total_likes)
        response_data['created'] = str(post.created_date)
        response_data['author'] = post.user.username
        response_data['image'] = str(post.pic.url)
        response_data['title'] = post.heading
        return HttpResponse(
           json.dumps(response_data),

          )
else:
    return HttpResponse(
    json.dumps({"Error": "An error occured"}),
       )

0 个答案:

没有答案