I'm trying to make a Django contact form with Bootstrap styles, but it's not working. I tried in the views with send_mail
instead of EmailMessage
, but it still does not work. When I click on the "Send" button, the page just reloads and nothing more happens, I don't get any email.
Note that I have changed the email address and password for security purposes, but it is a Gmail account.
Here are my files:
home.html
<footer class="bg-dark text-white pt-3" id="contact">
<div class="row text-center col-lg-12">
<div>
<h3>Contact</h3>
<img src="{% static 'home_app/img/contact.png' %}" class="img-fluid">
</div>
</div>
<div class="col-lg-12 mx-auto">
<form method="post">
{% csrf_token %}
<div class="row">
<div class="col-lg-6 col-sm-3" >
<input type="text" class="form-control" name="name" placeholder="Name and last name" required>
</div>
<div class="col-lg-6 col-sm-3">
<input type="tel" class="form-control" name="subject" placeholder="Subject" required>
</div>
<div class="col-lg-12 col-sm-6">
<input type="text" class="form-control" name="email" placeholder="email@example.com" required>
</div>
<div class="col-lg-12 col-sm-6">
<textarea class="form-control" name="text" placeholder="Write your message" rows="5"></textarea>
</div>
<div class="col-lg-12">
<button type="Submit" class="btn btn-primary w-100 fs-5">Send</button>
</div>
</div>
</form>
</div>
</footer>
views.py
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.core.mail import EmailMessage
def contact(request):
if request.method == "POST":
name = request.POST.get('name')
subject = request.POST.get('subject')
email = request.POST.get('email')
message = request.POST.get('text')
return redirect('contact')
email=EmailMessage("Message from Django",
"User: {} Subject: {} Address: {} Message:\n\n {}".format(name,subject,email,message),
"",["email@example.com"],reply_to=[email])
try:
email.send()
return redirect("/?valid")
except:
return redirect("/?notvalid")
return render(request,'home_app/home.html',{})
setting.py
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
EMAIL_PORT = 587
EMAIL_HOST_USER = "email@example.com"
EMAIL_HOST_PASSWORD = "password123"
If anyone can help me I will be so grateful
I solved the problem. the home.html has it's own view called home, and the contact section is in this html, so for any reason the contact view could not respond while the contact html section were in the home view. The solution was creating an html for the contact section, just with that the contact view could respond