在Django 1.11 admin中创建新对象时评估readonly字段

时间:2018-05-31 08:58:58

标签: django django-admin django-modeladmin

假设有以下模型

# models.py
class Person(models.Model):
    name = models.CharField(max_length=40)
    birthdate = models.DateField()
    age = models.CharField(max_length=3) # dont mind the type, this is just an example :)

期望的行为是在用户创建新的age对象时隐藏Person字段,并在用户提交表单时评估其值。此外,在admin中查看对象实例时,age字段应该是可见的。

为实现这一目标,我使用自定义ModelAdmin创建了ModelForm,如下所示

# admin.py
from django.contrib import admin
from django import forms
from .models import Person
from dateutil.relativedelta import relativedelta
import datetime

class PersonForm(forms.ModelForm):
    def clean(self):
        cleaned_data = super(PersonForm, self).clean()
        birthdate = cleaned_data.get('birthdate')
        cleaned_data['age'] = relativedelta(datetime.date.today(), birthdate).years
        return cleaned_data

class PersonAdmin(admin.ModelAdmin):
    form = PersonForm
    exclude = ('age',)

admin.site.register(Person, PersonAdmin)

但是,在提交表单后,age字段不会被填充,可能是因为它被排除在外。如果我删除了exclude,那么它可以正常工作,但表单会显示age字段,这不是所需的行为。

2 个答案:

答案 0 :(得分:1)

您可以使用ModelAdmin的{​​{3}}方法代替自定义表单:

 class PersonAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        birthdate = form.cleaned_data.get('birthdate')
        age = relativedelta(datetime.date.today(), birthdate).years 
        obj.age = age
        super().save_model(request, obj, form, change)

    def get_exclude(self, request, obj=None):
        if not obj:
            return ('age',)
        return self.exclude  

您也可以使用save_model

 class PersonAdmin(admin.ModelAdmin):
    readonly_fields = ('age',)

    def save_model(self, request, obj, form, change):
        birthdate = form.cleaned_data.get('birthdate')
        age = relativedelta(datetime.date.today(), birthdate).years 
        obj.age = age
        super().save_model(request, obj, form, change)

答案 1 :(得分:1)

或者您可以隐藏表单中的输入。

# admin.py
from django.contrib import admin
from django import forms
from .models import Person
from dateutil.relativedelta import relativedelta
import datetime

class PersonForm(forms.ModelForm):
    age = forms.CharField(widget=forms.HiddenInput, required=False)
    def clean(self):
        cleaned_data = super(PersonForm, self).clean()
        birthdate = cleaned_data.get('birthdate')
        cleaned_data['age'] = relativedelta(datetime.date.today(), birthdate).years
        return cleaned_data

只有当object为none(创建大小写)时才可以使用该表单。

class PersonAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        if not obj:
            kwargs['form'] = PersonForm
        return super().get_form(request, obj, **kwargs)

admin.site.register(Person, PersonAdmin)