在保存内联模型之前,在Django管理面板中操作数据

时间:2015-10-08 18:40:54

标签: django admin

我想更改管理页面中保存的数据。 我尝试过save_model。唯一的困难是我使用内联模型,如下所示:

# models.py
from django.db import models

class Material(models.Model):
    type = models.CharField(max_length=20, primary_key=True)
    def __unicode__(self):
        return self.type

class Prop(models.Model):
    color = models.CharField(max_length=20)
    material = models.ForeignKey(Material)
    def __unicode__(self):
        return "%s_%s" % (self.color, str(self.material))

class Pen(models.Model):
    label = models.CharField(max_length=20)
    prop = models.ForeignKey(Prop)
    def __unicode__(self):
        return "%s: %s" % (self.label, str(self.prop))

#admin.py
from django.contrib import admin
from django.conf.urls import url
from .models import Material, Prop, Pen


class PropInlineAdmin(admin.TabularInline):
    model = Prop
    extra = 1

class MaterialAdmin(admin.ModelAdmin):
    inlines = [PropInlineAdmin,]

    def save_model(self, request, obj, form, change):
        print obj.prop_set.values()
        obj.prop_set.color = 'Red'
        obj.save()

admin.site.register(Pen)
admin.site.register(Prop)
admin.site.register(Material, MaterialAdmin)

让我们说用户正在创建一个黑色的Material对象。 举个例子,我试图做的就是将其改为" Black"首字母大写。 一个问题是prop_set在保存之前没有color属性。 另一个问题是上述变化没有生效。 如何操作正在保存的内联值?

1 个答案:

答案 0 :(得分:1)

我明白了!

from django.contrib import admin
from django.conf.urls import url
from .models import Material, Prop, Pen


class PropInlineAdmin(admin.TabularInline):
    model = Prop
    extra = 1

class MaterialAdmin(admin.ModelAdmin):
    inlines = [PropInlineAdmin,]

    def save_formset(self, request, form, formset, change):
        for f in formset.forms:
            obj = f.instance 
            obj.color = obj.color.upper() # or whatever change you'd like
        formset.save()

admin.site.register(Pen)
admin.site.register(Prop)
admin.site.register(Material, MaterialAdmin)