1

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 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...

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

6 Comments

I tried that method without success. I have a field that I want to make hidden. The form element doesn't show as hidden when I apply this technique. Could you give me an example of how you would do that in django? ( how do you use the built-in widgets? )
Hey GregL83, this code works (tested just now on 1.2.3). What type of field are you trying to hide? Also, make sure you are calling the widget ()
form field " title = forms.CharField(label="Header", required=True) " and i'm doing: form['title'].widget = forms.HiddenInput()
Oops, that was my fault Greg, I apologize: the line should read form.fields['fieldname'].
I love python because of the shell. You can just dink around and figure it all out. iPython gives you autocomplete (push tab and see all methods), you can use the dir() builtin, and finally grep -ri "whatever_im_looking_for" path/to/django come in handy every day.
|
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.