article

Sunday, June 21, 2020

Django Simple Email Contact Form


Django Simple Email Contact Form

Create a simple contact form that sends email website.

Update urls.py


devproject/urls.py
 
#urls.py
from django.contrib import admin  
from myapp import views  
from django.conf.urls import url
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
]
Next create a new myapp/urls.py file in our app. myapp/urls.py
 
#urls.py
from django.contrib import admin
from django.urls import path

from myapp.views import contactView, successView

urlpatterns = [
    path('contact/', contactView, name='contact'),
    path('success/', successView, name='success'),
]
demoapp/forms.py
 
#forms.py
from django import forms

class ContactForm(forms.Form):
    from_email = forms.EmailField(required=True)
    subject = forms.CharField(required=True)
    message = forms.CharField(widget=forms.Textarea, required=True)
demoapp/views.py
 
#views.py
from django.shortcuts import render, redirect

from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from myapp.forms import ContactForm

def contactView(request):
    if request.method == 'GET':
        form = ContactForm()
    else:
        form = ContactForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            from_email = form.cleaned_data['from_email']
            message = form.cleaned_data['message']
            try:
                send_mail(subject, message, from_email, ['fidelbandoy622@gmail.com'])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('success')
    return render(request, "email.html", {'form': form})

def successView(request):
    return HttpResponse('Success! Thank you for your message.')

myapp/templates/email.html
//templates/email.html
{% extends 'base.html' %}

{% block title %}Contact Us{% endblock %}
{% load crispy_forms_tags %}

{% block content %}
<h3>Contact Us</h3>
<form method="post">
    {% csrf_token %}
    {{ form|crispy }}
    <div class="form-actions">
      <button type="submit" class="btn btn-success">Send</button>
    </div>
</form>
{% endblock %}
myapp/templates/base.html
//templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
 <title>{% block title %}Django Email Contact Form {% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Cairocoders</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
    <div class="navbar-nav">
   <a class="nav-item nav-link active" href="">Home</a>
    </div>
  </div>
</nav>
 <div class="container" style="padding:20px;">
    <div class="col-md-12 well">
        <h3 class="text-primary">Django Simple Email Contact Form</h3>
        <hr style="border-top:1px dotted #ccc;"/>
  {% block content %} {% endblock %}
    </div>
    </div> 
</body>
</html>
add 'crispy_forms', #pip install django-crispy-forms to settings.py INSTALLED_APPS

Related Post