简体   繁体   English

Python / Django:向UserCreationForm添加自定义字段时出现__dict__属性错误消息

[英]Python/Django: __dict__ attribute error message when adding custom fields to UserCreationForm

This error occurs because I have tried to add custom fields to UserCreationForm. 发生此错误是因为我尝试将自定义字段添加到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__'. 我现在已经制作了两个自定义字段 - cristinrolle -but但是当我按下注册按钮时,我收到以下错误消息: / accounts / signup /上的AttributeError - 'tuple'对象没有属性'__dict__'。

(However, the new user is actually registered and is visible in the admin panel). (但是,新用户实际上已注册,并且在管理面板中可见)。

In my models.py file, I have: 在我的models.py文件中,我有:

...

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: 在我的forms.py文件中,我有:

...
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: RankJameous在评论中提出的完整追溯如下:

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? 我做错了什么,我应该在哪里放置错误消息所要求的__dict__

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. 你试图在__init__设置字段标签,但是, fields是一个元组而不是字典,即使它是一个字典,这也不是正确的方法。

You should set the labels as a dict in the Form's Meta : 您应该在Form的Meta中将labels设置为dict:

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__ . 无需覆盖__init__

Finally, your save method should return only the user object: 最后,您的save方法应该只返回用户对象:

def save(self, commit=True):
    ...
    return user

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Django UserCreationForm 自定义字段 - Django UserCreationForm custom fields 为什么object()不具有__dict__来支持某些自定义Python类的实例不具有__dict__属性? - Why is `object()` not having `__dict__` to support the instances of some custom Python classes not having a `__dict__` attribute? 当 __dict__ 被覆盖时,Python 如何访问对象属性? - How does Python access an objects attribute when __dict__ is overridden? 对象在python3中没有属性'.__ dict__' - Object has no attribute '.__dict__' in python3 Python中的属性访问:第一个插槽,然后是__dict__? - Attribute access in Python: first slots, then __dict__? 使用自定义dict类作为Python类的__dict__属性的奇怪行为 - Odd behaviour using a custom dict class as the __dict__ attribute of Python classes 泡菜跨平台__dict__属性错误 - Pickle cross platform __dict__ attribute error 在Python的自定义类上挂钩__dict__? - Hook __dict__ on custom class in python? 为什么自定义Python类实例的`__dict__`属性是该类的描述符,而不是实例的实际属性? - Why is `__dict__` attribute of a custom Python class instance a descriptor of the class, instead of an actual attribute of the instances? 解释 __dict__ 属性 - Explain __dict__ attribute
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM