将带有id的网址传递给另一个网址

时间:2016-03-17 01:29:56

标签: python ajax django reactjs django-views

我有一个由url / add调用的模板,其中包含完全在reactjs上开发的多个注册页面。在url / add调用的add.html页面中也有一个图像上传表单(它也是使用reactjs开发的)并且有一个jax代码,需要url才能发布,我需要不同的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/";
     }
 });

2 个答案:

答案 0 :(得分:0)

在视图中的响应标题中返回“pk-user”

.bl1-title h2 {
     display: blocck; /* @BUGFIX was inline and Fx displayed it with an overflow of text */
}

现在您可以使用返回的用户ID

response['pk-user'] = rental.pk
return response

答案 1 :(得分:-1)

应该只是

{% url 'uploadImage' 'pk_id' %}

或者如果您有一个名为image的对象

{% url 'uploadImage' image.pk %}