Django不会将User识别为ModelForm中的属性

时间:2016-05-05 17:48:48

标签: python django python-2.7 django-models django-forms

我正在尝试创建一个编辑配置文件表单,我希望默认输入值是当前用户数据。例如,在用户名字段中,默认值将是当前用户的用户名。所以我制作了一个模型表格,我尝试了这个:

from __future__ import unicode_literals

from django import forms
from django.forms import ModelForm, Textarea
from django.db import models
from django.contrib.auth.models import User

class User_Edit(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username', 'email']
        widgets = {
            'username': Textarea(attrs={'value': model.username })
        }

但是Django说:AttributeError:类型对象'User'没有属性'username'

这也是完整的追溯:

Traceback (most recent call last):
File "/home/sebastian/Spartan/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/sebastian/Spartan/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "/home/sebastian/Spartan/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "/home/sebastian/Spartan/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/sebastian/Spartan/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/sebastian/Spartan/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/home/sebastian/Spartan/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/sebastian/Documents/project-spartan/profiles/models.py", line 8, in <module>
class User_Edit(forms.ModelForm):
File "/home/sebastian/Documents/project-spartan/profiles/models.py", line 9, in User_Edit
class Meta:
File "/home/sebastian/Documents/project-spartan/profiles/models.py", line 13, in Meta
'username': Textarea(attrs={'value': model.username })

AttributeError:类型对象'用户'没有属性'用户名'

1 个答案:

答案 0 :(得分:1)

基本上,您不应该在Meta类中设置每个字段的值。您可以初始化代表您正在寻找的用户的表单from an object,因此在您看来,您有:

#Whatever happens in your view function before you create the form

user_obj = User.objects.get(username = target_username,
    email=target_email)    #Or how ever else you want to get the user in question
form = User_EditForm(instance = user_obj)

#Rest of your view

为了让您的生活更轻松,您可能希望使用UpdateView代替,具体取决于您的具体用例。