Speed up development with full-stack environments for every branch.

Learn More

Making a Contact Form in Django [Python]

1273 Runs 4309 Views 1544 Copies
Saved

Saved

bhawani0915 49

bhawani0915
published 3 years ago

from django.core.mail import send_mail
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render

def contact(request):
    errors = []
    if request.method == 'POST':
        if not request.POST.get('subject', ''):
            errors.append('Enter a subject.')
        if not request.POST.get('message', ''):
            errors.append('Enter a message.')
        if request.POST.get('email') and '@' not in request.POST['email']:
            errors.append('Enter a valid e-mail address.')
        if not errors:
          try:
            send_mail(
                request.POST['subject'],
                request.POST['message'],
                request.POST.get('email', '[email protected]'),
                ['[email protected]'],
            )
            return HttpResponse('Thank you, form has been submitted successfully')
          except Exception, err: 
            return HttpResponse(str(err))
    return render(request, 'contact_form.html',
        {'errors': errors})
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).