是否基于ChoiceField选择启用/禁用Django表单字段?

时间:2018-11-18 09:15:06

标签: django django-forms

我有一个带有2个选项的ChoiceField和另一个Key的CharField。当ChoiceField设置为private时,我需要键字段仅可编辑或可见。我在forms.py中的表单如下所示:

class CBNewForm(forms.Form):
CHOICES = (('public', 'Public',), ('private', 'Private',))
title = forms.CharField()
category = forms.ChoiceField(choices=[(x,x) for x in CBData.getAllcategory()])
visibility = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)
key = forms.CharField(required=False)

def __init__(self, *args, **kwargs):
    super(CBNewForm, self).__init__(*args, **kwargs)
    self.initial['visibility'] = 'public'

所以我只需要在可见性=“私人”的情况下才能使“键”可见/可编辑。

我已经查看了here条评论,他们认为这需要使用javascript完成,因此我希望有人可以向我展示如何将javascript添加到我的.html文件中,以及我想要的。需要。

我的html文件非常简单:

{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<h1>New Page</h1>
<form action="" method="post">
    {% csrf_token %}{{ form|crispy }}
    <button class="btn btn-info ml-2" type="submit">Update</button>
</form>
{% endblock content %}

呈现的html:

    <nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4">


        <a class="navbar-brand dropdown-toggle" href="#" id="mainMenu" data-toggle="dropdown" aria-haspopup="true"
            aria-expanded="false">CorkBoard</a>
        <div class="dropdown-menu dropdown-menu-left" aria-labelledby="mainMenu">
            <a class="dropdown-item" href="/">Home</a>
            <a class="dropdown-item" href="/corkboards/dashboard/">Dashboard</a>
            <a class="dropdown-item" href="/corkboards/new/">New CorkBoard</a>
            <a class="dropdown-item" href="/corkboards/stats/">CorkBoard Stats</a>
            <div class="dropdown-divider"></div>
            <a class="dropdown-item" href="/corkboards/pin/4/">Pin Detail 4 test</a>
            <a class="dropdown-item" href="/corkboards/detail/3/">CB Detail 3 test</a>
        </div>

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse"
                aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle Navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse">

        <ul class="navbar-nav ml-auto">
            <li class="nav-item">
                <a class="nav-link dropdown-toggle" href="#" id="userMenu" data-toggle="dropdown" aria-haspopup="true"
                    aria-expanded="false">abcd</a>
                <div class="dropdown-menu dropdown-menu-right" aria-labelledby="userMenu">
                    <a class="dropdown-item" href="/users/password_change/">Change Password</a>
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item" href="/users/logout/">Log Out</a>
                </div>
            </li>
        </ul>

        </div>
    </nav>

    <div class="container">

    <h1>New corkboard</h1>
    <form action="" method="post">
        <input type="hidden" name="csrfmiddlewaretoken" value="I4sPqg8hnl7EfXgLAv0Mj0wPXtcjk4roADGAjjHx06TeovySQ0ENCcXEcWieS6KM">

<div id="div_id_title" class="form-group"> <label for="id_title" class="col-form-label  requiredField">
                Title<span class="asteriskField">*</span> </label> <div class=""> <input type="text" name="title" class="textinput textInput form-control" required id="id_title"> </div> </div> <div id="div_id_category" class="form-group"> <label for="id_category" class="col-form-label  requiredField">
                Category<span class="asteriskField">*</span> </label> <div 

    class=""> <select name="category" class="select form-control" id="id_category"> <option value="Education">Education</option> <option value="People">People</option> <option value="Sports">Sports</option> <option value="Other">Other</option> <option value="Architecture">Architecture</option> <option value="Travel">Travel</option> <option value="Pets">Pets</option> <option value="Food &amp; Drink">Food &amp; Drink</option> <option value="Home &amp; Garden">Home &amp; Garden</option> <option value="Photography">Photography</option> <option value="Technology">Technology</option> <option value="Art">Art</option>

    </select> </div> </div> <div id="div_id_visibility" class="form-group"> <label for="id_visibility_0" class="col-form-label  requiredField">
                    Visibility<span class="asteriskField">*</span> </label> <div class=""> <div class="form-check"> <label for="id_id_visibility_0_1" class="form-check-label"> <input type="radio" class="form-check-input" checked="checked" name="visibility" id="id_id_visibility_0_1" value="public" >
            Public
        </label> </div> <div class="form-check"> <label for="id_id_visibility_0_2" class="form-check-label"> <input type="radio" class="form-check-input" name="visibility" id="id_id_visibility_0_2" value="private" >
            Private
        </label> </div> </div> </div> <div id="div_id_password" class="form-group"> <label for="password_text" class="col-form-label ">
                Password
            </label> <div class=""> <input type="text" name="password" id="password_text" class="textinput textInput form-control"> </div> </div>

        <button class="btn btn-info ml-2" type="submit">Update</button>
    </form>

    <script>
        document.getElementById('private_box').onchange = function () {
            document.getElementById('password_text').disabled = !this.checked;
        };
    </script>

    </div>

1 个答案:

答案 0 :(得分:1)

从您呈现的html中,我认为将其添加到html模板的末尾(或添加到<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"> </script> <script> $(document).ready(function () { //function will wait for the page to fully load before executing $("input[type=radio][name=visibility]").change(function () { //specifying onchange function for input of type radio and name visibility console.log("Change!") if (this.value == "private") { //if the new value is private $("#password_text").prop('disabled', true);//would recommend readonly instead of disable for form integrity console.log("Disabling"); }else{ //if the new value is anything else $("#password_text").prop('disabled', false); console.log("Enabling"); } }); }); </script> 中)应该可以为您提供所需的行为:

jQuery

第一个脚本将包含afterSelect,这是一个受欢迎的库,您也可以下载并使用(我使用here中的CDN来将其包含在示例中)

注释中或多或少地解释了第二个脚本!