Django · Lesson 13 of 15
Sessions, Messages and Email
Store data per visitor, flash messages and send mail.
- Advanced
- 14 min read
- 3 objectives
Before this lessonLesson 12: DRF Auth, Permissions and Pagination
What you will learn
- Use the session
- Flash a message
- Send an email
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 4 hours
Create a free account to keep your progress on every device.
The session stores small bits of data per visitor. The messages framework is a flash queue on top of it. Email is how you leave the request/response cycle.
Sessions
def add_to_cart(request, sku):
cart = request.session.setdefault("cart", [])
cart.append(sku)
request.session.modified = True # required when you mutate a list in place
return redirect("cart")Do not store large objects or secrets in the session. The signed-cookie backend puts the whole payload on the client.
Messages
from django.contrib import messages
messages.success(request, "Post published.")
messages.error(request, "Could not save."){% for message in messages %}
<p class="{{ message.tags }}">{{ message }}</p>
{% endfor %}Sending email
from django.core.mail import send_mail
send_mail(
subject="Welcome",
message="Thanks for signing up.",
from_email="noreply@example.com",
recipient_list=[user.email],
fail_silently=False,
)In development, EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" prints mail to the terminal. In production use SMTP or an API (Anymail).
