def __init__(self, parent_model, admin_site): self.admin_site = admin_site self.parent_model = parent_model self.opts = self.model._meta self.has_registered_model = admin_site.is_registered(self.model) overrides = FORMFIELD_FOR_DBFIELD_DEFAULTS.copy() overrides.update(self.formfield_overrides) self.formfield_overrides = overrides if self.verbose_name is None: self.verbose_name = self.model._meta.verbose_name if self.verbose_name_plural is None: self.verbose_name_plural = self.model._meta.verbose_name_plural
def __init__(self, *args, **kwargs): super(PageAdmin, self).__init__(*args, **kwargs) setting = "RESOURCES_%s_TEXTWIDGET" % self.model._meta.model_name.upper() if hasattr(settings, setting): self.formfield_overrides = { models.TextField: {'widget': get_class_from_string(getattr(settings, setting)) } } overrides = FORMFIELD_FOR_DBFIELD_DEFAULTS.copy() overrides.update(self.formfield_overrides) self.formfield_overrides = overrides setting = "RESOURCES_%s_INLINES" % self.model._meta.model_name.upper() if hasattr(settings, setting): self.inlines = list(self.inlines) for i in getattr(settings, setting): self.inlines.append(get_class_from_string(i))
def __init__(self, *args, **kwargs): super(PageAdmin, self).__init__(*args, **kwargs) setting = "RESOURCES_%s_TEXTWIDGET" % self.model._meta.model_name.upper( ) if hasattr(settings, setting): self.formfield_overrides = { models.TextField: { 'widget': get_class_from_string(getattr(settings, setting)) } } overrides = FORMFIELD_FOR_DBFIELD_DEFAULTS.copy() overrides.update(self.formfield_overrides) self.formfield_overrides = overrides setting = "RESOURCES_%s_INLINES" % self.model._meta.model_name.upper() if hasattr(settings, setting): self.inlines = list(self.inlines) for i in getattr(settings, setting): self.inlines.append(get_class_from_string(i))
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) field_dict = getattr(self._meta.model, '_field_dict', None) if field_dict is None: field_dict = {f.name: f for f in self._meta.model._meta.fields} setattr(self._meta.model, '_field_dict', field_dict) for name, field in self.fields.items(): model_field = field_dict.get(name) if model_field is None: continue filed_mapper = FORMFIELD_FOR_DBFIELD_DEFAULTS.get(model_field.__class__, {}) form_class = filed_mapper.get('form_class') if form_class is not None: self.fields[name] = field = form_class(**field.__dict__) widget_class = filed_mapper.get('widget') if widget_class is not None: field.widget = widget_class()
def __init__(self, *args,**kwargs): super(RealEstateAppPopUpModelAdmin,self).__init__(*args,**kwargs) overrides = FORMFIELD_FOR_DBFIELD_DEFAULTS.copy() overrides.update(self.formfield_overrides) self.formfield_overrides = overrides
from django.views.decorators.csrf import csrf_protect from real_estate_app import widgets from real_estate_app.admin.actions import delete_selected_popup, make_enabled, make_disabled from real_estate_app.conf.settings import REAL_ESTATE_APP_AJAX_SEARCH, MEDIA_PREFIX as MEDIA_PREFIX_REAL_ESTATE from real_estate_app.utils import AutoCompleteObject from real_estate_app.apps.propertys.models import Property #TODO: make a wrapp function for delete elements with Property references. csrf_protect_m = method_decorator(csrf_protect) FORMFIELD_FOR_DBFIELD_DEFAULTS.update({ models.DateTimeField: { 'form_class': forms.SplitDateTimeField, 'widget': widgets.CustomAdminSplitDateTime }, models.DateField: {'widget':widgets.CustomAdminDateWidget}, }) class FaceBoxModelAdmin(ModelAdmin): def _media(self): from django.conf import settings from real_estate_app.conf.settings import MEDIA_REAL_ESTATE js = ['js/core.js', 'js/admin/RelatedObjectLookups.js', 'js/jquery.min.js', 'js/jquery.init.js'] jscustom = [] if self.actions is not None:
# Leaving commented lines for currently unsupported fields FORMFIELD_FOR_DBFIELD_DEFAULTS.update({ rest_fields.DateTimeField: { # 'form_class': forms.SplitDateTimeField, 'widget': widgets.AdminSplitDateTime }, rest_fields.DateField: { 'widget': widgets.AdminDateWidget }, # rest_fields.TimeField: {'widget': widgets.AdminTimeWidget}, rest_fields.TextField: { 'widget': widgets.AdminTextareaWidget }, rest_fields.URLField: { 'widget': widgets.AdminURLFieldWidget }, rest_fields.IntegerField: { 'widget': widgets.AdminIntegerFieldWidget }, # rest_fields.BigIntegerField: {'widget': widgets.AdminBigIntegerFieldWidget}, rest_fields.CharField: { 'widget': widgets.AdminTextInputWidget }, rest_fields.JSONField: { 'widget': widgets.AdminTextareaWidget }, # rest_fields.ImageField: {'widget': widgets.AdminFileWidget}, # rest_fields.FileField: {'widget': widgets.AdminFileWidget}, # rest_fields.EmailField: {'widget': widgets.AdminEmailInputWidget}, })
User.objects.create_superuser('admin', '*****@*****.**', 'admin') # Unauth # Fix datetime for slect django-suit from django.db import models as django_models from django import forms from django.contrib.admin.options import FORMFIELD_FOR_DBFIELD_DEFAULTS import suit.widgets FORMFIELD_FOR_DBFIELD_DEFAULTS.update({ django_models.DateTimeField: { 'form_class': forms.SplitDateTimeField, 'widget': suit.widgets.SuitSplitDateTimeWidget }, django_models.DateField: { 'widget': suit.widgets.SuitDateWidget }, django_models.TimeField: { 'widget': suit.widgets.SuitTimeWidget }, }) # End fix datetime for slect django-suit # Register your models here. from .models import Choice, Question class ChoiceInline(admin.TabularInline): model = Choice extra = 3
# if no other object of this type references the file # and it's not the default value for future objects, # delete it from the backend if not count and file.name != self.default and self.erasable: file.delete(save=save) # try to close the file, so it doesn't tie up resources. file.closed or file.close() class AdvancedImageField(AdvancedFileField, ImageField): attr_class = AdvancedImageFieldFile form_class = ClearableFormImageField def __init__(self, verbose_name=None, name=None, show_image=True, **kwargs): self.show_image = show_image super().__init__(verbose_name, name, **kwargs) def formfield(self, **kwargs): kwargs['form_class'] = self.form_class kwargs['clearable'] = self.clearable kwargs['show_image'] = self.show_image return super().formfield(**kwargs) # Register fields to use custom widgets in the Admin FORMFIELD_FOR_DBFIELD_DEFAULTS.update({ AdvancedFileField: {'widget': ClearableFileInput,}, AdvancedImageField: {'widget': ClearableImageFileInput,}, })
import suit.widgets from django import forms from django.contrib.admin.options import FORMFIELD_FOR_DBFIELD_DEFAULTS from django.db import models FORMFIELD_FOR_DBFIELD_DEFAULTS.update({ models.DateTimeField: { 'form_class': forms.SplitDateTimeField, 'widget': suit.widgets.SuitSplitDateTimeWidget }, models.DateField: {'widget': suit.widgets.SuitDateWidget}, models.TimeField: {'widget': suit.widgets.SuitTimeWidget}, })
def localize_fields(cls, localized_fields): """ For each field name in localized_fields, for each language in settings.LANGUAGES, add fields to cls, and remove the original field, instead replace it with a DefaultFieldDescriptor, which always returns the field in the current language. """ # never do this twice if hasattr(cls, 'localized_fields'): return cls # MSGID_LANGUAGE is the language that is used for the gettext message id's. # If it is not available, because the site isn't using subsites, the # LANGUAGE_CODE is good too. MSGID_LANGUAGE gives the opportunity to # specify a language not available in the site but which is still used for # the message id's. msgid_language = getattr(settings, 'MSGID_LANGUAGE', settings.LANGUAGE_CODE) # set the localized fields property cls.localized_fields = localized_fields for field in localized_fields: original_attr = get_field_from_model_by_name(cls, field) for cnt, language_code in enumerate(get_all_language_codes()): i18n_attr = copy.copy(original_attr) # add support for south introspection. i18n_attr._south_introspects = True i18n_attr.original_fieldname = field i18n_attr.include_in_xml = False lang_attr_name = get_real_fieldname(field, language_code) i18n_attr.name = lang_attr_name i18n_attr.creation_counter = i18n_attr.creation_counter + .01 * cnt # null must be allowed for the message id language because this # language might not be available at all in the backend if not i18n_attr.null and i18n_attr.default is NOT_PROVIDED: i18n_attr.null = True if language_code != msgid_language: # no validation for the fields that are language specific if not i18n_attr.blank: i18n_attr.blank = True if i18n_attr.verbose_name: i18n_attr.verbose_name = translation.string_concat( i18n_attr.verbose_name, u' (%s)' % language_code) cls.add_to_class(lang_attr_name, i18n_attr) # delete original field del cls._meta.local_fields[cls._meta.local_fields.index(original_attr)] # copy some values and functions from the original_attr # so the field can emulate the original_attr as good as possible kwargs = { 'serialize': getattr(original_attr, 'serialize', True), 'extra_attrs': getattr(original_attr, 'extra_attrs', None), 'max_length': getattr(original_attr, 'max_length', None), 'min_length': getattr(original_attr, 'min_length', None), 'form_field': original_attr.formfield( **FORMFIELD_FOR_DBFIELD_DEFAULTS.get( original_attr.__class__, {})), 'get_internal_type': original_attr.get_internal_type, 'unique': getattr(original_attr, 'unique', False), 'to_python': original_attr.to_python, } # copy __serialize__ if it was defined on the original attr if hasattr(original_attr, '__serialize__'): kwargs['__serialize__'] = original_attr.__serialize__ # add the DefaultFieldDescriptor where the original_attr was. cls.add_to_class(field, DefaultFieldDescriptor(field, **kwargs)) # update fields cache try: cls._meta._fill_fields_cache() except AttributeError: # Django 1.8 removed _fill_fields_cache cls._meta._expire_cache() cls._meta._get_fields(reverse=False) # return the finished product return cls
from django.conf import settings from django.contrib.admin.options import FORMFIELD_FOR_DBFIELD_DEFAULTS from django.db import models as django_models from django.core.exceptions import ValidationError import suit.widgets from teams.models import * from match.models import * from research.models import * DEBUG_COMPUTE_RANKING = False FORMFIELD_FOR_DBFIELD_DEFAULTS.update({ django_models.TimeField: { 'widget': suit.widgets.SuitTimeWidget }, }) PLANNING_SLOT_MINUTES = settings.PJC['planning_slot_minutes'] PLANNING_SLOT_SECONDS = PLANNING_SLOT_MINUTES * 60 SCHEDULE_MIN = arrow.get(settings.PJC['start_time'], 'HH:mm').time() SCHEDULE_MAX = arrow.get(settings.PJC['end_time'], 'HH:mm').replace(seconds=-2 * PLANNING_SLOT_SECONDS).time() time_validators = [ validators.MinValueValidator( SCHEDULE_MIN, message=SCHEDULE_MIN.strftime( "L'heure de passage doit être après %H:%M")),
from __future__ import print_function from django.contrib import admin from django.db import models from django.contrib.admin.options import FORMFIELD_FOR_DBFIELD_DEFAULTS from jalali_date import widgets as j_widgets from jalali_date import fields as j_fields overrides = FORMFIELD_FOR_DBFIELD_DEFAULTS.copy() overrides.update({ models.DateField: { 'form_class': j_fields.JalaliDateField, 'widget': j_widgets.AdminJalaliDateWidget }, models.DateTimeField: { 'form_class': j_fields.SplitJalaliDateTimeField, 'widget': j_widgets.AdminSplitJalaliDateTime }, }) def removed_in_next_version(msg=''): if msg: print('>>>\t \x1b[%sm%s\x1b[0m' % ('31', msg)) class ModelAdminJalaliMixin(object): formfield_overrides = overrides def __init__(self, *args, **kwargs): super(ModelAdminJalaliMixin, self).__init__(*args, **kwargs)
def __init__(self, *args, **kwargs): super(RealEstateAppPopUpModelAdmin, self).__init__(*args, **kwargs) overrides = FORMFIELD_FOR_DBFIELD_DEFAULTS.copy() overrides.update(self.formfield_overrides) self.formfield_overrides = overrides
from real_estate_app import widgets from real_estate_app.admin.actions import delete_selected_popup, make_enabled, make_disabled from real_estate_app.conf.settings import REAL_ESTATE_APP_AJAX_SEARCH, MEDIA_PREFIX as MEDIA_PREFIX_REAL_ESTATE from real_estate_app.utils import AutoCompleteObject from real_estate_app.apps.propertys.models import Property #TODO: make a wrapp function for delete elements with Property references. csrf_protect_m = method_decorator(csrf_protect) FORMFIELD_FOR_DBFIELD_DEFAULTS.update({ models.DateTimeField: { 'form_class': forms.SplitDateTimeField, 'widget': widgets.CustomAdminSplitDateTime }, models.DateField: { 'widget': widgets.CustomAdminDateWidget }, }) class FaceBoxModelAdmin(ModelAdmin): def _media(self): from django.conf import settings from real_estate_app.conf.settings import MEDIA_REAL_ESTATE js = [ 'js/core.js', 'js/admin/RelatedObjectLookups.js', 'js/jquery.min.js', 'js/jquery.init.js' ]
class AdvancedImageField(AdvancedFileField, ImageField): attr_class = AdvancedImageFieldFile form_class = ClearableFormImageField def __init__(self, verbose_name=None, name=None, show_image=True, **kwargs): self.show_image = show_image super().__init__(verbose_name, name, **kwargs) def formfield(self, **kwargs): kwargs['form_class'] = self.form_class kwargs['clearable'] = self.clearable kwargs['show_image'] = self.show_image return super().formfield(**kwargs) # Register fields to use custom widgets in the Admin FORMFIELD_FOR_DBFIELD_DEFAULTS.update({ AdvancedFileField: { 'widget': ClearableFileInput, }, AdvancedImageField: { 'widget': ClearableImageFileInput, }, })
def localize_fields(cls, localized_fields): """ For each field name in localized_fields, for each language in settings.LANGUAGES, add fields to cls, and remove the original field, instead replace it with a DefaultFieldDescriptor, which always returns the field in the current language. """ # never do this twice if hasattr(cls, 'localized_fields'): return cls # MSGID_LANGUAGE is the language that is used for the gettext message id's. # If it is not available, because the site isn't using subsites, the # LANGUAGE_CODE is good too. MSGID_LANGUAGE gives the opportunity to # specify a language not available in the site but which is still used for # the message id's. msgid_language = getattr(settings, 'MSGID_LANGUAGE', settings.LANGUAGE_CODE) # set the localized fields property cls.localized_fields = localized_fields for field in localized_fields: original_attr = get_field_from_model_by_name(cls, field) for cnt, language_code in enumerate(get_all_language_codes()): i18n_attr = copy.copy(original_attr) # add support for south introspection. i18n_attr._south_introspects = True i18n_attr.original_fieldname = field i18n_attr.include_in_xml = False lang_attr_name = get_real_fieldname(field, language_code) i18n_attr.name = lang_attr_name i18n_attr.creation_counter = i18n_attr.creation_counter + .01 * cnt # null must be allowed for the message id language because this # language might not be available at all in the backend if not i18n_attr.null and i18n_attr.default is NOT_PROVIDED: i18n_attr.null = True if language_code != msgid_language: # no validation for the fields that are language specific if not i18n_attr.blank: i18n_attr.blank = True if i18n_attr.verbose_name: i18n_attr.verbose_name = translation.string_concat( i18n_attr.verbose_name, u' (%s)' % language_code) cls.add_to_class(lang_attr_name, i18n_attr) # delete original field del cls._meta.local_fields[cls._meta.local_fields.index(original_attr)] # copy some values and functions from the original_attr # so the field can emulate the original_attr as good as possible kwargs = { 'serialize': getattr(original_attr, 'serialize', True), 'extra_attrs': getattr(original_attr, 'extra_attrs', None), 'max_length': getattr(original_attr, 'max_length', None), 'min_length': getattr(original_attr, 'min_length', None), 'form_field': original_attr.formfield(**FORMFIELD_FOR_DBFIELD_DEFAULTS.get( original_attr.__class__, {})), 'get_internal_type': original_attr.get_internal_type, 'unique': getattr(original_attr, 'unique', False), 'to_python': original_attr.to_python, } # copy __serialize__ if it was defined on the original attr if hasattr(original_attr, '__serialize__'): kwargs['__serialize__'] = original_attr.__serialize__ # add the DefaultFieldDescriptor where the original_attr was. cls.add_to_class(field, DefaultFieldDescriptor(field, **kwargs)) # update fields cache cls._meta._fill_fields_cache() # return the finished product return cls
return value return self.markdown_value_class(value) def pre_save(self, instance, add): value = getattr(instance, self.name, None) if self.markdown_cache_field and value: setattr(instance, self.markdown_cache_field, value.markdown()) return super().pre_save(instance, add) def formfield(self, **kwargs): return super().formfield(**{ 'form_class': self.markdown_form_class, 'value_class': self.markdown_value_class, **kwargs, }) class MarkdownCharField(BaseMarkdownModelField, models.CharField): pass class MarkdownTextField(BaseMarkdownModelField, models.TextField): pass # Register fields to use custom widgets in the Admin FORMFIELD_FOR_DBFIELD_DEFAULTS.update({ MarkdownCharField: {'widget': MarkdownTextInput,}, MarkdownTextField: {'widget': MarkdownTextarea,}, })
from ella.newman.models import DenormalizedCategoryUserRole, AdminUserDraft, AdminHelpItem from ella.newman.decorators import require_AJAX from ella.newman.permission import is_category_model, model_category_fk, model_category_fk_value, applicable_categories from ella.newman.permission import has_category_permission, get_permission, permission_filtered_model_qs, is_category_fk from ella.newman.forms import DraftForm from ella.newman.xoptions import XModelAdmin from ella.newman.licenses.models import License from ella.newman.config import STATUS_OK, STATUS_FORM_ERROR, STATUS_VAR_MISSING, STATUS_OBJECT_NOT_FOUND, AUTOSAVE_MAX_AMOUNT DEFAULT_LIST_PER_PAGE = getattr(settings, 'NEWMAN_LIST_PER_PAGE', 25) log = logging.getLogger('ella.newman') # update standard FORMFIELD_FOR_DBFIELD_DEFAULTS FORMFIELD_FOR_DBFIELD_DEFAULTS.update({ models.DateTimeField: {'widget': widgets.DateTimeWidget}, models.DateField: {'widget': widgets.DateWidget}, }) def formfield_for_dbfield_factory(cls, db_field, **kwargs): formfield_overrides = dict(FORMFIELD_FOR_DBFIELD_DEFAULTS, **cls.formfield_overrides) custom_param_names = ('request', 'user', 'model', 'super_field', 'instance') custom_params = {} # move custom kwargs from kwargs to custom_params for key in kwargs: if key not in custom_param_names: continue custom_params[key] = kwargs[key] if key == 'request': custom_params['user'] = custom_params[key].user for key in custom_param_names: kwargs.pop(key, None)
if self.markdown_cache_field and value: setattr(instance, self.markdown_cache_field, value.markdown()) return super().pre_save(instance, add) def formfield(self, **kwargs): return super().formfield( **{ 'form_class': self.markdown_form_class, 'value_class': self.markdown_value_class, **kwargs, }) class MarkdownCharField(BaseMarkdownModelField, models.CharField): pass class MarkdownTextField(BaseMarkdownModelField, models.TextField): pass # Register fields to use custom widgets in the Admin FORMFIELD_FOR_DBFIELD_DEFAULTS.update({ MarkdownCharField: { 'widget': MarkdownTextInput, }, MarkdownTextField: { 'widget': MarkdownTextarea, }, })