This error occurs because I have tried to add custom fields to UserCreationForm. I have now made my two custom fields— cristin and rolle —but when I press the signup button, I get the following error message: AttributeError at /accounts/signup/ – 'tuple' object has no attribute '__dict__'.
(However, the new user is actually registered and is visible in the admin panel).
In my models.py file, I have:
...
class User(auth.models.User,auth.models.PermissionsMixin):
def __str__(self):
return "@{}".format(self.username)
class Userextended(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
cristin = models.IntegerField()
rolle = models.CharField(max_length=100)
...
In my forms.py file, I have:
...
class UserCreateForm(UserCreationForm):
cristin = forms.IntegerField(required=False)
rolle = forms.CharField(max_length=100,required=True)
class Meta():
fields = ('username','first_name','last_name','email','password1','password2')
model = User
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['username'].label = 'Username'
self.fields['email'].label = 'Email Adress'
self.fields['first_name'].label = 'First name'
self.fields['last_name'].label = 'Last name'
self.fields['cristin'].label = 'Cristin ID'
self.fields['rolle'].label = 'Role'
def save(self, commit=True):
if not commit:
raise NotImplementedError("Can't create User and Userextended without database save")
user = super(UserCreateForm, self).save(commit=True)
user_profile = Userextended(user=user,cristin=self.cleaned_data['cristin'],rolle=self.cleaned_data['rolle'])
user_profile.save()
return user, user_profile
...
The full traceback, as requested by FamousJameous in the comment, is the following:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/accounts/signup/
Django Version: 1.11.2
Python Version: 3.6.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'debug_toolbar',
'bootstrap3',
'accounts']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware']
Traceback:
File ".../anaconda/envs/fairAppEnv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File ".../anaconda/envs/fairAppEnv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File ".../anaconda/envs/fairAppEnv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File ".../anaconda/envs/fairAppEnv/lib/python3.6/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File ".../anaconda/envs/fairAppEnv/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File ".../anaconda/envs/fairAppEnv/lib/python3.6/site-packages/django/views/generic/edit.py" in post
217. return super(BaseCreateView, self).post(request, *args, **kwargs)
File ".../anaconda/envs/fairAppEnv/lib/python3.6/site-packages/django/views/generic/edit.py" in post
183. return self.form_valid(form)
File ".../anaconda/envs/fairAppEnv/lib/python3.6/site-packages/django/views/generic/edit.py" in form_valid
163. return super(ModelFormMixin, self).form_valid(form)
File ".../anaconda/envs/fairAppEnv/lib/python3.6/site-packages/django/views/generic/edit.py" in form_valid
79. return HttpResponseRedirect(self.get_success_url())
File ".../anaconda/envs/fairAppEnv/lib/python3.6/site-packages/django/views/generic/edit.py" in get_success_url
148. url = self.success_url.format(**self.object.__dict__)
Exception Type: AttributeError at /accounts/signup/
Exception Value: 'tuple' object has no attribute '__dict__'
What am I doing wrong and where should I place the __dict__ that the error message is asking for?
You're trying to set the field labels in your __init__
, however, fields
is a tuple not a dict, and even if it was a dict, that isn't the right way to do this.
You should set the labels
as a dict in the Form's Meta
:
class UserCreateForm(UserCreationForm):
cristin = forms.IntegerField(required=False)
rolle = forms.CharField(max_length=100,required=True)
class Meta():
fields = ('username','first_name','last_name','email','password1','password2')
model = User
labels = {'username': 'Username',
'first_name': 'First name',
...
'role': 'Role'}
No need to override the __init__
.
Finally, your save
method should return only the user object:
def save(self, commit=True):
...
return user
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.