如何将图像保存到其关联的实例?

时间:2016-03-01 02:45:15

标签: python django django-views

如何将上传的图像填充到其关联的实例?我试过但是我收到了错误。我做的是

Models.py

class Rental(models.Model):
    ownerName = models.CharField(_("Owner's Name"),max_length=255, blank=True,null=True)
    listingName =  models.CharField(_("Lisitng Name"), max_length=255, blank=False,null=True)
    slug = models.SlugField(unique=True,blank=False,null=True)
    summary = models.TextField(max_length=500, blank=True,null=True)
    room = models.PositiveIntegerField(_("No of Rooms"), blank=False, null=True)


class GalleryImage(models.Model):
    rental = models.ForeignKey('Rental',on_delete=models.CASCADE,blank=True,null=True,
                                verbose_name=_('Rental'), related_name="gallery")
    image = models.ImageField(blank=True,upload_to='upload/',null=True)


def pre_save_post_receiver(sender,instance,*args,**kwargs):
    slug = slugify(instance.listingName)
    exists = Rental.objects.filter(slug=slug).exists()
    if exists:
        slug = "%s-%s"%(slug,instance.id)
    instance.slug = slug

pre_save.connect(pre_save_post_receiver,sender=Rental)

视图

class UploadImage(View):
model = Rental
def post(self,request,*args,**kwargs):
    print(request)
    f =request.FILES.getlist('image')
    print ('f',f)
    if request.FILES:
        # files = [request.FILES.getlist('image[%d]'%i) for i in range(0,len(request.FILES))]
        rental_id = request.POST.get('rental_id')
        rental = Rental.objects.get(id=rental_id)
        for file in request.FILES.getlist('image'):
            print('file',file)
            image = GalleryImage.objects.create(image=file,rental=rental)
            print('image',image)
            image.save()
    return HttpResponseRedirect('/')

urls.py

urlpatterns = [
    url(r'^$', LandingView.as_view(), name="landing_page"),
    url(r'^add/$', AddView.as_view(), name="add"),
    url(r'^roomlist/$', RoomList.as_view(), name="roomlist"),
    url(r'^rent/(?P<slug>\w+)/$', rent_detail, name="rent_detail"),
    url(r'^add/space/$', AddSpaceView.as_view(), name="addSpace"),
    url(r'^lang/$', Language.as_view(), name="lang"),
    url(r'^upload/image/$', UploadImage.as_view(), name="uploadImage"),
    url(r'^filter/space/$', FilterSpace.as_view(), name="filterSpace"),
    url(r'^api/', include(v1_api.urls)),
]

我在rental_id上收到错误。为了创建表单,我使用了reactjs和ajax。

我已更新urls.py

如果需要

使用reactjs和ajax

图片上传

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


      var image = [];
      image = new FormData(files);

      $.each(files,function(i,file){
        image.append('image',file);
      });

     $.ajax({
      url:"/upload/image/",
      data:image,
      contentType:false,
      processData:false,
      type:'POST',
      mimeType: "multipart/form-data",
      success: function(data) {
        console.log('success');
      }
     });
  }

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

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

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

    render() {
      return (
           <div>
                <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}>
                    Try dropping some files here, or click to select files to upload.
                </Dropzone>
              </form>
                {this.showFiles()}
              </div>
            </div>

      );
    }
  }

1 个答案:

答案 0 :(得分:0)

错误消息告诉您问题。

NameError: name 'rental_id' is not defined

您正尝试使用rental_id过滤Rental个对象,但尚未定义该变量。 您的帖子请求中可能有rental_id。如果是这样,请尝试添加:

rental_id = request.POST.get('rental_id')