Django Ajax成功发送新URL上下文
我有一个带有启动按钮的第一页,该过程已完成,它们全部重定向到结果页面,在那里我可以下载不同的结果。没有Ajax并具有“常规” Django,该过程正在起作用。但是,由于第一页中的其他功能,我必须与Ajax合作。而且,如果我不重新定义Ajax的成功部分,则什么都不会发生。.
我具有第一页的函数视图:
def launchCtd(request):
"""
This Function is activate when user click on the launch button of the convertToDose page.
It receive the request, create the JSON file and launch the ConvertToDose Analysis. Then it redirect to the Result page
"""
if request.method == 'POST':
#DO stuff
context = {
'filename': img_out_path,
'protocol_file': json_pactrlRectth,
}
#return render(request, 'result.html', context)
return JsonResponse(context, safe=False)# I trie to pass the url but it was not a success...
else:
#Ini Forms
context = {
#Send Forms
}
return render(request, 'template.html', context)
第一页的模板(仅AJAX Part)
$.ajax({
url: "",
type: "POST",
data: formData,
processData: false,
contentType: false,
beforeSend: function (xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", $('input[name="csrfmiddlewaretoken"]').val());
},
success: function(data){
//print okay with JSONResponse in view
console.log(data.protocol_file)
//First try to send data in new url => undefined element, after = I tried with data and with template data in the 1st page
//protocol_file = $("input[name='json_path']")
//filename = $("input[name='img_path']")
//Second try to send data in new url => undefined
$('#protocol_file').html(data.protocol_file);
$('#filename').html(data.filename);
//Third try => GetElementById is undefined error
//document.GetElementById("protocol_file").innerHTML = $("input[name='json_path']")
//document.GetElementById("filename").innerHTML = $("input[name='img_path']")
//Fourth try => synthaxe error, I also tried with a + like in some forum but it consider like a str and concat all...
window.location.href="/filmchromique/result/" {data:data}
#this one is working but with no data sended ....
//window.location.href="/filmchromique/result/"
},
error: function (data, textStatus, jqXHR) {
console.log(data)
}
});
结果页面的视图:
class displayResultPage(TemplateView):
template_name = 'result.html'
def post(self, request, *args, **kwargs):
self.object = self.get_object()
context = self.get_context_data(object=self.object)
return self.render_to_response(context)
def get_context_data(self, **kwargs):
kwargs = super(displayResultPage, self).get_context_data(**kwargs)
return kwargs
def post(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
bar = self.request.POST.get('foo', None)
if bar: self.template_name = 'result.html'
return self.render_to_response(context)
在我的模板结果中,我没有什么具体的,只有这些部分可能很有趣:
<div style="padding-bottom: 30%" class="row gx-5 justify-content-center">
{% if protocol_file is not null %}
<p id="protocol_file">Your file is here : {{ filename }}</p>
{% else %}
<h1 style="color: indianred">You must launch an analysis before accessing an image on this page</h1>
{% endif %}
{% if protocol_file is not null %}
<div class="row gx-5 justify-content-center">
<div class="col-lg-4 col-xl-6">
<a class="btn btn-primary btn-md" href="{% url 'json:downloadFile' protocol_file %}">Save protocol to local</a>
</div>
<br>
<div class="col-lg-4 col-xl-6">
<a class="btn btn-primary btn-md" href="{% url 'json:downloadFile' filename %}">Save image to local</a>
</div>
<br>
</div>
我找不到发送上下文的方法。如果您知道我该怎么做,请
度过美好的一天
,编辑
问题似乎不是在Ajax方面,而是在结果视图中,这里命名为DisplayResultpage。我使用了调试器,在第二个文章DEF中,数据在请求中(帖子)。因此,我想到在当前上下文中添加它们:
def post(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
context["filename"] = self.request.POST.get("img_path")
context["protocol_file"] = self.request.POST.get("json_path")...
但是数据未显示在模板中。
当我使用DebBugger时,遵循工作流程:
邮政函数称为 - &gt; self.get_context_data在 邮政功能 - &gt;返回post功能的self.render_to_response - &gt;在类TemplateView中完成的工作 - &gt;返回DisplayResultPage的get_context_data-&gt;课堂上的某件事 TemplatView-&GT;显示的页面
在“返回displayResultpage的get_context_data”步骤中,我找不到“邮政函数称为”步骤中上下文的数据。
如果您知道为什么,我认为这是这里的解决方案:)如果找到一种方法,我将发布它。
谢谢
I have a first page with a Launch button, the process is done and them all is redirect to a result page where I can download the different results. Without Ajax and with "regular" Django, the process is working. However, because of other functionalities in the first page, I have to work with Ajax. And if I do not redefined the success part of Ajax, nothing is happening..
I have a function view for the first page :
def launchCtd(request):
"""
This Function is activate when user click on the launch button of the convertToDose page.
It receive the request, create the JSON file and launch the ConvertToDose Analysis. Then it redirect to the Result page
"""
if request.method == 'POST':
#DO stuff
context = {
'filename': img_out_path,
'protocol_file': json_pactrlRectth,
}
#return render(request, 'result.html', context)
return JsonResponse(context, safe=False)# I trie to pass the url but it was not a success...
else:
#Ini Forms
context = {
#Send Forms
}
return render(request, 'template.html', context)
the template of the first page (only ajax part)
$.ajax({
url: "",
type: "POST",
data: formData,
processData: false,
contentType: false,
beforeSend: function (xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", $('input[name="csrfmiddlewaretoken"]').val());
},
success: function(data){
//print okay with JSONResponse in view
console.log(data.protocol_file)
//First try to send data in new url => undefined element, after = I tried with data and with template data in the 1st page
//protocol_file = $("input[name='json_path']")
//filename = $("input[name='img_path']")
//Second try to send data in new url => undefined
$('#protocol_file').html(data.protocol_file);
$('#filename').html(data.filename);
//Third try => GetElementById is undefined error
//document.GetElementById("protocol_file").innerHTML = $("input[name='json_path']")
//document.GetElementById("filename").innerHTML = $("input[name='img_path']")
//Fourth try => synthaxe error, I also tried with a + like in some forum but it consider like a str and concat all...
window.location.href="/filmchromique/result/" {data:data}
#this one is working but with no data sended ....
//window.location.href="/filmchromique/result/"
},
error: function (data, textStatus, jqXHR) {
console.log(data)
}
});
The view of the result page :
class displayResultPage(TemplateView):
template_name = 'result.html'
def post(self, request, *args, **kwargs):
self.object = self.get_object()
context = self.get_context_data(object=self.object)
return self.render_to_response(context)
def get_context_data(self, **kwargs):
kwargs = super(displayResultPage, self).get_context_data(**kwargs)
return kwargs
def post(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
bar = self.request.POST.get('foo', None)
if bar: self.template_name = 'result.html'
return self.render_to_response(context)
In my template result, I have nothing particular, only maybe these part could be interesting :
<div style="padding-bottom: 30%" class="row gx-5 justify-content-center">
{% if protocol_file is not null %}
<p id="protocol_file">Your file is here : {{ filename }}</p>
{% else %}
<h1 style="color: indianred">You must launch an analysis before accessing an image on this page</h1>
{% endif %}
{% if protocol_file is not null %}
<div class="row gx-5 justify-content-center">
<div class="col-lg-4 col-xl-6">
<a class="btn btn-primary btn-md" href="{% url 'json:downloadFile' protocol_file %}">Save protocol to local</a>
</div>
<br>
<div class="col-lg-4 col-xl-6">
<a class="btn btn-primary btn-md" href="{% url 'json:downloadFile' filename %}">Save image to local</a>
</div>
<br>
</div>
I do not find a way to send the context. If you have any idea how I can do it please
Have a good day
EDIT
The problem seems not to be in the Ajax side but in the result view, here named displayResultPage. I used the debugger, and in the second post def, data are in the request (POST). So I had the idea to add them in the current context :
def post(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
context["filename"] = self.request.POST.get("img_path")
context["protocol_file"] = self.request.POST.get("json_path")...
But the data are not displayed in the template.
When I use the debbugger, following the workflow :
the post function is called -> self.get_context_data called in the
post function -> return self.render_to_response of the post function
-> something done in class TemplateView -> come back in the get_context_data of displayResultPage -> something done in class
TemplatView -> page displayed
in the "come back in the get_context_data of displayResultPage" step, I do not find my data given to the context in the "the post function is called" step.
If you have any idea why, I think it is the solution here :) If I find a way I will post it.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论