上传图像django时出现500内部服务器错误

时间:2016-04-25 05:00:52

标签: python ajax django nginx django-1.9

我的表格分为两部分。我的意思是表单有租借信息字段和多个图像上传。我在前端使用reactjs,后端使用django。成功保存到数据库但是图像没有。它抛出了500个内部服务器错误。我在数字海洋上部署了我的应用程序(使用了nginx,gunicorn)。我的应用程序的链接是commonrentspace.me

这是我的代码

AddRent.js(上传图片代码更专注于缩短代码行)

 let image = [];
 class RenderPhotos extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            files: []
        };
    }

    onDrop(files) {
      console.log('Received files: ', files);
      this.setState({
          files: files
      });

           function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
        var csrftoken = getCookie('csrftoken');
        function csrfSafeMethod(method) {
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }
        $.ajaxSetup({
                beforeSend: function(xhr, settings) {
                    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                }
            });
            image = new FormData(files);
            $.each(files,function(i,file){
              image.append('image',file);
            });

    }

    showFiles() {
        const { files } = this.state;
        console.log('files',files);

        if (!files.length) {
            return null;
        }

        return (
            <div>
                <h3>Dropped files: </h3>
                <ul className="gallery">
                    {
                        _.map(files,(file, idx) => {
                            return (
                              <div className="col-md-3">
                                  <li key={idx}>
                                      <img src={file.preview} className="img-fluid" width={200}/>
                                      <div className="imageName">{file.name}</div>
                                  </li>
                                </div>
                            )
                        })
                    }
                </ul>
            </div>
        );
    }

    render() {
      return (
           <div>
                <h3 className="formHeadingh3">Photos can bring your space to life</h3>
                <p>Add photos of spaces to give more insight of your space </p>
                <hr/>
                <div className="col-md-12">
                <form method="POST" encType="multipart/form-data">
                <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}"/>
                  <Dropzone onDrop={this.onDrop.bind(this)}
                          style={style}
                          activeStyle={activeStyle}
                          accept="image/*">
                    Try dropping some files here, or click to select files to upload.
                </Dropzone>
              </form>
                {this.showFiles()}
              </div>
              <div className="row continueBtn text-right">
                    <button className="btn how-it-works pull-left" onClick={this.props.previousStep.bind(this)}><i className="fa fa-hand-o-left"></i></button>
                    <button className="btn how-it-works pull-right" onClick={this.nextStep.bind(this)}>Submit</button>
               </div>
            </div>

      );
    }

       nextStep(step){
                  var sendData={'ownerName':this.props.fieldValues.ownerName,
                        'email':this.props.fieldValues.email,
                        'phoneNumber':this.props.fieldValues.phoneNumber,
                        'listingName':this.props.fieldValues.listingName,
                        'summary':this.props.fieldValues.summary,
                        'property':this.props.fieldValues.property,
                        'room':this.props.fieldValues.room,
                        'price':this.props.fieldValues.price,
                        'city':this.props.fieldValues.city,
                        'place':this.props.fieldValues.place,
                        'water':this.props.fieldValues.water,
                        'amenities':this.props.fieldValues.amenities.join(', ')
                      }
                  $.ajax({
                  url:"/add/space/",
                  data:sendData,
                  type:'POST',
                  success: function(data, textStatus, xhr ) {
                    var pk = xhr.getResponseHeader('pk-user');
                    console.log('pk is',pk);
                    $.ajax({
                     url:"/upload/image/"+pk+"/",
                     data:image,
                     contentType:false,
                     processData:false,
                     type:'POST',
                     mimeType: "multipart/form-data",
                     success: function(data) {
                       console.log('success');
                     }
                    });
                   window.location.href="http://commonrentpspace.me/"; // if i use this to redirect, the images does not get upload
                  }
                 });
       }


}

Views.py

class AddView(TemplateView):
    template_name = 'rentals/add.html'

