简体   繁体   中英

Django: How to make all form fields hidden?

I have a Django form class with around 8 fields. How do I dynamically make all these form fields hidden in one of my views?

Sample:

class FormName(forms.Form):
    first_name = forms.CharField(max_length=20, widget=forms.TextInput(attrs="class":"validate[required,first_name]","tabindex":"4"}), required=True)
    middle_name = forms.CharField(max_length=20, widget=forms.TextInput(attrs="class":"validate[middle_name]","tabindex":"5"}), required=False)
    last_name = forms.CharField(max_length=40, widget=forms.TextInput(attrs="class":"validate[required,last_name]","tabindex":"6"}), required=True)

The reason I want to do this is because I would be using the same form in one of the sign up pages and then again use a similar form elsewhere, where I want these form fields to be hidden. I don't want to create a separate class duplicating the same fields with "widget=forms.HiddenInput()".

In cases when you need a form with hidden inputs, you can notify your form, by passing additional variable to the __init__ method like: form = FormName(is_hidden=True) . And your form might be looking like follows:

class FormName(forms.Form):
    first_name = forms.CharField(max_length=20, widget=forms.TextInput(attrs="class":"validate[required,first_name]","tabindex":"4"}), required=True)
    middle_name = forms.CharField(max_length=20, widget=forms.TextInput(attrs="class":"validate[middle_name]","tabindex":"5"}), required=False)
    last_name = forms.CharField(max_length=40, widget=forms.TextInput(attrs="class":"validate[required,last_name]","tabindex":"6"}), required=True)

    def __init__(self, *args, **kwargs):
        is_hidden = kwargs.pop('is_hidden', None)
        super(FormName, self).__init__(*args, **kwargs)
        if is_hidden:
            self.fields['first_name'].widget = forms.HiddenInput()
            self.fields['middle_name'].widget = forms.HiddenInput()
            self.fields['last_name'].widget = forms.HiddenInput()

In all other cases you can use your form as ussual, without passing is_hidden variable, and it will be using default widgets you defined.

Also, you can iterate over self.fields dictionary, and make all your field widgets hidden without having to override each of them manualy

I suggest using class based views, if you think you're gonna use something over and over again, for example : forms. Your views should look like this:

views.py:

class BaseView(object):

    def __init__(self, request = None , form  = None, <#define anything you want here, like model = None or template = None>):
        if form:
            self.form = form
        else:
            self.form = FormName

        if #AnythingIWant:
            self.anythingiwant = anythingiwant
        else:
            self.anythingiwant = defaultofanythingiwant

    def __call__(self, request):
        self.request = request
        if self.request.method == 'POST':
            return self.POST_handler()
        else:
            return self.GET_handler()

    def POST_handler(self):
        #method to handle post request

    def GET_handler(self):
        #method to handle get request
        #because u want specific form reusable just add:
        # context = {'form' : self.form()}
        # then render a template with the context above

    def extra_context(self):
        return {}

Later if you want to use that form, just inherit BaseView , like :

class IndexView(BaseView):
    #blahblahblah

And if you want to add something in your GET_handler() use extra_context , for example if you want to add another form :

views.py :

class ProfileView(BaseView):

    def extra_context(self):
        form = MyCustomForm()
        context = {'custom_form' : form}
        return context

as for urls.py:

url(r'^$', ProfileView(), name='profile_view'),

if you want to change the default form just override it like this :

url(r'^$', ProfileView(form = MyCustomCustomForm), name='profile_view'),

now you can use MyCustomCustomForm in every views that inherit BaseView . Good thing about using class based views is you can do that to everything, not just form, maybe you want to use some model over and over again

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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