我一直在尝试上传多张图片,但我的API在图片列表中只占用了一张图片。可能是什么原因导致不拍摄所有图像?我做错了什么?
这是我的代码。 的 urls.py
url(r'^api/', RentalList.as_view()),
url(r'^api/upload/', FileUploadView.as_view()),
url(r'^api/(?P<pk>[0-9]+)/$', RentalDetail.as_view()),
Models.py
class Rental(models.Model):
email = models.CharField(max_length=120,blank=True, null=True)
phoneNumber = models.PositiveIntegerField(blank=False,null=True,
help_text=_("Phone number of contact person"))
listingName = models.CharField(_("Lisitng Name"), max_length=255, blank=False, null=True,
help_text=_("Title of the rental space"))
summary = models.TextField(max_length=500, blank=True, null= True,
help_text=_("Description of the rental space"))
property = models.CharField(_("Property type"),max_length=10,null=True)
price = models.PositiveIntegerField(blank=False,null=True,
help_text=_("Rental price of the space per month"))
city = models.CharField(_("City"), max_length=255, blank=False, null=True,
help_text=_("City of the rental space"))
place = models.CharField(_("Place"), max_length=255, blank=False, null=True,
help_text=_("Place of the rental space"))
phone_image = models.CharField(max_length=2048,blank=True,null=True,
help_text=_("image form of the phone number"))
image = models.FileField(upload_to='upload/',null=True,blank=True)
Views.py
class RentalList(generics.ListCreateAPIView):
serializer_class = RentalSerializer
queryset = Rental.objects.all()
def get(self,request,format=None):
rental = self.get_queryset()
serializer_rental = RentalSerializer(rental,many=True)
return Response(serializer_rental.data)
@permission_classes((IsAdminUser, ))
def post(self,request,format=None):
user=request.user
serializer_rental = RentalSerializer(data=request.data,context={'user':user})
if serializer_rental.is_valid():
serializer_rental.save()
return Response(serializer_rental.data,status=status.HTTP_201_CREATED)
return Response(serializer_rental.errors,status=status.HTTP_400_BAD_REQUEST)
class RentalDetail(generics.RetrieveUpdateDestroyAPIView):
queryset=Rental.objects.all()
serializer_class = RentalSerializer
class FileUploadView(APIView):
parser_classes = (MultiPartParser, FormParser, )
def post(self, request, format=None):
uploaded_file = request.FILES['image']
print('up_file is',uploaded_file)
filename = '/media/upload'
with open(filename, 'wb+') as destination:
for chunk in uploaded_file.chunks():
print('chunk',chunk)
destination.write(chunk)
destination.close()
my_saved_file = open(filename)
return Response(uploaded_file.name, status.HTTP_201_CREATED)
registration.jsx
var RenderPhotos = React.createClass({
getInitialState: function () {
return {
files:[]
};
},
onDrop(files) {
console.log('Received files: ', files);
this.setState({
files: files
});
},
showFiles() {
const files = this.state.files || null;
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={100}/>
<div>{file.name}</div>
</li>
);
})
}
</ul>
</div>
);
},
render: function () {
return (
<div>
<h3>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">
<Dropzone onDrop={this.onDrop}
style={style}
activeStyle={activeStyle}>
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}>Back</button>
<button className="btn how-it-works" onClick={this.submitRent}>Submit</button>
</div>
</div>
);
},
submitRent: function(e) {
// want to store the data so that when user reverts back to this form the data should be in same previous state
var req = request.post('http://localhost:8000/api/upload/');
var image = [];
image = new FormData();
var that = this;
var index;
for (index = 0; index < that.state.files.length; ++index) {
console.log(that.state.files[index]);
image.append('image',that.state.files[index]);
}
req.send(image);
console.log('req is',req);
req.end((err, res) => {
if (err) {
console.log('error', err);
} else {
console.log('success', res);
}
});
}
});
我发布了所有代码,认为可能很容易跟踪错误。
我是否需要为图像创建ManyToMany字段?