我的模型是这样的:
class Activity(models.Model):
sub_choice = ((1, 'English'), (2, 'Math'),
(3, 'Physics'), (4, 'Chemistry'))
subject = models.IntegerField(choices=sub_choice, default=1, max_length=50)
hours = models.IntegerField(verbose_name='Time spent in hours', default=0)
我的admin.py看起来像这样:
class ActivityAdmin(ModelAdmin):
list_display = ('subject', 'hours')
admin.site.register(Activity, ActivityAdmin)
在我的列表显示中,我还想要创建某个特权的用户的名字。如何在没有明确要求活动的创建者将他们的名字放在表单中的情况下这样做。有什么方法可以获得使用User模型中的自定义函数来获取此信息?
答案 0 :(得分:1)
尝试使用用户模型。
models.py
from django.contrib.auth.models import User
class Activity(models.Model):
sub_choice = ((1, 'English'), (2, 'Math'),
(3, 'Physics'), (4, 'Chemistry'))
subject = models.IntegerField(choices=sub_choice, default=1, max_length=50)
hours = models.IntegerField(verbose_name='Time spent in hours', default=0)
owner = models.ForeignKeyField(User)
admin.py
class ActivityAdmin(ModelAdmin):
list_display = ('subject', 'hours', 'owner')
exclude = ['owner']
def save_model(self, request, obj, form, change):
"""
Given a model instance save it to the database.
"""
obj.owner = request.user
obj.save()
admin.site.register(Activity, ActivityAdmin)