2017-02-01 3 views
0

J'ai un ModelForm dans lequel j'ai affecté des identifiants à des widgets qui sont utilisés dans une réponse json pour enregistrer sans actualisation de page. J'ai récemment changé un champ à un champ booléen parce que je veux juste une case sur le formulaire pour assigner vrai, et la valeur par défaut est définie sur False.Comment affecter un attribut id à BooleanField dans ModelForm pour jsonresponse

Comment affecter un identifiant au champ booléen?

class PersonForm(forms.ModelForm): 

    make_person_coach = forms.BooleanField() 

    class Meta: 
     model = Person 
     fields = [ 'id', 'first_name', 'surname', 'email', 'make_person_coach', 'position', 'contract_type', 'mentor'] 
     labels = { 
      'first_name': _('First Name'), 
      'surname': _('Surname'), 
      'email': _('Email'), 
      'coach_id': _('Select Coach'), 
      'make_person_coach': _('Make person a coach?'), 
      'position': _('Position'), 
      'contract_type': _('Contract Type'), 
      'mentor': _('Mentor'), 
     } 

     widgets = { 
     'first_name': forms.TextInput(
      attrs={'placeholder': 'First Name', 'id': 'person-first-name'} 
     ), 
     'surname': forms.TextInput(
      attrs={'placeholder': 'Surname', 'id': 'person-surname'} 
     ), 
     'email': forms.TextInput(
      attrs={'placeholder': 'Email Address', 'id': 'person-email'} 
     ), 
     'position': forms.TextInput(
      attrs={'placeholder': 'Current position', 'id': 'person-position'} 
     ), 
     'contract_type': forms.Select(
      attrs={'placeholder': 'Select Contract Type', 'id': 'person-contract'} 
     ), 
     'mentor': forms.Select(
      attrs={'placeholder': 'Coach name', 'id': 'person-mentor'} 
     ), 

     } 

    def __init__(self, *args, **kwargs): 
     super(PersonForm, self).__init__(*args, **kwargs) 
     all_coaches = Person.objects.filter(make_person_coach="Person is a coach") 
     all_people = Person.objects.all() 
     self.fields['mentor'].empty_label = "Select Coach" 
     self.fields['mentor'].queryset = Person.objects.filter(make_person_coach=True) 

Voici où je reçois les données:

function create_person() { 
    console.log("create person is working!") 
    $.ajax({ 
     url : "{% url 'tande:create_person' %}", 
     type: "POST", 
     data: { first_name : $('#person-first-name').val(), surname : $('#person-surname').val(), email : $('#person-email').val(), is_coach : $('#person-is-coach').val(), position : $('#person-position').val(), contract_type : $('#person-contract').val(), mentor : $('#person-mentor').val()}, 
.... 

donc je dois attribuer le champ booléen l'id 'personne est entraîneur.

Répondre

0

Vous pouvez le faire par

forms.BooleanField(widget=forms.CheckboxInput(attrs={'id':'your id'})) 
+0

Merci qui est génial! –