我试图编写一个自定义方法来覆盖ModelAdmin中字段的默认视图,如下所述:https://docs.djangoproject.com/en/3.2/ref/contrib/admin/
所以这应该可以工作:
@admin.register(Contract)
class ContractDataAdmin(admin.ModelAdmin):
list_display = ("name", "status", "date_end")
list_filter = ('name','status', "date_end", "headquarters_access_list")
fields = ("name", "status", "date_start", "date_end", "manager_list", "buyer", "get_document_list_field", "headquarters_access_list")
@admin.display(empty_value='???')
def get_document_list_field(self, obj):
return "n".join([c.name for c in obj.document_list.all()])
其中模型为:
class Contract(models.Model):
class Meta:
verbose_name = _('Contract')
verbose_name_plural = _('Contracts')
name = models.CharField(max_length=255,
help_text=_('Contract name'),
verbose_name=_('contract name'))
status = models.CharField(max_length=255,
default=ContractStatus.OPEN,
choices=ContractStatus.choices(),
help_text=_('Status'),
verbose_name=_('Status'))
date_start = models.DateField(editable=True,
help_text=_('Start date'),
verbose_name=_('Start date'))
date_end = models.DateField(editable=True,
help_text=_('End date'),
verbose_name=_('End date'))
manager_list = models.ManyToManyField(User,
blank=True,
help_text=_('Manager list'),
verbose_name=_('Manager list'))
buyer = models.OneToOneField(CompanyData, # Committente
related_name="buyer",
on_delete=models.RESTRICT,
default=None,
null=True,
auto_created=False,
help_text=_('Buyer'),
verbose_name=_('buyer'))
headquarters_access_list = models.ManyToManyField(Headquarters,
blank=True,
help_text=_('Headquarters access list'),
verbose_name=_('Headquarters access list'))
contractor_list = models.ManyToManyField(CompanyData,
blank=True,
help_text=_('Contractors list'),
verbose_name=_('Contractors list'))
staff_list = models.ManyToManyField(UserData,
blank=True,
help_text=_('Staff list'),
verbose_name=_('Staff list'))
vehicle_list = models.ManyToManyField(VehicleData,
blank=True,
help_text=_('Vehicle list'),
verbose_name=_('Vehicle list'))
document_list = models.ManyToManyField(Document,
blank=True,
help_text=_('Document list'),
verbose_name=_('Document list'))
当去模型的变更页(/admin/common/contract/1/change/)我得到以下错误:
Traceback (most recent call last):
File "C:UsersusernameAppDataLocalpypoetryCachevirtualenvsmyproject-1PRTDUa5-py3.9libsite-packagesdjangocontribadminoptions.py", line 710, in get_form
return modelform_factory(self.model, **defaults)
File "C:UsersusernameAppDataLocalpypoetryCachevirtualenvsmyproject-1PRTDUa5-py3.9libsite-packagesdjangoformsmodels.py", line 563, in modelform_factory
return type(form)(class_name, (form,), form_class_attrs)
File "C:UsersusernameAppDataLocalpypoetryCachevirtualenvsmyproject-1PRTDUa5-py3.9libsite-packagesdjangoformsmodels.py", line 276, in __new__
raise FieldError(message)
During handling of the above exception (Unknown field(s) (get_document_list_field) specified for Contract), another exception occurred:
File "C:UsersusernameAppDataLocalpypoetryCachevirtualenvsmyproject-1PRTDUa5-py3.9libsite-packagesdjangocorehandlersexception.py", line 47, in inner
response = get_response(request)
File "C:UsersusernameAppDataLocalpypoetryCachevirtualenvsmyproject-1PRTDUa5-py3.9libsite-packagesdjangocorehandlersbase.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:UsersusernameAppDataLocalpypoetryCachevirtualenvsmyproject-1PRTDUa5-py3.9libsite-packagesdjangocontribadminoptions.py", line 616, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:UsersusernameAppDataLocalpypoetryCachevirtualenvsmyproject-1PRTDUa5-py3.9libsite-packagesdjangoutilsdecorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:UsersusernameAppDataLocalpypoetryCachevirtualenvsmyproject-1PRTDUa5-py3.9libsite-packagesdjangoviewsdecoratorscache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:UsersusernameAppDataLocalpypoetryCachevirtualenvsmyproject-1PRTDUa5-py3.9libsite-packagesdjangocontribadminsites.py", line 232, in inner
return view(request, *args, **kwargs)
File "C:UsersusernameAppDataLocalpypoetryCachevirtualenvsmyproject-1PRTDUa5-py3.9libsite-packagesdjangocontribadminoptions.py", line 1660, in change_view
return self.changeform_view(request, object_id, form_url, extra_context)
File "C:UsersusernameAppDataLocalpypoetryCachevirtualenvsmyproject-1PRTDUa5-py3.9libsite-packagesdjangoutilsdecorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:UsersusernameAppDataLocalpypoetryCachevirtualenvsmyproject-1PRTDUa5-py3.9libsite-packagesdjangoutilsdecorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:UsersusernameAppDataLocalpypoetryCachevirtualenvsmyproject-1PRTDUa5-py3.9libsite-packagesdjangocontribadminoptions.py", line 1540, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "C:UsersusernameAppDataLocalpypoetryCachevirtualenvsmyproject-1PRTDUa5-py3.9libsite-packagesdjangocontribadminoptions.py", line 1574, in _changeform_view
ModelForm = self.get_form(
File "C:UsersusernameAppDataLocalpypoetryCachevirtualenvsmyproject-1PRTDUa5-py3.9libsite-packagesdjangocontribadminoptions.py", line 712, in get_form
raise FieldError(
Exception Type: FieldError at /admin/common/contract/1/change/
Exception Value: Unknown field(s) (get_document_list_field) specified for Contract. Check fields/fieldsets/exclude attributes of class ContractDataAdmin.
问题在哪里?Get_document_list_field相当于官方文档中的view_birth_date:
from django.contrib import admin
class AuthorAdmin(admin.ModelAdmin):
fields = ('name', 'title', 'view_birth_date')
@admin.display(empty_value='???')
def view_birth_date(self, obj):
return obj.birth_date
什么是可能的方法做同样的?我需要在更改时自定义某个字段的视图。
自定义"字段";这是表单中显示的方法的结果您需要将其传递给readonly_fields
@admin.register(Contract)
class ContractDataAdmin(admin.ModelAdmin):
list_display = ("name", "status", "date_end")
list_filter = ('name','status', "date_end", "headquarters_access_list")
fields = ("name", "status", "date_start", "date_end", "manager_list", "buyer", "get_document_list_field", "headquarters_access_list")
readonly_fields = ("get_document_list_field", )
@admin.display(empty_value='???')
def get_document_list_field(self, obj):
return "n".join([c.name for c in obj.document_list.all()])