扩展Django Admin tabular.html自定义复选框操作

时间:2012-09-13 05:49:44

标签: python django

我有两个表被告和被告_Potential

class Defendant(models.Model):
    fullname         = models.CharField(max_length = 100, null = False,)
    fname            = models.CharField(max_length = 100, verbose_name = u'First Name', blank = True, null = True,)
    midname          = models.CharField(max_length = 100, verbose_name = u'Middle Name', blank = True, null = True,)
    lname            = models.CharField(max_length = 50, verbose_name = u'Last Name', null = True, blank = True,)
    marked           = models.CharField(max_length = 50, verbose_name = u'Check box mark', null = True, blank = True,)
class Defendant_Potential(models.Model):
    defendant    = models.ForeignKey('Defendant', related_name = "Defendant_defendantID",)
    midname      = models.CharField(max_length = 100, blank = True, null = True, default = None)
    address      = models.CharField(max_length = 100, null = False,)
    city         = models.CharField(max_length = 50, null = False,)
    state        = models.CharField(max_length = 5, null = False,)
    zip      = models.CharField(max_length = 50, null = False,)

其管理模型如:

class Defendant_Potential_Individual_Inline(admin.TabularInline):
    model = Defendant_Potential

    formset = NoDeleteAdminInlineFormSet
    readonly_fields = ('midname', 'address')
    extra = 0
    template = "admin/cdradmin/defendant/edit_inline/tabular.html"

class DefendantAdmin(admin.ModelAdmin):
    list_display = ('fullname', 'fname','midname','lname')

    inlines = [Defendant_Potential_Individual_Inline, ]

在tabular.html中,我有一个自定义复选框

<td><input type="checkbox"  name="defendant_potential_checked" data-defendant_id="{{ inline_admin_form.original.defendant_id }}" value="{{ inline_admin_form.original.id }}"></input></td>

我的Qustion是每当选中复选框,然后'被告'表更新标记字段(这应该发生在我们点击change_from.html上的提交按钮。

我对save_model,save_formset等进行了一些研究但是我没有得到任何人可以帮助我做到这一点的正确解决方案吗?

1 个答案:

答案 0 :(得分:1)

假设您必须建模:

class Hive(models.Model):
    name = models.CharField(max_length=100)
    marker = models.BooleanField(default=False)


class Bee(models.Model):
    hive = models.ForeignKey(Hive)
    name = models.CharField(max_length=100)

那么你的管理员可能会是这样的:

class BeeForm(forms.ModelForm):
    check = forms.BooleanField(label="check", required=False)
    class Meta:
        model = Bee

class BeeInline(admin.TabularInline):
    form = BeeForm
    model = Bee

class HiveAdmin(admin.ModelAdmin):
    inlines = (BeeInline,)
    def save_formset(self, request, form, formset, change):
        for bee_form in formset:
            if bee_form.cleaned_data.get('check') == True:
                form.instance.marker = True
                form.instance.save()
        super(HiveAdmin, self).save_formset(request, form, formset, change)

admin.site.register(Hive, HiveAdmin)