gpt4 book ai didi

python - 无法覆盖 save_model django admin?

转载 作者:行者123 更新时间:2023-12-05 01:44:38 29 4
gpt4 key购买 nike

我不明白我做错了什么。我希望用户只添加公告模型的标题和描述,其余的应该自动填写。这是我的模型:

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)

此外,一旦我从管理面板保存模型,终端上也不会显示 print("yes")。帮助!

最佳答案

1) admin.site.register(公告, AnnoucementAdmin)

2) 在save_model的最后添加'return'

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)

关于python - 无法覆盖 save_model django admin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45245705/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com