0

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>
6
  • 1
    Hello @C-Bizz you should provide error in question Commented May 31, 2021 at 15:49
  • 1
    You can't pass template in JsonResponse if you want to pass some code of HTML you can do something like this mytags = <h1>Hello</h1> and than you have to pass it like this in your JsonResponse return JsonResponse({'mymessage':mytags}) Commented May 31, 2021 at 15:59
  • Thanks @Ankit Tiwari for the explanation. In this case, the form to fill so as to send the email is in the template. How do I work arround this? Am I supposed to to copy the code for the form in the template and paste it in views.py in 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. Commented May 31, 2021 at 16:15
  • 1
    you want to send email to user after form submission? Commented May 31, 2021 at 16:17
  • 1
    you can do something like this in your view def send_mail(request): get_all_data_from_frontend and than send email to user after email is send to user you have to return success message as JsonResponse Commented May 31, 2021 at 16:19

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank so much @ Ankit Tiwari. When I test the code on Postman using post request I get an error: current_site = get_current_site(request) NameError: name 'get_current_site' is not defined
Hello @C-Bizz you don't need to add your current site in email the code i provided you it was used in my activate account logic i passes my current domain with token and user id but in your case you don;t need this so you can remove it
if you still want to use it for any purpose you can import it from django.contrib.sites.shortcuts import get_current_site than it will work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.