Forms, Gmail - Kitasio/MyWebDev GitHub Wiki

Creating a form

In your app create a file forms.py

from django import forms

class ContactUs(forms.Form):
    name = forms.CharField(label='name', max_length=100)
    email = forms.EmailField(label='email' ,max_length=100)

In views.py add a form function

from .forms import ContactUs

def get_form(request):
    if request.method == 'POST':
        form = ContactUs(request.POST)

        if form.is_valid():
            # What happens if form is valid
    else:
        form = ContactUs()

    return render(request, 'index.html', {'form': form})

Don't forget to add the view to urlpatterns in your app

urlpatterns = [
    path('', views.get_form, name='get_form'),
    path('', views.index, name='index'),
]

In the HTML file use forms like this:

<form method="POST">
    {% csrf_token %}
    {{ form }}
    <button type="submit" value="Submit" class="btn">Send</button>
</form>

For more functionality and to work it out with bootstrap - you can use crispy forms

Send with Gmail

Go to settings.py and add this at the bottom

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'your_password'
EMAIL_PORT = 587

Now you can send email from the form, go to views.py, import send_mail and add this to the code

from django.core.mail import send_mail

def get_form(request):
    if request.method == 'POST':
        form = ContactUs(request.POST)

        if form.is_valid():
######################################################################
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            send_mail('New Request From: '+name, email, '[email protected]', ['[email protected]'], fail_silently=False)
######################################################################
    else:
        form = ContactUs()

    return render(request, 'index.html', {'form': form})

In your Gmail account you should not have two steps authentication AND allow less secure apps

⚠️ **GitHub.com Fallback** ⚠️