Skip to content

Instantly share code, notes, and snippets.

@ErickMwazonga
Last active August 30, 2023 13:14
Show Gist options
  • Save ErickMwazonga/be9385f617e4978ed82bd60c77c36c53 to your computer and use it in GitHub Desktop.
Save ErickMwazonga/be9385f617e4978ed82bd60c77c36c53 to your computer and use it in GitHub Desktop.
FormView
def post(form):
form = FeedbackForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
subject = "A New Feedback"
ctx = {
'name': name,
'email': email,
'message': message
}
message = render_to_string('ecoke/includes/_email_feedback.html', ctx)
mail_admins(subject, message, fail_silently=True, html_message=None)
form.save()
messages.add_message(request, messages.SUCCESS, 'Thank you for your Feedback.')
return redirect(reverse('ecoke:index'))
def get(request):
if !request.user.is_authenticated():
return FeedbackForm()
user = get_object_or_404(User, username=username)
form = FeedbackForm(instance=user, initial={
'name': user.profile.get_screen_name,
'email': user.email,
})
return form
def feedback(request, username=None):
if request.method == 'POST':
post(form)
else:
form = get(request)
return render(request, 'ecoke/feedback.html', { 'form': form })
class FeedbackFormView(FormView):
form_class = FeedbackForm
template_name = 'ecoke/feedback.html'
def get_initial(self):
if self.request.user.is_authenticated():
return {
'name': self.request.user.profile.get_screen_name,
'email': self.request.user.email,
}
def form_valid(self, form):
success_message = 'Thank you for your Feedback.'
messages.add_message(self.request, messages.SUCCESS, success_message)
return super(FeedbackFormView, self).form_valid(form)
def form_invalid(self, form):
failure_message = 'Email not sent. Please try again.'
messages.add_message(self.request, messages.WARNING, failure_message)
return super(FeedbackFormView, self).form_invalid(form)
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
if !form.is_valid():
return self.form_invalid(form)
self.send_email(request, form)
return self.form_valid(form)
def send_email(self, request, form):
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
details = {
'name': name,
'email': email,
'message': message
}
subject = "[e-Coke] A New Feedback"
support_email = settings.CONTACTS['support_email']
txt_message = render_to_string('ecoke/includes/_email_feedback.html', details)
mail = EmailMultiAlternatives(subject, txt_message, email, [support_email])
mail.attach_alternative(txt_message, "text/html")
try:
mail.send()
except:
messages.add_message(request, messages.WARNING, 'Unable to send email verification. Please try again')
def get_success_url(self):
return reverse('ecoke:index')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment