Search code examples
pythondjangoemailframeworks

How to return Json data in django


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>

Solution

  • If you are using React than you have to get data from frontend you don't need to send a template you have to create a contact page in React which contain your contact form

    than you have to access all data in your view

    def send_mail(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
                }
               current_site = get_current_site(request)
               mail_subject = 'My Subject.'
               message = get_template('contact_us/contact_us.html').render(data)
               to_email = request.POST.get('email')
               email = EmailMessage(
                mail_subject, message, to=[to_email]
                )
               email.content_subtype = "html"
               email.send()
         return JsonResponse({"Success":'Check your email.'})
    

    you have to import this two things from django.template.loader import get_template from django.core.mail import EmailMessage

    **NOTE : ** use try: except: if you want except the exceptions and use email.send(fail_silently=False) to avoid email error such as failed to send mail etc.

    check official doc. for more information https://docs.djangoproject.com/en/3.2/topics/email/#emailmessage-objects