我使用obj.author = request user覆盖save_form以自动填充类Grievances中的author字段。效果很好。但是,为了内联的目的,我使用obj.status_author = request.user尝试相同的事情。不起作用 - 没有输入,并且sql执行失败,因为status_author是必填字段。
save_form的成功覆盖发生在我的GrievancesAdmin for obj.author。如果我为obj.status_author尝试相同的事情,但是在GrievanceStatusAdmin(内联)中,它在输入中不起任何作用。
我有以下文件:
models.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')
forms.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)
谢谢!
答案 0 :(得分:2)
您应该尝试以下内容!我试了一下...除了阻止因为你可能在页面上有其他形式,没有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
答案 1 :(得分:0)
对于内联管理员,您可能希望改为覆盖save_formset
。