简体   繁体   English

覆盖提交按钮 label 在 django 脆 forms

[英]Overwrite Submit button label in django crispy forms

I have an upload form which works fine.我有一个工作正常的上传表单。 The idea is that someone uploads a file and chooses a title.这个想法是有人上传一个文件并选择一个标题。 The file gets saved to the server and can't be changed but the title can.该文件被保存到服务器并且不能更改,但标题可以。 So I'm looking for a way to reuse the same form and change the label on the submit button from "Upload File" to "Save Changes".所以我正在寻找一种方法来重用相同的表单并将提交按钮上的 label 从“上传文件”更改为“保存更改”。

This is my upload form:这是我的上传表格:

class MyForm(forms.Form):
  field_1 = forms.FileField()
  field_2 = forms.CharField()
  
  def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_method = 'post'
        
        self.helper.layout = Layout(
            Row( Column('field_1', css_class='form-group col-md-12 mb-0') ),
            Row( Column('field_2', css_class='form-group col-md-12 mb-0') ),
            Submit('submit', 'Upload File', css_class='btn-success', formnovalidate='formnovalidate')) 

Now I want to create an "edit-variation" of the same form.现在我想创建一个相同形式的“编辑变体”。 The File field is changed to a CharField and made read only. File 字段更改为 CharField 并设置为只读。 It shows the server path of the file and can't be changed.它显示文件的服务器路径并且不能更改。 Now I'm trying to change the button label.现在我正在尝试更改按钮 label。

class MySecondForm(MyForm):
  field_1 = forms.CharField()
  
  def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['field_1'].widget.attrs['readonly'] = True
        self.helper['submit'].label = "Save Changes"

The above does not show an error but does not work.以上没有显示错误但不起作用。 The label remains "Upload File". label 仍然是“上传文件”。 I could of course just copy and change my FormHelper layout but my actual form has over 20 fields and I would rather not just copy paste the whole block just to change one label.我当然可以复制和更改我的 FormHelper 布局,但我的实际表单有 20 多个字段,我宁愿不只是复制粘贴整个块来更改一个 label。

Is there a way to set the label of an existing Submit?有没有办法设置现有提交的 label ?

You can definitely do this, Here's an updated version of your "edit" form, with a custom init method that updates the Submit button:您绝对可以这样做,这是您的“编辑”表单的更新版本,具有更新Submit按钮的自定义 init 方法:

class MySecondForm(MyForm):
    field_1 = forms.CharField()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['field_1'].widget.attrs['readonly'] = True
        # From crispy_forms.layout.Layout.__init__, it sets up self.fields 
        # as a list, which we can now alter b/c they've been created in the
        # parent class. Let's target the Submit() item, which is the last 
        # item in layout.fields:
        self.helper.layout.fields[-1].value = "Save Changes"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM