在 django-tables2 中显示错误概念

Display misconception in django-tables2

在我的应用程序中创建自定义用户模型后,我有一个继承自用户模型的 studentProfile,其中还包含头像、学期和 dept_name。效果很好。但是,当我尝试使用 django-tables2 显示此 studentProfile 数据时,所有行都显示“-”并且捕获的 ID 来自用户模型而不是 studentProfile。

The weirdiest thing is i can get all the values from user model correctly even when studentProfile is my table model for django-tables2

我不知道我做错了什么。非常感谢任何帮助

我的模型定义如下

class DepartmentData(models.Model):
    fid = models.ForeignKey(FacultyData, on_delete=models.CASCADE)
    dept_name = models.CharField(max_length=50)
    created_on = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.dept_name



class User(AbstractBaseUser):

    # add additional fields here
    user_id = models.CharField(max_length=15, unique=True)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    active = models.BooleanField(default=True)# can login
    staff = models.BooleanField(default=False)  # staff user non superuser
    admin = models.BooleanField(default=False)  # superuser

    USER_TYPE_CHOICES = (
        (1, 'student'),
        (2, 'lecturer'),
        (3, 'bursary'),
        (4, 'system'),
        (5, 'admin'),
    )

    user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES)
    USERNAME_FIELD = 'user_id'
    REQUIRED_FIELDS = ['first_name', 'last_name', 'user_type']

    objects = UserManager()

    def __str__(self):
        return self.user_id

    def get_full_name(self):
        return self.first_name + " " + self.last_name

    def get_user_type(self):
            return self.user_type

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True


    @property
    def is_staff(self):
        return self.staff

    @property
    def is_admin(self):
        return self.admin
    @property
    def is_active(self):
        return self.active


class StudentProfile(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    semester = models.ForeignKey(SemesterData, on_delete=models.SET_NULL, null=True)
    dept_name = models.ForeignKey(DepartmentData, on_delete=models.SET_NULL, null=True)
    avatar = models.ImageField(upload_to='avatars/', null=True, blank=True)

    def __str__(self):
        return self.user.first_name

class SemesterData(models.Model):
    sid = models.ForeignKey(SessionData, on_delete=models.CASCADE)
    semester_name = models.CharField(max_length=50)

    def __str__(self):
            return self.semester_name

    def current(self):

        if SettingsData.objects.all().count():
            st = SettingsData.objects.get(id=1)
            if self.id == st.current_id:
                return "Current Session-Semester"
            else:
                return format_html('<a href="{}"  class="btn btn-primary btn-sm">{}</a>', reverse('system:current_session_semester', args=[self.id]),
                                   'Set Current')
        else:
                return format_html('<a href="{}" class="btn btn-primary">{}</a>', reverse('system:current_session_semester', args=[self.id]),
                                   'Set Current')

这是我的 table.py

class StudentTable(tables.Table):

    user_id = tables.Column(attrs = {'th': {'class': 'danger'}})
    first_name = tables.Column(attrs = {'th': {'class': 'danger'}})
    last_name = tables.Column(attrs = {'th': {'class': 'danger'}})

    avatar = tables.Column(accessor ="user", verbose_name = "ass" )



    active = tables.Column(attrs = {'th': {'class': 'danger'}})

    last_login = tables.Column(attrs = {'th': {'class': 'danger'}})
    edit_Action = tables.LinkColumn('system:semester_edit', text='Edit', args=[A('pk')],attrs={'a':{'class':'btn btn-info btn-sm'}, 'td':{'align': 'center'}, 'th': {'class': 'danger'}}, orderable=False)

    class Meta:
        model = StudentProfile
        attrs = {'class':'table table-hover table-bordered table-responsive'}
        sequence = ('user_id', 'first_name', 'last_name', 'avatar')
        exclude = {'id', 'user', 'password', 'staff', 'admin'}
        empty_text = _("There are no students yet")
        template_name = 'django_tables2/bootstrap4.html'

我很想获得 department_name、semester_name 以及用作我的 table 模型的 studentProfile 中的字段

您看到当前配置的所有字段都是空值,因为您正在尝试访问字段 user_idfirst_namelast_name,这些字段不是 StudentProfile 模型,而是 User 模型的字段(StudentProfileuser 字段相关)。

也就是说,您应该通过 user 关系访问这些字段,如下所示:

class StudentTable(tables.Table):
    user_id = tables.Column(accessor='user.user_id', ...)
    first_name = tables.Column(accessor='user.first_name', ...)
    last_name = tables.Column(accessor='user.last_name', ...)
    ...

DepartmentDataSemesterData 关系而言,我不确定为什么默认情况下不显示它们,因为它们是 StudentProfile 模型的字段,并且它们不会通过 Meta 上的 exclude 属性 排除。您也许可以尝试在 fields 属性 中明确列出它们,看看是否有帮助。