Instead of rendering the html page, I want to return Json data from the following blocks of code but I don't know how to implement it. I don't want to use the rest_framework. When I use render the page renders but when I use JsonResponseit throws back an error.
views.py
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.core.mail import send_mail
def contact_us(request):
if request.method == "POST":
name = request.POST.get("name")
email = request.POST.get("email")
title = request.POST.get("title")
message = request.POST.get("message")
data = {
"name": name,
"email": email,
"title": title,
"message": message
}
message = '''
New message: {}
From: {}
'''.format(data["message"], data['email'])
send_mail(data["title"], message, '', ['[email protected]'])
return JsonResponse(request, 'contact_us/contact_us.html', safe=False)
contact.html
<form action="" method="POST" class="contact_us">
{% csrf_token %}
<div>
<div>Name</div>
<input type="text" name="name">
</div>
<div>
<div>Email</div>
<input type="text" name="email">
</div>
<div>
<div>Title</div>
<input type="text" name="title">
</div>
<div>
<div>Message</div>
<textarea name="message" cols="30" rows='10'></textarea>
</div>
<div>
<input type="submit", value="submit">
</div>
</form>
JsonResponseif you want to pass some code ofHTMLyou can do something like thismytags = <h1>Hello</h1>and than you have to pass it like this in yourJsonResponsereturn JsonResponse({'mymessage':mytags})views.pyin order for JsonResponse to work? If yes, is it a good practice? Sorry for asking many questions, I want to know how to work arround situations like this without using rest framework. I want to use a react application to fetch the Json data that will be returned.def send_mail(request):get_all_data_from_frontendand than send email to user after email is send to user you have to return success message asJsonResponse