To complete this recipe, execute the following steps:
- Add a new forms.py file with the message form containing two fields: the recipient selection and message text. Also, this form will have an initialization method, which will accept the request object, and then modify QuerySet for the recipient's selection field:
# email_messages/forms.py from django import forms from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _
class MessageForm(forms.Form): recipient = forms.ModelChoiceField( label=_("Recipient"), queryset=User.objects.all(), required=True) message = forms.CharField( label=_("Message"), widget=forms.Textarea, required=True) def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.request = request self.fields["recipient"].queryset = (
self.fields["recipient"].queryset.exclude(
pk=request.user.pk))
- Create views.py with the message_to_user() and message_sent() view functions in order to handle the form. As you can see, the request object is passed as the first parameter to the form, as follows:
# email_messages/views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from .forms import MessageForm
@login_required
def message_to_user(request):
if request.method == "POST":
form = MessageForm(request, data=request.POST)
if form.is_valid():
# do something with the form
return redirect("message_sent")
else:
form = MessageForm(request)
return render(request,
"email_messages/message_to_user.html",
{"form": form})
@login_required
def message_sent(request):
return render(request,
"email_messages/message_sent.html")
- Add a very basic template for the message form under templates/email_messages/message_to_user.html, as in the following:
{# email_messages/message_to_user.html #}
<form action="">
{{ form.as_p }}
</form>
- We need the template for when the message has been sent. Again, we define it here at templates/email_messages/message_sent.html with minimal content for demonstration:
{# email_messages/message_sent.html #}
<p>Thanks for sending your note!</p>
- Additionally, we need to wire up the URLs so that Django will know how to route the requests properly. First, we will create email_messages/urls.py, as follows:
# email_messages/urls.py
from django.urls import path
from .views import message_to_user, message_sent
urlpatterns = [
path('/', message_to_user, 'message_to_user'),
path('sent/', message_sent, 'message_sent'),
]
- We need to include these patterns in our urls.py project:
# project/urls.py
from django.urls import include, path
urlpatterns = [
# ...
path('email/', include('email_messages.urls')),
]