【发布时间】:2016-06-26 17:25:27
【问题描述】:
我在尝试将 id 从 django 模板传递到 reatjs 以将多个图像上传到其关联的外键对象时收到错误消息。错误显示为 unexpected token }。深入显示为
在控制台中
var uploadUrl = {
url:
};
我想做的是,我创建了一个具有多种形式的列表页面,它完全是使用 reactjs 开发的。我希望用户填写有关房间的数据并上传与其房间相关的多张图片。有两个模型,一个带有房间信息,另一个带有画廊(多个图像与一个租金相关联)。我希望上传的图片与其租金相关联,所以我将其编码如下
urls.py
urlpatterns = [
url(r'^add/$', AddView.as_view(), name="add"),
url(r'^add/space/$', AddSpaceView.as_view(), name="addSpace"),
url(r'^upload/image/(?P<pk>\d+)/$', ImageUpload, name="ImageUpload"),
]
views.py
def ImageUpload(request,pk=None): // for saving images only to its asscoiated rent
if request.POST or request.FILES:
rental = Rental.objects.get(id=pk)
for file in request.FILES.getlist('image'):
image = GalleryImage.objects.create(image=file,rental=rental)
image.save()
return render(request,'rentals/add.html')
class AddView(TemplateView): // for listing page
template_name = 'rentals/add.html'
class AddSpaceView(View): // for saving data to database except image
def post(self,request,*args,**kwargs):
if request.POST:
rental = Rental()
rental.ownerName = request.POST.get('ownerName')
rental.email = request.POST.get('email')
rental.phoneNumber = request.POST.get('phoneNumber')
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()
return HttpResponseRedirect('/')
listing.js(上传多张图片的ajax代码)
var image = [];
image = new FormData(files);
$.each(files,function(i,file){
image.append('image',file);
});
$.ajax({
url:"/upload/image/", // want to used id over here that is passed from add.html script tag so that image will be uploaded to its associated foriegn key object
data:image,
contentType:false,
processData:false,
type:'POST',
mimeType: "multipart/form-data",
success: function(data) {
console.log('success');
}
});
}
add.html 页面
<div id="listing">
</div>
{% include 'includes/script.html'%}
<script type="text/javascript">
var uploadUrl = {
url: {% for rental in object_list %} { "id": {{ rental.id }} } {% endfor %} // here is an error
};
console.log('url is', url);
$(function() {
app.showListingSpaceForm("listing");
});
</script>
代码可能解释了我想要实现的目标。如果还需要 models.py 进行更多审查,那么我将对其进行更新。
【问题讨论】:
-
我刚刚注意到您的 add.html 页面中有错误,应该是这样的:
url: {% for rental in object_list %} "id": {{ rental.id }} {% endfor %}
标签: javascript python ajax django reactjs