【发布时间】:2016-03-17 01:29:56
【问题描述】:
我有一个由 url /add 调用的模板,其中包含多个完全在 reactjs 上开发的注册页面。在由 url /add 调用的 add.html 页面中,也有一个图像上传表单(它也是使用 reactjs 开发的)并且有需要 url 发布的 ajax 代码,我需要不同的 url {% url 'uploadImage' pk %} 提供,以便我可以保存到其关联的实例。简而言之,表单在 add.html 中,表单需要 id 才能将数据保存到其关联的实例中。
这是我的代码
urls.py
url(r'^add/$', AddView.as_view(), name="add"), // presents add.html page which displays just multiple form
url(r'^upload/image/(?P<pk>\d+)/$', UploadImage.as_view(), name="uploadImage"), // used for uploading image that is on the add.html page
views.py
class AddView(TemplateView):
template_name = 'rentals/add.html'
class UploadImage(View):
model = Rental
template_name = 'rentals/add.html'
def get(self, request, *args, **kwargs):
return render(request, self.template_name)
def post(self,request,*args,**kwargs):
print(request)
if request.FILES:
rental = Rental.objects.get(pk=request.POST['rental'])
print ('rental is', rental)
for file in request.FILES.getlist('image'):
print('file',file)
image = Gallery.objects.create(image=file, rental=rental)
print('image',image)
return HttpResponseRedirect('/')
add.html
<div id="listing"> // this contains multiple form developed using reactjs code
</div>
{% include 'includes/script.html'%}
<script type="text/javascript">
var data = {
urltag: {% url 'uploadImage' %} // how can i pass url here if i pass with pk i get an error as this templated is called using /add but the form is also in this template which anyhow requires id
}
console.log('url is', data);
$(function() {
app.showListingSpaceForm("listing",data);
});
</script>
ajax 代码
$.ajax({
url:"/add/space/",
data:sendData,
type:'POST',
success: function(data, textStatus, xhr ) {
$.ajax({
url:"/upload/image/",
data:image,
contentType:false,
processData:false,
type:'POST',
mimeType: "multipart/form-data",
success: function(data) {
console.log('success');
}
});
window.location.href = "http://localhost:8000/";
}
});
【问题讨论】:
标签: python ajax django reactjs django-views