Created
October 7, 2016 15:13
-
-
Save tdsymonds/abdcb395f172a016ed785f59043749e3 to your computer and use it in GitHub Desktop.
Improves the filter_horizontal widget for many to many admin relationship to model using django-mptt and django-parler.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# models.py | |
from mptt.models import MPTTModel, TreeForeignKey | |
from parler.models import TranslatableModel, TranslatedFields | |
from .managers import CategoryManager | |
class Category(MPTTModel, TranslatableModel): | |
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) | |
translations = TranslatedFields( | |
name = models.CharField(_('Name'), max_length=100), | |
slug = models.SlugField(_('slug'), max_length=255, blank=True, allow_unicode=True), | |
meta = {'unique_together': (('language_code', 'slug'),)} | |
) | |
objects = CategoryManager() | |
... | |
class Article(TranslatableModel): | |
categories = models.ManyToManyField('Category', blank=True) | |
... | |
# mptt_m2m_admin.py | |
from django.forms import ModelMultipleChoiceField | |
from django.utils.encoding import smart_text | |
class MPTTMultipleChoiceField(ModelMultipleChoiceField): | |
def label_from_instance(self, obj): | |
level = getattr(obj, getattr(self.queryset.model._meta, 'level_attr', 'level'), 0) | |
return u'%s %s' % ('-'*level, smart_text(obj)) | |
# forms.py | |
from django.contrib.admin.widgets import FilteredSelectMultiple | |
from parler.forms import TranslatableModelForm | |
from .mptt_m2m_admin import MPTTMultipleChoiceField | |
from .models import Article, Category | |
class ArticleForm(TranslatableModelForm): | |
categories = MPTTMultipleChoiceField( | |
Category.objects.all(), | |
widget=FilteredSelectMultiple('Categories', False), | |
required=False | |
) | |
class Meta: | |
model = Article | |
fields = '__all__' | |
# admin.py | |
from django.contrib import admin | |
from parler.admin import TranslatableAdmin | |
from .forms import ArticleForm | |
from .models import Article | |
@admin.register(Article) | |
class ArticleAdmin(TranslatableAdmin): | |
form = ArticleForm |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment