【问题标题】:Dynamically Change Django Form's Fields动态更改 Django 表单的字段
【发布时间】:2020-05-06 13:12:09
【问题描述】:

在 django 自定义注册表单中,我在下面的代码中看到了 ChoiceField,但我想要的是根据 ChoiceField 选项更改字段。例如,如果 ChoiceField 被选为 Student,那么我想隐藏“电子邮件字段”或可能添加额外的字段。我知道我可以用 JavaScript 做到这一点,但我想改变表单。

class Signup_Form(UserCreationForm):
 def __init__(self, *args, **kwargs):
    super(Signup_Form, self).__init__(*args, **kwargs)
    # below changing on the fields of this form.
    self.fields['first_name'].label = "First Name"
    self.fields['last_name'].label = "Last Name"
    self.fields['email'].label = "Email"

 SIGNUP_USERS_TYPES = (
    ('Student', 'Student',),
    ('Admin', 'Admin',),)

 user_type = forms.ChoiceField(choices = SIGNUP_USERS_TYPES, required=True, label="Sign-up as :",)

 class Meta:
    model = User
    fields = ['user_type', 'first_name', 'last_name','email', 'username', 'password1', 'password2' ]

【问题讨论】:

    标签: python django django-forms user-registration


    【解决方案1】:

    在您的模板类中,您可能有以下 Javascript 来实现所需的行为。

    email 字段添加为条件字段,并根据user_type 字段中的值显示/隐藏电子邮件字段。

    <script>
        let conditional_fields = $("#id_email");
        if ($("#id_user_type").val() === 'Student') {
            conditional_fields.parent().parent().hide();
        }
        $("#id_user_type").change(function () {
            if ($(this).prop('value') === 'Student') {
                conditional_fields.parent().parent().hide();
            } else {
                conditional_fields.parent().parent().show();
            }
        });
    </script>
    

    【讨论】:

      猜你喜欢
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-28
      • 1970-01-01
      • 2015-09-09
      • 2011-02-07
      相关资源
      最近更新 更多