0

我在 django 中使用 Simple History 模块,我在模型中使用了以下代码来保存历史记录

history = HistoricalRecords(
    bases=[CustomHistoricalModel],
    user_model='userprofile.UserProfile',
    user_db_constraint=False,
)

===========================

class CustomHistoricalModel(models.Model):
    class Meta:
        abstract = True

    field1_id = models.IntegerField(null=True, )

    field2_date = models.DateTimeField(auto_now_add=True, )

    field3_user = models.ForeignKey(
        User,
        null=True,
        editable=False,
    )

    field4_userprofile = models.ForeignKey(
        'userprofile.UserProfile',
        null=True,
        editable=False,
        related_name='%(class)s_userprofile'
    )

    field5_type = models.CharField(
        max_length=1,
        editable=False,
        choices=all_CHOICES,
    )




class newTypes:
    CREATED = 'created1'
    CHANGED = 'updated1'
    DELETED = 'deleted1'


all_CHOICES = (
    (newTypes.CREATED, _('Created')),
    (newTypes.CHANGED, _('Changed')),
    (newTypes.DELETED, _('Deleted')), )

============================

in Admin.py

class CustomerAdmin(SimpleHistoryAdmin):
    list_display = ('name', 'address')


admin.site.register(Customer, CustomerAdmin)

我面临的问题是,当我通过我的 jango 应用程序登录时,我得到 request.user 作为 UserProfile 并且我能够成功地在应用程序中做这些事情。但是当我通过 django Admin 模块登录并在模型中添加数据时,我收到低于 500 错误的错误。

ValueError:无法分配“<UserProfile:UserProfile 对象>”:“HistoricalCustomerTable.history_user”必须是“用户”实例。

目前我的应用程序正在使用内置用户表进行身份验证,当我们通过管理模块登录时如何确保获取 UserProfile 对象?,或提出一些想法

好心提醒。

4

1 回答 1

0

谢谢大家,

解决方案-1:

我通过覆盖 simplehistory 的 getuser 并分配给模型类中定义的 historyrecords 的 getuser 属性以非常简单的方式实现了这一点。

解决方案2:

在 Admin.py 中注册模型并处理那里的用户之前,我找到了其他解决方案覆盖 save_model 方法,谢谢

于 2021-02-05T13:25:07.607 回答