gpt4 book ai didi

javascript - 尝试将 id 从 django 模板传递给 reactjs 时出现错误或空值

转载 作者:行者123 更新时间:2023-11-30 16:13:02 25 4
gpt4 key购买 nike

在尝试将 id 从 django 模板传递到 reatjs 以将多个图像上传到其关联的外键对象时,我收到一条错误消息,指出意外 token 。错误显示为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');
}
});
}

添加.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 进行更多审查,那么我将更新它。

最佳答案

您缺少一个基础部分:TemplateView 没有object_list 的概念,您必须自己填充它。如果您的 View 足够简单,请使用 ListView 并设置您的模型属性。如果没有,您必须手动填充对象列表,如下所示:

def get_context_data(self, **kwargs):
context['object_list'] = MyModel.objects.all()

这只是一个让您走上正确道路的例子。

关于javascript - 尝试将 id 从 django 模板传递给 reactjs 时出现错误或空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35940690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com