1👍
✅
Class-based views (and some neat Django shortcuts) to the rescue:
from django.core.mail import send_mail
from django.views import generic
from django.template import render_to_string
class ContactFormView(generic.FormView):
form_class = ContactForm
template_name = 'listing/listing_list.html'
success_url = 'listings'
location_type = None
def get_context_data(self, **kwargs):
context = super(ContactFormView, self).get_context_data(**kwargs)
context['listings'] = (Listing.objects
.filter(location_type=self.location_type)
.order_by('listing_order'))
return context
def form_valid(self, form):
message = render_to_string('contact_template.txt', form.cleaned_data)
send_mail('Form Submission from Listings Page', message,
form.cleaned_data['contact_email'])
return super(ContactFormView, self).form_valid(form)
class FullService(ContactFormView):
location_type='FULL_SERVICE'
class QuickServe(ContactFormView):
location_type='QUICK_SERVE'
Source:stackexchange.com