我正在开发一个非常基本的cms /博客。对于我自己的用途,它取决于django-adminfiles和django-markitup。因为我可能想要分发应用程序,所以我一直试图找出一种方法来检查是否满足这些依赖项,如果它们不在已安装的应用程序中,则会回退到django的默认值。
我想出了下面的代码并且它有效。事情是感觉很麻烦,并为脚本的头部添加了大量代码。我想知道是否有任何其他(推荐)处理依赖关系的方法。如果我回答了我自己的问题(因为代码正在运行),欢迎任何评论。
from django.conf import settings as django_settings
# Check installed apps for django-markitup and django-adminfiles
if 'adminfiles' in django_settings.INSTALLED_APPS:
from adminfiles.admin import FilePickerAdmin
adminfiles = True
#inherit from FilePickerAdmin
class ModelAdmin(FilePickerAdmin):
pass
else:
adminfiles = False
#inherit from admin.ModelAdmin if adminfiles =false
class ModelAdmin(admin.ModelAdmin):
pass
#then my own admin class inherits from ModelAdmin above
class HomePageAdmin(ModelAdmin):
exclude = ('slug',)
list_display = ('title', 'status',)
list_filter = ('section',)
if adminfiles:
adminfiles_fields = ('body')
我可以在新的django项目中使用该应用程序,或从已安装的应用程序中删除管理文件,它仍可在管理员中使用。
答案 0 :(得分:1)
这就是我最终的表现:
在app模块中创建一个settings.py文件:
import django
from django.conf import settings
SECTIONS_EXTRAS = getattr(settings, 'SECTIONS_EXTRAS', False)
我现在可以轻松地从项目的设置文件中打开和关闭设置。
然后将以下内容添加到admin.py:
from django.conf import settings as django_settings
from sections.models import HomePage,
from sections import settings
markitup = False
if settings.SECTIONS_EXTRAS:
# Check installed apps for django-markitup and django-adminfiles
if 'adminfiles' in django_settings.INSTALLED_APPS:
from adminfiles.admin import FilePickerAdmin
class ModelAdmin(FilePickerAdmin):
pass
if 'markitup' in django_settings.INSTALLED_APPS:
from markitup.widgets import MarkItUpWidget
markitup = True
else:
class ModelAdmin(admin.ModelAdmin):
pass
class HomePageAdmin(ModelAdmin):
exclude = ('slug',)
list_display = ('title', 'status', 'section')
list_filter = ('section',)
# Extras
adminfiles_fields = ('body')
if markitup:
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == 'body':
kwargs['widget'] = MarkItUpWidget()
return super(HomePageAdmin, self).formfield_for_dbfield(db_field, **kwargs)