Conditional Form Field in Django wizard form

Kan*_*and 5 python forms django django-formwizard python-3.x

I am using wizard forms in django. I want to create a form field only if answer to some other form field is marked "yes" otherwise I don't want this new form field. How can I do this ?
I have tried some other answers related to this but most of them tells about how to mark field required or not but I want to display that field only if answer to other field is "Yes"

Django Form Wizard with Conditional Questions

In below code I want to display field "Pool2" only if answer to field "Pool" is marked "yes" otherwise I don't want that field. Basically I want to get some details of pool in field "Pool2" if there is pool in user's house.

forms.py

class ListingForm2(forms.Form):
     Pool = (
        ("Yes","Yes"),
        ("No","No"),
    )
    Pool = forms.ChoiceField(choices = Pool,label = "Does your property have a pool ?")
    Pool2 = forms.CharField(required=False)
Run Code Online (Sandbox Code Playgroud)

Views.py

class ListingWizard(SessionWizardView):
    template_name = 'listing_form.html'
    form_list = [ListingForm1,ListingForm2,ListingForm3,ListingForm4]
    def done(self, form_list, **kwargs):
        save_data(form.cleaned_data for form in form_list)
        return render(self.request,'done.html',{
            'form_data' : [form.cleaned_data for form in form_list],
            })
Run Code Online (Sandbox Code Playgroud)

小智 8

你要做的事情必须用 JavaScript 来完成,你可以只用 Django 帖子来完成,但这不是正确的方法。

看一下这个:

class BookForm(forms.ModelForm):
    has_sequel = forms.BooleanField(initial=True)

    class Meta:
        model = Book
        fields = ['author', 'length', 'has_sequel', 'sequel']

    class Media:
        js = ('book_form.js', )

    def clean(self):
        if self.cleaned_data['has_sequel'] and self.cleaned_data['sequel'] is None:
            raise ValidationError('You should indicate the sequel if the book has one.')


class BookView(FormView):
    template_name = 'book_form.html'
    form_class = BookForm
    success_url = '/done/'
Run Code Online (Sandbox Code Playgroud)

这段代码包含一个带有表单的 Javascript,这样你就可以用它自己的 Javascript 重用表单,Javascript 代码应该是这样的(你可能需要根据你在模板中打印表单的方式来更改 javascript):

$(document).ready(function() {
    $('#id_has_sequel')[0].addEventListener('change', (event) => {
        let sequelField = $('#id_sequel').parents('p');
        if (event.target.checked) {
            sequelField.show();
        } else {
            sequelField.hide();
        }
    })
});
Run Code Online (Sandbox Code Playgroud)

模板应该是这样的:

{% load static %}

<head>
    <title>Book form</title>

    <script src="{% static 'jquery-3.4.1.min.js' %}"></script>
    {{ form.media }}
</head>

<form method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Send message">
</form>
Run Code Online (Sandbox Code Playgroud)

如果您有任何问题,请随时提出,但尝试在没有 Javascript 的情况下执行此操作并不是一个好方法。同样,您会发现某种 Django 小部件也将使用 Javascript。