0

I am new to Django. I create a form for identification with two fields for upload images - main_photo, profile_photo

I have a Django form that upload images. With the help of ajax FormData() (I'm working with her wrong maybe), I send them to a function via POST request. But I can not store them. Help me.

template

<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.');
      }
    })
  })

views

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})

forms

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

    def clean_image(self):
        ...

    def clean_image2(self):
        ...
unknown
  • 252
  • 3
  • 12
  • 37
  • What result is your current code producing, and how does this result differ from the result you expected? – Cat Mar 31 '19 at 19:42
  • @Cat, _Empty_ **QueryDict** (`request.POST`, `request.FILES`) come to the function, and the **images uploaded** and transmitted via the `POST request` (using `ajax`) should come. These images are recorded in the `FormData`. Perhaps I do not correctly form the request ... _Sry for my bad english._ – unknown Mar 31 '19 at 19:55
  • Sorry, I'm not sure what's wrong there. Maybe this can help https://stackoverflow.com/questions/21044798/how-to-use-formdata-for-ajax-file-upload ? (or the mdn reference https://developer.mozilla.org/en-US/docs/Web/API/FormData ?) – Cat Mar 31 '19 at 21:31

1 Answers1

0

view

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})

script

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.');
      }
    })
  })
unknown
  • 252
  • 3
  • 12
  • 37