Reputation: 3289
I've researched this to death, but have not found exactly what I need to get the last part of my form completed.
I have a simple 2-field form in my footer for newsletter signup. I am utilizing an inclusion_tag
since I need to include the form on every page.
The form works; with a couple of hitches, for arguments sake, it works, I hit submit and the email is sent to me. The problem is that I am getting a 500(internal server error)
in console on the ajax url. I am assuming that its not really supposed to redirect to the url, but rather just process the form. Below is my code; I hope someone can easily point out my issues. Thanks.
Inclusion Tag
@register.inclusion_tag('includes/cta_form.html', takes_context=True)
def footer_newsletter_signup(context):
title = 'Newsletter Signup'
form = CTASignupForm()
context = {
'form': form,
'title': title,
}
return context
Ajax
$('#sendSignupForm').click(function (e) {
e.preventDefault();
var mForm = $('#signupForm').serialize();
console.log(mForm);
$.ajax({
type: 'POST',
url: '{% url 'pages:cta_signup' %}',
data: mForm,
success: function (data) {
$("input").val('')
},
error: function (data) {
$("input").addClass('error')
}
})
})
cta_form.html
<form action="{% url 'pages:cta_signup' %}" method="POST" id="signupForm">
{% csrf_token %}
{{ form.name }}
{{ form.email }}
<button class="btn btn-black no-margin-bottom btn-small" type="submit" id="sendSignupForm">Submit</button>
</form>
View
def cta_signup(request):
if request.method == "POST":
form = CTASignupForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
subject = 'This is a response from Soledad Footer Signup Form'
from_email = settings.DEFAULT_FROM_EMAIL
recipient_list = [from_email, '[email protected]']
ctx = {
'subject': subject,
'name': name,
'email': email
}
message = get_template('email_forms/cta_signup_email.html').render(Context(ctx))
msg = EmailMessage(subject, message, from_email=from_email, to=recipient_list)
msg.content_subtype = 'html'
msg.send()
messages.success(request, "Thank you, we received your message")
if form.errors:
json_data = json.dumps(form.errors)
return HttpResponseBadRequest(json_data, content_type='application/json')
else:
raise Http404
Screenshot of Console Error
Upvotes: 0
Views: 417
Reputation: 599450
A view must always return a response. You don't, if the form is valid; that's a server error.
Return HttpResponse()
at the end of the is_valid block.
Upvotes: 2