Django inline_formset-确保至少选择一项

时间:2018-10-22 10:58:00

标签: django django-forms

我有一个inlineformset_factory,其中我需要为至少一种提交的表单选择“结果”:

这些是我的表格:

class CBVQuestionForm(forms.ModelForm):
    class Meta:
        model = Question
        fields = ['id','question','image','time','weight','company','tags','category','author']
        widgets = {'id': forms.HiddenInput(),
                   'time' : forms.NumberInput(attrs={'class': 'form-control quiz-search-box'}),
                   'weight' : forms.NumberInput(attrs={'class': 'form-control quiz-search-box'}),
                   'company' : forms.HiddenInput(),
                   'author' : forms.HiddenInput(),
                   'tags' : TagWidget(attrs={'class':'form-control'}),
        }

    def clean_tags(self):
        data = self.cleaned_data['tags']
        for d in data:
            d = d.replace('[','').replace(']','')
        return data


class AnswerForm(forms.ModelForm):
    class Meta:
        model = Answer
        exclude = ['user_answer']
        fields = ['result','question','answer']
        widgets = {
            'result' : forms.CheckboxInput(
                attrs = {
                    'class' : 'right_answer'
                }
            ),
            'question' : forms.HiddenInput(),
            'answer' : forms.Textarea(
                attrs = {
                    'class' : 'form-control quiz-search-box',
                    'required' : '',
                    'rows' : 3,
                }
            ),

        }

AnswerFormSet = forms.inlineformset_factory(
    Question,
    Answer,
    form=AnswerForm,
    extra=0,
    can_delete = True,
    can_order = False,
    max_num=4,
    min_num=1
)

我正在使用JQuery强制第一个内联表单将结果设置为true,然后确保是否选择了另一个结果,再次使用JQuery将其保留为仅选中的一个,就像这样:

$('#qform').on('change', 'input.right_answer', function() {
    $('input.right_answer').not(this).prop('checked', false);
    $(this).prop("checked", "checked");
});
$(document).ready(function() {
    // set the first check box to checked
    {% if not edit %}
    $('#id_answer_set-0-result').prop("checked", "checked")
    {% endif %}
})

问题是,如果在选择表单集作为正确答案时删除了该表单集,那么我将无法捕获它并确保检查了其他内容。

我尝试了很多事情,例如:

$( "#qform" ).submit(function( event ) {
    checked = $("input.right_answer:checked").length;
    if (checked == 0) {
        event.preventDefault()
    }
});

$('#answerTable').bind('rowAddOrRemove', function(event){
    checked = $("input.right_answer:checked").length;
    if (checked == 0) {
        $('#qform').find('input.right_answer:first', function() {
            $(this).prop("checked", "checked")
        })
    }
});

我什么都无法工作,将不胜感激。

从表格中提取

<form  id= "qform" method="post" action="" enctype="multipart/form-data" >   {% csrf_token %}
...
            <table class="table" id="answerTable">
                {{ answers.management_form }}
                {% for form in answers %}
                    {% if forloop.first %}
                        <thead>
                        <tr>
                            {% for field in form.visible_fields %}
                                <th>{{ field.label|capfirst }}</th>
                            {% endfor %}
                        </tr>
                        </thead>
                    {% endif %}
                    <tr class="formset_row">
                        {% for field in form.visible_fields %}
                            <td>
                                {# Include the hidden fields in the form #}
                                {% if forloop.first %}
                                    {% for hidden in form.hidden_fields %}
                                        {{ hidden }}
                                    {% endfor %}
                                {% endif %}
                                {{ field.errors.as_ul }}
                                {{ field }}
                            </td>
                        {% endfor %}
                    </tr>
                {% endfor %}
            </table>
</form>

请注意,由于我使用的是Django inlineformset,因此如果表单集是从后端传递的,则在删除时仅由JavaScript隐藏,然后在后端删除。

0 个答案:

没有答案