Reputation: 5879
I want to make a view where the user can change the attributes for his User object: first_name, last_name and email address. Django has a built in UserCreationForm for creating users. I already have an extended version that also includes email, first_name and last_name. Now I am trying to extend that one to not include the password and username.
from django.contrib.auth.forms import UserCreationForm
class ExtendedUserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'password1', 'password2',
'email', "first_name", 'last_name' )
class UserEditForm(ExtendedUserCreationForm):
class Meta:
model = User
exclude = ('username', 'password1', 'password2')
The UserEditForm I am looking for will of course not be able to create new instances, but it will only be used to edit existing instances:
form = UserEditForm(instance=request.user)
However, the username field and password fields are still shown. How can I exclude these?
Upvotes: 3
Views: 4076
Reputation: 7943
You can just remove the password2 field in the init of the form like so:
class MyUserCreationForm(UserCreationForm):
def __init__(self, *args, **kargs):
super(MyUserCreationForm, self).__init__(*args, **kargs)
del self.fields['password2']
Upvotes: 6
Reputation: 55
think that would give the idea...
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
#first_name = forms.CharField(required=True)
#last_name = forms.CharField(required=True)
username = forms.CharField (required=True)
class Meta:
model = User
fields = ('first_name','last_name','username','email', 'password1', 'password2')
def __init__ (self, *args, **kwargs):
super(RegistrationForm,self).__init__(*args, **kwargs)
#remove what you like...
self.fields.pop ('first_name')
self.fields.pop ('last_name')
self.fields.pop ('password1')
self.fields.pop ('password2')
Upvotes: 1
Reputation: 31951
It's not a bad idea to have a look at a class you subclass. password1
and password2
fields are defined in form directly, not in the model. So exclude
and fields
will have no effect on them. Just make your own ModelForm
as @MatthewSchinckel suggests.
Upvotes: 2
Reputation: 35599
Why not just use a ModelForm
, and exclude the fields you don't want? That seems like it would be a simpler solution.
Upvotes: 1