如何在ModelForm中为jsonresponse

时间:2017-02-01 11:54:18

标签: jquery python django

我有一个ModelForm,我已将id分配给小部件,这些小部件在jsonresponse中用于保存而不刷新页面。我最近将一个字段更改为一个布尔字段,因为我只想在表单上选中一个复选框来指定True,默认设置为False。

如何为布尔字段分配ID?

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)

以下是我获取数据的地方:

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()},
....

所以我需要为布尔字段指定id'person-is-coach'。

1 个答案:

答案 0 :(得分:0)

你可以通过

来完成
forms.BooleanField(widget=forms.CheckboxInput(attrs={'id':'your id'}))