如何从Django模型的BaseTable中的TabularInline中获取和保存当前用户ID

时间:2019-01-21 04:24:01

标签: python django django-models

如何使用django admin中的自定义Mixin从BaseTable获取当前用户ID并将其保存在TabularInline中。通过模型传递的值为NULL。

models.py

class BaseTable(models.Model):
    created_at = models.DateTimeField(auto_now_add=True, editable=False)
modified_at = models.DateTimeField(auto_now=True, editable=False)

    created_by = models.ForeignKey(User, on_delete=models.PROTECT, related_name='%(class)s_createdby', editable=False)
modified_by = models.ForeignKey(User, on_delete=models.PROTECT ,related_name='%(class)s_modifiedby', editable=False)

class Meta:
abstract = True


class CheckOutItem(BaseTable): // inherited

admin.py

首先是Mixin

class AuditMixin(object):
def save_model(self, request, obj, form, change):
    if obj.created_by_id is None:
        obj.created_by_id = request.user.id
    obj.modified_by_id = request.user.id
    super(AuditMixin, self).save_model(request, obj, form, change)

...还有管理员模型

class CheckOutItemInline(AuditMixin, admin.TabularInline):
model = CheckOutItem
extra = 1



@admin.register(CheckOut)
class CheckoutAdmin(AuditMixin, admin.ModelAdmin):
model = CheckOut

跟踪错误日志。

  

/ admin / system / checkout / add /中的IntegrityError(1048,“列”   'created_by_id'不能为空”)请求方法:POST请求   网址:http://192.168.4.100/admin/system/checkout/add/ Django   版本:2.1.1异常类型:IntegrityError异常值:(1048,   “列'created_by_id'不能为空”)异常   位置:/home/ricardo/www/developer/python/bmhair/env/lib/python3.6/site-packages/django/db/backends/mysql/base.py   在执行中,第76行Python可执行文件:/ usr / bin / python3 Python   版本:3.6.7 Python路径:
  ['/ home / ricardo / www / developer / python / bmhair / framework',   '/home/ricardo/www/developer/python/bmhair/env/lib/python3.6/site-packages',   '/usr/lib/python36.zip'、'/usr/lib/python3.6',   '/usr/lib/python3.6/lib-dynload',   '/usr/local/lib/python3.6/dist-packages',   '/ usr / lib / python3 / dist-packages']服务器时间:Seg,2019年1月21日   00:06:27 -0400

本地Vars

  

args(“'2019-01-21 04:06:27.441238'”,“'2019-01-21   04:06:27.441335'“,'NULL','NULL','11','2',”'1.00'“,   “ '35 .00'”,“ '35 .00'”)db <_mysql.connection在'localhost'打开   7F1CC050E338> EXC查询   (b'INSERT INTO system_checkoutitemcreated_atmodified_at,   created_by_' b'idmodified_by_idcheckout_idservice_id,   quantityunity_value' b"total_value)值('2019-01-21   04:06:27.441238','2019-01-21 04:06:27“ b” .441335',NULL,NULL,11,   2,'1.00','35 .00','35 .00')“)

0 个答案:

没有答案