Hello,
I have a simple “newsletter” signup form. It is defined as below:
The model is created like this:
class Subscriber(models.Model):
email = models.EmailField(max_length=254)
def __str__(self):
return self.email
This is the form to subscribe:
<form action="" id="newsletterForm" method="post" role="form">
{% csrf_token %}
<input type="email" name="email" required><input type="submit" value="Subscribe">
</form>
This is the AJAX code to submit the data:
<script>
$('#newsletterForm').submit(function(e){
e.preventDefault()
$.ajax({
type : "POST",
url : "/subscribe/",
data : {
subscriber_email : $('#email').val(),
csrfmiddlewaretoken : '{{ csrf_token }}',
datatype : "json",
},
success: function(){
alert('Success')
},
failure: function(){
alert('Error')
},
});
});
</script>
And this is the function to save the data:
def subscribe(request):
if request.is_ajax():
subscriber_email = request.POST.get('subscriber_email')
subscriber = Subscriber(email = subscriber_email)
subscriber.save()
response = {}
return JsonResponse(response)
Everything works fine, except that I see new “empty” row in the database. Email address is blank?