I am using Ajax to convert my form data to JSON and sending it to my Django view. After successful processing I am returning a template response with some context data which I am not able to refer back in my HTML. I am stuck getting this to work. Any help would be really appreciated. Below is my HTML code and my Django view.
View:
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
});
URLs:
urlpatterns = [
url(r'^customer_attribute/',csrf_exempt(CustomerAttributeView.as_view())),
]
My HTML code where I am trying to refer the context data I am returning from the view:
<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>
I don't see either the success_msg
nor the error_msg
in my HTML. Is there anything I am doing wrong here?