简体   繁体   中英

Upload Image File to server

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'

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM