33๐
โ
A simple example could be:
urls.py
from django.conf.urls import patterns, url
from yourapp import views
urlpatterns = patterns(
'',
url(r'^email/$',
views.email,
name='email'
),
url(r'^thanks/$',
views.thanks,
name='thanks'
),
)
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)
views.py
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from yourapp.forms import ContactForm
def email(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, ['admin@example.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('thanks')
return render(request, "yourapp/email.html", {'form': form})
def thanks(request):
return HttpResponse('Thank you for your message.')
email.html
<form method="post">
{% csrf_token %}
{{ form }}
<div class="form-actions">
<button type="submit">Send</button>
</div>
</form>
๐คiago1460
0๐
If simplicity is important, Formspree might be an alternative. They make it super easy.
You just need to insert something like this in your code:
<form action="https://formspree.io/your@email.com"
method="POST">
<input type="text" name="name">
<input type="email" name="_replyto">
<textarea name="message"></textarea>
<input type="submit" value="Send">
</form>
Then you validate the e-mail, and you are ready to go.
For further information, this video explains how to do it.
๐คJ0ANMM
- Django: Is it possible to create a model without an app?
- Django โ http code 304, how to workaround in the testserver?
- How do I check if a given datetime object is "between" two datetimes?
0๐
- From django.conf.urls import patterns, url
- From yourapp import views
Example
urlpatterns = patterns(
'',
url(r'^email/$',
views.email,
name='email'
),
url(r'^thanks/$',
views.thanks,
name='thanks'
),
)
๐คAvinash Kumar
- How to properly runserver on different settings for Django?
- How to limit queryset/the records to view in Django admin site?
- How to obtain a plain text Django error page
- Django: model has two ManyToMany relations through intermediate model
- How to Model a Foreign Key in a Reusable Django App?
Source:stackexchange.com