class ConceptAdmin(ImportExportMixin, ImproveRawIdFieldsFormMixin, TreeAdmin): change_list_template = 'admin/tree_change_list.html' search_fields = ['title'] inlines = [LabelInline, MappedUriInline] fieldsets = ( (None, { 'fields': ( 'title', 'definition', 'example', 'tags', '_position', '_ref_node_id'), }), ('Search', { 'classes': ('collapse',), 'fields': ('alternative_parents', 'related_match', 'exact_match', 'close_match'), }), ) resource_class = ConceptResource form = movenodeform_factory(Concept, exclude = [], widgets = { #'parent': ConceptSelectWidget, #'tags': TagWidget, 'alternative_parents': ConceptTagAdminWidget, 'related_match': ConceptTagAdminWidget, 'exact_match': ConceptTagAdminWidget, 'close_match': ConceptTagAdminWidget, } )
class CategorySiteAdmin(TreeAdmin): list_display = ('title', 'icon', 'show', ) list_filter = ('show', ) search_fields = ('title',) class Media: js = [ '/static/grappelli/tinymce/jscripts/tiny_mce/tiny_mce.js', '/static/grappelli/tinymce_setup/tinymce_setup.js', ] def icon(self, obj): from sorl.thumbnail import get_thumbnail try: im = get_thumbnail(obj.image, '60x60', crop='center', quality=99) return '<img src="{}" border="0" alt="" align="center" />'.format(im.url) except BaseException as exc: return '<img src="" border="0" alt="" width="60" height="60" align="center" />' icon.short_description = 'Миниатюра' icon.allow_tags = True icon.admin_order_field = 'title' prepopulated_fields = {'slug_title': ('title', )} # filter_horizontal = ('themes',) form = movenodeform_factory(CategorySite)
class StandardNodeAdmin(TreeAdmin): list_filter = ("document__country", "document") search_fields = [ "identifier", "title", "learning_objectives__text", "notes" ] form = movenodeform_factory(StandardNode) inlines = [LearningObjectiveInline]
class StorageAdmin(TreeAdmin): list_display = ('location', 'container_type',) list_filter = ('container_type',) form = movenodeform_factory(Storage) inlines = [ ItemInline ]
class GPCSectorAdmin(TreeAdmin): view_on_site = False list_display = ('name', ) save_as = True # date_hierarchy = ('creation_date') form = movenodeform_factory(GPCSector)
class HomePageBannersAdmin(TreeAdmin, admin.ModelAdmin): list_display = ['banner_title', 'desktop_banner_avatar', 'mobile_banner_avatar', 'published', 'created_on', 'updated_on' ] form = movenodeform_factory(models.HomePageBanners)
class NodeAdmin(TreeAdmin): list_display = ( 'parent', 'sib_order', 'desc', ) form = movenodeform_factory(models.Node)
class QuestionAdmin(TreeAdmin): form = movenodeform_factory(Question) list_filter = ('questionaire__law_case', 'questionaire') inlines = [ ConditionInline, ]
class NodeAdmin(TreeAdmin): list_display = ["name", "description_length"] list_filter = [HasDescriptionFilter] actions = [export_descriptions] fields = [ "name", "description", "display_type", "_position", "_ref_node_id", "tags", "representative_media", ] raw_id_fields = [ "representative_media", ] filter_horizontal = ["tags"] form = movenodeform_factory(Node) search_fields = [ "name", ] def description_length(self, node): return node.description_length def get_queryset(self, request): return Node.objects.annotate(description_length=Length("description"))
class MyAdmin(TreeAdmin): fields = ( 'name', '_position', '_ref_node_id', ) form = movenodeform_factory(TreeCategory)
class FoodAdmin(TreeAdmin): form = movenodeform_factory(Keyword) ordering = ( 'space', 'path', ) actions = [sort_tree, enable_tree_sorting, disable_tree_sorting]
class ContentAdmin(TreeAdmin): form = movenodeform_factory(Content) list_display = ('title', 'enabled', 'hidden') list_filter = ['enabled', 'hidden', 'category', 'type'] prepopulated_fields = {'slug': ('title', )} # fieldsets = [ # (_(u'General info'), { # 'fields': ['title', 'slug', 'content', 'tags', ('category', 'type', 'date_published', 'enabled')], # }), # (_(u'Extended settings'), { # 'classes': ('collapse',), # 'fields': ['meta_keywords', 'meta_description', 'hidden', 'image'], # }) # # ] def get_form(self, request, obj=None, **kwargs): form = super(ContentAdmin, self).get_form(request, obj, **kwargs) form.base_fields['slug'].widget.attrs['style'] = 'width: 50%;' form.base_fields['title'].widget.attrs['style'] = 'width: 50%;' form.base_fields['meta_keywords'].widget.attrs['style'] = 'width: 50%;' form.base_fields['meta_description'].widget.attrs[ 'style'] = 'width: 50%;' form.base_fields['tags'].widget.attrs['style'] = 'width: 50%;' form.base_fields['category'].widget.attrs[ 'style'] = 'min-width: 200px;' return form def save_model(self, request, obj, form, change): if hasattr(obj, 'user') is False: obj.user = request.user obj.save()
class ClassificationAdmin(AssignClassificationParentMixin, TreeAdmin): fields = ( 'name', 'slug', '_position', '_ref_node_id', ) form = movenodeform_factory(Classification) prepopulated_fields = {"slug": ["name"]} search_fields = ["name"] list_display = ('name', 'num_publicbodies', 'publicbody_link') actions = AssignClassificationParentMixin.actions def get_queryset(self, request): """Use this so we can annotate with additional info.""" qs = super(ClassificationAdmin, self).get_queryset(request) return qs.annotate(num_publicbodies=Count('publicbody', distinct=True)) def num_publicbodies(self, obj): """# of companies an expert has.""" return obj.num_publicbodies num_publicbodies.short_description = _('# public bodies') def publicbody_link(self, obj): return format_html( '<a href="{}">{}</a>', reverse('admin:publicbody_publicbody_changelist') + ('?classification__id__exact={}'.format(obj.id)), _('Public bodies with this classification'))
class CategoryAdmin(TreeAdmin): form = movenodeform_factory(Category) list_display = ('name', 'depth', 'total',) fields = ( 'name', '_position', '_ref_node_id', )
class ServiceAdmin(TreeAdmin): form = movenodeform_factory(Service) list_display = ('title', 'course', 'get_categories_changelist', 'get_price_changelist') list_filter = ('course', 'category') search_fields = ('title', ) fields = ('title', 'min_price', 'max_price', '_position', '_ref_node_id', 'course', 'category')
def test_site_initial(self): site = Site(domain='x.com', name='x') site.full_clean() site.save() form_for_class = movenodeform_factory(model=MenuItem, form=MenuItemTreeForm) form = form_for_class(data=None, files=None) self.assertEqual(form.fields['site'].initial, 2)
class GeographyAdmin(TreeAdmin): form = movenodeform_factory(models.Geography) list_display = ( "name", "code", "level", "version", "created", "updated" ) search_fields = ("name", "code") list_filter = ("level", "version")
class PublisherAdmin(ImportExportMixin, TreeAdmin): change_list_template = 'admin/tree_change_list.html' list_display = ['name', 'agency_type'] list_filter = ['agency_type'] search_fields = ['name'] prepopulated_fields = {"slug": ("name",)} resource_class = PublisherResource form = movenodeform_factory(Publisher)
class ConceptAdmin(TreeAdmin): fields = ( 'label', 'name', '_position', '_ref_node_id', ) form = movenodeform_factory(Concept)
class CategoryXMLAdmin(TreeAdmin): list_display = ('title', 'maker', 'category_site') list_filter = ('status', 'maker', CategorySiteListFilter,) search_fields = ('title',) actions = [category_xml_add_category_site, category_xml_clear_category_site, category_xml_add_maker] form = movenodeform_factory(CategorySite, exclude=('cat_id', 'import_fl',))
class BlogsAdmin(TreeAdmin, admin.ModelAdmin): list_display = [ 'blog_topic', 'blog_title', 'slug', 'content_published_date', 'created_on', 'updated_on', 'published' ] prepopulated_fields = { 'slug': ('blog_title', ), } form = movenodeform_factory(models.Blogs)
class ClassificationAdmin(AssignClassificationParentMixin, TreeAdmin): fields = ( 'name', 'slug', '_position', '_ref_node_id', ) form = movenodeform_factory(Classification) prepopulated_fields = {"slug": ["name"]} search_fields = ["name"] actions = AssignClassificationParentMixin.actions
class NewsCategoryAdmin(EnhancedModelAdminMixin, TreeAdmin): form = movenodeform_factory(NewsCategory) prepopulated_fields = {"slug": ("name", )} class Media: css = { 'all': ('%soscar_news/css/%s' % (settings.STATIC_URL, 'oscar_news_admin.css'), ) } def get_prepopulated_fields(self, request, obj=None): return {'slug': ('name', )}
class CategoryAdmin(AssignCategoryParentMixin, TreeAdmin): fields = ( 'name', 'slug', 'is_topic', '_position', '_ref_node_id', ) form = movenodeform_factory(Category) prepopulated_fields = {"slug": ["name"]} search_fields = ["name"] actions = AssignCategoryParentMixin.actions
class ModelTreeAdmin(TreeAdmin): """ A custom model class to allow drag & drop in Django admin """ # pylint: disable=undefined-loop-variable #: The form is dynamically generated via :func:`treebeard.forms.movenodeform_factory` form = movenodeform_factory(model) # Filters in the right sidebar of the lists list_filter = ("region", ) #: Which fields are displayed as columns in the lists list_display = ("__str__", "region") #: How lists of objects should be ordered ordering = ("region", )
class OrganizationAdmin(TreeAdmin): model = Organization list_display = ( 'id', 'name', 'cti_contributor', 'org_tag', 'status', ) list_display_links = ('id', 'name') list_filter = ('status', 'cti_contributor') search_fields = ('name', 'city', 'state', 'country') form = movenodeform_factory(Organization) inlines = [LinkInline]
class CategoryForm(movenodeform_factory(Category)): def __init__(self, *args, **kwargs): super(CategoryForm, self).__init__(*args, **kwargs) self.fields['description'].widget = CKEditorWidget() # # class PackageOptionChoiceForm(forms.ModelForm): # class Meta: # model = PackageOptionChoice # # def __init__(self, *args, **kwargs): # super(PackageOptionChoiceForm, self).__init__(*args, **kwargs) # self.fields['variant'].choices = OptionInfo.objects.filter(multi_option__product=)
class categoryAdmin(TreeAdmin): search_fields = ["name", "description"] readonly_fields = ["slug"] exclude = ["id", "search_vector"] def has_add_permission(self, request, obj=None): return False def has_change_permission(self, request, obj=None): return False def has_delete_permission(self, request, obj=None): return False form = movenodeform_factory(Category)
class ParentAdmin(TreeAdmin): fieldsets = [ ('', { 'fields': ['title', 'parent', 'slug', 'data', 'content_type'] }), ] #list_display = ('title', 'parent', 'level') list_display = ('title', 'parent') list_filter = ['parent'] search_fields = ['title'] #form = ParentForm ordering = ['title'] prepopulated_fields = { 'slug': ('title', ), } form = movenodeform_factory(BlogParent)
class CategoryAdmin(TreeAdmin): form = movenodeform_factory(Category) list_display = ['name', 'slug', 'sku_allowed'] list_editable = ['slug', 'sku_allowed'] fieldsets = ((None, { 'fields': ('name', 'slug', 'sku_allowed', 'size_set') }), (_('Tree position'), { 'fields': ('_position', '_ref_node_id') }), (_('Filters'), { 'fields': ( 'filter_price_allowed', 'filter_color_allowed', 'filter_size_allowed', 'filter_fabric_allowed', ), 'classes': ('collapse', ) }), SEO_ADMIN_FIELDSET)
class PathAdmin(LeafletGeoAdminMixin, TreeAdmin): form = movenodeform_factory(Path, form=PathAdminForm) list_display = ('name', 'slug') fieldsets = ((None, { 'fields': ('name', ('_position', '_ref_node_id'), 'description', 'geom') }), ) class Meta: model = Path fields = '__all__' class Media: js = ( 'poimap/js/path_admin_form.js', '@mapbox/togeojson/togeojson.js', )
def test_slug_not_in_cd(self): form_for_class = movenodeform_factory(model=MenuItem, form=MenuItemTreeForm, exclude=['menu_slug']) bound_data = { '_ref_node_id': 0, '_save': 'Save', '_position': 'first-child', 'site': 1, 'is_published': 'on', 'uri': '/aaaaaaaaaaaaa/', 'title': 'yays', } form = form_for_class(data=bound_data, files=None) self.assertTrue(form.is_valid()) form.save() self.assertIn('menu_slug', form.cleaned_data) self.assertEqual(form.cleaned_data['menu_slug'], 'aaaaaaaaaaaaa')
slug_prefix = '' if parent: slug_prefix = (parent.slug + Category._slug_separator) slug = '%s%s' % (slug_prefix, slugify(name)) # check if slug is conflicting try: category = Category.objects.get(slug=slug) except Category.DoesNotExist: pass else: if category.pk != self.instance.pk: return True return False CategoryForm = movenodeform_factory(Category, form=BaseCategoryForm) class ProductClassSelectForm(forms.Form): """ Form which is used before creating a product to select it's product class """ product_class = forms.ModelChoiceField( label=_("Create a new product of type"), empty_label=_("-- Choose type --"), queryset=ProductClass.objects.all()) def __init__(self, *args, **kwargs): """
Category = get_model('catalogue', 'Category') StockRecord = get_model('partner', 'StockRecord') ProductCategory = get_model('catalogue', 'ProductCategory') ProductImage = get_model('catalogue', 'ProductImage') ProductRecommendation = get_model('catalogue', 'ProductRecommendation') AttributeOptionGroup = get_model('catalogue', 'AttributeOptionGroup') AttributeOption = get_model('catalogue', 'AttributeOption') Option = get_model('catalogue', 'Option') ProductSelect = get_class('dashboard.catalogue.widgets', 'ProductSelect') (RelatedFieldWidgetWrapper, RelatedMultipleFieldWidgetWrapper) = get_classes('dashboard.widgets', ('RelatedFieldWidgetWrapper', 'RelatedMultipleFieldWidgetWrapper')) CategoryForm = movenodeform_factory( Category, fields=['name', 'description', 'image']) class ProductClassSelectForm(forms.Form): """ Form which is used before creating a product to select it's product class """ product_class = forms.ModelChoiceField( label=_("Create a new product of type"), empty_label=_("-- Choose type --"), queryset=ProductClass.objects.all()) def __init__(self, *args, **kwargs): """
base_url = forms.CharField( required=False, label='Base URL (optional)') def clean(self): cleaned_data = super(CloneHierarchyForm, self).clean() name = cleaned_data.get('name') base_url = cleaned_data.get('base_url') if not base_url: # If there's no base_url, derive it from the name. cleaned_data['base_url'] = slugify(name) base_url = cleaned_data['base_url'] if Hierarchy.objects.filter(name=name).exists(): raise forms.ValidationError( 'There\'s already a hierarchy with the name: {}'.format( name)) if Hierarchy.objects.filter(base_url=base_url).exists(): raise forms.ValidationError( 'There\'s already a hierarchy with the base_url: {}'.format( base_url)) return cleaned_data MoveSectionForm = movenodeform_factory( Section, exclude=('label', 'slug', 'hierarchy', 'show_toc', 'deep_toc') )
from ..models import FileNode from .. import settings as app_settings from django import forms from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import filesizeformat import os from treebeard.forms import movenodeform_factory FormBase = movenodeform_factory(FileNode) class FileNodeForm(FormBase): node_type = forms.fields.ChoiceField(widget=forms.HiddenInput(), choices=((FileNode.FILE, _('file')), (FileNode.FOLDER, _('folder')))) # disable posting of _position, we're always expecting # 'sorted-child' instead of user-entered value _position = forms.ChoiceField(required=True, label=_("Position"), initial='sorted-child', widget=forms.HiddenInput()) def __init__(self, *args, **kwargs): super(FileNodeForm, self).__init__(*args, **kwargs) self.fields['_ref_node_id'].label = _('Containing folder') @classmethod def add_subtree(cls, for_node, node, options): if node.is_folder(): return super(FileNodeForm, cls).add_subtree(for_node, node, options) def clean_node_type(self): return int(self.cleaned_data['node_type']) def clean(self):
import datetime from django.contrib import admin from treebeard.admin import admin_factory from treebeard.forms import movenodeform_factory from treebeard.tests.models import BASE_MODELS for model in BASE_MODELS: form_class = movenodeform_factory(model) admin_class = admin_factory(form_class) admin.site.register(model, admin_class)
def register(model): form_class = movenodeform_factory(model) admin_class = admin_factory(form_class) admin.site.register(model, admin_class)
def get_form_class(self): if self.model_admin.move_form_select_indentation: formclass = MoveForm else: formclass = NoIndentationMoveForm return movenodeform_factory(self.model, form=formclass, fields=[])
from .models import Category class CategoryWizard(Wizard): def get_success_url(self, *args, **kwargs): # Since categories do not have their own urls, return None so that # cms knows that it should just close the wizard window (reload # current page) return None class CreateCategoryForm(BaseFormMixin, TranslatableModelForm, MoveNodeForm): """ The model form for Category wizad. """ class Meta: model = Category fields = ['name', 'slug', ] aldryn_category_wizard = CategoryWizard( title=_(u"New category"), weight=290, form=movenodeform_factory(Category, form=CreateCategoryForm), description=_(u"Create a new category.") ) wizard_pool.register(aldryn_category_wizard)
If the user isn't a staff user, this validation ensures that at least one stock record's partner is associated with a users partners. """ if any(self.errors): return if self.require_user_stockrecord: stockrecord_partners = set([form.cleaned_data.get('partner', None) for form in self.forms]) user_partners = set(self.user.partners.all()) if not user_partners & stockrecord_partners: raise exceptions.ValidationError( _("At least one stock record must be set to a partner that" "you're associated with.")) CategoryForm = movenodeform_factory(Category, form=BaseCategoryForm, exclude=('partner',) ) class ProductForm(CoreProductForm): class Meta: model = Product fields = ['title', 'upc', 'description', 'shipping_price'] widgets = { 'structure': forms.HiddenInput() } class ProductCategoryForm(forms.ModelForm): def __init__(self,user, *args, **kwargs): super(ProductCategoryForm, self).__init__(*args, **kwargs) self.user = user
def move_form(self): MoveSectionForm = movenodeform_factory( type(self), exclude=('label', 'slug', 'hierarchy', 'show_toc', 'deep_toc')) return MoveSectionForm(instance=self)
from oscar.core.loading import get_class, get_model from oscar.core.utils import slugify from oscar.forms.widgets import ImageInput Product = get_model("catalogue", "Product") ProductClass = get_model("catalogue", "ProductClass") ProductAttribute = get_model("catalogue", "ProductAttribute") Category = get_model("catalogue", "Category") StockRecord = get_model("partner", "StockRecord") ProductCategory = get_model("catalogue", "ProductCategory") ProductImage = get_model("catalogue", "ProductImage") ProductRecommendation = get_model("catalogue", "ProductRecommendation") ProductSelect = get_class("dashboard.catalogue.widgets", "ProductSelect") CategoryForm = movenodeform_factory(Category, fields=["name", "description", "image"]) class ProductClassSelectForm(forms.Form): """ Form which is used before creating a product to select it's product class """ product_class = forms.ModelChoiceField( label=_("Create a new product of type"), empty_label=_("-- Choose type --"), queryset=ProductClass.objects.all() ) def __init__(self, *args, **kwargs): """ If there's only one product class, pre-select it """
from treebeard.forms import movenodeform_factory from oscar.forms.widgets import DatePickerInput from oscar.templatetags.currency_filters import currency PersonGroup = get_model('oscar_ficta', 'PersonGroup') Person = get_model('oscar_ficta', 'Person') LegalAddress = get_model('oscar_ficta', 'LegalAddress') BankAccount = get_model('oscar_ficta', 'BankAccount') Bank = get_model('oscar_ficta', 'Bank') Invoice = get_model('invoice', 'Invoice') GroupForm = movenodeform_factory( PersonGroup, fields=['name', 'description', 'image']) class PersonSearchForm(forms.Form): name = forms.CharField(label=_("Title or name"), required=False) vatin = forms.CharField(label=_("VAT number"), required=False) status = forms.ChoiceField(label=_("State status"), choices=Person.status_choices, required=False) class NewPersonForm(forms.ModelForm): # name = forms.CharField(label=_('Name or title'), max_length=200) # vatin = VATNumberFormField(countries=countries, # label=_("VAT number"), # help_text=_("VAT or tax payer ID")) # reason_code = forms.CharField( # label=_("Code for Reason of registration, e.g. KPP in Russia"), # max_length=9, required=False)