gpt4 book ai didi

django - 覆盖管理员中的 save_form 对于内联管理员不起作用

转载 作者:行者123 更新时间:2023-12-01 21:26:56 25 4
gpt4 key购买 nike

我使用 obj.author = request user 覆盖 save_form 以自动填充类 Grievances 中的作者字段。效果很好。但是,出于内联的目的,我使用 obj.status_author = request.user 尝试同样的操作。不起作用 - 未输入任何内容,并且 sql 执行失败,因为 status_author 是必填字段。

save_form 的成功覆盖发生在我的 obj.author 的 GrievancesAdmin 中。如果我对 obj.status_author 尝试同样的操作,但在 GrievanceStatusAdmin (内联)中,它不会在输入中不起作用。

我有以下文件:

模型.py

class Grievances(models.Model):
title = models.CharField(max_length=90)
author = models.ForeignKey(User, related_name='grievance_author')
firefighter = models.ForeignKey(User, related_name='firefighter_harmed')
...

class GrievanceStatus(models.Model):
title = models.ForeignKey(Grievances)
updatetext = models.TextField(blank=True)
action = models.CharField(max_length=20)
status_author = models.ForeignKey(User, related_name='grievance_status_author')

表单.py

class UserModelChoiceField(forms.ModelChoiceField):
""" Override to use full name in ChoiceField """
def label_from_instance(self, obj):
return "%s (%s)" % (obj.get_full_name(), obj.username)

class GrievanceForm(forms.ModelForm):
firefighter = UserModelChoiceField(User.objects.all().order_by('last_name'))
class Meta:
model = Grievances

class GrievanceStatusForm(forms.ModelForm):
class Meta:
model = GrievanceStatus
fields = ('action', 'updatetext', )

admin.py

class GrievanceStatusInline(admin.StackedInline):
model = GrievanceStatus
fk_name = 'title'
form = GrievanceStatusForm
list_select_related = True

class GrievancesAdmin(admin.ModelAdmin):
list_display = ('title', 'firefighter',)
inlines = [ GrievanceStatusInline ]
form = GrievanceForm

def save_formset(self, request, form, formset, change):
### something is wrong with the following line but i'm not sure what ###
obj2 = super(GrievancesAdmin, self).save_formset(request, form, formset, change)
obj2.status_author = request.user
formset.save()

def save_form(self, request, form, change):
obj = super(GrievancesAdmin, self).save_form(request, form, change)
obj.firefighter = User.objects.get(username__exact=obj.firefighter)
obj.status_author = request.user
if not change:
obj.author = request.user
obj.date_updated = datetime.datetime.now()
return obj
admin.site.register(Grievances, GrievancesAdmin)

谢谢!

最佳答案

您应该尝试以下操作!我在那里放置了一个 try... except block ,因为页面上可能还有其他没有 status_author 属性的表单!

class GrievancesAdmin(admin.ModelAdmin):

def save_formset(self, request, form, formset, change):
formset.save()
if not change:
for f in formset.forms:
try:
obj = f.instance
obj.status_author = request.user
obj.save()
except:
continue

关于django - 覆盖管理员中的 save_form 对于内联管理员不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4153690/

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