1

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")
Django Dg
  • 97
  • 4
  • 19

2 Answers2

0

You should use django.forms to handle and validate data. https://docs.djangoproject.com/en/2.1/topics/forms/

In your Person model add choices enum:

class Person(models.Model):

    GENDER_MALE = 'M'
    GENDER_FEMALE = 'F'
    GENDER_CHOICES = (
        (GENDER_MALE, 'Male', ), 
        (GENDER_FEMALE, 'Female', ), 
    )

    name = models.CharField(max_length=50)
    date = models.DateField()
    description = models.TextField()
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)

    def __str__(self):
        return str(self.name)

In your PersonForm override field widget:

from django import forms

class PersonForm(forms.ModelForm):

    gender = forms.ChoiceField(choices=Person.GENDER_CHOICES, widget=forms.RadioSelect())

    class Meta:
        model = Person
Fabio Caccamo
  • 1,871
  • 19
  • 21
  • 1
    It's not needed to override the form field, since a model field with `choices` set will automatically be a `ChoiceField`. You just want to override the default widget (`RadioSelect` instead of `Select`). – dirkgroten Mar 05 '19 at 11:20
0

You have to set the value of the radio button to be the same as the first index of the choiceField. I strongly suggest you to use forms for such simple use-case because you get a lot out of the box.

<input type="radio" name="gender"  value="M"> Male<br>
<input type="radio" name="gender"  value="F"> Female<br>

You could create PersonFrom like this:

class PersonForm(model.ModelForm):
    class Meta:
        model = Person

And in the view:

if request.method == "POST":
        person_form = PersonForm(request.POST)
        if person_form.is_valid():
            person_form.save()

        return render(request,'./addPerson.html', {'person_form': person_form })

else:
    print("this is a get METHOD")

You would need to update the template to use the forms. You could read more about it here.

  • i tried your answer and create a **modelForm** but now it doesn;t save any of the insert record into the database yet it alert me that the data are saved. – Django Dg Mar 05 '19 at 11:49
  • You will need to update also the template. It's not saving because the data is not valid I guess. The data argument of the ajax must be with the same with names of the form fields. ```data: { name:name, birthdate:birthdate, description:description, gender:radioValue }``` – Kristiyan Gospodinov Mar 05 '19 at 12:24