我正在尝试通过ajax上传图像,并且前端代码似乎正在运行,并且图像数据位于request.FILES
中。但是图片并未在服务器端上传。
这是我的django视图:
@login_required
def update_profile_image(request):
print(request.FILES)
if request.method == 'POST':
p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
if p_form.is_valid():
p_form.save()
context = {'None': 'none'}
return JsonResponse(context)
else:
return HttpResponse('None')
该表单有效,但图像未上传到MEDIA目录中。
我的模特:
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{ self.user.username } Profile'
和表格:
from django.db import models
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
顺便说一下,这是我的AJAX调用(正如我所说的那样,它可以正常工作)。
$(document).on('submit', '#profile_edit_form', function(event){
event.preventDefault();
$.ajax({
url : "/users/update_profile_image/",
type : 'POST',
//enctype : "multipart/form-data", //it is done inside jquery
data : formdata,
cache : false,
contentType : false,
processData : false,
success : function(data) {
console.log('success');
//$('#profile_picture').html(data.)
},
error: function(data) {
console.log('image-fail');
}
});
});
我的视图功能出了什么问题?
谢谢!