在相关模型中显示auth.User字段

时间:2017-01-14 11:42:28

标签: django python-3.x django-models django-forms django-1.10

我创建了这个Django模型:

class Teacher(models.Model):
    user = models.OneToOneField('auth.User', on_delete=models.CASCADE, default=1)
    surname = models.CharField(max_length=15, null=True)
    creation_date = models.DateTimeField('creation date', auto_now_add=True)
    deletion_date = models.DateTimeField('deletion date', null=True, blank=True)

以及以只读模式表示它的表单:

class TeacherViewForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(TeacherViewForm, self).__init__(*args, **kwargs)
        instance = getattr(self, 'instance', None)
        if instance and instance.pk:
            for field in self.fields:
                self.fields[field].widget.attrs['disabled'] = True

    class Meta:
        model = Teacher
        exclude = ['deletion_date']

视图如下所示:

class TeacherViewDetail(generic.DetailView):
    model = Teacher
    template_name = 'control/teacher_detail.html'
    form_class = TeacherViewForm

    def get_form(self):
        # Instantiate the form
        form = self.form_class(instance=self.object)

        return form

    def get_context_data(self, **kwargs):
        context = super(TeacherViewDetail, self).get_context_data(**kwargs)
        context.update({
            'form': self.get_form(),
        })

        return context

如您所见,OneToOneTeacher模型之间存在auth.User关系。我需要在first_name模型中显示last_nameauth.User,但只显示username

如何以与显示字段Teacher.surname相同的方式显示这些字段? 我是否必须将它们包含在模型,form.fields中,或者是否有必须修改的属性才能实现它?

由于

1 个答案:

答案 0 :(得分:0)

您必须删除user字段并添加相应的字段。然后在表单的__init__中填写初始值:

# forms.py
class TeacherViewForm(ModelForm):
    first_name = forms.CharField()
    last_name = forms.CharField()

    def __init__(self, *args, **kwargs):
        super(TeacherViewForm, self).__init__(*args, **kwargs)
        instance = getattr(self, 'instance', None)
        if instance and instance.pk:
            for field in self.fields:
                self.fields[field].widget.attrs['disabled'] = True
            # set initial values
            self.fields['first_name'].initial = instance.user.first_name
            self.fields['last_name'].initial = instance.user.last_name

    class Meta:
        model = Teacher
        exclude = ['user', 'deletion_date']  # exclude user

但是如果禁用所有字段,为什么要使用表单呢?您可以在模板中更自由地呈现所有这些信息。