启用/禁用基于ChoiceField选择的Django表单字段? [英] Enable/Disable Django form fields based on ChoiceField selection?

查看:66
本文介绍了启用/禁用基于ChoiceField选择的Django表单字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a ChoiceField with 2 options and another CharField for key. I need the key field to only be editable or visible when the ChoiceField is set to private. My form in forms.py looks like this:

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'

所以我只需要在可见性=私人的情况下才可以显示/编辑键 。

So I need the 'key' to only be visible/editable if the visibility = 'private'.

我查看了评论,他们建议需要使用javascript完成此操作,因此我希望有人可以向我展示如何将javascript添加到我的.html文件中,并完全满足我的需求。

I've looked at the comments here and they suggest that this needs to be done in javascript so I'm hoping someone can show me how to add javascript to my .html files and excatly what i'd need.

我的h tml文件非常简单:

My html file is very simple:

{% 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>


推荐答案

从呈现的html中,我认为将其添加到html模板的末尾(或在 {%block page_js%} 中)应会为您提供所需的行为:

From your rendered html, I think adding this to the end of your html template (or in a {% block page_js %} ) should give you the desired behavior:

<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 是一个受欢迎的库,您也可以下载和使用(我从此处使用CDN,将其包含在

The first script will include jQuery, which is a popular library that you can also download and use (I use the CDN from here to include it in the example)

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

The second script is more-or-less explained in the comments!

这篇关于启用/禁用基于ChoiceField选择的Django表单字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