0

Have a little problem with uploar file image to server

That is JS code for ajax send file to server

/** * * Init Crope Image * */

    $('input[type=file]').change(function(){
        files = this.files;
    });

    $('#upload_photo').click(function (event) {
        event.stopPropagation(); // Остановка происходящего
        event.preventDefault();  // Полная остановка происходящего

        var data = new FormData();
        $.each( files, function( key, value ){
            data.append( key, value );
        });

        var obj = {
            csrfmiddlewaretoken: $('input[name^="csrfmiddlewaretoken"]').val(),
            action: 'upload_photo',
            file: data
        };

        $.ajax({
            url: /user_ajax_set_photo/,
            type: 'POST',
            data: data,
            cache: false,
            dataType: 'json',
            processData: false,
            contentType: false,
            success: function( response, textStatus, jqXHR ){

                if( response.error === 'false' ){

                    console.log('Загружен' + response.error );

                }
                else{
                    console.log('ОШИБКИ ОТВЕТА сервера: ' + response.error );
                }
            },
            error: function( jqXHR, textStatus, errorThrown ){
                console.log('ОШИБКИ AJAX запроса: ' + textStatus );
            }
        });
    });
}

That us my View

def user_ajax_set_photo(request):
    if request.method == 'POST':
        form = FileUploadForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            print 'valid form'
        else:
            print 'invalid form'
            print form.errors
    return True

And for last that is my Form

class FileUploadForm(forms.Form):

    class Meta:
        model = RegModel
        fields = ['image']

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request", None)
        super(FileUploadForm, self).__init__(*args, **kwargs)

    def save(self):
        photo = super(FileUploadForm, self).save(commit=False)
        artist = RegModel.objects.get(id=self.request.user.id)
        photo.artist = artist
        photo.save()
        return photo

Can u tell me where is my promlems...

Last error from backtrase

AttributeError: 'bool' object has no attribute 'get'
2
  • What's the line and file where that error occurs? Commented Mar 13, 2017 at 20:07
  • Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 42, in inner response = get_response(request) File "C:\Python27\lib\site-packages\django\utils\deprecation.py", line 138, in call response = self.process_response(request, response) File "C:\Python27\lib\site-packages\django\middleware\clickjacking.py", line 32, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'bool' object has no attribute 'get' Commented Mar 13, 2017 at 20:09

1 Answer 1

1

The problem here is that your view must return some kind of Django Response object. Given that you're using AJAX here, I'm guessing you'd want to use the JSONResponse object:

from django.http import JSONResponse

def user_ajax_set_photo(request):
    if request.method == 'POST':
        form = FileUploadForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            print 'valid form'
        else:
            print 'invalid form'
            print form.errors
    return JSONResponse([True], safe=False)

Note that in JSON you can't just have a floating Boolean value, so I wrapped that in an array. By default, when you pass a non-dict object into JSONResponse, you have to also pass safe=False.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.