Python / Django - Edit Model Forms After Creation
I have a strong background in PHP / ZEND and I'm now using learning Python / Django. In Zend you can take a form element object and开发者_JS百科 edit it pretty much at any time. 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.
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:
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.
精彩评论