【发布时间】:2020-06-29 16:45:43
【问题描述】:
我正在使用 Ajax 将表单数据转换为 JSON 并将其发送到我的 Django 视图。成功处理后,我将返回一个模板响应,其中包含一些我无法在我的 HTML 中引用的上下文数据。我坚持让这个工作。任何帮助将非常感激。下面是我的 HTML 代码和我的 Django 视图。
查看:
class CustomerAttributeView(View):
"""
Saves the attribute details for a user.
Updates if already present
"""
page = 'customer_attributes.html'
def get(self, request):
return render(request, self.page)
def post(self, request):
try:
user = User.objects.get(id=request.session['user_id'])
data = json.loads(request.POST.get('data'))
attribute_ids_mapped_to_customer = CustomerAttributeMapping.objects.\
filter(consuming_app_id=user.consuming_app_id).values_list('id', flat=True)
#If no attributes mapped to the user then create and return
if not attribute_ids_mapped_to_customer:
insert_or_update_customer_attributes(user, data)
context_data = {
'success_msg': 'Attribute details saved successfully'
}
return TemplateResponse(request, self.page, context=context_data)
except Exception as e:
logging.error("Error: " + str(e))
context_data = {
'error_msg': 'Error in saving customer attributes',
'status_code': 400
}
return TemplateResponse(request, self.page, context=context_data)
AJAX:
$.ajax({
url : "customer_attribute/", // the endpoint
type : "POST", // http method
data : {data:JSON.stringify(attribute_data)}, // data sent with the post request
});
网址:
urlpatterns = [
url(r'^customer_attribute/',csrf_exempt(CustomerAttributeView.as_view())),
]
我试图引用从视图返回的上下文数据的 HTML 代码:
<span class="success-msg" id="success_msg">{% if success_msg %}{{ success_msg }}{% else %} {{""}} {% endif %}</span>
<span class="error" id="error_msg">{% if error_msg %}{{ error_msg }}{% else %} {{""}} {% endif %}</span>
我的 HTML 中既没有看到 success_msg 也没有看到 error_msg。我在这里做错了什么吗?
【问题讨论】:
-
模板由 Django 在发送到浏览器之前呈现。执行 javascript 后,您无法使用 django 模板执行任何操作。
标签: javascript python django ajax