[英]Django Model Admin: How to auto assign and hide created_by field with current user and display after save?
I am working certain model Accounting which consists of following model attributes.我正在处理某些 model 会计,其中包括以下 model 属性。
class Accounting(model.Model):
booking = models.OneToOneField(Booking, on_delete=models.PROTECT, null=True)
description = models.CharField(max_length=100, validators=[])
created_by = models.ForeignKey(User, on_delete=models.PROTECT)
bus_company = models.ForeignKey(BusCompany, models.PROTECT)
in admin.py I have done so far在 admin.py 中我到目前为止所做的
@admin.register(Accounting)
class AccountingAdmin(ModelAdmin):
list_display =(
'bus_company',
'description ',
'bus_company ',
)
Now when I use Django admin for adding Accounting
.现在,当我使用 Django admin 添加Accounting
时。 I want to hide created_by
and want to set the current logged in user as the created_by
.我想隐藏created_by
并将当前登录的用户设置为created_by
。 Currently it is superuser
so after adding of data The created_by fields also gets update and displayed how can I do this?目前它是superuser
,所以在添加数据后 created_by 字段也会更新并显示我该怎么做?
To hide the filed, set editable to False要隐藏文件,请将 editable 设置为 False
created_by = models.Model(editable=False)
Now, also add blank=True to created_by and overwrite the save method:现在,还要将 blank=True 添加到 created_by 并覆盖 save 方法:
created_by = models.Model(blank=True,null=True,editable=False)
def save(self,user,*args,**kwargs):
user = user
super().save(*args,**kwargs)
Now at the time of saving this object:现在在保存这个 object 时:
def view_name(request):
user = request.user
atributes = {'booking':'blabl','description':'blablablab'
,'bus_company':'blab blab'}
account = Account(**atributes)
account.save(user=user)
I added read_only fields in admin我在管理员中添加了只读字段
@admin.register(Accounting)
class AccountingAdmin(ModelAdmin):
list_display =(
'bus_company',
'description ',
'bus_company ',
)
readonly_fields = (
'created_by',
)
def save_model(self, request, obj, form, change):
if not change:
obj.created_by = request.user
obj.save()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.