python - How to send two variables with html as a JSON in Django? -
i want render 2 different html samples , send response ajax request.
i have in view:
def getclasses(request): user = request.user aircomcode = request.post.get('aircompany_choice', false) working_row = pr_aircompany.objects.get(user=user, aircomcode=aircomcode) economy_classes = working_row.economy_class business_classes = working_row.business_class economy = render_to_response('dbmanager/classes.html', {"classes": economy_classes}, content_type="text/html") business = render_to_response('dbmanager/classes.html', {"classes": business_classes}, content_type="text/html") return jsonresponse({"economy": economy, "business": business})
with error:
django.http.response.httpresponse object @ 0x7f501dc56588 not json serializable"
how can task?
in js when response insert received html corespoding blocks. this:
$.ajax({ # ajax-sending user's data user's classes url: url, type: 'post', data: {"aircompany_choice": aircompany_choice}, # send selected aircompanies retrieving classes required headers: {"x-csrftoken":csrftoken}, # prevent csrf attack }).done (result) -> add_booking_classes.find(".economy-classes").children(":nth-child(2)").html(result["economy"]) add_booking_classes.find(".business-classes").children(":nth-child(2)").html(result["business"])
try django's render_to_string
:
economy = render_to_string('dbmanager/classes.html', {"classes": economy_classes}) business = render_to_string('dbmanager/classes.html', {"classes": business_classes})
render_to_string()
loads template, renders , returns resulting string. can send these resulting strings json.
your final code becomes:
from django.template.loader import render_to_string def getclasses(request): user = request.user aircomcode = request.post.get('aircompany_choice', false) working_row = pr_aircompany.objects.get(user=user, aircomcode=aircomcode) economy_classes = working_row.economy_class business_classes = working_row.business_class economy = render_to_string('dbmanager/classes.html', {"classes": economy_classes}) business = render_to_string('dbmanager/classes.html', {"classes": business_classes}) return jsonresponse({"economy": economy, "business": business})
Comments
Post a Comment