我的网址标记一直出错。语法是正确的,我尝试了不同的解决方案,在SO上问但没有运气。
my urls.py
urlpatterns = [
url(r'^$', LandingView.as_view(), name="landing_page"),
url(r'^add/$', AddView.as_view(), name="add"),
url(r'^rent/(?P<slug>\w+)/$', rent_detail, name="rent_detail"),
url(r'^add/space/$', AddSpaceView.as_view(), name="addSpace"),
url(r'^lang/$', Language.as_view(), name="lang"),
url(r'^upload/image/(?P<pk>\d+)/$', ImageUpload, name="ImageUpload"),
url(r'^filter/space/$', FilterSpace.as_view(), name="filterSpace"),
url(r'^api/', include(v1_api.urls)),
]
views.py
def ImageUpload(self, request, *args, **kwargs):
try:
rental = Rental.objects.get(pk = kwargs.get('pk'))
except Rental.DoesNotExist:
error_dict = {'message': 'Rental spae not found'}
return self.render(request,'rentals/add.html',error_dict)
for file in request.FILES.getlist('image'):
image = GalleryImage.objects.create(image=file,rental=rental)
response_dict = {
'message': 'File Uploaded Successfully'
}
context = {
'rental':rental
}
return self.render(request,'rentals/add.html',context)
class AddView(TemplateView):
template_name = 'rentals/add.html'
add.html
<div id="listing">
</div>
<script type="text/javascript">
// want to passs url for uploading image in ajax url parameter
var data = {
urltag: "{% url 'ImageUpload' rental.id %}"
}
console.log('url is', data);
$(function() {
app.showListingSpaceForm("listing",data);
});
</script>
用于上传图片的ajax
$.ajax({
url:"/upload/image/", // upload form is in add.html which is developed using frontend library reactjs and i need to pass id here so that the image will be saved to its associated rent.
data:image,
contentType:false,
processData:false,
type:'POST',
mimeType: "multipart/form-data",
success: function(data) {
console.log('success');
}
});
}
更新:Ajax代码,我希望在网址中使用ID将图片上传到相关的租金
答案 0 :(得分:3)
当你转到/add/
时,Django会运行AddView
,因为你有一个网址模式。
url(r'^add/$', AddView.as_view(), name="add"),
该视图将呈现rentals/add.html
,因为您有:
class AddView(TemplateView):
template_name = 'rentals/add.html'
渲染模板会失败,因为您在网址标记中使用了rental
,但您尚未在任何地方定义租借。
{% url 'ImageUpload' rental.id %}
除非您的AddView
可以在模板上下文中设置rental
,否则使用这样的网址标记将无效。
答案 1 :(得分:2)
您需要明确传递kwarg参数,因为您在urls.py中定义了它:
var data = {
urltag: "{% url 'ImageUpload' pk=rental.id %}"
}