django – 在管理员中覆盖save_form不适用于内联管理员

我重写save_form以使用obj.author = request user自动填充类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)

谢谢!

最佳答案 你应该尝试类似以下的东西!我试了一下…除了块之外,因为你的页面上也可能有其他形式,没有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
点赞