2015-09-01 30 views
4

我有一个Django脆皮形式:一个典型的注册形式,包含电子邮件地址,密码字段和提交动作。 。if语句以Django脆皮形式,条件表单布局

我已经过了,从我的网址Python文件Django的香脆形式称为“billing_secret”的隐藏字段中的计费秘诀是在不同的URL不同

目标: 为了有一个条款及条件无线电复选框启用/禁用特定计费秘密提交按钮,因此URL。

我需要添加两件事情。

  1. 脆皮表单中添加一个if语句只显示了一定的计费SE无线电复选框CRET。例如,如果计费秘密是“苹果”显示无线电并且默认为“否”。如果计费密码是隐藏的,则默认为是。

这是我到目前为止(不工作)。道歉我对Python完全陌生。

email = forms.EmailField(label=_("Email")) 
password1 = forms.CharField(widget=forms.PasswordInput,label=_("Password")) 
billing_secret = forms.CharField() 
termsandcond = forms.TypedChoiceField(
     label = "Do you agree to the T&C's?", 
     choices = ((1, "Yes"), (0, "No")), 
     coerce = lambda x: bool(int(x)), 
     widget = forms.RadioSelect, 
     initial = '0', 
     required = True, 
    ) 

def __init__(self, *args, **kwargs): 
    billing_secret = kwargs.pop('billing_secret', None) 
    super(RegistrationForm, self).__init__(*args, **kwargs) 
    self.helper = FormHelper() 
    self.helper.form_method = 'post' 
    self.helper.form_action = '.' 

    self.helper.layout = Layout(
     Field('email', placeholder=_("Email")), 
     Field('password1', placeholder=_("Password")), 
     Field('billing_secret', value=billing_secret, type="hidden"), 

     if billing_secret is 'apples': 
      return InlineRadios('termsandcond'), 
     else: 
      return InlineRadios('termsandcond', initial="1", type="hidden"), 

     Submit("save", _("Get Started"),css_class="pull-right"), 
    ) 
  • 禁用当单选按钮的值是“无”的提交按钮,并启用时‘是’
  • 我打算包括这样:

    http://jsfiddle.net/8YBu5/7/

    这样,用户必须同意给T & C'S被允许与BIL如果在提交指定的URL的细节之前报名时灵秘是“苹果”。如果它们位于不同的URL上,则收音机不存在,并且提交按钮已启用。

    回答

    6

    使默认按钮隐藏:

    Submit("save", _("Get Started"),css_class="pull-right", style='display: none;') 
    

    并与JavaScript的单选按钮,当接受用户只需点击选择按钮,显示它做检查。

    编辑: 对于条件元素:

    self.helper.layout = Layout(
        Field('email', placeholder=_("Email")), 
        Field('password1', placeholder=_("Password")), 
        Field('billing_secret', value=billing_secret, type="hidden"), 
    ) 
    
    if billing_secret is 'apples': 
        self.helper.layout.append(InlineRadios('termsandcond')) 
    else: 
        self.helper.layout.append(InlineRadios('termsandcond', initial="1", type="hidden")) 
    self.helper.layout.append(Submit("save", _("Get Started"),css_class="pull-right", style='display: none;')) 
    
    +0

    是,但我需要的收音机是唯一的形式为特定billing_secret。所以我的第一个问题是如何基于billing_secret变量有条件地添加表单元素。一旦我弄清楚,我应该能够启用/禁用与JS的按钮。感谢您的建议。 :) –

    +0

    您可以看到编辑条件元素 – Mounir

    +0

    ,谢谢@mounir。有效。欣赏它! –