[Fixed]-Missing Variable Error in Django Form After Form Submission

1👍

Answering this

Ok, so here is where I am confused. I have a dozen views and this form is a Call-to-Action form that sits at the top of the footer. How do I bind this form to every view without repeating the code everywhere? Thank you for your help.

You need to create separate view to handle this form and provide action param in form tag pointing to this view.

Here is general idea, code my not work

#template
<form action='{% url "send-mail" %}' method='POST' role='form' class="form-inline">
  ...
#views
def send_mail(request):
    form = MailingListForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            mailing_list_full_name = form.cleaned_data.get('mailing_list_full_name')
            mailing_list_phone = form.cleaned_data.get('mailing_list_phone')
            mailing_list_email = form.cleaned_data.get('mailing_list_email')
            mailing_list_subject = 'Submission from Newsletter Signup'
            mailing_list_message = 'Yes, please add me to marketing emails.'
            from_email = settings.DEFAULT_FROM_EMAIL
            recipient_list = [from_email, 'charles@studiorooster.com']
            ctx = {
                'mailing_list_subject': mailing_list_subject,
                'mailing_list_full_name': mailing_list_full_name,
                'mailing_list_email': mailing_list_email,
                'mailing_list_phone': mailing_list_phone,
                'mailing_list_message': mailing_list_message
            }

            message = get_template('pages/newsletter_signup_email.html').render(Context(ctx))
            msg = EmailMessage(mailing_list_subject, message, to=recipient_list, from_email=from_email)
            msg.content_subtype = 'html'
            msg.send()

            messages.success(request, "Thank you, you've been added to our list.")
            return HttpResponse('/')

#tags
@register.inclusion_tag('pages/tags/footer_newsletter_signup.html', takes_context=True)
def footer_newsletter_signup(context):
    title = 'Newsletter Signup'
    form = MailingListForm()
    context = {
        'form': form,
        'title': title,
    }
    return context

#url
url('r^send-mail/$', send_mail, name='send-email')

Leave a comment