I am building a modelform for a booking request form
I would like the form to be submitted and on a successful form submission an email needs to be sent
to the customer and/or a user within the company.
I’m trying to understand where is the optimal/best place/best practice place for the message to be sent?
Option 1 - Override the save() in the modelform
class BookingRequestForm(forms.ModelForm): class Meta: model = BookingRequest fields = [ "title", "first_name", "last_name", "email", "phone", "date_of_birth", "address", "referrer", "returning", "reason", ] def save(self): instance = super(BookingRequestForm, self).save() send_mail( "Subject here", "Here is the message.", "firstname.lastname@example.org", ["email@example.com"], fail_silently=False, ) return instance
Option 2 - override form_valid in the view and send email before model is saved.
class BookingRequestView(CreateView): form_class = BookingRequestForm template_name = "booking/booking_request.html" success_url = reverse_lazy("booking-thanks") def form_valid(self, form): """If the form is valid, send an email and then save the form.""" send_mail( "Subject here", "Here is the message.", "firstname.lastname@example.org", ["email@example.com"], fail_silently=False, ) return super(BookingRequestView, self).form_valid(form)
Option 3 - Both are wrong and I should be using signals?
Option 4 - The whole approach is wrong and I should be doing it another way ??
Both option 1 and 2 work but I was just wondering about best practice? I think the Django docs could use some clarity in this area which I will gladly provide one I get my head around this
My gut says option 1 is the best as we are only sending after the object has been persisted whereas in option 2 and email may get sent but something goes wrong and the object does not get saved.
Or maybe I’m just overthinking this and it doesn’t matter!?
Thanks for your help in advance