我在尝试将id从django模板传递到reatjs以将多个图像上传到其关联的外键对象时收到错误消息。该错误显示为意外令牌} 。深度显示为
在控制台中
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进行更详细的审查,那么我将更新它。
答案 0 :(得分:2)
你错过了一个基本的部分:TemplateView没有object_list
的概念,你必须自己填充它。如果您的视图足够简单,请使用ListView
并设置您的模型属性。如果没有,您必须手动填充对象列表,如下所示:
def get_context_data(self, **kwargs):
context['object_list'] = MyModel.objects.all()
这只是让你走上正确道路的一个例子。