i have a form that allow user to enter a new record to the database by filling the text fields and choose one of the radio button.
the system work as it should and save the data of the text field except the radio button where its always empty. Yet if i print the radio button value its printed correctly.
models.py
class Person(models.Model):
boolChoice = (
("M","Male"),("F","Female")
)
name = models.CharField(max_length=50)
date = models.DateField()
description = models.TextField()
gender = models.CharField(max_length = 1,choices=boolChoice)
def __str__(self):
return str(self.name)
addPerson.html
{% extends 'base.html' %}
{% block content %}
<div class="hero__content">
<form method="POST" class="form-style-9">{% csrf_token %}
{{ form.as_p }}
<ul>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<li>
<h2>Add Member</h2>
</li>
<li>
<input type="text" name="name" class="field-style field-split align-right" placeholder= "enter ur name " id="name"/>
</li>
<li>
<input type="date" name="date" class="field-style field-full align-none" placeholder= " your birthdate" id="birthdate" />
</li>
<li>
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
</li>
<li>
<textarea name="description" class="field-style" placeholder= "introduce yourself " id="description"></textarea>
</li>
<li>
<input type="submit" class="field-style field-full align-none" id="save" value="ADD" />
<script type="text/javascript">
$(function(){
$('#save').on('click',function(e){
e.preventDefault()
name=$('#name').val()
birthdate=$('#birthdate').val()
description=$('#description').val()
radioValue = $("input[name = 'gender']:checked").val()
if (radioValue){
alert("radioValue =", radioValue)
}
$.ajax({
url:'/addperson/',
method:'POST',
data: {
na:name,
bi:birthdate,
de:description,
ra:radioValue
},
headers:{
'X-CSRFToken':'{{csrf_token}}'
}
}).done(function(msg) {
document.location = "/home.html"
alert('ﻟﻘﺪ ﺗﻢّ ﺣﻔﻆ اﻟﻤﻌﻠﻮﻣﺎﺕ')
}).fail(function(err){
alert('ﻟﻢ ﻳﺘﻢ اﻟﺤﻔﻆ')
})
})
})
</script>
</li>
</ul>
</form>
</div>
{% endblock %}
views.py
def addperson(request):
print("request method = " , request.method)
if request.method == "POST":
name = request.POST['na']
birthdate = request.POST['bi']
description=request.POST['de']
gender=request.POST['ra']
person=Person.objects.create(
name=name,
date=birthdate,
description=description,
gender = gender
)
print("name = ", name + "birthdate = " , birthdate + "dec = ", description + "gender = " , gender)
person.save()
return render(request,'./addPerson.html')
else:
print("this is a get METHOD")
– Mohit Harshan Mar 05 '19 at 11:15