Django AbstractUser不允许保存字段数据

2024-03-29 12:37:26 发布

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

我有一个模型对象,它用AbstractUser扩展User对象以添加字段。但是,使用html表单时,我无法将任何内容保存到这些字段中。另外,当我试图在shell中保存时,如果字段在列表中,我就不能保存…但是如果字段在列表之外,我可以保存。我在Postgres中使用django1.6。我快疯了。你知道吗

只有当模型使用AbstractUser时才有问题,普通模型没有这个问题。

class AccountForm(ModelForm):
    class Meta:
        model = Employee

    def __init__(self, *args, **kwargs):
        super(AccountForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-2 control-label'
        self.helper.field_class = 'col-lg-4'

        self.helper.layout = Layout(
            Fieldset('Account Modify',
                'irc_name',
                'forum_username',
                ),
            FormActions(
                Submit('submit', 'Submit', css_class='btn-primary')
                )
            )


class Employee(AbstractUser):
    irc_name = models.CharField(max_length="25")
    forum_username = models.CharField(max_length="25")


class AccountModify(LoginRequiredMixin, UpdateView):
    model = Employee
    form_class = AccountForm
    template_name = 'bot_data/account_modify.html'
    success_url = '/'

Shell会话:

>>> foo = Employee.objects.all()
>>> foo[1]
<Employee: dar777>
>>> foo[1].irc_name
u''
>>> foo[1].irc_name = "Steve"
>>> foo[1].irc_name
u''
>>> bar = foo[1]
>>> bar
<Employee: dar777>
>>> bar.irc_name
u''
>>> bar.irc_name = "Steve"
>>> bar.irc_name
'Steve'
>>> 

Tags: 对象name模型selfformhelperfoohtml
1条回答
网友
1楼 · 发布于 2024-03-29 12:37:26

每次对queryset django进行切片时,都会得到in memory object的新实例

foo = Employee.objects.all()
foo[1] -> new instance 
foo[1].irc_name = 1234 -> new instance
foo[1].save()
print foo[1].irc_name -> will print u''

最佳实践是避免对queryset进行切片。你可以在这个视频http://www.youtube.com/watch?v=t_ziKY1ayCo#t=1923(绑定到时间)中找到完整答案

相关问题 更多 >