Почему изображения неправильно сохраняются при загрузке с мобильного телефона с помощью Ajax
?
У меня есть 2 fields
для загрузки изображений. Когда я нажимаю submit
, они переходят на Django
через Ajax
. Затем они обрабатываются и сохраняются в базе данных.
Проблема в том, что мой код работает только для загрузки изображений с computer
. А при загрузке из mobile phone (iphone)
просто создается запись в базе данных, есть ссылки на эти фотографии, но когда я пытаюсь открыть их - я получаю ошибку 403 . Когда я пытаюсь вручную изменить эти фотографии со страницы администрирования - я получаю ту же ошибку - 403 .
models.py
from djlime.utils import get_file_path
class RequestUser(models.Model):
main_photo = models.ImageField(_('main_photo'), upload_to=get_file_path)
profile_photo = models.ImageField(_('profile_photo'), upload_to=get_file_path)
@property
def upload_dir(self):
return 'accounts/request_user/images'
forms.py
class IdentificationForm(forms.ModelForm):
class Meta:
model = RequestUser
fields = ('main_photo', 'profile_photo', )
widget= {
'main_photo': forms.FileInput(
attrs={
'style': 'display: none',
}
),
'profile_photo': forms.FileInput(
attrs={
'style': 'display: none',
}
)
}
def __init__(self, *args, **kwargs):
super(IdentificationForm, self).__init__(*args, **kwargs)
self.fields['main_photo'].widget.attrs = {'class':'file_dnl'}
self.fields['profile_photo'].widget.attrs = {'class':'file_dnl'}
def clean_image(self):
cd_image = self.cleaned_data['main_photo']
return cd_image
def clean_image2(self):
cd_image = self.cleaned_data['profile_photo']
return cd_image
views.py
def identification_view(request):
if request.method == 'POST':
form = IdentificationForm(request.POST, request.FILES)
if request.is_ajax():
main_photo = request.FILES.get('file1')
profile_photo = request.FILES.get('file2')
RequestUser.objects.create(
user = request.user,
main_photo = main_photo,
profile_photo = profile_photo
)
return HttpResponse('image upload success')
else:
form = IdentificationForm()
identifications = RequestUser.objects.filter(user = request.user)
return render(request, 'accounts/identification.html', {'form': form, 'identifications': identifications})
identification.html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" class="edit_form new_event" enctype="multipart/form-data" method="POST">
<input type='hidden' name='csrfmiddlewaretoken' value='bBfv5mapMAVzI35UGp0H4LfbKR9avG4id6Me01bRZfAefjzKwcL3xj1lDiLBBR5L' />
<div class="field inline">
<div class="subhead">Main photo:</div>
<input type="file" name="main_photo" required class="file_dnl" id="id_main_photo" />
<label for="foto1" class="id_foto">
<div class="addPhoto">
<div class="button" id='foto1_button'></div>
</div>
</label>
<div id='profile_photo' style='display:none; text-align:center'></div>
</div>
<div class="field inline">
<div class="subhead">Profile photo:</div>
<input type="file" name="profile_photo" required class="file_dnl" id="id_profile_photo" />
<label for="foto2" class="id_foto">
<div class="addPhoto">
<div class="button" id='foto2_button'></div>
</div>
</label>
<div id='profile_photo' style='display:none; text-align:center'></div>
</div>
<div class="center">
<button class="submit mgln" type='button'>Submit</button>
</div>
</form>
<script>
$("input[name='main_photo']").change(function(){
var filename = $(this).val().replace(/.*\\/, "");
console.log(filename)
$("#main_photo").html(filename).css('display', 'block');
});
$("input[name='profile_photo']").change(function(){
var filename = $(this).val().replace(/.*\\/, "");
console.log(filename)
$("#profile_photo").html(filename).css('display', 'block');
});
$('#foto1_button').on('click', function(){
document.getElementById("id_main_photo").click();
});
$('#foto2_button').on('click', function(){
document.getElementById("id_profile_photo").click();
});
var token = 'bBfv5mapMAVzI35UGp0H4LfbKR9avG4id6Me01bRZfAefjzKwcL3xj1lDiLBBR5L';
$('.mgln').on('click', function(){
formData = new FormData();
formData.append('file1', $('input[name=main_photo]')[0].files[0])
formData.append('file2', $('input[name=profile_photo]')[0].files[0])
$.ajax({
headers: { "X-CSRFToken": token },
type: "POST",
url: "/identification/",
data: formData,
processData: false,
contentType: false,
success: function(result) {
alert('Ok.');
},
error: function(result) {
alert('Not ok.');
}
})
})
</script>