forms.py:
class TestPicForm(forms.ModelForm):
x = forms.FloatField(widget=forms.HiddenInput())
class Meta:
from .models import TestPic
model = TestPic
fields = ('file', 'file_50', 'x', )
def save(self):
user_photo = super(TestPicForm, self).save()
x = self.cleaned_data.get('x')
image = Image.open(user_photo.file)
# image_50 = Image.open(user_photo.file_50)
cropped_image = image.crop((x, 2x, x + 10, y + 10)).resize((300, 300), Image.ANTIALIAS)
cropped_50_image = image.crop((x, 2x, x + 50, y + 50)).resize((10, 150), Image.ANTIALIAS)
cropped_image.save(user_photo.file.path)
cropped_50_image.save(user_photo.file_50.path)
return user_photo
我之前问过抽象问题,但是现在我可以更具体地提出一个问题。
在此代码上,我仅上传一个文件,但将其保存到多个字段中。(在这种情况下,为file
,file_50
)
models.py:
class TestPic(models.Model):
file = models.ImageField(null=True, blank=True, default=None)
file_50 = models.ImageField(null=True, blank=True, default=None)
jquery-ajax.html:
<form method="post" enctype="multipart/form-data" id="form_upload">
<input type="file" name="file" required id="input_file"></form>
<script>
$("#upload_btn").click(function () {
var x = 1
var form_file = _form_upload.find('#form_upload')[0];
var form_data = new FormData(form_file);
form_data.append('x', x);
$.ajax({
url:'/ajax/',
type:'post',
dataType:'json',
cache:false,
processData: false,
contentType: false,
data:form_data,
success:function (data) {
}
});
});
</script>
views.py:
if request.is_ajax():
testpic = TestPic.objects.get(pk=1)
form = TestPicForm(request.POST, request.FILES, instance=testpic)
if form.is_valid():
form.save()
return JsonResponse({'success': 'file_uploaded'})
return JsonResponse({'success': 'file_uploaded with: ' + 'failed form_valid'})
返回The 'file_50' attribute has no file associated with it.
我认为在forms.py
中,cropped_50_image.save(user_photo.file_50.path)
是个问题。
如何解决这个问题?