如何在Django中上传文件?

时间:2017-03-25 17:09:56

标签: python ajax django

我很抱歉,但我对Django来说真的很新,我已经尝试过文档中的步骤了。不幸的是,它没有像我期望的那样工作。我希望在执行这些步骤后,它会将文件保存到我的媒体文件夹中。如果可能的话,我也想使用AJAX,但我无法理解这一流程。

HTML

 <form method="post" enctype="multipart/form-data">
            {% csrf_token %}
            <input type="file" name="myfile">
            <button type="submit">Upload</button>
 </form>

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    email = models.TextField(max_length=500, blank=True)
    contact_number = models.CharField(max_length=30, blank=True)
    profile_picture = models.FileField(null=True,blank=True)

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

forms.py

class UploadForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('profile_picture',)

views.py

def model_form_upload(request):
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('/home/')

我试图为用户的个人资料保存照片。请帮我。如果有办法用AJAX做到这一点,那也会有所帮助。

1 个答案:

答案 0 :(得分:0)

继承人我是如何解决我的问题的:

我使用此方法从输入中提取我的图像

  function extractPhoto(input) {
        var files = input[0].files;
        if (!files.length) {
            alert('Unable to upload: no file selected');
            return;
        }
        return files[0]
    }

然后我使用jQuery的FormData和ajax将提取的照片传递给我的视图

 var image = $("#image");
        $("#uploadbutton").click(function () {
            const form = new FormData();
            form.append('image', extractPhoto(image));

            generateCSRFToken();
            $.ajax({
                url: '/upload_photo/',
                data: form,
                type: "POST",
                contentType: false,
                processData: false,
                success: function (data) {
                    location.reload();
                },
                error: function (data) {

                }

            })
        });

然后我在views.py

中处理它
def upload_photo(request):
        if 'image' not in request.FILES:
            return HttpResponse(status=400)

        user = request.user

        user.profile.profile_picture = request.FILES.get('image')
        user.profile.save();

        return HttpResponse(status=200)