简体   繁体   English

Python / Django-创建后编辑模型表单

[英]Python / Django - Edit Model Forms After Creation

I have a strong background in PHP / ZEND and I'm now using learning Python / Django. 我在PHP / ZEND方面有很强的背景,现在我正在学习Python / Django。 In Zend you can take a form element object and edit it pretty much at any time. 在Zend中,您可以随时使用表单元素对象并对其进行几乎任何编辑。 This is great because you can take a form object and make small alterations to it on demand without created a completely new form object. 这很棒,因为您可以采用表单对象并按需对其进行小的更改,而无需创建全新的表单对象。 I am trying to do this is in Django. 我正在尝试在Django中执行此操作。

I have a form. 我有一个表格。 Lets call it vote. 让我们称之为投票。 This form may need a different widget applied in a different view method. 此表单可能需要以不同的视图方法应用不同的窗口小部件。 I don't want to recreate the entire form with such a small change... 我不想用这么小的更改来重新创建整个表格...

ie

form = VoteForm(initial={})
## then something like
form.field.widget = newWidget

Basically, I want to modify a model form element after the object has been created inside the views... 基本上,我想在视图内部创建对象之后修改模型表单元素。

You answered your own question: that's (almost) exactly how you do it! 您回答了自己的问题:这几乎就是您的操作方式!

# tested on 1.2.3  
form = VoteForm(initial={})
form.fields['field_name'].widget = forms.HiddenInput() # make sure you call widget()

form.as_p() # shows new widget

Another way is to override the form's init () method, something like: 另一种方法是重写表单的init ()方法,例如:

class VoteForm(forms.Form):
    myfield = ...
    def __init__(self, hide_field=False, *args, **kwargs):
        super(VoteForm, self).__init__(*args, **kwargs)
        if hide_field:
            self.fields['myfield'].widget = ...

form = VoteForm(hide_field=True, initial={})

I personally prefer this method, keeps all the form logic in one place instead of spread around. 我个人更喜欢这种方法,将所有表单逻辑都放在一个地方,而不是四处散布。 Assuming your forms and views are in separate files, means you won't have to do multiple 'from django import forms' to get the widgets in the views. 假设您的表单和视图位于单独的文件中,则意味着您无需执行多个“从django导入表单”即可在视图中获取小部件。

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

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