python-customuser模型不返回用户名

2021-01-08 27点热度 0人点赞 0条评论

我有一个自定义模型

class customuser(AbstractUser):
    # additional fields    
    def __str__(self):
        return self.username

我有另一个模型,它成为这个模型的外键

class bfs_support_ticket_model(models.Model):
    ticket_created_by = models.ForeignKey(customuser, on_delete = models.CASCADE)

为什么Django不呈现表单的用户名,而是正确地呈现或返回所有地方的用户名?

class ticket_edit_form(ticket_create_form):

    # ticket_created_by = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'readonly' : True})) # does not work in this way

    def __init__(self, *args, **kwargs):
        super(ticket_edit_form,self).__init__(*args, **kwargs)
        # self.fields['ticket_created_by'].disabled = True
        self.fields['ticket_created_by'].widget = forms.TextInput(attrs={'class' : 'form-control', 'readonly' : True}) # doesnot work in this way too

    class Meta:
        model=bfs_support_ticket_model
        exclude=['ticket_last_updated_by']

当形式被呈现时,它只是打印 customuser.id 而不是 customuser.username

但是当没有初始化表单时,它会正确地返回 customuser.username

即何时

class ticket_edit_form(ticket_create_form):

    def __init__(self, *args, **kwargs):
        super(ticket_edit_form,self).__init__(*args, **kwargs)
        self.fields['ticket_created_by'].disabled = True # only this line present it renders customuser.username


    class Meta:
        model=bfs_support_ticket_model
        exclude=['ticket_last_updated_by']

请帮帮我,我哪里出错了

编辑:为什么

self.fields['ticket_created_by'].disabled = True # prints username

self.fields['ticket_created_by'].widget = forms.TextInput(attrs={'class' : 'form-control', 'readonly' : True}) # this doesn't
查看隐藏内容需要支付:¥1
查看

未经允许不得转载!python-customuser模型不返回用户名

本文地址:https://ans.52learn.online/2179

ANS52LEARN

DO BEST