如何为jsonrespons的ModelForm中的BooleanField分配id属性

2024-05-16 06:29:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个ModelForm,其中我为jsonresponse中使用的小部件分配了id,以便在不刷新页面的情况下保存。我最近将一个字段更改为布尔字段,因为我只希望窗体上的复选框指定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”。你知道吗


Tags: nameidmakeemailpositionformsvalsurname