Как сохранить изображения, которые я получаю в запросе POST, используя ajax? - PullRequest
1 голос
/ 31 марта 2019

Я новичок в Джанго.Я создаю форму для идентификации с двумя полями для загрузки изображений - main_photo, profile_photo

У меня есть форма Django, которая загружает изображения.С помощью ajax FormData () ( я с ней неправильно работаю, может быть ), я отправляю их в функцию через POST request.Но я не могу их хранить.Помогите мне.

шаблон

<input type="hidden" name="csrfmiddlewaretoken" value="9S6oPbkHujBnxaKHSxzU5W4mdkEs6Lbbf3g0OIJAk3lBfaMV8bafzpz8QudIuofJ">
  9S6oPbkHujBnxaKHSxzU5W4mdkEs6Lbbf3g0OIJAk3lBfaMV8bafzpz8QudIuofJ
    <div class="field inline">
        <div class="subhead"></div>

        <input type="file" name="main_photo" required="" id="id_main_photo">
        <label for="foto1" class="id_foto">
            <div class="addPhoto">
                <div class="button"></div>
            </div>
        </label>
    </div>
    <div class="field inline">
        <div class="subhead"></div>
        <input type="file" name="profile_photo" required="" id="id_profile_photo">
        <label for="foto2" class="id_foto">
            <div class="addPhoto">
                <div class="button"></div>
            </div>
        </label>
    </div>
    <div class="center">
      <button class="submit mgln" type="button"></button>
    </div>

jquery

var token = '{{csrf_token}}';
$('.mgln').on('click', function(){

    photo = new FormData();
    photo.append('file1', $('input[name=main_photo]').prop('files')[0])
    photo.append('file2', $('input[name=profile_photo]').prop('files')[0])
    photo1 = photo.getAll('file1')
    photo2 = photo.getAll('file1')
  data = {
      photo1: photo1,
      photo2: photo2,
    }
    console.log(data)
    $.ajax({
      headers: { "X-CSRFToken": token },
      type: "POST",
      url: "{% url 'identification_view' %}",
      data: data,
      processData: false,
      contentType: false,
      success: function(result) {
        alert('Ok.');
      },
      error: function(result) {
        alert('Error.');
      }
    })
  })

просмотров

def identification_view(request):
    if request.method == 'POST':
        form = IdentificationForm(request.POST, request.FILES)
        if request.is_ajax():
            print(request.POST.values())      #[]
            print(request.FILES.values())     #[]
            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})

формы

class IdentificationForm(forms.ModelForm):
    class Meta:
        model = RequestUser
        fields = ('main_photo', 'profile_photo', )

    def clean_image(self):
        ...

    def clean_image2(self):
        ...

1 Ответ

0 голосов
/ 01 апреля 2019

вид

def identification_view(request):
    if request.method == 'POST':
        form = IdentificationForm(request.POST, request.FILES)
        if request.is_ajax():
            print(dir(request.FILES))
            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})

Сценарий

var token = '{{csrf_token}}';
$('.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: "{% url 'identification_view' %}",
      data: formData,
      processData: false,
      contentType: false,
      success: function(result) {
        alert('ok.');
      },
      error: function(result) {
        alert('error.');
      }
    })
  })
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...