class AddSpaceView(View):
    def post(self,request,*args,**kwargs):
        print ('add space view',request)
        if request.POST:
            response = HttpResponse('')
            print('owner name is',request.POST.get('ownerName'))
            print('amenities',request.POST.get('amenities'))
            rental = Rental()
            rental.ownerName = request.POST.get('ownerName')
            rental.email = request.POST.get('email')
            rental.phoneNumber = request.POST.get('phoneNumber')
            rental.listingName = request.POST.get('listingName')
            rental.summary = request.POST.get('summary')
            rental.property = request.POST.get('property')
            rental.room = request.POST.get('room')
            rental.price = request.POST.get('price')
            rental.city = request.POST.get('city')
            rental.place = request.POST.get('place')
            rental.water = request.POST.get('water')
            rental.amenities = request.POST.get('amenities')
            rental.save()
            response['pk-user'] = rental.pk
            return response

        return HttpResponse('Rental Information successfully added')


 class UploadImage(View):
    model = Rental
    template_name = 'rentals/add.html'
    print "Hello"
    def get(self, request, *args, **kwargs):
        return render(request, self.template_name)
    def post(self,request,*args,**kwargs):
        try:
            rental = Rental.objects.get(pk = self.kwargs['pk'])
        except Rental.DoesNotExist:
            error_dict = {'message': 'Rental spae not found'}
        print "Error Rental do not exist"
            return self.render(request,'rentals/add.html',error_dict)
        if request.FILES:
            for file in request.FILES.getlist('image'):
                print('file',file)
                image = Gallery.objects.create(rental = rental, image=file)
                print('image',image)
        print "Uploading Image"
        return HttpResponse("Uploaded successfully")

nginx配置

upstream app_server {
    server 127.0.0.1:9000 fail_timeout=0;
}

server {
    listen 80 default_server;


    root /usr/share/nginx/html;
    index index.html index.htm;

    client_max_body_size 4G;
    server_name _;

    keepalive_timeout 5;


    gzip                on;
    gzip_http_version   1.0;
    gzip_comp_level     2;
    gzip_proxied        any;
    gzip_min_length     1100;
    gzip_buffers        16 8k;
    gzip_types          text/plain text/html text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;

    # Some version of IE 6 don't handle compression well on some mime-types, so just disable for them
    gzip_disable "MSIE [1-6].(?!.*SV1)";

    # Set a vary header so downstream proxies don't send cached gzipped content to IE6
    gzip_vary on;



    # Your Django project's media files - amend as required
    location /media  {
        alias /home/django/django_project/media/;
    }

    # your Django project's static files - amend as required
    location /static {
        alias /home/django/django_project/static;
    }

     # Proxy the static assests for the Django Admin panel
    location /static/admin {
       alias /home/django/django_project/static/admin/;
    }

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://app_server;
    }
}

upstream app_server {
    server 127.0.0.1:9000 fail_timeout=0;
}

server {
    listen 80 default_server;


    root /usr/share/nginx/html;
    index index.html index.htm;

    client_max_body_size 4G;
    server_name _;

    keepalive_timeout 5;


    gzip                on;
    gzip_http_version   1.0;
    gzip_comp_level     2;
    gzip_proxied        any;
    gzip_min_length     1100;
    gzip_buffers        16 8k;
    gzip_types          text/plain text/html text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;

    # Some version of IE 6 don't handle compression well on some mime-types, so just disable for them
    gzip_disable "MSIE [1-6].(?!.*SV1)";

    # Set a vary header so downstream proxies don't send cached gzipped content to IE6
    gzip_vary on;



    # Your Django project's media files - amend as required
    location /media  {
        alias /home/django/django_project/media/;
    }

    # your Django project's static files - amend as required
    location /static {
        alias /home/django/django_project/static;
    }

     # Proxy the static assests for the Django Admin panel
    location /static/admin {
       alias /home/django/django_project/static/admin/;
    }

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://app_server;
    }
}

我是否需要提供任何其他信息?可能是什么原因?

0 个答案:

没有答案