Django无法将User识别为ModelForm属性

2024-05-19 22:47:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图做一个编辑配置文件的形式,我希望默认的输入值是当前的用户数据。例如,在用户名字段中,默认值为当前用户用户名。所以我做了一个模型,我试着这样做:

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:type对象“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:类型对象“User”没有属性“username”


Tags: djangoinpyimporthomemodelsliblocal
1条回答
网友
1楼 · 发布于 2024-05-19 22:47:25

基本上,您不应该设置元类中每个字段的值。您可以初始化一个表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,这取决于您的具体用例。你知道吗

相关问题 更多 >