Customuser模型不返回用户名

时间:2019-11-07 10:28:53

标签: python django

我有一个

的customuser模型
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

2 个答案:

答案 0 :(得分:0)

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

    def __str__(self):
            return self.ticket_created_by.customuser.username

答案 1 :(得分:0)

观察:

由于该字段是外键,因此将其呈现为modelchoicefield,因此将该字段初始化为charfield,仅打印db中存在的确切值(在本例中为customuser.id

要使其正确呈现,我必须将其初始化为modelchoicefield,例如

ticket_created_by = forms.ModelChoiceField(queryset = customuser.objects.all(), widget = forms.Select(attrs={'class' : 'custom-select custom-select-sm mb-3', 'disabled' : True}))

如果这是正确的解决方案,请提出建议