我不明白我做错了什么。我希望用户只添加Annoucement模型的标题和描述,其余应自动填充。这是我的模特:
class Annoucement(models.Model):
username = models.ForeignKey(User, on_delete=None)
title = models.CharField(max_length=500, default="")
description = models.TextField(max_length=5000, default="")
datetime = models.DateTimeField(default=datetime.now)
def __str__(self):
return self.title + " " + self.username.username
这是admin.py文件。
from django.contrib import admin
from .models import Profile, Activity, View, Annoucement
# Register your models here.
class AnnoucementAdmin(admin.ModelAdmin):
fields = ['title', 'description']
def save_model(self, request, obj, form, change):
obj.username = request.user
print("yes")
super(AnnoucementAdmin, self).save_model(request, obj, form, change)
admin.site.register(Profile)
admin.site.register(Activity)
admin.site.register(View)
admin.site.register(Annoucement)
此外,一旦我从管理面板保存模型,打印(“是”)也不会出现在终端上。帮助!
答案 0 :(得分:1)
你必须通过AnnoucementAdmin类,如下所示:
....
admin.site.register(Annoucement, AnnoucementAdmin)
答案 1 :(得分:1)
1)admin.site.register(Annoucement, AnnoucementAdmin)
2)在'return'
的最后一个
save_model
class AnnoucementAdmin(admin.ModelAdmin):
fields = ['title', 'description']
def save_model(self, request, obj, form, change):
obj.username = request.user
print("yes")
return super(AnnoucementAdmin, self).save_model(request, obj, form, change)