Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a field from the parent Form in a subclass?

class LoginForm(forms.Form):     nickname = forms.CharField(max_length=100)     username = forms.CharField(max_length=100)     password = forms.CharField(widget=forms.PasswordInput)   class LoginFormWithoutNickname(LoginForm):     # i don't want the field nickname here     nickname = None #?? 

Is there a way to achieve this?

Note: i don't have a ModelForm, so the Meta class with exclude doesn't work.

like image 403
apelliciari Avatar asked Mar 21 '13 20:03

apelliciari


People also ask

How do I remove a field from form?

To remove a single element from the form, hover over it and select the trashcan icon in the top-right of that field, or drag and drop it from your form to the left panel. To remove all fields from your form, use the Remove All or Add All buttons in the left panel.

How do I delete a field in Django?

If you want to drop the data completely, you need to create a Django migration (using ./manage.py makemigrations preferably) that will remove those columns from the database.


2 Answers

You can alter the fields in a subclass by overriding the init method:

class LoginFormWithoutNickname(LoginForm):     def __init__(self, *args, **kwargs):         super(LoginFormWithoutNickname, self).__init__(*args, **kwargs)         self.fields.pop('nickname') 
like image 53
garnertb Avatar answered Sep 22 '22 06:09

garnertb


Django 1.7 addressed this in commit b16dd1fe019 for ticket #8620. In Django 1.7, it becomes possible to do nickname = None in the subclass as the OP suggests. From the documentation changes in the commit:

It's possible to opt-out from a Field inherited from a parent class by shadowing it. While any non-Field value works for this purpose, it's recommended to use None to make it explicit that a field is being nullified.

like image 35
cjerdonek Avatar answered Sep 21 '22 06:09

cjerdonek