code
stringlengths
1
1.72M
language
stringclasses
1 value
# -*- encoding: utf-8 -*- from models import Streaming from django.contrib import admin admin.site.register(Streaming)
Python
# -*- encoding: utf-8 -*- from django.template import RequestContext from django.shortcuts import render_to_response from django.views.decorators.cache import cache_page from models import Streaming @cache_page(60 * 15) def streaming(request): stream = request.section.stream.get() return render_to_response('streaming/streaming.html', {'stream': stream,}, context_instance=RequestContext(request))
Python
# -*- encoding: utf-8 -*- from django.db import models from django.contrib.sitemaps import ping_google from django.conf import settings from django.utils.translation import get_language from modulo.utils import APPS import mptt from multilingual.translation import Translation from multilingual.languages import get_translated_field_alias from hashlib import sha1 # Always use lazy translations in Django models from django.utils.translation import ugettext_lazy as _ class Section(models.Model): app = models.CharField(_(u'app'), choices=APPS, max_length=31, help_text=_(u"Select the app to use with this section"), default='page') parent = models.ForeignKey('self', null=True, blank=True, related_name='children', help_text=_(u"Select the place to add this section.")) last_modif = models.DateField(_('last modification'), auto_now=True) class Translation(Translation): title = models.CharField(_(u'title'), max_length=255, help_text = _(u'Title of the section')) slug = models.SlugField(_(u'slug'), unique=True, help_text=_(u'The section\'s URL. As to be meanful and contains only ASCII')) menuTop = models.BooleanField(_(u'Main menu'), help_text=_(u"Check if you want to display this section in the main menu ?")) orderTop = models.IntegerField(_(u"Ordre des onglets"), editable = False, default = 0) titleTop = models.CharField(_(u"Main menu title"), max_length=50, blank=True) menuLeft = models.BooleanField(_(u'Left menu'), help_text=_(u"Check if you want to display this section in the secondary menu ?")) orderLeft = models.IntegerField(_(u"Ordre des liens"), editable = False, default = 0) titleLeft = models.CharField(_(u"Left menu title"), max_length=50, blank=True) content = models.TextField(_(u'content'), blank=True) sha1 = models.CharField(u'SHA1 Path ID', max_length=40, editable=False, db_index=True) def save(self): path = Section.objects.get(pk=self.master_id).path(self.slug,self.language_code) self.sha1 = sha1(path).hexdigest() if self.menuTop and self.orderTop == 0: self.orderTop = Section.objects.filter(menuTop__exact=1).count()+1 if self.menuLeft and self.orderLeft == 0: self.orderLeft = Section.objects.filter(menuLeft__exact=1,parent=self.master_id).count()+1 super(Section.Translation, self).save() def delete(self): super(Section.Translation, self).save() menusTop = Section.objects.filter(level__exact=0).filter(menuTop=True).exclude(title__exact='').order_by('orderTop') i = 1 for m in menusTop: m.orderTop = i m.save() i += 1 menusLeft = Section.objects.filter(parent=self.master_id, menuLeft=True).exclude(title__exact='').order_by('orderLeft') i = 1 for m in menusLeft: m.orderLeft = i m.save() i += 1 def path(self, last_slug=None, language_code=None): if not last_slug: last_slug = self.slug if language_code is None: language_code = get_language() parents = self.get_ancestors() items = [] field_alias = get_translated_field_alias('slug', language_code) for a in parents: slug = getattr(a, field_alias, None) if slug is not None: items.append(slug) items.append(last_slug) return u'/%s/' % (u'/'.join(items)) def __unicode__(self): return u'%s' % (self.title) def get_absolute_url(self): return self.path() def save(self, force_insert=False, force_update=False): super(Section, self).save(force_insert, force_update) if not settings.DEBUG: try: ping_google() except Exception: # We could have a variety of HTTP-related exceptions # and we don't care pass class Meta: ordering = ['level'] mptt.register(Section) class Widget(models.Model): section = models.ForeignKey(Section, related_name='widgets', null=True, blank=True, help_text=_(u'Select the host page')) class Translation(Translation): slug = models.SlugField(u'Slug') title = models.CharField(_(u"title"), max_length=100) content = models.TextField(_(u'content')) link = models.CharField(_(u'URL'), max_length=256, help_text=_(u"/slug/ for a local link or http://www.url.com/ for an external link."),blank=True) class Meta: verbose_name = _(u"Fixed block content") verbose_name = _(u"Fixed blocks content") def __unicode__(self): return u'%s' % self.title
Python
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
Python
# -*- coding: utf-8 -*- class ModuleNotInstalled(Exception): def __init__(self, app): self.app = app def __str__(self): return repr("%s app is not installed" % self.app)
Python
# -*- coding: utf-8 -*- from models import Section, Widget from django.contrib import admin from django.utils.translation import ugettext as _ from multilingual.admin import MultilingualModelAdmin class SectionAdmin(MultilingualModelAdmin): list_display = ('title', 'slug', 'app', 'parent', 'menuTop') list_display_links = ('title', 'slug') list_filter = ['app'] ordering = ['tree_id','level'] limit_choices_to = ['app'] search_fields = ['title', 'slug'] use_prepopulated_fields = {'slug': ('title',)} class Media: js = ( "/medias/admin/tinymce/jscripts/tiny_mce/tiny_mce.js", "/medias/js/tiny_conf.js", ) class WidgetAdmin(MultilingualModelAdmin): list_display = ('title', 'slug', 'section', 'link') list_display_links = ('title', 'slug') search_fields = ['title','slug'] use_prepopulated_fields = {'slug': ('title',),} class Media: js = ( "/medias/admin/tinymce/jscripts/tiny_mce/tiny_mce.js", "/medias/js/tiny_conf.js", ) admin.site.register(Section, SectionAdmin) admin.site.register(Widget, WidgetAdmin)
Python
# -*- encoding: utf-8 -*- from hashlib import sha1 from django.conf import settings from django.db import connection from django.http import Http404, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.auth.decorators import user_passes_test from models import Section from exception import ModuleNotInstalled from django.views.decorators.cache import cache_page # sitemap def sitemap(request): sections = Section.objects.exclude(title__exact='').order_by('tree_id', 'level') return render_to_response('page/sitemap.html', {'sections': sections}, context_instance=RequestContext(request)) # Page @cache_page(60 * 15) def page(request): if request.section.app == 'home': page = "page/home.html" else: page = "page/index.html" return render_to_response(page, {'section': request.section}, context_instance=RequestContext(request)) def get_view(app, request, *args, **kwargs): # Default Modulo functions if app == 'sitemap': return sitemap(request, *args, **kwargs) elif app == 'page' or app == 'home': return page(request, *args, **kwargs) # Specific and pluggable modulo app elif app == 'contact': try: from modulo.contact.views import contact return contact(request, *args, **kwargs) except ImportError: pass elif app == 'groups': try: from modulo.groups.views import groups, group if request.object_id is not None: return group(request, *args, **kwargs) else: return groups(request, *args, **kwargs) except ImportError: pass elif app == 'gallery': try: from modulo.gallery.views import galleries, gallery if request.object_id is not None: return gallery(request, *args, **kwargs) else: return galleries(request, *args, **kwargs) except ImportError: pass elif app == 'map': try: from modulo.map.views import map return map(request, *args, **kwargs) except ImportError: pass elif app == 'schedule': try: from modulo.schedule.views import schedule_day return schedule_day(request, *args, **kwargs) except ImportError: pass elif app == 'sponsors': try: from modulo.sponsors.views import sponsors return sponsors(request, *args, **kwargs) except ImportError: pass elif app == 'streaming': try: from modulo.streaming.views import streaming return streaming(request, *args, **kwargs) except ImportError: pass raise ModuleNotInstalled(app) def views_switcher(request, url, *args, **kwargs): # We compute the sha1 hash of the url sha1_id = sha1(url).hexdigest() ## # We are looking in the database if we have one section with this hash cursor = connection.cursor() cursor.execute("SELECT master_id FROM page_section_translation WHERE sha1 = %s", [sha1_id]) row = cursor.fetchone() # If there is no result it doesn't exists if row: request.section = Section.objects.get(pk=row[0]) path = request.section.get_absolute_url() if sha1_id != sha1(path).hexdigest(): # If it is not the good URL for this language # We change to the good one return HttpResponseRedirect(path) return get_view(request.section.app, request, *args, **kwargs) elif request.object_id is None: # Try the section with associated objects info = url.split('/') if len(info) > 3: if info[-2].isdigit() or info[-3].isdigit(): if info[-2].isdigit(): # URL du TYPE : /*/news/1/ id = int(info[-2]) info = info[:-2] info.append('') url = '/'.join(info) else: # URL du TYPE : /*/news/1/Le-succes-d-ionyse/ id = int(info[-3]) info = info[:-3] info.append('') url = '/'.join(info) request.object_id = id return views_switcher(request, url, *args, **kwargs) # If this section doesn't exist for this language, we come back to the home page raise Http404 @user_passes_test(lambda u: u.is_superuser) def changeMenuOrder(request, section_id=None): if section_id is not None: menus = Section.objects.filter(parent=section_id).filter(menuLeft=True).exclude(content__exact='').order_by('orderLeft') i=1 for m in menus: if m.orderLeft != i: m.orderLeft = i m.save() i=i+1 else: menus = Section.objects.filter(level__exact=0).filter(menuTop=True).exclude(content__exact='').order_by('orderTop') i=1 for m in menus: if m.orderTop != i: m.orderTop = i m.save() i=i+1 if request.method == "POST": if request.POST['menu'] == 'top': if section_id is not None: for m in menus: if m.orderLeft != request.POST[str(m.orderLeft)]: m.orderLeft = request.POST[str(m.orderLeft)] m.save() else: for m in menus: if m.orderTop != request.POST[str(m.orderTop)]: m.orderTop = request.POST[str(m.orderTop)] m.save() return HttpResponseRedirect(request.path) return render_to_response('admin/changeMenuOrder.html', {'menus': menus, 'section': section_id}, context_instance=RequestContext(request))
Python
# -*- encoding: utf-8 -*- from django import forms from django.conf import settings from django.core.mail import EmailMessage from django.utils.translation import ugettext_lazy as _ class ContactForm(forms.Form): name = forms.CharField(label=_(u'Nom '), required=False) mail = forms.EmailField(label=_(u'Email *')) subject = forms.CharField(label=_(u'Objet'), required=False) message = forms.CharField(label=_(u"Message *"), widget=forms.Textarea) def send(self, mails=[]): if self.is_valid(): if not mails: mails = [a[1] for a in settings.ADMINS] subject = u'[%s] %s' % (settings.SITE_NAME, self.cleaned_data['subject']) msg = EmailMessage(subject, self.cleaned_data['message'], self.cleaned_data['mail'], mails) try: msg.send() except: return False return True return False
Python
# -*- encoding: utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from modulo.page.models import Section class Contact(models.Model): section = models.ForeignKey(Section, limit_choices_to = {'app': 'contact'}, related_name=u'contacts', help_text=_(u'Sélection de la page contact à laquelle se rattache le destinataire.')) email = models.EmailField(_('email')) def __unicode__(self): return u'%s > %s' % (self.section, self.email)
Python
# -*- encoding: utf-8 -*- from models import Contact from django.contrib import admin from multilingual.admin import MultilingualModelAdmin class ContactAdmin(MultilingualModelAdmin): list_display = ('email','section') search_fields = ['email'] ordering = ['section'] admin.site.register(Contact, ContactAdmin)
Python
# -*- encoding: utf-8 -*- from django.template import RequestContext from django.shortcuts import render_to_response from django.utils.translation import ugettext_lazy as _ from django.views.decorators.cache import cache_page from forms import ContactForm from models import Contact @cache_page(60 * 15) def contact(request): contacts = request.section.contacts.order_by('email') mails = [c.email for c in contacts] message = None contact_form = ContactForm() if request.method == "POST": contact_form = ContactForm(request.POST) if contact_form.is_valid(): contact_form.send(mails) message = _(u'Message envoyé') contact_form = ContactForm() else: message = _(u'Le mail n\'a pu être envoyé') return render_to_response('contact/contact.html', {'form': contact_form, 'message': message,}, context_instance=RequestContext(request))
Python
from django.conf.urls.defaults import * from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/section/change_order/((?P<section_id>\d+)/)?$', 'modulo.page.views.changeMenuOrder'), (r'^admin/sponsors/change_order/$', 'modulo.sponsors.views.changeSponsorOrder'), (r'^admin/map/change_order/$', 'modulo.map.views.changeMapOrder'), (r'^admin/gallery/change_order/$', 'modulo.gallery.views.changeGalleryOrder'), (r'^admin/map/select_map/$', 'django.views.generic.simple.direct_to_template', {'template': 'map/select_form.html'}), (r'^admin/filebrowser/', include('filebrowser.urls')), (r'^admin/', include(admin.site.urls)), (r'^grappelli/', include('grappelli.urls')), (r'^$', 'django.views.generic.simple.redirect_to', {'url': '/accueil/'}), # URL des medias # (r'^medias/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', {'packages': 'django.conf'}), )
Python
# -*- encoding: utf-8 -*- from django.http import Http404 from django.conf import settings from modulo.page.views import views_switcher class PageFallbackMiddleware(object): """ If no urls.py rules took this URL, it could be a page """ def process_response(self, request, response): if response.status_code != 404: return response # No need to check for a rubrique it is a specific module try: request.section = None request.object_id = None return views_switcher(request, request.path_info) # Return the original response if any errors happened. Because this # is a middleware, we can't assume the errors will be caught elsewhere. except Http404: return response except: if settings.DEBUG: raise return response
Python
# -*- encoding: utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from multilingual.translation import TranslationModel from modulo.groups.models import Group from modulo.map.models import Map from modulo.page.models import Section class Schedule(models.Model): CONCERT_DAYS = (('friday', _(u'Vendredi')), ('saturday', _(u'Samedi')), ('sunday', _(u'Dimanche')), ('monday', _(u'Lundi')),) section = models.ForeignKey(Section, related_name="day", limit_choices_to = {'app': 'schedule'}, help_text=_(u"Selection de la rubrique contenant cet horaire.")) day = models.CharField(_(u'Jour'), choices=CONCERT_DAYS, max_length=8) def __unicode__(self): from templatetags.schedule_extras import day return u"%s" % day(self.day) class Meta: verbose_name = _('programme') class Concert(models.Model): PLAYING_TIME = ((30, '30mn'), (60, '1h'), (90, '1h30'), (120, '2h'), (180, '3h'), (210, '3h30'),) day = models.ForeignKey(Schedule, verbose_name=_(u'Jour'), related_name="concerts") scene = models.ForeignKey(Map, related_name="concerts") group = models.ForeignKey(Group, related_name="concerts", null=True, blank=True) starting_time = models.TimeField(_('Horaire de début')) playing_time = models.IntegerField(_('Durée'), choices=PLAYING_TIME, default=60) conf = models.BooleanField(_(u'Conférence ?'), default=False) class Meta: ordering = ['day', 'scene', 'starting_time'] verbose_name = _('concert') class Translation(TranslationModel): name = models.CharField(_(u'nom'), max_length=30, blank=True) description = models.CharField(_(u'description'), max_length=30, blank=True) def get_absolute_url(self): return u"%s" % self.group.get_absolute_url def __unicode__(self): retour = u"%s - %s : "% (self.day, self.scene) if self.name: retour += u"%s - " % self.name if self.group: retour += u"%s - " % self.group retour += u"%s pour %s mn" % (self.starting_time, self.playing_time) return retour
Python
# -*- coding: utf-8 -*- from django import template from modulo.schedule.models import Schedule register = template.Library() @register.filter(name='day') def day(value): """ Affiche le nom du jour """ for days in Schedule.CONCERT_DAYS: if value == days[0]: return days[1]
Python
# -*- encoding: utf-8 -*- from models import Schedule, Concert from django.contrib import admin from multilingual.admin import MultilingualModelAdmin class ConcertAdmin(MultilingualModelAdmin): list_display = ('day', 'scene', 'group', 'starting_time', 'playing_time') list_display_links = ('day', 'starting_time') list_filter = ['day', 'scene'] ordering = ['day','scene', 'starting_time'] limit_choices_to = ['day', 'scene', 'group'] admin.site.register(Concert, ConcertAdmin) admin.site.register(Schedule)
Python
# -*- encoding: utf-8 -*- from django.template import RequestContext from django.shortcuts import render_to_response, get_object_or_404 from django.views.decorators.cache import cache_page import datetime from models import Schedule @cache_page(15 * 60) def schedule_day(request): schedule = request.section.day.get() concerts = schedule.concerts.all()#select_related().order('scene', 'starting_time') stacks = [] current_scene = None current_stack = [] DELAY = {'friday': {'start': 20, 'nb': 8}, 'saturday': {'start': 13, 'nb': 24}, 'sunday': {'start': 13.5, 'nb': 22}, 'monday': {'start': 13.5, 'nb': 22}} for s in concerts: if getattr(current_scene, 'id', None) != s.scene.id: if current_scene is not None: # Changement de scene stacks.append({'scene': current_scene, 'stack': current_stack}) current_scene = s.scene last_schedule = Schedule() last_schedule.starting_time = datetime.time(hour=int(DELAY[concerts[0].day.day]['start']), minute=float(DELAY[concerts[0].day.day]['start'] - int(DELAY[concerts[0].day.day]['start'])) * 60) last_schedule.playing_time = 0 current_stack = [] if last_schedule is not None: # Ce n'est pas le premier concert de la scène time = (datetime.datetime.combine(datetime.date.today(), s.starting_time) - (datetime.datetime.combine(datetime.date.today(), last_schedule.starting_time) + datetime.timedelta(minutes=last_schedule.playing_time))) empty = {'colspan': time.seconds / 1800} # 60 seconds * 30 minutes = 1800 current_stack.append(empty) s.colspan = s.playing_time / 30 # Une case = 30 minutes current_stack.append(s) last_schedule = s stacks.append({'scene': current_scene, 'stack': current_stack}) hours = [] first = True for i in range(DELAY[last_schedule.day.day]['nb']): hour = float(i) / 2 + DELAY[last_schedule.day.day]['start'] - 0.5 if int(hour) == hour and not first: hours.append(int(hour)) else: hours.append('') first = False return render_to_response('schedule/schedule.html', {'day': schedule.day, 'stacks': stacks, 'hours': hours}, context_instance=RequestContext(request))
Python
""" Support for models' internal Translation class. """ ##TODO: this is messy and needs to be cleaned up from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.db.models import signals from django.db.models.base import ModelBase from django.utils.translation import get_language from multilingual.languages import * from multilingual.exceptions import TranslationDoesNotExist from multilingual.fields import TranslationForeignKey from multilingual import manager from multilingual.utils import GLL # To Be Depricated #from multilingual.utils import install_multilingual_modeladmin_new from new import instancemethod def translation_save_translated_fields(instance, **kwargs): """ Save all the translations of instance in post_save signal handler. """ if not hasattr(instance, '_translation_cache'): return for l_id, translation in instance._translation_cache.iteritems(): # set the translation ID just in case the translation was # created while instance was not stored in the DB yet # note: we're using _get_pk_val here even though it is # private, since that's the most reliable way to get the value # on older Django (pk property did not exist yet) translation.master_id = instance._get_pk_val() translation.save() def fill_translation_cache(instance): """ Fill the translation cache using information received in the instance objects as extra fields. You can not do this in post_init because the extra fields are assigned by QuerySet.iterator after model initialization. """ if hasattr(instance, '_translation_cache'): # do not refill the cache return instance._translation_cache = {} for language_code in get_language_code_list(): # see if translation for language_code was in the query field_alias = get_translated_field_alias('code', language_code) if getattr(instance, field_alias, None) is not None: field_names = [f.attname for f in instance._meta.translation_model._meta.fields] # if so, create a translation object and put it in the cache field_data = {} for fname in field_names: field_data[fname] = getattr(instance, get_translated_field_alias(fname, language_code)) translation = instance._meta.translation_model(**field_data) instance._translation_cache[language_code] = translation # In some situations an (existing in the DB) object is loaded # without using the normal QuerySet. In such case fallback to # loading the translations using a separate query. # Unfortunately, this is indistinguishable from the situation when # an object does not have any translations. Oh well, we'll have # to live with this for the time being. if len(instance._translation_cache.keys()) == 0: for translation in instance.translations.all(): instance._translation_cache[translation.language_code] = translation class TranslatedFieldProxy(property): """ This is a proxy field to be set onto the main class to proxy to a translation. """ def __init__(self, field_name, alias, field, language_code=None, fallback=False): self.field_name = field_name self.field = field self.admin_order_field = alias self._language_code = language_code self.fallback = fallback @property def language_code(self): """ If _language_code is None we are the _current field, so we use the currently used language for lookups. """ if self._language_code: return self._language_code return get_language() def __get__(self, obj, objtype=None): if obj is None: return self return getattr(obj, 'get_' + self.field_name)(self.language_code, self.fallback) def __set__(self, obj, value): language_code = self.language_code return getattr(obj, 'set_' + self.field_name)(value, self.language_code) short_description = property(lambda self: self.field.short_description) def getter_generator(field_name, short_description): """ Generate get_'field name' method for field field_name. """ def get_translation_field(cls, language_code=None, fallback=False): try: return getattr(cls.get_translation(language_code, fallback=fallback), field_name) except TranslationDoesNotExist: return None get_translation_field.short_description = short_description return get_translation_field def setter_generator(field_name): """ Generate set_'field name' method for field field_name. """ def set_translation_field(cls, value, language_code=None): setattr(cls.get_translation(language_code, True), field_name, value) set_translation_field.short_description = "set " + field_name return set_translation_field def get_translation(cls, language_code, create_if_necessary=False, fallback=False): """ Get a translation instance for the given `language_id_or_code`. If the translation does not exist: 1. if `create_if_necessary` is True, this function will create one 2. otherwise, if `fallback` is True, this function will search the list of languages looking for the first existing translation 3. if all of the above fails to find a translation, raise the TranslationDoesNotExist exception """ # fill the cache if necessary cls.fill_translation_cache() if language_code is None: language_code = getattr(cls, '_default_language', None) if language_code is None: language_code = get_default_language() force = False if GLL.is_active: language_code = GLL.language_code force = True if language_code in cls._translation_cache: return cls._translation_cache.get(language_code, None) if create_if_necessary: new_translation = cls._meta.translation_model(master=cls, language_code=language_code) cls._translation_cache[language_code] = new_translation return new_translation # only fall backif we're not in 'force' mode (GLL) elif (not force) and fallback: for fb_lang_code in get_fallbacks(language_code): trans = cls._translation_cache.get(fb_lang_code, None) if trans: return trans raise TranslationDoesNotExist(language_code) class TranslationModel(object): """ A superclass for translatablemodel.Translation inner classes. """ def contribute_to_class(cls, main_cls, name): """ Handle the inner 'Translation' class. """ # delay the creation of the *Translation until the master model is # fully created signals.class_prepared.connect(cls.finish_multilingual_class, sender=main_cls, weak=False) # connect the post_save signal on master class to a handler # that saves translations signals.post_save.connect(translation_save_translated_fields, sender=main_cls) contribute_to_class = classmethod(contribute_to_class) def create_translation_attrs(cls, main_cls): """ Creates get_'field name'(language_code) and set_'field name'(language_id) methods for all the translation fields. Adds the 'field name' properties too. Returns the translated_fields hash used in field lookups, see multilingual.query. It maps field names to (field, language_id) tuples. """ translated_fields = {} for fname, field in cls.__dict__.items(): if isinstance(field, models.fields.Field): translated_fields[fname] = (field, None) # add get_'fname' and set_'fname' methods to main_cls getter = getter_generator(fname, getattr(field, 'verbose_name', fname)) setattr(main_cls, 'get_' + fname, getter) setter = setter_generator(fname) setattr(main_cls, 'set_' + fname, setter) # add the 'fname' proxy property that allows reads # from and writing to the appropriate translation setattr(main_cls, fname, TranslatedFieldProxy(fname, fname, field, fallback=True)) # add the 'fname'_any fallback setattr(main_cls, fname + FALLBACK_FIELD_SUFFIX, TranslatedFieldProxy(fname, fname, field, fallback=True)) # create the 'fname'_'language_code' proxy properties for language_code in get_language_code_list(): fname_lng = fname + '_' + language_code.replace('-', '_') translated_fields[fname_lng] = (field, language_code) setattr(main_cls, fname_lng, TranslatedFieldProxy(fname, fname_lng, field, language_code)) # add the 'fname'_'language_code'_any fallback proxy setattr(main_cls, fname_lng + FALLBACK_FIELD_SUFFIX, TranslatedFieldProxy(fname, fname_lng, field, language_code, fallback=True)) fname_current = fname + '_current' setattr(main_cls, fname_current, TranslatedFieldProxy(fname, fname_current, field, None)) setattr(main_cls, fname_current + FALLBACK_FIELD_SUFFIX, TranslatedFieldProxy(fname, fname_current, field, None, fallback=True)) return translated_fields create_translation_attrs = classmethod(create_translation_attrs) def get_unique_fields(cls): """ Return a list of fields with "unique" attribute, which needs to be augmented by the language. """ unique_fields = [] for fname, field in cls.__dict__.items(): if isinstance(field, models.fields.Field): if getattr(field,'unique',False): try: field.unique = False except AttributeError: # newer Django defines unique as a property # that uses _unique to store data. We're # jumping over the fence by setting _unique, # so this sucks, but this happens early enough # to be safe. field._unique = False unique_fields.append(fname) return unique_fields get_unique_fields = classmethod(get_unique_fields) def finish_multilingual_class(cls, *args, **kwargs): """ Create a model with translations of a multilingual class. """ main_cls = kwargs['sender'] translation_model_name = main_cls.__name__ + "Translation" # create the model with all the translatable fields unique = [('language_code', 'master')] for f in cls.get_unique_fields(): unique.append(('language_code',f)) class TransMeta: pass try: meta = cls.Meta except AttributeError: meta = TransMeta meta.ordering = ('language_code',) meta.unique_together = tuple(unique) meta.app_label = main_cls._meta.app_label if not hasattr(meta, 'db_table'): meta.db_table = main_cls._meta.db_table + '_translation' trans_attrs = cls.__dict__.copy() trans_attrs['Meta'] = meta # TODO: increase the length of this field, but to what??? trans_attrs['language_code'] = models.CharField(max_length=15, blank=True, choices=get_language_choices(), db_index=True) related_name = getattr(meta, 'related_name', 'translations') if hasattr(meta, 'related_name'): delattr(meta, 'related_name') edit_inline = True trans_attrs['master'] = TranslationForeignKey(main_cls, blank=False, null=False, related_name=related_name,) trans_attrs['__str__'] = lambda self: ("%s object, language_code=%s" % (translation_model_name, self.language_code)) trans_model = ModelBase(translation_model_name, (models.Model,), trans_attrs) trans_model._meta.translated_fields = cls.create_translation_attrs(main_cls) trans_model._meta.related_name = related_name _old_init_name_map = main_cls._meta.__class__.init_name_map def init_name_map(self): cache = _old_init_name_map(self) for name, field_and_lang_id in trans_model._meta.translated_fields.items(): #import sys; sys.stderr.write('TM %r\n' % trans_model) cache[name] = (field_and_lang_id[0], trans_model, True, False) return cache main_cls._meta.init_name_map = instancemethod(init_name_map, main_cls._meta, main_cls._meta.__class__) main_cls._meta.translation_model = trans_model main_cls._meta.force_language = None main_cls.Translation = trans_model main_cls.get_translation = get_translation main_cls.fill_translation_cache = fill_translation_cache # Note: don't fill the translation cache in post_init, as all # the extra values selected by QAddTranslationData will be # assigned AFTER init() # signals.post_init.connect(fill_translation_cache, # sender=main_cls) finish_multilingual_class = classmethod(finish_multilingual_class) # The following will be deprecated: Translation = TranslationModel def install_translation_library(): # modify ModelBase.__new__ so that it understands how to handle the # 'Translation' inner class if getattr(ModelBase, '_multilingual_installed', False): # don't install it twice return _old_new = ModelBase.__new__ def multilingual_modelbase_new(cls, name, bases, attrs): if 'Translation' in attrs: if not issubclass(attrs['Translation'], Translation): raise ValueError, ("%s.Translation must be a subclass " + " of multilingual.Translation.") % (name,) # Make sure that if the class specifies objects then it is # a subclass of our Manager. # # Don't check other managers since someone might want to # have a non-multilingual manager, but assigning a # non-multilingual manager to objects would be a common # mistake. if ('objects' in attrs) and (not isinstance(attrs['objects'], manager.Manager)): raise ValueError, ("Model %s specifies translations, " + "so its 'objects' manager must be " + "a subclass of multilingual.Manager.") % (name,) # Change the default manager to multilingual.Manager. if not 'objects' in attrs: attrs['objects'] = manager.Manager() return _old_new(cls, name, bases, attrs) ModelBase.__new__ = staticmethod(multilingual_modelbase_new) ModelBase._multilingual_installed = True # To Be Deprecated #install_multilingual_modeladmin_new() # install the library install_translation_library()
Python
""" Django-multilingual: a QuerySet subclass for models with translatable fields. This file contains the implementation for QSRF Django. """ import datetime from copy import deepcopy from django.core.exceptions import FieldError from django.db import connection from django.db.models.fields import FieldDoesNotExist from django.db.models.query import QuerySet, Q from django.db.models.sql.query import Query from django.db import connections, DEFAULT_DB_ALIAS from django.db.models.sql.datastructures import ( EmptyResultSet, Empty, MultiJoin) from django.db.models.sql.constants import * from django.db.models.sql.where import WhereNode, EverythingNode, AND, OR try: # handle internal API changes in Django rev. 9700 from django.db.models.sql.where import Constraint def constraint_tuple(alias, col, field, lookup_type, value): return (Constraint(alias, col, field), lookup_type, value) except ImportError: # backwards compatibility, for Django versions 1.0 to rev. 9699 def constraint_tuple(alias, col, field, lookup_type, value): return (alias, col, field, lookup_type, value) from multilingual.languages import ( get_translation_table_alias, get_language_code_list, get_default_language, get_translated_field_alias) from compiler import MultilingualSQLCompiler __ALL__ = ['MultilingualModelQuerySet'] class MultilingualQuery(Query): def __init__(self, model, where=WhereNode): self.extra_join = {} self.include_translation_data = True extra_select = {} super(MultilingualQuery, self).__init__(model, where=where) opts = self.model._meta qn = self.get_compiler(DEFAULT_DB_ALIAS).quote_name_unless_alias qn2 = self.get_compiler(DEFAULT_DB_ALIAS).connection.ops.quote_name master_table_name = opts.db_table translation_opts = opts.translation_model._meta trans_table_name = translation_opts.db_table if hasattr(opts, 'translation_model'): master_table_name = opts.db_table for language_code in get_language_code_list(): for fname in [f.attname for f in translation_opts.fields]: table_alias = get_translation_table_alias(trans_table_name, language_code) field_alias = get_translated_field_alias(fname, language_code) extra_select[field_alias] = qn2(table_alias) + '.' + qn2(fname) self.add_extra(extra_select, None, None, None, None, None) self._trans_extra_select_count = len(self.extra_select) def clone(self, klass=None, **kwargs): defaults = { 'extra_join': self.extra_join, 'include_translation_data': self.include_translation_data, } defaults.update(kwargs) return super(MultilingualQuery, self).clone(klass=klass, **defaults) def add_filter(self, filter_expr, connector=AND, negate=False, trim=False, can_reuse=None, process_extras=True): """ Copied from add_filter to generate WHERES for translation fields. """ arg, value = filter_expr parts = arg.split(LOOKUP_SEP) if not parts: raise FieldError("Cannot parse keyword query %r" % arg) # Work out the lookup type and remove it from 'parts', if necessary. if len(parts) == 1 or parts[-1] not in self.query_terms: lookup_type = 'exact' else: lookup_type = parts.pop() # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all # uses of None as a query value. if value is None: if lookup_type != 'exact': raise ValueError("Cannot use None as a query value") lookup_type = 'isnull' value = True elif (value == '' and lookup_type == 'exact' and self.get_compiler(DEFAULT_DB_ALIAS).connection.features.interprets_empty_strings_as_nulls): lookup_type = 'isnull' value = True elif callable(value): value = value() opts = self.get_meta() alias = self.get_initial_alias() allow_many = trim or not negate try: field, target, opts, join_list, last, extra_filters = self.setup_joins( parts, opts, alias, True, allow_many, can_reuse=can_reuse, negate=negate, process_extras=process_extras) except MultiJoin, e: self.split_exclude(filter_expr, LOOKUP_SEP.join(parts[:e.level]), can_reuse) return #NOTE: here comes Django Multilingual if hasattr(opts, 'translation_model'): field_name = parts[-1] if field_name == 'pk': field_name = opts.pk.name translation_opts = opts.translation_model._meta if field_name in translation_opts.translated_fields.keys(): field, model, direct, m2m = opts.get_field_by_name(field_name) if model == opts.translation_model: language_code = translation_opts.translated_fields[field_name][1] if language_code is None: language_code = get_default_language() master_table_name = opts.db_table trans_table_alias = get_translation_table_alias( model._meta.db_table, language_code) new_table = (master_table_name + "__" + trans_table_alias) self.where.add(constraint_tuple(new_table, field.column, field, lookup_type, value), connector) return final = len(join_list) penultimate = last.pop() if penultimate == final: penultimate = last.pop() if trim and len(join_list) > 1: extra = join_list[penultimate:] join_list = join_list[:penultimate] final = penultimate penultimate = last.pop() col = self.alias_map[extra[0]][LHS_JOIN_COL] for alias in extra: self.unref_alias(alias) else: col = target.column alias = join_list[-1] while final > 1: # An optimization: if the final join is against the same column as # we are comparing against, we can go back one step in the join # chain and compare against the lhs of the join instead (and then # repeat the optimization). The result, potentially, involves less # table joins. join = self.alias_map[alias] if col != join[RHS_JOIN_COL]: break self.unref_alias(alias) alias = join[LHS_ALIAS] col = join[LHS_JOIN_COL] join_list = join_list[:-1] final -= 1 if final == penultimate: penultimate = last.pop() if (lookup_type == 'isnull' and value is True and not negate and final > 1): # If the comparison is against NULL, we need to use a left outer # join when connecting to the previous model. We make that # adjustment here. We don't do this unless needed as it's less # efficient at the database level. self.promote_alias(join_list[penultimate]) if connector == OR: # Some joins may need to be promoted when adding a new filter to a # disjunction. We walk the list of new joins and where it diverges # from any previous joins (ref count is 1 in the table list), we # make the new additions (and any existing ones not used in the new # join list) an outer join. join_it = iter(join_list) table_it = iter(self.tables) join_it.next(), table_it.next() table_promote = False join_promote = False for join in join_it: table = table_it.next() if join == table and self.alias_refcount[join] > 1: continue join_promote = self.promote_alias(join) if table != join: table_promote = self.promote_alias(table) break self.promote_alias_chain(join_it, join_promote) self.promote_alias_chain(table_it, table_promote) self.where.add(constraint_tuple(alias, col, field, lookup_type, value), connector) if negate: self.promote_alias_chain(join_list) if lookup_type != 'isnull': if final > 1: for alias in join_list: if self.alias_map[alias][JOIN_TYPE] == self.LOUTER: j_col = self.alias_map[alias][RHS_JOIN_COL] entry = self.where_class() entry.add(constraint_tuple(alias, j_col, None, 'isnull', True), AND) entry.negate() self.where.add(entry, AND) break elif not (lookup_type == 'in' and not value) and field.null: # Leaky abstraction artifact: We have to specifically # exclude the "foo__in=[]" case from this handling, because # it's short-circuited in the Where class. entry = self.where_class() entry.add(constraint_tuple(alias, col, None, 'isnull', True), AND) entry.negate() self.where.add(entry, AND) if can_reuse is not None: can_reuse.update(join_list) if process_extras: for filter in extra_filters: self.add_filter(filter, negate=negate, can_reuse=can_reuse, process_extras=False) def _setup_joins_with_translation(self, names, opts, alias, dupe_multis, allow_many=True, allow_explicit_fk=False, can_reuse=None, negate=False, process_extras=True): """ This is based on a full copy of Query.setup_joins because currently I see no way to handle it differently. TO DO: there might actually be a way, by splitting a single multi-name setup_joins call into separate calls. Check it. -- marcin@elksoft.pl Compute the necessary table joins for the passage through the fields given in 'names'. 'opts' is the Options class for the current model (which gives the table we are joining to), 'alias' is the alias for the table we are joining to. If dupe_multis is True, any many-to-many or many-to-one joins will always create a new alias (necessary for disjunctive filters). Returns the final field involved in the join, the target database column (used for any 'where' constraint), the final 'opts' value and the list of tables joined. """ joins = [alias] last = [0] dupe_set = set() exclusions = set() extra_filters = [] for pos, name in enumerate(names): try: exclusions.add(int_alias) except NameError: pass exclusions.add(alias) last.append(len(joins)) if name == 'pk': name = opts.pk.name try: field, model, direct, m2m = opts.get_field_by_name(name) except FieldDoesNotExist: for f in opts.fields: if allow_explicit_fk and name == f.attname: # XXX: A hack to allow foo_id to work in values() for # backwards compatibility purposes. If we dropped that # feature, this could be removed. field, model, direct, m2m = opts.get_field_by_name(f.name) break else: names = opts.get_all_field_names() + self.aggregate_select.keys() raise FieldError("Cannot resolve keyword %r into field. " "Choices are: %s" % (name, ", ".join(names))) if not allow_many and (m2m or not direct): for alias in joins: self.unref_alias(alias) raise MultiJoin(pos + 1) #=================================================================== # Django Multilingual NG Specific Code START #=================================================================== if hasattr(opts, 'translation_model'): translation_opts = opts.translation_model._meta if model == opts.translation_model: language_code = translation_opts.translated_fields[name][1] if language_code is None: language_code = get_default_language() #TODO: check alias master_table_name = opts.db_table trans_table_alias = get_translation_table_alias( model._meta.db_table, language_code) new_table = (master_table_name + "__" + trans_table_alias) qn = self.get_compiler(DEFAULT_DB_ALIAS).quote_name_unless_alias qn2 = self.get_compiler(DEFAULT_DB_ALIAS).connection.ops.quote_name trans_join = ("JOIN %s AS %s ON ((%s.master_id = %s.%s) AND (%s.language_code = '%s'))" % (qn2(model._meta.db_table), qn2(new_table), qn2(new_table), qn(master_table_name), qn2(model._meta.pk.column), qn2(new_table), language_code)) self.extra_join[new_table] = trans_join target = field continue #=================================================================== # Django Multilingual NG Specific Code END #=================================================================== elif model: # The field lives on a base class of the current model. # Skip the chain of proxy to the concrete proxied model proxied_model = get_proxied_model(opts) for int_model in opts.get_base_chain(model): if int_model is proxied_model: opts = int_model._meta else: lhs_col = opts.parents[int_model].column dedupe = lhs_col in opts.duplicate_targets if dedupe: exclusions.update(self.dupe_avoidance.get( (id(opts), lhs_col), ())) dupe_set.add((opts, lhs_col)) opts = int_model._meta alias = self.join((alias, opts.db_table, lhs_col, opts.pk.column), exclusions=exclusions) joins.append(alias) exclusions.add(alias) for (dupe_opts, dupe_col) in dupe_set: self.update_dupe_avoidance(dupe_opts, dupe_col, alias) cached_data = opts._join_cache.get(name) orig_opts = opts dupe_col = direct and field.column or field.field.column dedupe = dupe_col in opts.duplicate_targets if dupe_set or dedupe: if dedupe: dupe_set.add((opts, dupe_col)) exclusions.update(self.dupe_avoidance.get((id(opts), dupe_col), ())) if process_extras and hasattr(field, 'extra_filters'): extra_filters.extend(field.extra_filters(names, pos, negate)) if direct: if m2m: # Many-to-many field defined on the current model. if cached_data: (table1, from_col1, to_col1, table2, from_col2, to_col2, opts, target) = cached_data else: table1 = field.m2m_db_table() from_col1 = opts.pk.column to_col1 = field.m2m_column_name() opts = field.rel.to._meta table2 = opts.db_table from_col2 = field.m2m_reverse_name() to_col2 = opts.pk.column target = opts.pk orig_opts._join_cache[name] = (table1, from_col1, to_col1, table2, from_col2, to_col2, opts, target) int_alias = self.join((alias, table1, from_col1, to_col1), dupe_multis, exclusions, nullable=True, reuse=can_reuse) if int_alias == table2 and from_col2 == to_col2: joins.append(int_alias) alias = int_alias else: alias = self.join( (int_alias, table2, from_col2, to_col2), dupe_multis, exclusions, nullable=True, reuse=can_reuse) joins.extend([int_alias, alias]) elif field.rel: # One-to-one or many-to-one field if cached_data: (table, from_col, to_col, opts, target) = cached_data else: opts = field.rel.to._meta target = field.rel.get_related_field() table = opts.db_table from_col = field.column to_col = target.column orig_opts._join_cache[name] = (table, from_col, to_col, opts, target) alias = self.join((alias, table, from_col, to_col), exclusions=exclusions, nullable=field.null) joins.append(alias) else: # Non-relation fields. target = field break else: orig_field = field field = field.field if m2m: # Many-to-many field defined on the target model. if cached_data: (table1, from_col1, to_col1, table2, from_col2, to_col2, opts, target) = cached_data else: table1 = field.m2m_db_table() from_col1 = opts.pk.column to_col1 = field.m2m_reverse_name() opts = orig_field.opts table2 = opts.db_table from_col2 = field.m2m_column_name() to_col2 = opts.pk.column target = opts.pk orig_opts._join_cache[name] = (table1, from_col1, to_col1, table2, from_col2, to_col2, opts, target) int_alias = self.join((alias, table1, from_col1, to_col1), dupe_multis, exclusions, nullable=True, reuse=can_reuse) alias = self.join((int_alias, table2, from_col2, to_col2), dupe_multis, exclusions, nullable=True, reuse=can_reuse) joins.extend([int_alias, alias]) else: # One-to-many field (ForeignKey defined on the target model) if cached_data: (table, from_col, to_col, opts, target) = cached_data else: local_field = opts.get_field_by_name( field.rel.field_name)[0] opts = orig_field.opts table = opts.db_table from_col = local_field.column to_col = field.column target = opts.pk orig_opts._join_cache[name] = (table, from_col, to_col, opts, target) alias = self.join((alias, table, from_col, to_col), dupe_multis, exclusions, nullable=True, reuse=can_reuse) joins.append(alias) for (dupe_opts, dupe_col) in dupe_set: try: self.update_dupe_avoidance(dupe_opts, dupe_col, int_alias) except NameError: self.update_dupe_avoidance(dupe_opts, dupe_col, alias) if pos != len(names) - 1: if pos == len(names) - 2: raise FieldError("Join on field %r not permitted. Did you misspell %r for the lookup type?" % (name, names[pos + 1])) else: raise FieldError("Join on field %r not permitted." % name) return field, target, opts, joins, last, extra_filters def setup_joins(self, names, opts, alias, dupe_multis, allow_many=True, allow_explicit_fk=False, can_reuse=None, negate=False, process_extras=True): if not self.include_translation_data: return super(MultilingualQuery, self).setup_joins(names, opts, alias, dupe_multis, allow_many, allow_explicit_fk, can_reuse, negate, process_extras) else: return self._setup_joins_with_translation(names, opts, alias, dupe_multis, allow_many, allow_explicit_fk, can_reuse, negate, process_extras) def get_count(self, using=None): # optimize for the common special case: count without any # filters if ((not (self.select or self.where)) and self.include_translation_data): obj = self.clone(extra_select = {}, extra_join = {}, include_translation_data = False) return obj.get_count(using) else: return super(MultilingualQuery, self).get_count(using) def get_compiler(self, using=None, connection=None): if using is None and connection is None: raise ValueError("Need either using or connection") if using: connection = connections[using] return MultilingualSQLCompiler(self, connection, using) class MultilingualModelQuerySet(QuerySet): """ A specialized QuerySet that knows how to handle translatable fields in ordering and filtering methods. """ def __init__(self, model=None, query=None, using=None): query = query or MultilingualQuery(model) super(MultilingualModelQuerySet, self).__init__(model, query, using) self._field_name_cache = None def __deepcopy__(self, memo): """ Deep copy of a QuerySet doesn't populate the cache """ obj_dict = deepcopy(self.__dict__, memo) obj_dict['_iter'] = None #======================================================================= # Django Multilingual NG Specific Code START #======================================================================= obj = self.__class__(self.model) # add self.model as first argument #======================================================================= # Django Multilingual NG Specific Code END #======================================================================= obj.__dict__.update(obj_dict) return obj def for_language(self, language_code): """ Set the default language for all objects returned with this query. """ clone = self._clone() clone._default_language = language_code return clone def iterator(self): """ Add the default language information to all returned objects. """ default_language = getattr(self, '_default_language', None) for obj in super(MultilingualModelQuerySet, self).iterator(): obj._default_language = default_language yield obj def _clone(self, klass=None, **kwargs): """ Override _clone to preserve additional information needed by MultilingualModelQuerySet. """ clone = super(MultilingualModelQuerySet, self)._clone(klass, **kwargs) clone._default_language = getattr(self, '_default_language', None) return clone def order_by(self, *field_names): if hasattr(self.model._meta, 'translation_model'): trans_opts = self.model._meta.translation_model._meta new_field_names = [] for field_name in field_names: prefix = '' if field_name[0] == '-': prefix = '-' field_name = field_name[1:] field_and_lang = trans_opts.translated_fields.get(field_name) if field_and_lang: field, language_code = field_and_lang if language_code is None: language_code = 'fr' real_name = get_translated_field_alias(field.attname, language_code) new_field_names.append(prefix + real_name) else: new_field_names.append(prefix + field_name) return super(MultilingualModelQuerySet, self).extra(order_by=new_field_names) else: return super(MultilingualModelQuerySet, self).order_by(*field_names) def _get_all_field_names(self): if self._field_name_cache is None: self._field_name_cache = self.model._meta.get_all_field_names() + ['pk'] return self._field_name_cache def values(self, *fields): for field in fields: if field not in self._get_all_field_names(): raise NotImplementedError("Multilingual fields cannot be queried using queryset.values(...)") return super(MultilingualModelQuerySet, self).values(*fields) def values_list(self, *fields, **kwargs): for field in fields: if field not in self._get_all_field_names(): raise NotImplementedError("Multilingual fields cannot be queried using queryset.values(...)") return super(MultilingualModelQuerySet, self).values(*fields, **kwargs)
Python
""" Django-multilingual: a QuerySet subclass for models with translatable fields. This file contains the implementation for QSRF Django. Huge thanks to hubscher.remy for writing this! """ from django.db.models.sql.compiler import SQLCompiler from multilingual.languages import ( get_translation_table_alias, get_language_code_list, get_default_language, get_translated_field_alias) __ALL__ = ['MultilingualSQLCompiler'] class MultilingualSQLCompiler(SQLCompiler): def pre_sql_setup(self): """ Adds the JOINS and SELECTS for fetching multilingual data. """ super(MultilingualSQLCompiler, self).pre_sql_setup() if not self.query.include_translation_data: return opts = self.query.model._meta qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name if hasattr(opts, 'translation_model'): master_table_name = self.query.join((None, opts.db_table, None, None)) translation_opts = opts.translation_model._meta trans_table_name = translation_opts.db_table for language_code in get_language_code_list(): table_alias = get_translation_table_alias(trans_table_name, language_code) trans_join = ("LEFT JOIN %s AS %s ON ((%s.master_id = %s.%s) AND (%s.language_code = '%s'))" % (qn2(translation_opts.db_table), qn2(table_alias), qn2(table_alias), qn(master_table_name), qn2(opts.pk.column), qn2(table_alias), language_code)) self.query.extra_join[table_alias] = trans_join def get_from_clause(self): """ Add the JOINS for related multilingual fields filtering. """ result = super(MultilingualSQLCompiler, self).get_from_clause() if not self.query.include_translation_data: return result from_ = result[0] for join in self.query.extra_join.values(): from_.append(join) return (from_, result[1])
Python
""" Django-multilingual: language-related settings and functions. """ # Note: this file did become a mess and will have to be refactored # after the configuration changes get in place. #retrieve language settings from settings.py from multilingual import settings from django.utils.translation import ugettext_lazy as _ from multilingual.exceptions import LanguageDoesNotExist try: from threading import local except ImportError: from django.utils._threading_local import local thread_locals = local() def get_language_count(): return len(settings.LANGUAGES) def get_language_name(language_code): return settings.LANG_DICT[language_code] def get_language_bidi(language_code): return language_code in settings.LANGUAGES_BIDI def get_language_code_list(): return settings.LANG_DICT.keys() def get_language_choices(): return settings.LANGUAGES def set_default_language(language_code): """ Set the default language for the whole translation mechanism. """ thread_locals.DEFAULT_LANGUAGE = language_code def get_default_language(): """ Return the language code set by set_default_language. """ return getattr(thread_locals, 'DEFAULT_LANGUAGE', settings.DEFAULT_LANGUAGE) get_default_language_code = get_default_language def _to_db_identifier(name): """ Convert name to something that is usable as a field name or table alias in SQL. For the time being assume that the only possible problem with name is the presence of dashes. """ return name.replace('-', '_') def get_translation_table_alias(translation_table_name, language_code): """ Return an alias for the translation table for a given language_code. Used in SQL queries. """ return (translation_table_name + '_' + _to_db_identifier(language_code)) def get_language_idx(language_code): return get_language_code_list().index(language_code) def get_translated_field_alias(field_name, language_code): """ Return an alias for field_name field for a given language_code. Used in SQL queries. """ return ('_trans_' + field_name + '_' + _to_db_identifier(language_code)) def get_fallbacks(language_code): fallbacks = settings.FALLBACK_LANGUAGES.get(language_code, []) if len(language_code) != 2 and settings.IMPLICIT_FALLBACK: if not language_code[:2] in fallbacks: fallbacks.insert(0, language_code[:2]) if language_code is not None and language_code not in fallbacks: fallbacks.insert(0, language_code) return fallbacks FALLBACK_FIELD_SUFFIX = '_any'
Python
from multilingual.languages import get_language_code_list, get_default_language_code from multilingual.settings import LANG_DICT from django.conf import settings def multilingual(request): """ Returns context variables containing information about available languages. """ codes = sorted(get_language_code_list()) return {'LANGUAGE_CODES': codes, 'LANGUAGE_CODES_AND_NAMES': [(c, LANG_DICT.get(c, c)) for c in codes], 'DEFAULT_LANGUAGE_CODE': get_default_language_code(), 'ADMIN_MEDIA_URL': settings.ADMIN_MEDIA_PREFIX}
Python
""" Multilingual model support. This code is put in multilingual.models to make Django execute it during application initialization. TO DO: remove it. Right now multilingual must be imported directly into any file that defines translatable models, so it will be installed anyway. This module is here only to make it easier to upgrade from versions that did not require TranslatableModel.Translation classes to subclass multilingual.Translation to versions that do. """ from translation import install_translation_library install_translation_library()
Python
from django.db import models from django.contrib.sites.models import Site from django.utils.translation import ugettext_lazy as _ from multilingual.translation import Translation as TranslationBase from multilingual.exceptions import TranslationDoesNotExist from multilingual.manager import MultilingualManager class MultilingualFlatPage(models.Model): # non-translatable fields first url = models.CharField(_('URL'), max_length=100, db_index=True) enable_comments = models.BooleanField(_('enable comments')) template_name = models.CharField(_('template name'), max_length=70, blank=True, help_text=_("Example: 'flatpages/contact_page.html'. If this isn't provided, the system will use 'flatpages/default.html'.")) registration_required = models.BooleanField(_('registration required'), help_text=_("If this is checked, only logged-in users will be able to view the page.")) sites = models.ManyToManyField(Site) objects = MultilingualManager() # And now the translatable fields class Translation(TranslationBase): """ The definition of translation model. The multilingual machinery will automatically add these to the Category class: * get_title(language_id=None) * set_title(value, language_id=None) * get_content(language_id=None) * set_content(value, language_id=None) * title and content properties using the methods above """ title = models.CharField(_('title'), max_length=200) content = models.TextField(_('content'), blank=True) class Meta: db_table = 'multilingual_flatpage' verbose_name = _('multilingual flat page') verbose_name_plural = _('multilingual flat pages') ordering = ('url',) def __unicode__(self): # note that you can use name and description fields as usual try: return u"%s -- %s" % (self.url, self.title) except TranslationDoesNotExist: return u"-not-available-" def get_absolute_url(self): return self.url
Python
from django.conf.urls.defaults import * urlpatterns = patterns('multilingual.flatpages.views', (r'^(?P<url>.*)$', 'multilingual_flatpage'), )
Python
from multilingual.flatpages.views import multilingual_flatpage from django.http import Http404 from django.conf import settings class FlatpageFallbackMiddleware(object): def process_response(self, request, response): if response.status_code != 404: return response # No need to check for a flatpage for non-404 responses. try: return multilingual_flatpage(request, request.path_info) # Return the original response if any errors happened. Because this # is a middleware, we can't assume the errors will be caught elsewhere. except Http404: return response except: if settings.DEBUG: raise return response
Python
from django import forms from django.contrib import admin from multilingual.flatpages.models import MultilingualFlatPage from django.utils.translation import ugettext_lazy as _ from multilingual.admin import MultilingualModelAdmin, MultilingualModelAdminForm class MultilingualFlatpageForm(MultilingualModelAdminForm): url = forms.RegexField(label=_("URL"), max_length=100, regex=r'^[-\w/]+$', help_text = _("Example: '/about/contact/'. Make sure to have leading" " and trailing slashes."), error_message = _("This value must contain only letters, numbers," " underscores, dashes or slashes.")) class Meta: model = MultilingualFlatPage class MultilingualFlatPageAdmin(MultilingualModelAdmin): form = MultilingualFlatpageForm use_fieldsets = ( (None, {'fields': ('title', 'url', 'sites', 'content')}), (_('Advanced options'), {'classes': ('collapse',), 'fields': ('enable_comments', 'registration_required', 'template_name')}), ) list_display = ('url', 'title') list_filter = ('sites', 'enable_comments', 'registration_required') search_fields = ('url', 'title') admin.site.register(MultilingualFlatPage, MultilingualFlatPageAdmin)
Python
from multilingual.flatpages.models import MultilingualFlatPage from django.template import loader, RequestContext from django.shortcuts import get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.conf import settings from django.core.xheaders import populate_xheaders from django.utils.safestring import mark_safe from django.utils.translation import get_language import multilingual DEFAULT_TEMPLATE = 'flatpages/default.html' def multilingual_flatpage(request, url): """ Multilingual flat page view. Models: `multilingual.flatpages.models` Templates: Uses the template defined by the ``template_name`` field, or `flatpages/default.html` if template_name is not defined. Context: flatpage `flatpages.flatpages` object """ if not url.endswith('/') and settings.APPEND_SLASH: return HttpResponseRedirect("%s/" % request.path) if not url.startswith('/'): url = "/" + url f = get_object_or_404(MultilingualFlatPage, url__exact=url, sites__id__exact=settings.SITE_ID) # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and not request.user.is_authenticated(): from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) # Serve the content in the language defined by the Django translation module # if possible else serve the default language. f._default_language = get_language() if f.template_name: t = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: t = loader.get_template(DEFAULT_TEMPLATE) # To avoid having to always use the "|safe" filter in flatpage templates, # mark the title and content as already safe (since they are raw HTML # content in the first place). f.title = mark_safe(f.title) f.content = mark_safe(f.content) c = RequestContext(request, { 'flatpage': f, }) response = HttpResponse(t.render(c)) populate_xheaders(request, response, MultilingualFlatPage, f.id) return response
Python
from django.db import models class TranslationForeignKey(models.ForeignKey): """ """ def south_field_triple(self): from south.modelsinspector import introspector field_class = "django.db.models.fields.related.ForeignKey" args, kwargs = introspector(self) return (field_class, args, kwargs)
Python
from django.utils.translation import get_language from multilingual.exceptions import LanguageDoesNotExist from multilingual.languages import set_default_language class DefaultLanguageMiddleware(object): """ Binds DEFAULT_LANGUAGE_CODE to django's currently selected language. The effect of enabling this middleware is that translated fields can be accessed by their name; i.e. model.field instead of model.field_en. """ def process_request(self, request): assert hasattr(request, 'session'), "The DefaultLanguageMiddleware \ middleware requires session middleware to be installed. Edit your \ MIDDLEWARE_CLASSES setting to insert \ 'django.contrib.sessions.middleware.SessionMiddleware'." try: set_default_language(get_language()) except LanguageDoesNotExist: # Try without the territory suffix set_default_language(get_language()[:2])
Python
import math import StringIO import tokenize from django import template from django import forms from django.template import Node, NodeList, Template, Context, resolve_variable from django.template.loader import get_template, render_to_string from django.conf import settings from django.utils.html import escape from multilingual.languages import ( get_default_language, get_language_code_list, get_language_name, get_language_bidi, get_language_idx ) from multilingual.utils import GLL register = template.Library() def language_name(language_code): """ Return the name of the language with id=language_code """ return get_language_name(language_code) def language_bidi(language_code): """ Return whether the language with id=language_code is written right-to-left. """ return get_language_bidi(language_code) def language_for_id(language_id): return get_language_idx(language_for_id) class EditTranslationNode(template.Node): def __init__(self, form_name, field_name, language=None): self.form_name = form_name self.field_name = field_name self.language = language def render(self, context): form = resolve_variable(self.form_name, context) model = form._meta.model trans_model = model._meta.translation_model if self.language: language_code = self.language.resolve(context) else: language_code = get_default_language() real_name = "%s.%s.%s.%s" % (self.form_name, trans_model._meta.object_name.lower(), get_language_idx(language_code), self.field_name) return str(resolve_variable(real_name, context)) def do_edit_translation(parser, token): bits = token.split_contents() if len(bits) not in [3, 4]: raise template.TemplateSyntaxError, \ "%r tag requires 3 or 4 arguments" % bits[0] if len(bits) == 4: language = parser.compile_filter(bits[3]) else: language = None return EditTranslationNode(bits[1], bits[2], language) def reorder_translation_formset_by_language_code(inline_admin_form): """ Shuffle the forms in the formset of multilingual model in the order of their language_ids. """ lang_to_form = dict([(form.form.initial['language_id'], form) for form in inline_admin_form]) return [lang_to_form[language_code] for language_code in get_language_code_list()] class GLLNode(template.Node): def __init__(self, language_code, nodelist): self.language_code = language_code self.nodelist = nodelist def render(self, context): if self.language_code[0] == self.language_code[-1] and self.language_code[0] in ('"',"'"): language_code = self.language_code[1:-1] else: language_code = template.Variable(self.language_code).resolve(context) GLL.lock(language_code) output = self.nodelist.render(context) GLL.release() return output def gll(parser, token): bits = token.split_contents() if len(bits) != 2: raise template.TemplateSyntaxError("gll takes exactly one argument") language_code = bits[1] nodelist = parser.parse(('endgll',)) parser.delete_first_token() return GLLNode(language_code, nodelist) register.filter(language_for_id) register.filter(language_name) register.filter(language_bidi) register.tag('edit_translation', do_edit_translation) register.filter(reorder_translation_formset_by_language_code) register.tag('gll', gll)
Python
from django.conf import settings from django.core.exceptions import ImproperlyConfigured LANGUAGES = settings.LANGUAGES LANG_DICT = dict(LANGUAGES) def get_fallback_languages(): fallbacks = {} for lang in LANG_DICT: fallbacks[lang] = [lang] for other in LANG_DICT: if other != lang: fallbacks[lang].append(other) return fallbacks FALLBACK_LANGUAGES = getattr(settings, 'MULTILINGUAL_FALLBACK_LANGUAGES', get_fallback_languages()) IMPLICIT_FALLBACK = getattr(settings, 'MULTILINGUAL_IMPLICIT_FALLBACK', True) DEFAULT_LANGUAGE = getattr(settings, 'MULTILINGUAL_DEFAULT_LANGUAGE', LANGUAGES[0][0]) mcp = "multilingual.context_processors.multilingual" if mcp not in settings.TEMPLATE_CONTEXT_PROCESSORS: found = ','.join(settings.TEMPLATE_CONTEXT_PROCESSORS) raise ImproperlyConfigured( "django-multilingual-ng requires the '%s' context processor. " "Only found: %s" % (mcp, found) )
Python
from multilingual.languages import get_default_language from django.utils.decorators import method_decorator def is_multilingual_model(model): """ Return True if `model` is a multilingual model. """ return hasattr(model._meta, 'translation_model') class GLLError(Exception): pass class GlobalLanguageLock(object): """ The Global Language Lock can be used to force django-multilingual-ng to use a specific language and not try to fall back. """ def __init__(self): self._language_code = None def lock(self, language_code): self._language_code = language_code def release(self): self._language_code = None @property def language_code(self): if self._language_code is not None: return self._language_code raise GLLError("The Global Lnaguage Lock is not active") @property def is_active(self): return self._language_code is not None GLL = GlobalLanguageLock() def gll_unlock_decorator(func): def _decorated(*args, **kwargs): if not GLL.is_active: return func(*args, **kwargs) language_code = GLL.language_code GLL.release() result = func(*args, **kwargs) GLL.lock(language_code) return result _decorated.__name__ = func.__name__ _decorated.__doc__ = func.__doc__ return _decorated gll_unlock = method_decorator(gll_unlock_decorator)
Python
"""Admin suppor for inlines Peter Cicman, Divio GmbH, 2008 """ from django.utils.text import capfirst, get_text_list from django.contrib.admin.util import flatten_fieldsets from django.http import HttpResponseRedirect from django.utils.encoding import force_unicode import re from copy import deepcopy from django.conf import settings from django import forms from django.contrib import admin from django.db.models import Model from django.forms.util import ErrorList, ValidationError from django.forms.models import BaseInlineFormSet, ModelFormMetaclass from django.utils.translation import ugettext as _ from django.template.loader import find_template from django.template import TemplateDoesNotExist from multilingual.languages import get_default_language from multilingual.utils import GLL MULTILINGUAL_PREFIX = '_ml__trans_' MULTILINGUAL_INLINE_PREFIX = '_ml__inline_trans_' def gll(func): def wrapped(cls, request, *args, **kwargs): cls.use_language = request.GET.get('lang', request.GET.get('language', get_default_language())) GLL.lock(cls.use_language) resp = func(cls, request, *args, **kwargs) GLL.release() return resp wrapped.__name__ = func.__name__ wrapped.__doc__ = func.__doc__ return wrapped def relation_hack(form, fields, prefix=''): opts = form.instance._meta localm2m = [m2m.attname for m2m in opts.local_many_to_many] externalfk = [obj.field.related_query_name() for obj in opts.get_all_related_objects()] externalm2m = [m2m.get_accessor_name() for m2m in opts.get_all_related_many_to_many_objects()] for name, db_field in fields: full_name = '%s%s' % (prefix, name) if full_name in form.fields: value = getattr(form.instance, name, '') # check for (local) ForeignKeys if isinstance(value, Model): value = value.pk # check for (local) many to many fields elif name in localm2m: value = value.all() # check for (external) ForeignKeys elif name in externalfk: value = value.all() # check for (external) many to many fields elif name in externalm2m: value = value.all() form.fields[full_name].initial = value class MultilingualInlineModelForm(forms.ModelForm): def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=':', empty_permitted=False, instance=None): """ Fill initial ML Fields """ super(MultilingualInlineModelForm, self).__init__(data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted, instance) # only read initial data if the object already exists, not if we're adding it! if self.instance.pk: relation_hack(self, get_translated_fields(self.instance), MULTILINGUAL_INLINE_PREFIX) class MultilingualInlineFormSet(BaseInlineFormSet): def get_queryset(self): if self.queryset is not None: qs = self.queryset else: qs = self.model._default_manager.get_query_set() if not qs.ordered: qs = qs.order_by(self.model._meta.pk.name) if self.max_num > 0: _queryset = qs[:self.max_num] else: _queryset = qs return _queryset def save_new(self, form, commit=True): """ NOTE: save_new method is completely overridden here, there's no other way to pretend double save otherwise. Just assign translated data to object """ kwargs = {self.fk.get_attname(): self.instance.pk} new_obj = self.model(**kwargs) self._prepare_multilingual_object(new_obj, form) return forms.save_instance(form, new_obj, exclude=[self._pk_field.name], commit=commit) def save_existing(self, form, instance, commit=True): """ NOTE: save_new method is completely overridden here, there's no other way to pretend double save otherwise. Just assign translated data to object """ self._prepare_multilingual_object(instance, form) return forms.save_instance(form, instance, exclude=[self._pk_field.name], commit=commit) def _prepare_multilingual_object(self, obj, form): opts = obj._meta for realname, fieldname in self.ml_fields.items(): field = opts.get_field_by_name(realname)[0] m = re.match(r'^%s(?P<field_name>.*)$' % MULTILINGUAL_INLINE_PREFIX, fieldname) if m: field.save_form_data(self.instance, form.cleaned_data[fieldname]) setattr(obj, realname, getattr(self.instance, realname.rsplit('_', 1)[0])) class MultilingualInlineAdmin(admin.TabularInline): formset = MultilingualInlineFormSet form = MultilingualInlineModelForm template = 'admin/multilingual/edit_inline/tabular.html' # css class added to inline box inline_css_class = None use_language = None #TODO: add some nice template def __init__(self, parent_model, admin_site): super(MultilingualInlineAdmin, self).__init__(parent_model, admin_site) if hasattr(self, 'use_fields'): # go around admin fields structure validation self.fields = self.use_fields def get_formset(self, request, obj=None, **kwargs): FormSet = super(MultilingualInlineAdmin, self).get_formset(request, obj, **kwargs) FormSet.use_language = self.use_language FormSet.ml_fields = {} for name, field in get_translated_fields(self.model, self.use_language): fieldname = '%s%s' % (MULTILINGUAL_INLINE_PREFIX, name) FormSet.form.base_fields[fieldname] = self.formfield_for_dbfield(field, request=request) FormSet.ml_fields[name] = fieldname return FormSet class MultilingualModelAdminForm(forms.ModelForm): # for rendering / saving multilingual fields connecte to model, takes place # when admin per language is ussed def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=':', empty_permitted=False, instance=None): """ Fill up initial ML Fields """ super(MultilingualModelAdminForm, self).__init__(data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted, instance) # only try to fill intial data if we are not adding an object! if self.instance.pk: fields = [(f, getattr(self.instance, "%s_%s" % (f, GLL.language_code), '')) for f in self.ml_fields] relation_hack(self, fields) def clean(self): cleaned_data = super(MultilingualModelAdminForm, self).clean() self.validate_ml_unique() return cleaned_data def validate_ml_unique(self): form_errors = [] if not hasattr(self.instance._meta, 'translation_model'): return for check in self.instance._meta.translation_model._meta.unique_together[:]: lookup_kwargs = {'language_code': GLL.language_code} for field_name in check: #local_name = "%s_%s" % (field_name, self.use_language) if self.cleaned_data.get(field_name) is not None: lookup_kwargs[field_name] = self.cleaned_data.get(field_name) if len(check) == 2 and 'master' in check and 'language_code' in check: continue qs = self.instance._meta.translation_model.objects.filter(**lookup_kwargs) if self.instance.pk is not None: qs = qs.exclude(master=self.instance.pk) if qs.count(): model_name = capfirst(self.instance._meta.verbose_name) field_labels = [] for field_name in check: if field_name == "language_code": field_labels.append(_("language")) elif field_name == "master": continue else: field_labels.append(self.instance._meta.translation_model._meta.get_field_by_name(field_name)[0].verbose_name) field_labels = get_text_list(field_labels, _('and')) form_errors.append( _(u"%(model_name)s with this %(field_label)s already exists.") % \ {'model_name': unicode(model_name), 'field_label': unicode(field_labels)} ) if form_errors: # Raise the unique together errors since they are considered # form-wide. raise ValidationError(form_errors) def save(self, commit=True): self._prepare_multilingual_object(self.instance, self) return super(MultilingualModelAdminForm, self).save(commit) def _prepare_multilingual_object(self, obj, form): opts = self.instance._meta for name in self.ml_fields: field = opts.get_field_by_name(name)[0] # respect save_form_data field.save_form_data(self.instance, form.cleaned_data[name]) setattr(obj, "%s_%s" % (name, GLL.language_code), getattr(self.instance, name)) class MultilingualModelAdmin(admin.ModelAdmin): # use special template to render tabs for languages on top change_form_template = "admin/multilingual/change_form.html" form = MultilingualModelAdminForm _multilingual_model_admin = True use_language = None fill_check_field = None def __init__(self, model, admin_site): if hasattr(self, 'use_fieldsets'): # go around admin fieldset structure validation self.fieldsets = self.use_fieldsets if hasattr(self, 'use_prepopulated_fields'): # go around admin fieldset structure validation self.prepopulated_fields = self.use_prepopulated_fields super(MultilingualModelAdmin, self).__init__(model, admin_site) def get_fill_check_field(self): if self.fill_check_field is None and hasattr(self.model._meta, 'translation_model'): opts = self.model._meta.translation_model._meta for field in opts.fields: if field.attname in ('language_code', 'master_id'): continue if not (field.blank or field.null): self.fill_check_field = field.attname break return self.fill_check_field def get_form(self, request, obj=None, **kwargs): # assign language to inlines, so they now how to render for inline in self.inline_instances: if isinstance(inline, MultilingualInlineAdmin): inline.use_language = self.use_language Form = super(MultilingualModelAdmin, self).get_form(request, obj, **kwargs) Form.ml_fields = {} for name, field in get_default_translated_fields(self.model): if not field.editable: continue form_field = self.formfield_for_dbfield(field) local_name = "%s_%s" % (name, self.use_language) Form.ml_fields[name] = form_field Form.base_fields[name] = form_field Form.use_language = self.use_language return Form @gll def change_view(self, *args, **kwargs): return super(MultilingualModelAdmin, self).change_view(*args, **kwargs) @gll def add_view(self, *args, **kwargs): return super(MultilingualModelAdmin, self).add_view(*args, **kwargs) @gll def delete_view(self, *args, **kwargs): return super(MultilingualModelAdmin, self).delete_view(*args, **kwargs) def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): # add context variables filled_languages = [] fill_check_field = self.get_fill_check_field() if obj and fill_check_field is not None: filled_languages = [t[0] for t in obj.translations.filter(**{'%s__isnull' % fill_check_field:False, '%s__gt' % fill_check_field:''}).values_list('language_code')] context.update({ 'current_language_index': self.use_language, 'current_language_code': self.use_language, 'filled_languages': filled_languages, 'old_template': self.get_old_template(), }) return super(MultilingualModelAdmin, self).render_change_form(request, context, add, change, form_url, obj) def get_old_template(self): opts = self.model._meta app_label = opts.app_label search_templates = [ "admin/%s/%s/change_form.html" % (app_label, opts.object_name.lower()), "admin/%s/change_form.html" % app_label, "admin/change_form.html" ] for template in search_templates: try: find_template(template) return template except TemplateDoesNotExist: pass def response_change(self, request, obj): # because save & continue - so it shows the same language if request.POST.has_key("_continue"): opts = obj._meta msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)} self.message_user(request, msg + ' ' + _("You may edit it again below.")) lang, path = request.GET.get('language', get_default_language()), request.path if lang: lang = "language=%s" % lang if request.REQUEST.has_key('_popup'): path += "?_popup=1" + "&%s" % lang else: path += "?%s" % lang return HttpResponseRedirect(path) return super(MultilingualModelAdmin, self).response_change(request, obj) class Media: css = { 'all': ('%smultilingual/admin/css/style.css' % settings.MEDIA_URL,) } def get_translated_fields(model, language=None): meta = model._meta if not hasattr(meta, 'translated_fields'): meta = meta.translation_model._meta # returns all the translatable fields, except of the default ones if not language: for name, (field, non_default) in meta.translated_fields.items(): if non_default: yield name, field else: # if language is defined return fields in the same order, like they are defined in the # translation class for field in meta.fields: if field.primary_key: continue name = field.name + "_%s" % language field = meta.translated_fields.get(name, None) if field: yield name, field[0] def get_default_translated_fields(model): if hasattr(model._meta, 'translation_model'): for name, (field, non_default) in model._meta.translation_model._meta.translated_fields.items(): if not non_default: yield name, field
Python
from django.core.exceptions import ImproperlyConfigured from django.db import models from multilingual.utils import is_multilingual_model def get_field(cls, model, opts, label, field): """ Just like django.contrib.admin.validation.get_field, but knows about translation models. """ trans_model = model._meta.translation_model try: (f, lang_id) = trans_model._meta.translated_fields[field] return f except KeyError: # fall back to the old way -- see if model contains the field # directly pass try: return opts.get_field(field) except models.FieldDoesNotExist: raise ImproperlyConfigured("'%s.%s' refers to field '%s' that is " \ "missing from model '%s'." \ % (cls.__name__, label, field, model.__name__)) def validate_admin_registration(cls, model): """ Validates a class specified as a model admin. Right now this means validating prepopulated_fields, as for multilingual models DM handles them by itself. """ if not is_multilingual_model(model): return from django.contrib.admin.validation import check_isdict, check_isseq opts = model._meta # this is heavily based on django.contrib.admin.validation. if hasattr(cls, '_dm_prepopulated_fields'): check_isdict(cls, '_dm_prepopulated_fields', cls.prepopulated_fields) for field, val in cls._dm_prepopulated_fields.items(): f = get_field(cls, model, opts, 'prepopulated_fields', field) if isinstance(f, (models.DateTimeField, models.ForeignKey, models.ManyToManyField)): raise ImproperlyConfigured("'%s.prepopulated_fields['%s']' " "is either a DateTimeField, ForeignKey or " "ManyToManyField. This isn't allowed." % (cls.__name__, field)) check_isseq(cls, "prepopulated_fields['%s']" % field, val) for idx, f in enumerate(val): get_field(cls, model, opts, "prepopulated_fields['%s'][%d]" % (f, idx), f)
Python
class TranslationDoesNotExist(Exception): """ The requested translation does not exist """ pass class LanguageDoesNotExist(Exception): """ The requested language does not exist """ pass
Python
from django.core.management.base import AppCommand from django.db import models from django.utils.importlib import import_module from django.conf import settings from django.db import connection from django.core.management import call_command from multilingual.utils import is_multilingual_model from multilingual.languages import get_language_choices from inspect import isclass from south.db import db def get_code_by_id(lid): return settings.LANGUAGES[lid-1][0] class Command(AppCommand): """ Migrate the data from an id base translation table to a code based table. """ def handle(self, *args, **kwargs): if self.are_you_sure(): super(Command, self).handle(*args, **kwargs) print self.style.HTTP_SUCCESS('Done.') else: print self.style.NOTICE('Aborted.') def are_you_sure(self): n = self.style.NOTICE e = self.style.ERROR print e("WARNING!") + n(" This command will ") + e("delete") + n(""" data from your database! All language_id columns in all multilingual tables of the apps you specified will be deleted. Their values will be converted to the new language_code format. Please make a backup of your database before running this command.""") answer = raw_input("Are you sure you want to continue? [yes/no]\n") if answer.lower() == 'yes': return True elif answer.lower() == 'no': return False while True: answer = raw_input("Please answer with either 'yes' or 'no'\n") if answer.lower() == 'yes': return True elif answer.lower() == 'no': return False def handle_app(self, app, **options): appname = app.__name__ print 'handling app %s' % appname for obj in [getattr(app, name) for name in dir(app)]: if not isclass(obj): continue if not issubclass(obj, models.Model): continue if not is_multilingual_model(obj): continue print 'altering model %s' % obj table = obj._meta.translation_model._meta.db_table db.debug = True # do this in a transaction db.start_transaction() # first add the column with nullable values, and no index lc_field = models.CharField(max_length=15, blank=True, null=True) db.add_column(table, 'language_code', lc_field) # migrate the model print 'migrating data' # do the conversion server-side # all modern RDBMSs support the case statement update_sql = "UPDATE %s SET language_code = (CASE language_id %s END)" % (table, ' '.join( "WHEN %d THEN '%s'" % (lid, get_code_by_id(lid)) for lid in range(1, len(settings.LANGUAGES) + 1) ) ) db.execute(update_sql) print 'deleting language_id column' db.delete_unique(table, ['language_id', 'master_id']) db.delete_column(table, 'language_id') print 'setting up constraints and indices' # alter the column to set not null lc_field.null = False db.alter_column(table, 'language_code', lc_field) ## we don't really need this indexed. all queries should hit the unique index #db.create_index(table, ['language_code']) # and create a unique index for master & language db.create_unique(table, ['language_code', 'master_id']) # south might fail to commit if we don't do it explicitly db.commit_transaction()
Python
""" Django-multilingual-ng: multilingual model support for Django 1.2. Note about version numbers: - uneven minor versions are considered unstable releases - even minor versions are considered stable releases """ VERSION = ('0', '1', '30') __version__ = '.'.join(VERSION) try: """ WARNING: All these names imported here WILL BE DEPRECATED! """ from multilingual import models from multilingual.exceptions import TranslationDoesNotExist, LanguageDoesNotExist from multilingual.languages import (set_default_language, get_default_language, get_language_code_list) from multilingual.settings import FALLBACK_LANGUAGES from multilingual.translation import Translation from multilingual.admin import MultilingualModelAdmin, MultilingualInlineAdmin from multilingual.manager import Manager ModelAdmin = MultilingualModelAdmin except ImportError: pass
Python
from django.db import models from multilingual.query import MultilingualModelQuerySet from multilingual.languages import * class MultilingualManager(models.Manager): """ A manager for multilingual models. TO DO: turn this into a proxy manager that would allow developers to use any manager they need. It should be sufficient to extend and additionaly filter or order querysets returned by that manager. """ def get_query_set(self): return MultilingualModelQuerySet(self.model) Manager = MultilingualManager # backwards compat, will be depricated
Python
import urllib, urllib2, simplejson from datetime import datetime from django.utils.http import urlquote from time import sleep import re htmlCodes = [ ['&', '&amp;'], ['<', '&lt;'], ['>', '&gt;'], ['"', '&quot;'], ] htmlCodesReversed = htmlCodes[:] htmlCodesReversed.reverse() def htmlDecode(s, codes=htmlCodesReversed): """ Returns the ASCII decoded version of the given HTML string. This does NOT remove normal HTML tags like <p>. It is the inverse of htmlEncode().""" for code in codes: s = s.replace(code[1], code[0]) return s hash_regex = re.compile(r'#[0-9a-zA-Z+_]*',re.IGNORECASE) user_regex = re.compile(r'@[0-9a-zA-Z+_]*',re.IGNORECASE) url_regex = re.compile( r'https?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|' #domain... r'localhost|' #localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip r'(?::\d+)?' # optional port r'(?:[/?]\S+|/?)', re.IGNORECASE) def search_result(query=['#fimu', 'fimu2010'], url=None): """ Return the tweets result of the search in JSON >>> results = search_result(['google']) >>> for s in results['results']: ... print s['from_user'], ' : ', s['text'] ... """ if url: theurl = "http://search.twitter.com/search.json%s" % url else: theurl = "http://search.twitter.com/search.json?q=%s&rpp=2" % "+OR+".join([urllib.quote(q) for q in query]) handle = urllib2.Request(theurl) try: return simplejson.load(urllib2.urlopen(handle)) except IOError, e: # This is reached when allocated API requests to IP are completed. print "parsing the search json from search.twitter.com, failed" return False def create_list_from_result(results): """ Extract the tweet information from the JSON search results >>> results = search_result(['google']) >>> tweets = create_list_from_result(results) >>> for tweet in tweets: ... print tweet['user'], 'at', tweet['date'], 'writes', tweet['text'] """ tweets = [] if results: for s in results['results']: tweet = s['text'] for tl in url_regex.finditer(tweet): tweet = tweet.replace(tl.group(0), '<a href="'+tl.group(0)+'">'+ tl.group(0)+'</a>') for tt in user_regex.finditer(tweet): url_tweet = tt.group(0).replace('@','') tweet = tweet.replace(tt.group(0), '<a href="http://twitter.com/'+ url_tweet+'" title="'+ tt.group(0)+'">'+ tt.group(0)+'</a>') for th in hash_regex.finditer(tweet): url_hash = th.group(0).replace('#','%23') if len ( th.group(0) ) > 2: tweet = tweet.replace(th.group(0), '<a href="http://search.twitter.com/search?q='+ url_hash+'" title="'+ th.group(0)+'">'+ th.group(0)+'</a>'); tweets.append({'user': s['from_user'], 'avatar': s['profile_image_url'], 'source': htmlDecode(s['source']), 'date': datetime.strptime(s['created_at'], "%a, %d %b %Y %H:%M:%S +0000"), 'text': tweet}) return tweets if __name__=='__main__': url = None while True: results = search_result(['#twitter'], url) url = results['refresh_url'] messages = create_list_from_result(results) for tweet in messages: print tweet['user'], 'at', tweet['date'], 'writes :', tweet['text'] sleep(2) print '\n' , '=============== REFRESH============', '\n'
Python
# Copyright (c) 2008 Joost Cassee # Licensed under the terms of the MIT License (see LICENSE.txt) from django.db import models from django.contrib.admin import widgets as admin_widgets from tinymce import widgets as tinymce_widgets class HTMLField(models.TextField): """ A large string field for HTML content. It uses the TinyMCE widget in forms. """ def formfield(self, **kwargs): defaults = {'widget': tinymce_widgets.TinyMCE} defaults.update(kwargs) # As an ugly hack, we override the admin widget if defaults['widget'] == admin_widgets.AdminTextareaWidget: defaults['widget'] = tinymce_widgets.AdminTinyMCE return super(HTMLField, self).formfield(**defaults)
Python
""" Based on "TinyMCE Compressor PHP" from MoxieCode. http://tinymce.moxiecode.com/ Copyright (c) 2008 Jason Davies Licensed under the terms of the MIT License (see LICENSE.txt) """ from datetime import datetime import os from django.conf import settings from django.core.cache import cache from django.http import HttpResponse from django.shortcuts import Http404 from django.template import RequestContext from django.template.loader import render_to_string from django.utils.text import compress_string from django.utils.cache import patch_vary_headers, patch_response_headers import tinymce.settings def get_file_contents(filename): try: f = open(os.path.join(tinymce.settings.JS_ROOT, filename)) try: return f.read() finally: f.close() except IOError: return "" def split_commas(str): if str == '': return [] return str.split(",") def gzip_compressor(request): plugins = split_commas(request.GET.get("plugins", "")) languages = split_commas(request.GET.get("languages", "")) themes = split_commas(request.GET.get("themes", "")) isJS = request.GET.get("js", "") == "true" compress = request.GET.get("compress", "true") == "true" suffix = request.GET.get("suffix", "") == "_src" and "_src" or "" content = [] response = HttpResponse() response["Content-Type"] = "text/javascript" if not isJS: response.write(render_to_string('tinymce/tiny_mce_gzip.js', { 'base_url': tinymce.settings.JS_BASE_URL, }, context_instance=RequestContext(request))) return response patch_vary_headers(response, ['Accept-Encoding']) now = datetime.utcnow() response['Date'] = now.strftime('%a, %d %b %Y %H:%M:%S GMT') cacheKey = '|'.join(plugins + languages + themes) cacheData = cache.get(cacheKey) if not cacheData is None: if cacheData.has_key('ETag'): if_none_match = request.META.get('HTTP_IF_NONE_MATCH', None) if if_none_match == cacheData['ETag']: response.status_code = 304 response.content = '' response['Content-Length'] = '0' return response if cacheData.has_key('Last-Modified'): if_modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE', None) if if_modified_since == cacheData['Last-Modified']: response.status_code = 304 response.content = '' response['Content-Length'] = '0' return response # Add core, with baseURL added content.append(get_file_contents("tiny_mce%s.js" % suffix).replace( "tinymce._init();", "tinymce.baseURL='%s';tinymce._init();" % tinymce.settings.JS_BASE_URL)) # Patch loading functions content.append("tinyMCE_GZ.start();") # Add core languages for lang in languages: content.append(get_file_contents("langs/%s.js" % lang)) # Add themes for theme in themes: content.append(get_file_contents("themes/%s/editor_template%s.js" % (theme, suffix))) for lang in languages: content.append(get_file_contents("themes/%s/langs/%s.js" % (theme, lang))) # Add plugins for plugin in plugins: content.append(get_file_contents("plugins/%s/editor_plugin%s.js" % (plugin, suffix))) for lang in languages: content.append(get_file_contents("plugins/%s/langs/%s.js" % (plugin, lang))) # Add filebrowser if tinymce.settings.USE_FILEBROWSER: content.append(render_to_string('tinymce/filebrowser.js', {}, context_instance=RequestContext(request)).encode("utf-8")) # Restore loading functions content.append("tinyMCE_GZ.end();") # Compress if compress: content = compress_string(''.join(content)) response['Content-Encoding'] = 'gzip' response['Content-Length'] = str(len(content)) response.write(content) timeout = 3600 * 24 * 10 patch_response_headers(response, timeout) cache.set(cacheKey, { 'Last-Modified': response['Last-Modified'], 'ETag': response['ETag'], }) return response
Python
# Copyright (c) 2008 Joost Cassee # Licensed under the terms of the MIT License (see LICENSE.txt) from django.conf.urls.defaults import * urlpatterns = patterns('tinymce.views', url(r'^js/textareas/(?P<name>.+)/$', 'textareas_js', name='tinymce-js'), url(r'^js/textareas/(?P<name>.+)/(?P<lang>.*)$', 'textareas_js', name='tinymce-js-lang'), url(r'^spellchecker/$', 'spell_check'), url(r'^flatpages_link_list/$', 'flatpages_link_list'), url(r'^compressor/$', 'compressor', name='tinymce-compressor'), url(r'^filebrowser/$', 'filebrowser', name='tinymce-filebrowser'), url(r'^preview/(?P<name>.+)/$', 'preview', name='tinymce-preview'), )
Python
# Copyright (c) 2009 Joost Cassee # Licensed under the terms of the MIT License (see LICENSE.txt) from django import template from django.template.loader import render_to_string import tinymce.settings register = template.Library() def tinymce_preview(element_id): return render_to_string('tinymce/preview_javascript.html', {'base_url': tinymce.settings.JS_BASE_URL, 'element_id': element_id}) register.simple_tag(tinymce_preview)
Python
# Copyright (c) 2008 Joost Cassee # Licensed under the terms of the MIT License (see LICENSE.txt)
Python
import os from django.conf import settings DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG', {'theme': "simple", 'relative_urls': False}) USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False) USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False) USE_FILEBROWSER = getattr(settings, 'TINYMCE_FILEBROWSER', 'filebrowser' in settings.INSTALLED_APPS) JS_URL = getattr(settings, 'TINYMCE_JS_URL', os.path.join(settings.ADMIN_MEDIA_PREFIX, "tinymce/jscripts/tiny_mce/tiny_mce.js")) JS_ROOT = getattr(settings, 'TINYMCE_JS_ROOT', os.path.join(settings.ADMIN_MEDIA_PREFIX, "tinymce/jscripts/tiny_mce/")) JS_BASE_URL = JS_URL[:JS_URL.rfind('/')]
Python
# Copyright (c) 2008 Joost Cassee # Licensed under the terms of the MIT License (see LICENSE.txt) """ This TinyMCE widget was copied and extended from this code by John D'Agostino: http://code.djangoproject.com/wiki/CustomWidgetsTinyMCE """ from django import forms from django.conf import settings from django.contrib.admin import widgets as admin_widgets from django.core.urlresolvers import reverse from django.forms.widgets import flatatt from django.utils.encoding import smart_unicode from django.utils.html import escape from django.utils import simplejson from django.utils.datastructures import SortedDict from django.utils.safestring import mark_safe from django.utils.translation import get_language, ugettext as _ import tinymce.settings class TinyMCE(forms.Textarea): """ TinyMCE widget. Set settings.TINYMCE_JS_URL to set the location of the javascript file. Default is "MEDIA_URL + 'js/tiny_mce/tiny_mce.js'". You can customize the configuration with the mce_attrs argument to the constructor. In addition to the standard configuration you can set the 'content_language' parameter. It takes the value of the 'language' parameter by default. In addition to the default settings from settings.TINYMCE_DEFAULT_CONFIG, this widget sets the 'language', 'directionality' and 'spellchecker_languages' parameters by default. The first is derived from the current Django language, the others from the 'content_language' parameter. """ def __init__(self, content_language=None, attrs=None, mce_attrs={}): super(TinyMCE, self).__init__(attrs) self.mce_attrs = mce_attrs if content_language is None: content_language = mce_attrs.get('language', None) self.content_language = content_language def render(self, name, value, attrs=None): if value is None: value = '' value = smart_unicode(value) final_attrs = self.build_attrs(attrs) final_attrs['name'] = name assert 'id' in final_attrs, "TinyMCE widget attributes must contain 'id'" mce_config = tinymce.settings.DEFAULT_CONFIG.copy() mce_config.update(get_language_config(self.content_language)) if tinymce.settings.USE_FILEBROWSER: mce_config['file_browser_callback'] = "djangoFileBrowser" mce_config.update(self.mce_attrs) mce_config['mode'] = 'exact' mce_config['elements'] = final_attrs['id'] mce_config['strict_loading_mode'] = 1 mce_json = simplejson.dumps(mce_config) html = [u'<textarea%s>%s</textarea>' % (flatatt(final_attrs), escape(value))] if tinymce.settings.USE_COMPRESSOR: compressor_config = { 'plugins': mce_config.get('plugins', ''), 'themes': mce_config.get('theme', 'advanced'), 'languages': mce_config.get('language', ''), 'diskcache': True, 'debug': False, } compressor_json = simplejson.dumps(compressor_config) html.append(u'<script type="text/javascript">tinyMCE_GZ.init(%s)</script>' % compressor_json) html.append(u'<script type="text/javascript">tinyMCE.init(%s)</script>' % mce_json) return mark_safe(u'\n'.join(html)) def _media(self): if tinymce.settings.USE_COMPRESSOR: js = [reverse('tinymce-compressor')] else: js = [tinymce.settings.JS_URL] if tinymce.settings.USE_FILEBROWSER: js.append(reverse('tinymce-filebrowser')) return forms.Media(js=js) media = property(_media) class AdminTinyMCE(admin_widgets.AdminTextareaWidget, TinyMCE): pass def get_language_config(content_language=None): language = get_language()[:2] if content_language: content_language = content_language[:2] else: content_language = language config = {} config['language'] = language lang_names = SortedDict() for lang, name in settings.LANGUAGES: if lang[:2] not in lang_names: lang_names[lang[:2]] = [] lang_names[lang[:2]].append(_(name)) sp_langs = [] for lang, names in lang_names.items(): if lang == content_language: default = '+' else: default = '' sp_langs.append(u'%s%s=%s' % (default, ' / '.join(names), lang)) config['spellchecker_languages'] = ','.join(sp_langs) if content_language in settings.LANGUAGES_BIDI: config['directionality'] = 'rtl' else: config['directionality'] = 'ltr' if tinymce.settings.USE_SPELLCHECKER: config['spellchecker_rpc_url'] = reverse('tinymce.views.spell_check') return config
Python
# Copyright (c) 2008 Joost Cassee # Licensed under the terms of the MIT License (see LICENSE.txt) import logging from django.core import urlresolvers from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext, loader from django.utils import simplejson from django.utils.translation import ugettext as _ from tinymce.compressor import gzip_compressor from tinymce.widgets import get_language_config def textareas_js(request, name, lang=None): """ Returns a HttpResponse whose content is a Javscript file. The template is loaded from 'tinymce/<name>_textareas.js' or '<name>/tinymce_textareas.js'. Optionally, the lang argument sets the content language. """ template_files = ( 'tinymce/%s_textareas.js' % name, '%s/tinymce_textareas.js' % name, ) template = loader.select_template(template_files) vars = get_language_config(lang) vars['content_language'] = lang context = RequestContext(request, vars) return HttpResponse(template.render(context), content_type="application/x-javascript") def spell_check(request): """ Returns a HttpResponse that implements the TinyMCE spellchecker protocol. """ try: import enchant raw = request.raw_post_data input = simplejson.loads(raw) id = input['id'] method = input['method'] params = input['params'] lang = params[0] arg = params[1] if not enchant.dict_exists(str(lang)): raise RuntimeError("dictionary not found for language '%s'" % lang) checker = enchant.Dict(lang) if method == 'checkWords': result = [word for word in arg if not checker.check(word)] elif method == 'getSuggestions': result = checker.suggest(arg) else: raise RuntimeError("Unkown spellcheck method: '%s'" % method) output = { 'id': id, 'result': result, 'error': None, } except Exception: logging.exception("Error running spellchecker") return HttpResponse(_("Error running spellchecker")) return HttpResponse(simplejson.dumps(output), content_type='application/json') def preview(request, name): """ Returns a HttpResponse whose content is an HTML file that is used by the TinyMCE preview plugin. The template is loaded from 'tinymce/<name>_preview.html' or '<name>/tinymce_preview.html'. """ template_files = ( 'tinymce/%s_preview.html' % name, '%s/tinymce_preview.html' % name, ) template = loader.select_template(template_files) return HttpResponse(template.render(RequestContext(request)), content_type="text/html") def flatpages_link_list(request): """ Returns a HttpResponse whose content is a Javscript file representing a list of links to flatpages. """ from django.contrib.flatpages.models import FlatPage link_list = [(page.title, page.url) for page in FlatPage.objects.all()] return render_to_link_list(link_list) def compressor(request): """ Returns a GZip-compressed response. """ return gzip_compressor(request) def render_to_link_list(link_list): """ Returns a HttpResponse whose content is a Javscript file representing a list of links suitable for use wit the TinyMCE external_link_list_url configuration option. The link_list parameter must be a list of 2-tuples. """ return render_to_js_vardef('tinyMCELinkList', link_list) def render_to_image_list(image_list): """ Returns a HttpResponse whose content is a Javscript file representing a list of images suitable for use wit the TinyMCE external_image_list_url configuration option. The image_list parameter must be a list of 2-tuples. """ return render_to_js_vardef('tinyMCEImageList', image_list) def render_to_js_vardef(var_name, var_value): output = "var %s = %s" % (var_name, simplejson.dumps(var_value)) return HttpResponse(output, content_type='application/x-javascript') def filebrowser(request): fb_url = "%s://%s%s" % (request.is_secure() and 'https' or 'http', request.get_host(), urlresolvers.reverse('filebrowser-index')) return render_to_response('tinymce/filebrowser.js', {'fb_url': fb_url}, context_instance=RequestContext(request))
Python
# Copyright (c) 2008 Joost Cassee # Licensed under the terms of the MIT License (see LICENSE.txt)
Python
from django import template from django.conf import settings register = template.Library() def googleanalytics(tracking_code=None): """ Includes the google analytics tracking code, using the code number in GOOGLE_ANALYTICS_ACCOUNT_CODE setting or the tag's param if given. Syntax:: {% googleanalytics [code_number] %} Example:: {% googleanalytics %} or if you want to override account code the code: {% googleanalytics "UA-000000-0" %} """ if tracking_code is None: tracking_code = getattr(settings, 'GOOGLE_ANALYTICS_ACCOUNT_CODE', None) use_legacy_code = getattr(settings, 'GOOGLE_ANALYTICS_LEGACY_CODE', False) return {'tracking_code': tracking_code, 'use_legacy_code': use_legacy_code} register.inclusion_tag('google_analytics/tracking_code.html')(googleanalytics)
Python
""" Form components for working with trees. """ from django import forms from django.forms.forms import NON_FIELD_ERRORS from django.forms.util import ErrorList from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ from mptt.exceptions import InvalidMove __all__ = ('TreeNodeChoiceField', 'TreeNodePositionField', 'MoveNodeForm') # Fields ###################################################################### class TreeNodeChoiceField(forms.ModelChoiceField): """A ModelChoiceField for tree nodes.""" def __init__(self, level_indicator=u'---', *args, **kwargs): self.level_indicator = level_indicator if kwargs.get('required', True) and not 'empty_label' in kwargs: kwargs['empty_label'] = None super(TreeNodeChoiceField, self).__init__(*args, **kwargs) def label_from_instance(self, obj): """ Creates labels which represent the tree level of each node when generating option labels. """ return u'%s %s' % (self.level_indicator * getattr(obj, obj._meta.level_attr), smart_unicode(obj)) class TreeNodePositionField(forms.ChoiceField): """A ChoiceField for specifying position relative to another node.""" FIRST_CHILD = 'first-child' LAST_CHILD = 'last-child' LEFT = 'left' RIGHT = 'right' DEFAULT_CHOICES = ( (FIRST_CHILD, _('First child')), (LAST_CHILD, _('Last child')), (LEFT, _('Left sibling')), (RIGHT, _('Right sibling')), ) def __init__(self, *args, **kwargs): if 'choices' not in kwargs: kwargs['choices'] = self.DEFAULT_CHOICES super(TreeNodePositionField, self).__init__(*args, **kwargs) # Forms ####################################################################### class MoveNodeForm(forms.Form): """ A form which allows the user to move a given node from one location in its tree to another, with optional restriction of the nodes which are valid target nodes for the move. """ target = TreeNodeChoiceField(queryset=None) position = TreeNodePositionField() def __init__(self, node, *args, **kwargs): """ The ``node`` to be moved must be provided. The following keyword arguments are also accepted:: ``valid_targets`` Specifies a ``QuerySet`` of valid targets for the move. If not provided, valid targets will consist of everything other node of the same type, apart from the node itself and any descendants. For example, if you want to restrict the node to moving within its own tree, pass a ``QuerySet`` containing everything in the node's tree except itself and its descendants (to prevent invalid moves) and the root node (as a user could choose to make the node a sibling of the root node). ``target_select_size`` The size of the select element used for the target node. Defaults to ``10``. ``position_choices`` A tuple of allowed position choices and their descriptions. Defaults to ``TreeNodePositionField.DEFAULT_CHOICES``. ``level_indicator`` A string which will be used to represent a single tree level in the target options. """ self.node = node valid_targets = kwargs.pop('valid_targets', None) target_select_size = kwargs.pop('target_select_size', 10) position_choices = kwargs.pop('position_choices', None) level_indicator = kwargs.pop('level_indicator', None) super(MoveNodeForm, self).__init__(*args, **kwargs) opts = node._meta if valid_targets is None: valid_targets = node._tree_manager.exclude(**{ opts.tree_id_attr: getattr(node, opts.tree_id_attr), '%s__gte' % opts.left_attr: getattr(node, opts.left_attr), '%s__lte' % opts.right_attr: getattr(node, opts.right_attr), }) self.fields['target'].queryset = valid_targets self.fields['target'].widget.attrs['size'] = target_select_size if level_indicator: self.fields['target'].level_indicator = level_indicator if position_choices: self.fields['position_choices'].choices = position_choices def save(self): """ Attempts to move the node using the selected target and position. If an invalid move is attempted, the related error message will be added to the form's non-field errors and the error will be re-raised. Callers should attempt to catch ``InvalidNode`` to redisplay the form with the error, should it occur. """ try: self.node.move_to(self.cleaned_data['target'], self.cleaned_data['position']) return self.node except InvalidMove, e: self.errors[NON_FIELD_ERRORS] = ErrorList(e) raise
Python
""" New instance methods for Django models which are set up for Modified Preorder Tree Traversal. """ def get_ancestors(self, ascending=False): """ Creates a ``QuerySet`` containing the ancestors of this model instance. This defaults to being in descending order (root ancestor first, immediate parent last); passing ``True`` for the ``ascending`` argument will reverse the ordering (immediate parent first, root ancestor last). """ if self.is_root_node(): return self._tree_manager.none() opts = self._meta return self._default_manager.filter(**{ '%s__lt' % opts.left_attr: getattr(self, opts.left_attr), '%s__gt' % opts.right_attr: getattr(self, opts.right_attr), opts.tree_id_attr: getattr(self, opts.tree_id_attr), }).order_by('%s%s' % ({True: '-', False: ''}[ascending], opts.left_attr)) def get_children(self): """ Creates a ``QuerySet`` containing the immediate children of this model instance, in tree order. The benefit of using this method over the reverse relation provided by the ORM to the instance's children is that a database query can be avoided in the case where the instance is a leaf node (it has no children). """ if self.is_leaf_node(): return self._tree_manager.none() return self._tree_manager.filter(**{ self._meta.parent_attr: self, }) def get_descendants(self, include_self=False): """ Creates a ``QuerySet`` containing descendants of this model instance, in tree order. If ``include_self`` is ``True``, the ``QuerySet`` will also include this model instance. """ if not include_self and self.is_leaf_node(): return self._tree_manager.none() opts = self._meta filters = {opts.tree_id_attr: getattr(self, opts.tree_id_attr)} if include_self: filters['%s__range' % opts.left_attr] = (getattr(self, opts.left_attr), getattr(self, opts.right_attr)) else: filters['%s__gt' % opts.left_attr] = getattr(self, opts.left_attr) filters['%s__lt' % opts.left_attr] = getattr(self, opts.right_attr) return self._tree_manager.filter(**filters) def get_descendant_count(self): """ Returns the number of descendants this model instance has. """ return (getattr(self, self._meta.right_attr) - getattr(self, self._meta.left_attr) - 1) / 2 def get_next_sibling(self): """ Returns this model instance's next sibling in the tree, or ``None`` if it doesn't have a next sibling. """ opts = self._meta if self.is_root_node(): filters = { '%s__isnull' % opts.parent_attr: True, '%s__gt' % opts.tree_id_attr: getattr(self, opts.tree_id_attr), } else: filters = { opts.parent_attr: getattr(self, '%s_id' % opts.parent_attr), '%s__gt' % opts.left_attr: getattr(self, opts.right_attr), } sibling = None try: sibling = self._tree_manager.filter(**filters)[0] except IndexError: pass return sibling def get_previous_sibling(self): """ Returns this model instance's previous sibling in the tree, or ``None`` if it doesn't have a previous sibling. """ opts = self._meta if self.is_root_node(): filters = { '%s__isnull' % opts.parent_attr: True, '%s__lt' % opts.tree_id_attr: getattr(self, opts.tree_id_attr), } order_by = '-%s' % opts.tree_id_attr else: filters = { opts.parent_attr: getattr(self, '%s_id' % opts.parent_attr), '%s__lt' % opts.right_attr: getattr(self, opts.left_attr), } order_by = '-%s' % opts.right_attr sibling = None try: sibling = self._tree_manager.filter(**filters).order_by(order_by)[0] except IndexError: pass return sibling def get_root(self): """ Returns the root node of this model instance's tree. """ if self.is_root_node(): return self opts = self._meta return self._default_manager.get(**{ opts.tree_id_attr: getattr(self, opts.tree_id_attr), '%s__isnull' % opts.parent_attr: True, }) def get_siblings(self, include_self=False): """ Creates a ``QuerySet`` containing siblings of this model instance. Root nodes are considered to be siblings of other root nodes. If ``include_self`` is ``True``, the ``QuerySet`` will also include this model instance. """ opts = self._meta if self.is_root_node(): filters = {'%s__isnull' % opts.parent_attr: True} else: filters = {opts.parent_attr: getattr(self, '%s_id' % opts.parent_attr)} queryset = self._tree_manager.filter(**filters) if not include_self: queryset = queryset.exclude(pk=self.pk) return queryset def insert_at(self, target, position='first-child', commit=False): """ Convenience method for calling ``TreeManager.insert_node`` with this model instance. """ self._tree_manager.insert_node(self, target, position, commit) def is_child_node(self): """ Returns ``True`` if this model instance is a child node, ``False`` otherwise. """ return not self.is_root_node() def is_leaf_node(self): """ Returns ``True`` if this model instance is a leaf node (it has no children), ``False`` otherwise. """ return not self.get_descendant_count() def is_root_node(self): """ Returns ``True`` if this model instance is a root node, ``False`` otherwise. """ return getattr(self, '%s_id' % self._meta.parent_attr) is None def move_to(self, target, position='first-child'): """ Convenience method for calling ``TreeManager.move_node`` with this model instance. """ self._tree_manager.move_node(self, target, position)
Python
""" Signal receiving functions which handle Modified Preorder Tree Traversal related logic when model instances are about to be saved or deleted. """ import operator from django.db.models.query import Q __all__ = ('pre_save',) def _insertion_target_filters(node, order_insertion_by): """ Creates a filter which matches suitable right siblings for ``node``, where insertion should maintain ordering according to the list of fields in ``order_insertion_by``. For example, given an ``order_insertion_by`` of ``['field1', 'field2', 'field3']``, the resulting filter should correspond to the following SQL:: field1 > %s OR (field1 = %s AND field2 > %s) OR (field1 = %s AND field2 = %s AND field3 > %s) """ fields = [] filters = [] for field in order_insertion_by: value = getattr(node, field) filters.append(reduce(operator.and_, [Q(**{f: v}) for f, v in fields] + [Q(**{'%s__gt' % field: value})])) fields.append((field, value)) return reduce(operator.or_, filters) def _get_ordered_insertion_target(node, parent): """ Attempts to retrieve a suitable right sibling for ``node`` underneath ``parent`` (which may be ``None`` in the case of root nodes) so that ordering by the fields specified by the node's class' ``order_insertion_by`` option is maintained. Returns ``None`` if no suitable sibling can be found. """ right_sibling = None # Optimisation - if the parent doesn't have descendants, # the node will always be its last child. if parent is None or parent.get_descendant_count() > 0: opts = node._meta order_by = opts.order_insertion_by[:] filters = _insertion_target_filters(node, order_by) if parent: filters = filters & Q(**{opts.parent_attr: parent}) # Fall back on tree ordering if multiple child nodes have # the same values. order_by.append(opts.left_attr) else: filters = filters & Q(**{'%s__isnull' % opts.parent_attr: True}) # Fall back on tree id ordering if multiple root nodes have # the same values. order_by.append(opts.tree_id_attr) try: right_sibling = \ node._default_manager.filter(filters).order_by(*order_by)[0] except IndexError: # No suitable right sibling could be found pass return right_sibling def pre_save(instance, **kwargs): """ If this is a new node, sets tree fields up before it is inserted into the database, making room in the tree structure as neccessary, defaulting to making the new node the last child of its parent. It the node's left and right edge indicators already been set, we take this as indication that the node has already been set up for insertion, so its tree fields are left untouched. If this is an existing node and its parent has been changed, performs reparenting in the tree structure, defaulting to making the node the last child of its new parent. In either case, if the node's class has its ``order_insertion_by`` tree option set, the node will be inserted or moved to the appropriate position to maintain ordering by the specified field. """ if kwargs.get('raw'): return opts = instance._meta parent = getattr(instance, opts.parent_attr) if not instance.pk: if (getattr(instance, opts.left_attr) and getattr(instance, opts.right_attr)): # This node has already been set up for insertion. return if opts.order_insertion_by: right_sibling = _get_ordered_insertion_target(instance, parent) if right_sibling: instance.insert_at(right_sibling, 'left') return # Default insertion instance.insert_at(parent, position='last-child') else: # TODO Is it possible to track the original parent so we # don't have to look it up again on each save after the # first? old_parent = getattr(instance._default_manager.get(pk=instance.pk), opts.parent_attr) if parent != old_parent: setattr(instance, opts.parent_attr, old_parent) try: if opts.order_insertion_by: right_sibling = _get_ordered_insertion_target(instance, parent) if right_sibling: instance.move_to(right_sibling, 'left') return # Default movement instance.move_to(parent, position='last-child') finally: # Make sure the instance's new parent is always # restored on the way out in case of errors. setattr(instance, opts.parent_attr, parent)
Python
""" A custom manager for working with trees of objects. """ from django.db import connection, models, transaction from django.utils.translation import ugettext as _ from mptt.exceptions import InvalidMove __all__ = ('TreeManager',) qn = connection.ops.quote_name COUNT_SUBQUERY = """( SELECT COUNT(*) FROM %(rel_table)s WHERE %(mptt_fk)s = %(mptt_table)s.%(mptt_pk)s )""" CUMULATIVE_COUNT_SUBQUERY = """( SELECT COUNT(*) FROM %(rel_table)s WHERE %(mptt_fk)s IN ( SELECT m2.%(mptt_pk)s FROM %(mptt_table)s m2 WHERE m2.%(tree_id)s = %(mptt_table)s.%(tree_id)s AND m2.%(left)s BETWEEN %(mptt_table)s.%(left)s AND %(mptt_table)s.%(right)s ) )""" class TreeManager(models.Manager): """ A manager for working with trees of objects. """ def __init__(self, parent_attr, left_attr, right_attr, tree_id_attr, level_attr): """ Tree attributes for the model being managed are held as attributes of this manager for later use, since it will be using them a **lot**. """ super(TreeManager, self).__init__() self.parent_attr = parent_attr self.left_attr = left_attr self.right_attr = right_attr self.tree_id_attr = tree_id_attr self.level_attr = level_attr def add_related_count(self, queryset, rel_model, rel_field, count_attr, cumulative=False): """ Adds a related item count to a given ``QuerySet`` using its ``extra`` method, for a ``Model`` class which has a relation to this ``Manager``'s ``Model`` class. Arguments: ``rel_model`` A ``Model`` class which has a relation to this `Manager``'s ``Model`` class. ``rel_field`` The name of the field in ``rel_model`` which holds the relation. ``count_attr`` The name of an attribute which should be added to each item in this ``QuerySet``, containing a count of how many instances of ``rel_model`` are related to it through ``rel_field``. ``cumulative`` If ``True``, the count will be for each item and all of its descendants, otherwise it will be for each item itself. """ opts = self.model._meta if cumulative: subquery = CUMULATIVE_COUNT_SUBQUERY % { 'rel_table': qn(rel_model._meta.db_table), 'mptt_fk': qn(rel_model._meta.get_field(rel_field).column), 'mptt_table': qn(opts.db_table), 'mptt_pk': qn(opts.pk.column), 'tree_id': qn(opts.get_field(self.tree_id_attr).column), 'left': qn(opts.get_field(self.left_attr).column), 'right': qn(opts.get_field(self.right_attr).column), } else: subquery = COUNT_SUBQUERY % { 'rel_table': qn(rel_model._meta.db_table), 'mptt_fk': qn(rel_model._meta.get_field(rel_field).column), 'mptt_table': qn(opts.db_table), 'mptt_pk': qn(opts.pk.column), } return queryset.extra(select={count_attr: subquery}) def get_query_set(self): """ Returns a ``QuerySet`` which contains all tree items, ordered in such a way that that root nodes appear in tree id order and their subtrees appear in depth-first order. """ return super(TreeManager, self).get_query_set().order_by( self.tree_id_attr, self.left_attr) def insert_node(self, node, target, position='last-child', commit=False): """ Sets up the tree state for ``node`` (which has not yet been inserted into in the database) so it will be positioned relative to a given ``target`` node as specified by ``position`` (when appropriate) it is inserted, with any neccessary space already having been made for it. A ``target`` of ``None`` indicates that ``node`` should be the last root node. If ``commit`` is ``True``, ``node``'s ``save()`` method will be called before it is returned. """ if node.pk: raise ValueError(_('Cannot insert a node which has already been saved.')) if target is None: setattr(node, self.left_attr, 1) setattr(node, self.right_attr, 2) setattr(node, self.level_attr, 0) setattr(node, self.tree_id_attr, self._get_next_tree_id()) setattr(node, self.parent_attr, None) elif target.is_root_node() and position in ['left', 'right']: target_tree_id = getattr(target, self.tree_id_attr) if position == 'left': tree_id = target_tree_id space_target = target_tree_id - 1 else: tree_id = target_tree_id + 1 space_target = target_tree_id self._create_tree_space(space_target) setattr(node, self.left_attr, 1) setattr(node, self.right_attr, 2) setattr(node, self.level_attr, 0) setattr(node, self.tree_id_attr, tree_id) setattr(node, self.parent_attr, None) else: setattr(node, self.left_attr, 0) setattr(node, self.level_attr, 0) space_target, level, left, parent = \ self._calculate_inter_tree_move_values(node, target, position) tree_id = getattr(parent, self.tree_id_attr) self._create_space(2, space_target, tree_id) setattr(node, self.left_attr, -left) setattr(node, self.right_attr, -left + 1) setattr(node, self.level_attr, -level) setattr(node, self.tree_id_attr, tree_id) setattr(node, self.parent_attr, parent) if commit: node.save() return node def move_node(self, node, target, position='last-child'): """ Moves ``node`` relative to a given ``target`` node as specified by ``position`` (when appropriate), by examining both nodes and calling the appropriate method to perform the move. A ``target`` of ``None`` indicates that ``node`` should be turned into a root node. Valid values for ``position`` are ``'first-child'``, ``'last-child'``, ``'left'`` or ``'right'``. ``node`` will be modified to reflect its new tree state in the database. This method explicitly checks for ``node`` being made a sibling of a root node, as this is a special case due to our use of tree ids to order root nodes. """ if target is None: if node.is_child_node(): self._make_child_root_node(node) elif target.is_root_node() and position in ['left', 'right']: self._make_sibling_of_root_node(node, target, position) else: if node.is_root_node(): self._move_root_node(node, target, position) else: self._move_child_node(node, target, position) transaction.commit_unless_managed() def root_node(self, tree_id): """ Returns the root node of the tree with the given id. """ return self.get(**{ self.tree_id_attr: tree_id, '%s__isnull' % self.parent_attr: True, }) def root_nodes(self): """ Creates a ``QuerySet`` containing root nodes. """ return self.filter(**{'%s__isnull' % self.parent_attr: True}) def _calculate_inter_tree_move_values(self, node, target, position): """ Calculates values required when moving ``node`` relative to ``target`` as specified by ``position``. """ left = getattr(node, self.left_attr) level = getattr(node, self.level_attr) target_left = getattr(target, self.left_attr) target_right = getattr(target, self.right_attr) target_level = getattr(target, self.level_attr) if position == 'last-child' or position == 'first-child': if position == 'last-child': space_target = target_right - 1 else: space_target = target_left level_change = level - target_level - 1 parent = target elif position == 'left' or position == 'right': if position == 'left': space_target = target_left - 1 else: space_target = target_right level_change = level - target_level parent = getattr(target, self.parent_attr) else: raise ValueError(_('An invalid position was given: %s.') % position) left_right_change = left - space_target - 1 return space_target, level_change, left_right_change, parent def _close_gap(self, size, target, tree_id): """ Closes a gap of a certain ``size`` after the given ``target`` point in the tree identified by ``tree_id``. """ self._manage_space(-size, target, tree_id) def _create_space(self, size, target, tree_id): """ Creates a space of a certain ``size`` after the given ``target`` point in the tree identified by ``tree_id``. """ self._manage_space(size, target, tree_id) def _create_tree_space(self, target_tree_id): """ Creates space for a new tree by incrementing all tree ids greater than ``target_tree_id``. """ opts = self.model._meta cursor = connection.cursor() cursor.execute(""" UPDATE %(table)s SET %(tree_id)s = %(tree_id)s + 1 WHERE %(tree_id)s > %%s""" % { 'table': qn(opts.db_table), 'tree_id': qn(opts.get_field(self.tree_id_attr).column), }, [target_tree_id]) def _get_next_tree_id(self): """ Determines the next largest unused tree id for the tree managed by this manager. """ opts = self.model._meta cursor = connection.cursor() cursor.execute('SELECT MAX(%s) FROM %s' % ( qn(opts.get_field(self.tree_id_attr).column), qn(opts.db_table))) row = cursor.fetchone() return row[0] and (row[0] + 1) or 1 def _inter_tree_move_and_close_gap(self, node, level_change, left_right_change, new_tree_id, parent_pk=None): """ Removes ``node`` from its current tree, with the given set of changes being applied to ``node`` and its descendants, closing the gap left by moving ``node`` as it does so. If ``parent_pk`` is ``None``, this indicates that ``node`` is being moved to a brand new tree as its root node, and will thus have its parent field set to ``NULL``. Otherwise, ``node`` will have ``parent_pk`` set for its parent field. """ opts = self.model._meta inter_tree_move_query = """ UPDATE %(table)s SET %(level)s = CASE WHEN %(left)s >= %%s AND %(left)s <= %%s THEN %(level)s - %%s ELSE %(level)s END, %(tree_id)s = CASE WHEN %(left)s >= %%s AND %(left)s <= %%s THEN %%s ELSE %(tree_id)s END, %(left)s = CASE WHEN %(left)s >= %%s AND %(left)s <= %%s THEN %(left)s - %%s WHEN %(left)s > %%s THEN %(left)s - %%s ELSE %(left)s END, %(right)s = CASE WHEN %(right)s >= %%s AND %(right)s <= %%s THEN %(right)s - %%s WHEN %(right)s > %%s THEN %(right)s - %%s ELSE %(right)s END, %(parent)s = CASE WHEN %(pk)s = %%s THEN %(new_parent)s ELSE %(parent)s END WHERE %(tree_id)s = %%s""" % { 'table': qn(opts.db_table), 'level': qn(opts.get_field(self.level_attr).column), 'left': qn(opts.get_field(self.left_attr).column), 'tree_id': qn(opts.get_field(self.tree_id_attr).column), 'right': qn(opts.get_field(self.right_attr).column), 'parent': qn(opts.get_field(self.parent_attr).column), 'pk': qn(opts.pk.column), 'new_parent': parent_pk is None and 'NULL' or '%s', } left = getattr(node, self.left_attr) right = getattr(node, self.right_attr) gap_size = right - left + 1 gap_target_left = left - 1 params = [ left, right, level_change, left, right, new_tree_id, left, right, left_right_change, gap_target_left, gap_size, left, right, left_right_change, gap_target_left, gap_size, node.pk, getattr(node, self.tree_id_attr) ] if parent_pk is not None: params.insert(-1, parent_pk) cursor = connection.cursor() cursor.execute(inter_tree_move_query, params) def _make_child_root_node(self, node, new_tree_id=None): """ Removes ``node`` from its tree, making it the root node of a new tree. If ``new_tree_id`` is not specified a new tree id will be generated. ``node`` will be modified to reflect its new tree state in the database. """ left = getattr(node, self.left_attr) right = getattr(node, self.right_attr) level = getattr(node, self.level_attr) tree_id = getattr(node, self.tree_id_attr) if not new_tree_id: new_tree_id = self._get_next_tree_id() left_right_change = left - 1 self._inter_tree_move_and_close_gap(node, level, left_right_change, new_tree_id) # Update the node to be consistent with the updated # tree in the database. setattr(node, self.left_attr, left - left_right_change) setattr(node, self.right_attr, right - left_right_change) setattr(node, self.level_attr, 0) setattr(node, self.tree_id_attr, new_tree_id) setattr(node, self.parent_attr, None) def _make_sibling_of_root_node(self, node, target, position): """ Moves ``node``, making it a sibling of the given ``target`` root node as specified by ``position``. ``node`` will be modified to reflect its new tree state in the database. Since we use tree ids to reduce the number of rows affected by tree mangement during insertion and deletion, root nodes are not true siblings; thus, making an item a sibling of a root node is a special case which involves shuffling tree ids around. """ if node == target: raise InvalidMove(_('A node may not be made a sibling of itself.')) opts = self.model._meta tree_id = getattr(node, self.tree_id_attr) target_tree_id = getattr(target, self.tree_id_attr) if node.is_child_node(): if position == 'left': space_target = target_tree_id - 1 new_tree_id = target_tree_id elif position == 'right': space_target = target_tree_id new_tree_id = target_tree_id + 1 else: raise ValueError(_('An invalid position was given: %s.') % position) self._create_tree_space(space_target) if tree_id > space_target: # The node's tree id has been incremented in the # database - this change must be reflected in the node # object for the method call below to operate on the # correct tree. setattr(node, self.tree_id_attr, tree_id + 1) self._make_child_root_node(node, new_tree_id) else: if position == 'left': if target_tree_id > tree_id: left_sibling = target.get_previous_sibling() if node == left_sibling: return new_tree_id = getattr(left_sibling, self.tree_id_attr) lower_bound, upper_bound = tree_id, new_tree_id shift = -1 else: new_tree_id = target_tree_id lower_bound, upper_bound = new_tree_id, tree_id shift = 1 elif position == 'right': if target_tree_id > tree_id: new_tree_id = target_tree_id lower_bound, upper_bound = tree_id, target_tree_id shift = -1 else: right_sibling = target.get_next_sibling() if node == right_sibling: return new_tree_id = getattr(right_sibling, self.tree_id_attr) lower_bound, upper_bound = new_tree_id, tree_id shift = 1 else: raise ValueError(_('An invalid position was given: %s.') % position) root_sibling_query = """ UPDATE %(table)s SET %(tree_id)s = CASE WHEN %(tree_id)s = %%s THEN %%s ELSE %(tree_id)s + %%s END WHERE %(tree_id)s >= %%s AND %(tree_id)s <= %%s""" % { 'table': qn(opts.db_table), 'tree_id': qn(opts.get_field(self.tree_id_attr).column), } cursor = connection.cursor() cursor.execute(root_sibling_query, [tree_id, new_tree_id, shift, lower_bound, upper_bound]) setattr(node, self.tree_id_attr, new_tree_id) def _manage_space(self, size, target, tree_id): """ Manages spaces in the tree identified by ``tree_id`` by changing the values of the left and right columns by ``size`` after the given ``target`` point. """ opts = self.model._meta space_query = """ UPDATE %(table)s SET %(left)s = CASE WHEN %(left)s > %%s THEN %(left)s + %%s ELSE %(left)s END, %(right)s = CASE WHEN %(right)s > %%s THEN %(right)s + %%s ELSE %(right)s END WHERE %(tree_id)s = %%s AND (%(left)s > %%s OR %(right)s > %%s)""" % { 'table': qn(opts.db_table), 'left': qn(opts.get_field(self.left_attr).column), 'right': qn(opts.get_field(self.right_attr).column), 'tree_id': qn(opts.get_field(self.tree_id_attr).column), } cursor = connection.cursor() cursor.execute(space_query, [target, size, target, size, tree_id, target, target]) def _move_child_node(self, node, target, position): """ Calls the appropriate method to move child node ``node`` relative to the given ``target`` node as specified by ``position``. """ tree_id = getattr(node, self.tree_id_attr) target_tree_id = getattr(target, self.tree_id_attr) if (getattr(node, self.tree_id_attr) == getattr(target, self.tree_id_attr)): self._move_child_within_tree(node, target, position) else: self._move_child_to_new_tree(node, target, position) def _move_child_to_new_tree(self, node, target, position): """ Moves child node ``node`` to a different tree, inserting it relative to the given ``target`` node in the new tree as specified by ``position``. ``node`` will be modified to reflect its new tree state in the database. """ left = getattr(node, self.left_attr) right = getattr(node, self.right_attr) level = getattr(node, self.level_attr) target_left = getattr(target, self.left_attr) target_right = getattr(target, self.right_attr) target_level = getattr(target, self.level_attr) tree_id = getattr(node, self.tree_id_attr) new_tree_id = getattr(target, self.tree_id_attr) space_target, level_change, left_right_change, parent = \ self._calculate_inter_tree_move_values(node, target, position) tree_width = right - left + 1 # Make space for the subtree which will be moved self._create_space(tree_width, space_target, new_tree_id) # Move the subtree self._inter_tree_move_and_close_gap(node, level_change, left_right_change, new_tree_id, parent.pk) # Update the node to be consistent with the updated # tree in the database. setattr(node, self.left_attr, left - left_right_change) setattr(node, self.right_attr, right - left_right_change) setattr(node, self.level_attr, level - level_change) setattr(node, self.tree_id_attr, new_tree_id) setattr(node, self.parent_attr, parent) def _move_child_within_tree(self, node, target, position): """ Moves child node ``node`` within its current tree relative to the given ``target`` node as specified by ``position``. ``node`` will be modified to reflect its new tree state in the database. """ left = getattr(node, self.left_attr) right = getattr(node, self.right_attr) level = getattr(node, self.level_attr) width = right - left + 1 tree_id = getattr(node, self.tree_id_attr) target_left = getattr(target, self.left_attr) target_right = getattr(target, self.right_attr) target_level = getattr(target, self.level_attr) if position == 'last-child' or position == 'first-child': if node == target: raise InvalidMove(_('A node may not be made a child of itself.')) elif left < target_left < right: raise InvalidMove(_('A node may not be made a child of any of its descendants.')) if position == 'last-child': if target_right > right: new_left = target_right - width new_right = target_right - 1 else: new_left = target_right new_right = target_right + width - 1 else: if target_left > left: new_left = target_left - width + 1 new_right = target_left else: new_left = target_left + 1 new_right = target_left + width level_change = level - target_level - 1 parent = target elif position == 'left' or position == 'right': if node == target: raise InvalidMove(_('A node may not be made a sibling of itself.')) elif left < target_left < right: raise InvalidMove(_('A node may not be made a sibling of any of its descendants.')) if position == 'left': if target_left > left: new_left = target_left - width new_right = target_left - 1 else: new_left = target_left new_right = target_left + width - 1 else: if target_right > right: new_left = target_right - width + 1 new_right = target_right else: new_left = target_right + 1 new_right = target_right + width level_change = level - target_level parent = getattr(target, self.parent_attr) else: raise ValueError(_('An invalid position was given: %s.') % position) left_boundary = min(left, new_left) right_boundary = max(right, new_right) left_right_change = new_left - left gap_size = width if left_right_change > 0: gap_size = -gap_size opts = self.model._meta # The level update must come before the left update to keep # MySQL happy - left seems to refer to the updated value # immediately after its update has been specified in the query # with MySQL, but not with SQLite or Postgres. move_subtree_query = """ UPDATE %(table)s SET %(level)s = CASE WHEN %(left)s >= %%s AND %(left)s <= %%s THEN %(level)s - %%s ELSE %(level)s END, %(left)s = CASE WHEN %(left)s >= %%s AND %(left)s <= %%s THEN %(left)s + %%s WHEN %(left)s >= %%s AND %(left)s <= %%s THEN %(left)s + %%s ELSE %(left)s END, %(right)s = CASE WHEN %(right)s >= %%s AND %(right)s <= %%s THEN %(right)s + %%s WHEN %(right)s >= %%s AND %(right)s <= %%s THEN %(right)s + %%s ELSE %(right)s END, %(parent)s = CASE WHEN %(pk)s = %%s THEN %%s ELSE %(parent)s END WHERE %(tree_id)s = %%s""" % { 'table': qn(opts.db_table), 'level': qn(opts.get_field(self.level_attr).column), 'left': qn(opts.get_field(self.left_attr).column), 'right': qn(opts.get_field(self.right_attr).column), 'parent': qn(opts.get_field(self.parent_attr).column), 'pk': qn(opts.pk.column), 'tree_id': qn(opts.get_field(self.tree_id_attr).column), } cursor = connection.cursor() cursor.execute(move_subtree_query, [ left, right, level_change, left, right, left_right_change, left_boundary, right_boundary, gap_size, left, right, left_right_change, left_boundary, right_boundary, gap_size, node.pk, parent.pk, tree_id]) # Update the node to be consistent with the updated # tree in the database. setattr(node, self.left_attr, new_left) setattr(node, self.right_attr, new_right) setattr(node, self.level_attr, level - level_change) setattr(node, self.parent_attr, parent) def _move_root_node(self, node, target, position): """ Moves root node``node`` to a different tree, inserting it relative to the given ``target`` node as specified by ``position``. ``node`` will be modified to reflect its new tree state in the database. """ left = getattr(node, self.left_attr) right = getattr(node, self.right_attr) level = getattr(node, self.level_attr) tree_id = getattr(node, self.tree_id_attr) new_tree_id = getattr(target, self.tree_id_attr) width = right - left + 1 if node == target: raise InvalidMove(_('A node may not be made a child of itself.')) elif tree_id == new_tree_id: raise InvalidMove(_('A node may not be made a child of any of its descendants.')) space_target, level_change, left_right_change, parent = \ self._calculate_inter_tree_move_values(node, target, position) # Create space for the tree which will be inserted self._create_space(width, space_target, new_tree_id) # Move the root node, making it a child node opts = self.model._meta move_tree_query = """ UPDATE %(table)s SET %(level)s = %(level)s - %%s, %(left)s = %(left)s - %%s, %(right)s = %(right)s - %%s, %(tree_id)s = %%s, %(parent)s = CASE WHEN %(pk)s = %%s THEN %%s ELSE %(parent)s END WHERE %(left)s >= %%s AND %(left)s <= %%s AND %(tree_id)s = %%s""" % { 'table': qn(opts.db_table), 'level': qn(opts.get_field(self.level_attr).column), 'left': qn(opts.get_field(self.left_attr).column), 'right': qn(opts.get_field(self.right_attr).column), 'tree_id': qn(opts.get_field(self.tree_id_attr).column), 'parent': qn(opts.get_field(self.parent_attr).column), 'pk': qn(opts.pk.column), } cursor = connection.cursor() cursor.execute(move_tree_query, [level_change, left_right_change, left_right_change, new_tree_id, node.pk, parent.pk, left, right, tree_id]) # Update the former root node to be consistent with the updated # tree in the database. setattr(node, self.left_attr, left - left_right_change) setattr(node, self.right_attr, right - left_right_change) setattr(node, self.level_attr, level - level_change) setattr(node, self.tree_id_attr, new_tree_id) setattr(node, self.parent_attr, parent)
Python
import re from django.test import TestCase from mptt.exceptions import InvalidMove from mptt.tests import doctests from mptt.tests.models import Category, Genre def get_tree_details(nodes): """Creates pertinent tree details for the given list of nodes.""" opts = nodes[0]._meta return '\n'.join(['%s %s %s %s %s %s' % (n.pk, getattr(n, '%s_id' % opts.parent_attr) or '-', getattr(n, opts.tree_id_attr), getattr(n, opts.level_attr), getattr(n, opts.left_attr), getattr(n, opts.right_attr)) for n in nodes]) leading_whitespace_re = re.compile(r'^\s+', re.MULTILINE) def tree_details(text): """ Trims leading whitespace from the given text specifying tree details so triple-quoted strings can be used to provide tree details in a readable format (says who?), to be compared with the result of using the ``get_tree_details`` function. """ return leading_whitespace_re.sub('', text) # genres.json defines the following tree structure # # 1 - 1 0 1 16 action # 2 1 1 1 2 9 +-- platformer # 3 2 1 2 3 4 | |-- platformer_2d # 4 2 1 2 5 6 | |-- platformer_3d # 5 2 1 2 7 8 | +-- platformer_4d # 6 1 1 1 10 15 +-- shmup # 7 6 1 2 11 12 |-- shmup_vertical # 8 6 1 2 13 14 +-- shmup_horizontal # 9 - 2 0 1 6 rpg # 10 9 2 1 2 3 |-- arpg # 11 9 2 1 4 5 +-- trpg class ReparentingTestCase(TestCase): """ Test that trees are in the appropriate state after reparenting and that reparented items have the correct tree attributes defined, should they be required for use after a save. """ fixtures = ['genres.json'] def test_new_root_from_subtree(self): shmup = Genre.objects.get(id=6) shmup.parent = None shmup.save() self.assertEqual(get_tree_details([shmup]), '6 - 3 0 1 6') self.assertEqual(get_tree_details(Genre.tree.all()), tree_details("""1 - 1 0 1 10 2 1 1 1 2 9 3 2 1 2 3 4 4 2 1 2 5 6 5 2 1 2 7 8 9 - 2 0 1 6 10 9 2 1 2 3 11 9 2 1 4 5 6 - 3 0 1 6 7 6 3 1 2 3 8 6 3 1 4 5""")) def test_new_root_from_leaf_with_siblings(self): platformer_2d = Genre.objects.get(id=3) platformer_2d.parent = None platformer_2d.save() self.assertEqual(get_tree_details([platformer_2d]), '3 - 3 0 1 2') self.assertEqual(get_tree_details(Genre.tree.all()), tree_details("""1 - 1 0 1 14 2 1 1 1 2 7 4 2 1 2 3 4 5 2 1 2 5 6 6 1 1 1 8 13 7 6 1 2 9 10 8 6 1 2 11 12 9 - 2 0 1 6 10 9 2 1 2 3 11 9 2 1 4 5 3 - 3 0 1 2""")) def test_new_child_from_root(self): action = Genre.objects.get(id=1) rpg = Genre.objects.get(id=9) action.parent = rpg action.save() self.assertEqual(get_tree_details([action]), '1 9 2 1 6 21') self.assertEqual(get_tree_details(Genre.tree.all()), tree_details("""9 - 2 0 1 22 10 9 2 1 2 3 11 9 2 1 4 5 1 9 2 1 6 21 2 1 2 2 7 14 3 2 2 3 8 9 4 2 2 3 10 11 5 2 2 3 12 13 6 1 2 2 15 20 7 6 2 3 16 17 8 6 2 3 18 19""")) def test_move_leaf_to_other_tree(self): shmup_horizontal = Genre.objects.get(id=8) rpg = Genre.objects.get(id=9) shmup_horizontal.parent = rpg shmup_horizontal.save() self.assertEqual(get_tree_details([shmup_horizontal]), '8 9 2 1 6 7') self.assertEqual(get_tree_details(Genre.tree.all()), tree_details("""1 - 1 0 1 14 2 1 1 1 2 9 3 2 1 2 3 4 4 2 1 2 5 6 5 2 1 2 7 8 6 1 1 1 10 13 7 6 1 2 11 12 9 - 2 0 1 8 10 9 2 1 2 3 11 9 2 1 4 5 8 9 2 1 6 7""")) def test_move_subtree_to_other_tree(self): shmup = Genre.objects.get(id=6) trpg = Genre.objects.get(id=11) shmup.parent = trpg shmup.save() self.assertEqual(get_tree_details([shmup]), '6 11 2 2 5 10') self.assertEqual(get_tree_details(Genre.tree.all()), tree_details("""1 - 1 0 1 10 2 1 1 1 2 9 3 2 1 2 3 4 4 2 1 2 5 6 5 2 1 2 7 8 9 - 2 0 1 12 10 9 2 1 2 3 11 9 2 1 4 11 6 11 2 2 5 10 7 6 2 3 6 7 8 6 2 3 8 9""")) def test_move_child_up_level(self): shmup_horizontal = Genre.objects.get(id=8) action = Genre.objects.get(id=1) shmup_horizontal.parent = action shmup_horizontal.save() self.assertEqual(get_tree_details([shmup_horizontal]), '8 1 1 1 14 15') self.assertEqual(get_tree_details(Genre.tree.all()), tree_details("""1 - 1 0 1 16 2 1 1 1 2 9 3 2 1 2 3 4 4 2 1 2 5 6 5 2 1 2 7 8 6 1 1 1 10 13 7 6 1 2 11 12 8 1 1 1 14 15 9 - 2 0 1 6 10 9 2 1 2 3 11 9 2 1 4 5""")) def test_move_subtree_down_level(self): shmup = Genre.objects.get(id=6) platformer = Genre.objects.get(id=2) shmup.parent = platformer shmup.save() self.assertEqual(get_tree_details([shmup]), '6 2 1 2 9 14') self.assertEqual(get_tree_details(Genre.tree.all()), tree_details("""1 - 1 0 1 16 2 1 1 1 2 15 3 2 1 2 3 4 4 2 1 2 5 6 5 2 1 2 7 8 6 2 1 2 9 14 7 6 1 3 10 11 8 6 1 3 12 13 9 - 2 0 1 6 10 9 2 1 2 3 11 9 2 1 4 5""")) def test_invalid_moves(self): # A node may not be made a child of itself action = Genre.objects.get(id=1) action.parent = action platformer = Genre.objects.get(id=2) platformer.parent = platformer self.assertRaises(InvalidMove, action.save) self.assertRaises(InvalidMove, platformer.save) # A node may not be made a child of any of its descendants platformer_4d = Genre.objects.get(id=5) action.parent = platformer_4d platformer.parent = platformer_4d self.assertRaises(InvalidMove, action.save) self.assertRaises(InvalidMove, platformer.save) # New parent is still set when an error occurs self.assertEquals(action.parent, platformer_4d) self.assertEquals(platformer.parent, platformer_4d) # categories.json defines the following tree structure: # # 1 - 1 0 1 20 games # 2 1 1 1 2 7 +-- wii # 3 2 1 2 3 4 | |-- wii_games # 4 2 1 2 5 6 | +-- wii_hardware # 5 1 1 1 8 13 +-- xbox360 # 6 5 1 2 9 10 | |-- xbox360_games # 7 5 1 2 11 12 | +-- xbox360_hardware # 8 1 1 1 14 19 +-- ps3 # 9 8 1 2 15 16 |-- ps3_games # 10 8 1 2 17 18 +-- ps3_hardware class DeletionTestCase(TestCase): """ Tests that the tree structure is maintained appropriately in various deletion scenrios. """ fixtures = ['categories.json'] def test_delete_root_node(self): # Add a few other roots to verify that they aren't affected Category(name='Preceding root').insert_at(Category.objects.get(id=1), 'left', commit=True) Category(name='Following root').insert_at(Category.objects.get(id=1), 'right', commit=True) self.assertEqual(get_tree_details(Category.tree.all()), tree_details("""11 - 1 0 1 2 1 - 2 0 1 20 2 1 2 1 2 7 3 2 2 2 3 4 4 2 2 2 5 6 5 1 2 1 8 13 6 5 2 2 9 10 7 5 2 2 11 12 8 1 2 1 14 19 9 8 2 2 15 16 10 8 2 2 17 18 12 - 3 0 1 2"""), 'Setup for test produced unexpected result') Category.objects.get(id=1).delete() self.assertEqual(get_tree_details(Category.tree.all()), tree_details("""11 - 1 0 1 2 12 - 3 0 1 2""")) def test_delete_last_node_with_siblings(self): Category.objects.get(id=9).delete() self.assertEqual(get_tree_details(Category.tree.all()), tree_details("""1 - 1 0 1 18 2 1 1 1 2 7 3 2 1 2 3 4 4 2 1 2 5 6 5 1 1 1 8 13 6 5 1 2 9 10 7 5 1 2 11 12 8 1 1 1 14 17 10 8 1 2 15 16""")) def test_delete_last_node_with_descendants(self): Category.objects.get(id=8).delete() self.assertEqual(get_tree_details(Category.tree.all()), tree_details("""1 - 1 0 1 14 2 1 1 1 2 7 3 2 1 2 3 4 4 2 1 2 5 6 5 1 1 1 8 13 6 5 1 2 9 10 7 5 1 2 11 12""")) def test_delete_node_with_siblings(self): Category.objects.get(id=6).delete() self.assertEqual(get_tree_details(Category.tree.all()), tree_details("""1 - 1 0 1 18 2 1 1 1 2 7 3 2 1 2 3 4 4 2 1 2 5 6 5 1 1 1 8 11 7 5 1 2 9 10 8 1 1 1 12 17 9 8 1 2 13 14 10 8 1 2 15 16""")) def test_delete_node_with_descendants_and_siblings(self): """ Regression test for Issue 23 - we used to use pre_delete, which resulted in tree cleanup being performed for every node being deleted, rather than just the node on which ``delete()`` was called. """ Category.objects.get(id=5).delete() self.assertEqual(get_tree_details(Category.tree.all()), tree_details("""1 - 1 0 1 14 2 1 1 1 2 7 3 2 1 2 3 4 4 2 1 2 5 6 8 1 1 1 8 13 9 8 1 2 9 10 10 8 1 2 11 12""")) class IntraTreeMovementTestCase(TestCase): pass class InterTreeMovementTestCase(TestCase): pass class PositionedInsertionTestCase(TestCase): pass
Python
from django.db import models import mptt class Category(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey('self', null=True, blank=True, related_name='children') def __unicode__(self): return self.name def delete(self): super(Category, self).delete() class Genre(models.Model): name = models.CharField(max_length=50, unique=True) parent = models.ForeignKey('self', null=True, blank=True, related_name='children') def __unicode__(self): return self.name class Insert(models.Model): parent = models.ForeignKey('self', null=True, blank=True, related_name='children') class MultiOrder(models.Model): name = models.CharField(max_length=50) size = models.PositiveIntegerField() date = models.DateField() parent = models.ForeignKey('self', null=True, blank=True, related_name='children') def __unicode__(self): return self.name class Node(models.Model): parent = models.ForeignKey('self', null=True, blank=True, related_name='children') class OrderedInsertion(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey('self', null=True, blank=True, related_name='children') def __unicode__(self): return self.name class Tree(models.Model): parent = models.ForeignKey('self', null=True, blank=True, related_name='children') mptt.register(Category) mptt.register(Genre) mptt.register(Insert) mptt.register(MultiOrder, order_insertion_by=['name', 'size', 'date']) mptt.register(Node, left_attr='does', right_attr='zis', level_attr='madness', tree_id_attr='work') mptt.register(OrderedInsertion, order_insertion_by=['name']) mptt.register(Tree)
Python
import doctest import unittest from mptt.tests import doctests from mptt.tests import testcases def suite(): s = unittest.TestSuite() s.addTest(doctest.DocTestSuite(doctests)) s.addTest(unittest.defaultTestLoader.loadTestsFromModule(testcases)) return s
Python
import os DIRNAME = os.path.dirname(__file__) DEBUG = True DATABASE_ENGINE = 'sqlite3' DATABASE_NAME = os.path.join(DIRNAME, 'mptt.db') #DATABASE_ENGINE = 'mysql' #DATABASE_NAME = 'mptt_test' #DATABASE_USER = 'root' #DATABASE_PASSWORD = '' #DATABASE_HOST = 'localhost' #DATABASE_PORT = '3306' #DATABASE_ENGINE = 'postgresql_psycopg2' #DATABASE_NAME = 'mptt_test' #DATABASE_USER = 'postgres' #DATABASE_PASSWORD = '' #DATABASE_HOST = 'localhost' #DATABASE_PORT = '5432' INSTALLED_APPS = ( 'mptt', 'mptt.tests', )
Python
r""" >>> from datetime import date >>> from mptt.exceptions import InvalidMove >>> from mptt.tests.models import Genre, Insert, MultiOrder, Node, OrderedInsertion, Tree >>> def print_tree_details(nodes): ... opts = nodes[0]._meta ... print '\n'.join(['%s %s %s %s %s %s' % \ ... (n.pk, getattr(n, '%s_id' % opts.parent_attr) or '-', ... getattr(n, opts.tree_id_attr), getattr(n, opts.level_attr), ... getattr(n, opts.left_attr), getattr(n, opts.right_attr)) \ ... for n in nodes]) >>> import mptt >>> mptt.register(Genre) Traceback (most recent call last): ... AlreadyRegistered: The model Genre has already been registered. # Creation #################################################################### >>> action = Genre.objects.create(name='Action') >>> platformer = Genre.objects.create(name='Platformer', parent=action) >>> platformer_2d = Genre.objects.create(name='2D Platformer', parent=platformer) >>> platformer = Genre.objects.get(pk=platformer.pk) >>> platformer_3d = Genre.objects.create(name='3D Platformer', parent=platformer) >>> platformer = Genre.objects.get(pk=platformer.pk) >>> platformer_4d = Genre.objects.create(name='4D Platformer', parent=platformer) >>> rpg = Genre.objects.create(name='Role-playing Game') >>> arpg = Genre.objects.create(name='Action RPG', parent=rpg) >>> rpg = Genre.objects.get(pk=rpg.pk) >>> trpg = Genre.objects.create(name='Tactical RPG', parent=rpg) >>> print_tree_details(Genre.tree.all()) 1 - 1 0 1 10 2 1 1 1 2 9 3 2 1 2 3 4 4 2 1 2 5 6 5 2 1 2 7 8 6 - 2 0 1 6 7 6 2 1 2 3 8 6 2 1 4 5 # Utilities ################################################################### >>> from mptt.utils import previous_current_next, tree_item_iterator, drilldown_tree_for_node >>> for p,c,n in previous_current_next(Genre.tree.all()): ... print (p,c,n) (None, <Genre: Action>, <Genre: Platformer>) (<Genre: Action>, <Genre: Platformer>, <Genre: 2D Platformer>) (<Genre: Platformer>, <Genre: 2D Platformer>, <Genre: 3D Platformer>) (<Genre: 2D Platformer>, <Genre: 3D Platformer>, <Genre: 4D Platformer>) (<Genre: 3D Platformer>, <Genre: 4D Platformer>, <Genre: Role-playing Game>) (<Genre: 4D Platformer>, <Genre: Role-playing Game>, <Genre: Action RPG>) (<Genre: Role-playing Game>, <Genre: Action RPG>, <Genre: Tactical RPG>) (<Genre: Action RPG>, <Genre: Tactical RPG>, None) >>> for i,s in tree_item_iterator(Genre.tree.all()): ... print (i, s['new_level'], s['closed_levels']) (<Genre: Action>, True, []) (<Genre: Platformer>, True, []) (<Genre: 2D Platformer>, True, []) (<Genre: 3D Platformer>, False, []) (<Genre: 4D Platformer>, False, [2, 1]) (<Genre: Role-playing Game>, False, []) (<Genre: Action RPG>, True, []) (<Genre: Tactical RPG>, False, [1, 0]) >>> for i,s in tree_item_iterator(Genre.tree.all(), ancestors=True): ... print (i, s['new_level'], s['ancestors'], s['closed_levels']) (<Genre: Action>, True, [], []) (<Genre: Platformer>, True, [u'Action'], []) (<Genre: 2D Platformer>, True, [u'Action', u'Platformer'], []) (<Genre: 3D Platformer>, False, [u'Action', u'Platformer'], []) (<Genre: 4D Platformer>, False, [u'Action', u'Platformer'], [2, 1]) (<Genre: Role-playing Game>, False, [], []) (<Genre: Action RPG>, True, [u'Role-playing Game'], []) (<Genre: Tactical RPG>, False, [u'Role-playing Game'], [1, 0]) >>> action = Genre.objects.get(pk=action.pk) >>> [item.name for item in drilldown_tree_for_node(action)] [u'Action', u'Platformer'] >>> platformer = Genre.objects.get(pk=platformer.pk) >>> [item.name for item in drilldown_tree_for_node(platformer)] [u'Action', u'Platformer', u'2D Platformer', u'3D Platformer', u'4D Platformer'] >>> platformer_3d = Genre.objects.get(pk=platformer_3d.pk) >>> [item.name for item in drilldown_tree_for_node(platformer_3d)] [u'Action', u'Platformer', u'3D Platformer'] # Forms ####################################################################### >>> from mptt.forms import TreeNodeChoiceField, MoveNodeForm >>> f = TreeNodeChoiceField(queryset=Genre.tree.all()) >>> print(f.widget.render("test", None)) <select name="test"> <option value="1"> Action</option> <option value="2">--- Platformer</option> <option value="3">------ 2D Platformer</option> <option value="4">------ 3D Platformer</option> <option value="5">------ 4D Platformer</option> <option value="6"> Role-playing Game</option> <option value="7">--- Action RPG</option> <option value="8">--- Tactical RPG</option> </select> >>> f = TreeNodeChoiceField(queryset=Genre.tree.all(), required=False) >>> print(f.widget.render("test", None)) <select name="test"> <option value="" selected="selected">---------</option> <option value="1"> Action</option> <option value="2">--- Platformer</option> <option value="3">------ 2D Platformer</option> <option value="4">------ 3D Platformer</option> <option value="5">------ 4D Platformer</option> <option value="6"> Role-playing Game</option> <option value="7">--- Action RPG</option> <option value="8">--- Tactical RPG</option> </select> >>> f = TreeNodeChoiceField(queryset=Genre.tree.all(), empty_label=u'None of the below') >>> print(f.widget.render("test", None)) <select name="test"> <option value="" selected="selected">None of the below</option> <option value="1"> Action</option> <option value="2">--- Platformer</option> <option value="3">------ 2D Platformer</option> <option value="4">------ 3D Platformer</option> <option value="5">------ 4D Platformer</option> <option value="6"> Role-playing Game</option> <option value="7">--- Action RPG</option> <option value="8">--- Tactical RPG</option> </select> >>> f = TreeNodeChoiceField(queryset=Genre.tree.all(), required=False, empty_label=u'None of the below') >>> print(f.widget.render("test", None)) <select name="test"> <option value="" selected="selected">None of the below</option> <option value="1"> Action</option> <option value="2">--- Platformer</option> <option value="3">------ 2D Platformer</option> <option value="4">------ 3D Platformer</option> <option value="5">------ 4D Platformer</option> <option value="6"> Role-playing Game</option> <option value="7">--- Action RPG</option> <option value="8">--- Tactical RPG</option> </select> >>> f = TreeNodeChoiceField(queryset=Genre.tree.all(), level_indicator=u'+--') >>> print(f.widget.render("test", None)) <select name="test"> <option value="1"> Action</option> <option value="2">+-- Platformer</option> <option value="3">+--+-- 2D Platformer</option> <option value="4">+--+-- 3D Platformer</option> <option value="5">+--+-- 4D Platformer</option> <option value="6"> Role-playing Game</option> <option value="7">+-- Action RPG</option> <option value="8">+-- Tactical RPG</option> </select> >>> form = MoveNodeForm(Genre.objects.get(pk=7)) >>> print(form) <tr><th><label for="id_target">Target:</label></th><td><select id="id_target" name="target" size="10"> <option value="1"> Action</option> <option value="2">--- Platformer</option> <option value="3">------ 2D Platformer</option> <option value="4">------ 3D Platformer</option> <option value="5">------ 4D Platformer</option> <option value="6"> Role-playing Game</option> <option value="8">--- Tactical RPG</option> </select></td></tr> <tr><th><label for="id_position">Position:</label></th><td><select name="position" id="id_position"> <option value="first-child">First child</option> <option value="last-child">Last child</option> <option value="left">Left sibling</option> <option value="right">Right sibling</option> </select></td></tr> >>> form = MoveNodeForm(Genre.objects.get(pk=7), level_indicator=u'+--', target_select_size=5) >>> print(form) <tr><th><label for="id_target">Target:</label></th><td><select id="id_target" name="target" size="5"> <option value="1"> Action</option> <option value="2">+-- Platformer</option> <option value="3">+--+-- 2D Platformer</option> <option value="4">+--+-- 3D Platformer</option> <option value="5">+--+-- 4D Platformer</option> <option value="6"> Role-playing Game</option> <option value="8">+-- Tactical RPG</option> </select></td></tr> <tr><th><label for="id_position">Position:</label></th><td><select name="position" id="id_position"> <option value="first-child">First child</option> <option value="last-child">Last child</option> <option value="left">Left sibling</option> <option value="right">Right sibling</option> </select></td></tr> # TreeManager Methods ######################################################### >>> Genre.tree.root_node(action.tree_id) <Genre: Action> >>> Genre.tree.root_node(rpg.tree_id) <Genre: Role-playing Game> >>> Genre.tree.root_node(3) Traceback (most recent call last): ... DoesNotExist: Genre matching query does not exist. >>> [g.name for g in Genre.tree.root_nodes()] [u'Action', u'Role-playing Game'] # Model Instance Methods ###################################################### >>> action = Genre.objects.get(pk=action.pk) >>> [g.name for g in action.get_ancestors()] [] >>> [g.name for g in action.get_ancestors(ascending=True)] [] >>> [g.name for g in action.get_children()] [u'Platformer'] >>> [g.name for g in action.get_descendants()] [u'Platformer', u'2D Platformer', u'3D Platformer', u'4D Platformer'] >>> [g.name for g in action.get_descendants(include_self=True)] [u'Action', u'Platformer', u'2D Platformer', u'3D Platformer', u'4D Platformer'] >>> action.get_descendant_count() 4 >>> action.get_previous_sibling() >>> action.get_next_sibling() <Genre: Role-playing Game> >>> action.get_root() <Genre: Action> >>> [g.name for g in action.get_siblings()] [u'Role-playing Game'] >>> [g.name for g in action.get_siblings(include_self=True)] [u'Action', u'Role-playing Game'] >>> action.is_root_node() True >>> action.is_child_node() False >>> action.is_leaf_node() False >>> platformer = Genre.objects.get(pk=platformer.pk) >>> [g.name for g in platformer.get_ancestors()] [u'Action'] >>> [g.name for g in platformer.get_ancestors(ascending=True)] [u'Action'] >>> [g.name for g in platformer.get_children()] [u'2D Platformer', u'3D Platformer', u'4D Platformer'] >>> [g.name for g in platformer.get_descendants()] [u'2D Platformer', u'3D Platformer', u'4D Platformer'] >>> [g.name for g in platformer.get_descendants(include_self=True)] [u'Platformer', u'2D Platformer', u'3D Platformer', u'4D Platformer'] >>> platformer.get_descendant_count() 3 >>> platformer.get_previous_sibling() >>> platformer.get_next_sibling() >>> platformer.get_root() <Genre: Action> >>> [g.name for g in platformer.get_siblings()] [] >>> [g.name for g in platformer.get_siblings(include_self=True)] [u'Platformer'] >>> platformer.is_root_node() False >>> platformer.is_child_node() True >>> platformer.is_leaf_node() False >>> platformer_3d = Genre.objects.get(pk=platformer_3d.pk) >>> [g.name for g in platformer_3d.get_ancestors()] [u'Action', u'Platformer'] >>> [g.name for g in platformer_3d.get_ancestors(ascending=True)] [u'Platformer', u'Action'] >>> [g.name for g in platformer_3d.get_children()] [] >>> [g.name for g in platformer_3d.get_descendants()] [] >>> [g.name for g in platformer_3d.get_descendants(include_self=True)] [u'3D Platformer'] >>> platformer_3d.get_descendant_count() 0 >>> platformer_3d.get_previous_sibling() <Genre: 2D Platformer> >>> platformer_3d.get_next_sibling() <Genre: 4D Platformer> >>> platformer_3d.get_root() <Genre: Action> >>> [g.name for g in platformer_3d.get_siblings()] [u'2D Platformer', u'4D Platformer'] >>> [g.name for g in platformer_3d.get_siblings(include_self=True)] [u'2D Platformer', u'3D Platformer', u'4D Platformer'] >>> platformer_3d.is_root_node() False >>> platformer_3d.is_child_node() True >>> platformer_3d.is_leaf_node() True # The move_to method will be used in other tests to verify that it calls the # TreeManager correctly. ####################### # Intra-Tree Movement # ####################### >>> root = Node.objects.create() >>> c_1 = Node.objects.create(parent=root) >>> c_1_1 = Node.objects.create(parent=c_1) >>> c_1 = Node.objects.get(pk=c_1.pk) >>> c_1_2 = Node.objects.create(parent=c_1) >>> root = Node.objects.get(pk=root.pk) >>> c_2 = Node.objects.create(parent=root) >>> c_2_1 = Node.objects.create(parent=c_2) >>> c_2 = Node.objects.get(pk=c_2.pk) >>> c_2_2 = Node.objects.create(parent=c_2) >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 14 2 1 1 1 2 7 3 2 1 2 3 4 4 2 1 2 5 6 5 1 1 1 8 13 6 5 1 2 9 10 7 5 1 2 11 12 # Validate exceptions are raised appropriately >>> root = Node.objects.get(pk=root.pk) >>> Node.tree.move_node(root, root, position='first-child') Traceback (most recent call last): ... InvalidMove: A node may not be made a child of itself. >>> c_1 = Node.objects.get(pk=c_1.pk) >>> c_1_1 = Node.objects.get(pk=c_1_1.pk) >>> Node.tree.move_node(c_1, c_1_1, position='last-child') Traceback (most recent call last): ... InvalidMove: A node may not be made a child of any of its descendants. >>> Node.tree.move_node(root, root, position='right') Traceback (most recent call last): ... InvalidMove: A node may not be made a sibling of itself. >>> c_2 = Node.objects.get(pk=c_2.pk) >>> Node.tree.move_node(c_1, c_1_1, position='left') Traceback (most recent call last): ... InvalidMove: A node may not be made a sibling of any of its descendants. >>> Node.tree.move_node(c_1, c_2, position='cheese') Traceback (most recent call last): ... ValueError: An invalid position was given: cheese. # Move up the tree using first-child >>> c_2_2 = Node.objects.get(pk=c_2_2.pk) >>> c_1 = Node.objects.get(pk=c_1.pk) >>> Node.tree.move_node(c_2_2, c_1, 'first-child') >>> print_tree_details([c_2_2]) 7 2 1 2 3 4 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 14 2 1 1 1 2 9 7 2 1 2 3 4 3 2 1 2 5 6 4 2 1 2 7 8 5 1 1 1 10 13 6 5 1 2 11 12 # Undo the move using right >>> c_2_1 = Node.objects.get(pk=c_2_1.pk) >>> c_2_2.move_to(c_2_1, 'right') >>> print_tree_details([c_2_2]) 7 5 1 2 11 12 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 14 2 1 1 1 2 7 3 2 1 2 3 4 4 2 1 2 5 6 5 1 1 1 8 13 6 5 1 2 9 10 7 5 1 2 11 12 # Move up the tree with descendants using first-child >>> c_2 = Node.objects.get(pk=c_2.pk) >>> c_1 = Node.objects.get(pk=c_1.pk) >>> Node.tree.move_node(c_2, c_1, 'first-child') >>> print_tree_details([c_2]) 5 2 1 2 3 8 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 14 2 1 1 1 2 13 5 2 1 2 3 8 6 5 1 3 4 5 7 5 1 3 6 7 3 2 1 2 9 10 4 2 1 2 11 12 # Undo the move using right >>> c_1 = Node.objects.get(pk=c_1.pk) >>> Node.tree.move_node(c_2, c_1, 'right') >>> print_tree_details([c_2]) 5 1 1 1 8 13 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 14 2 1 1 1 2 7 3 2 1 2 3 4 4 2 1 2 5 6 5 1 1 1 8 13 6 5 1 2 9 10 7 5 1 2 11 12 COVERAGE | U1 | U> | D1 | D> ------------+----+----+----+---- first-child | Y | Y | | last-child | | | | left | | | | right | | | Y | Y # Move down the tree using first-child >>> c_1_2 = Node.objects.get(pk=c_1_2.pk) >>> c_2 = Node.objects.get(pk=c_2.pk) >>> Node.tree.move_node(c_1_2, c_2, 'first-child') >>> print_tree_details([c_1_2]) 4 5 1 2 7 8 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 14 2 1 1 1 2 5 3 2 1 2 3 4 5 1 1 1 6 13 4 5 1 2 7 8 6 5 1 2 9 10 7 5 1 2 11 12 # Undo the move using last-child >>> c_1 = Node.objects.get(pk=c_1.pk) >>> Node.tree.move_node(c_1_2, c_1, 'last-child') >>> print_tree_details([c_1_2]) 4 2 1 2 5 6 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 14 2 1 1 1 2 7 3 2 1 2 3 4 4 2 1 2 5 6 5 1 1 1 8 13 6 5 1 2 9 10 7 5 1 2 11 12 # Move down the tree with descendants using first-child >>> c_1 = Node.objects.get(pk=c_1.pk) >>> c_2 = Node.objects.get(pk=c_2.pk) >>> Node.tree.move_node(c_1, c_2, 'first-child') >>> print_tree_details([c_1]) 2 5 1 2 3 8 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 14 5 1 1 1 2 13 2 5 1 2 3 8 3 2 1 3 4 5 4 2 1 3 6 7 6 5 1 2 9 10 7 5 1 2 11 12 # Undo the move using left >>> c_2 = Node.objects.get(pk=c_2.pk) >>> Node.tree.move_node(c_1, c_2, 'left') >>> print_tree_details([c_1]) 2 1 1 1 2 7 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 14 2 1 1 1 2 7 3 2 1 2 3 4 4 2 1 2 5 6 5 1 1 1 8 13 6 5 1 2 9 10 7 5 1 2 11 12 COVERAGE | U1 | U> | D1 | D> ------------+----+----+----+---- first-child | Y | Y | Y | Y last-child | Y | | | left | | Y | | right | | | Y | Y # Move up the tree using right >>> c_2_2 = Node.objects.get(pk=c_2_2.pk) >>> c_1_1 = Node.objects.get(pk=c_1_1.pk) >>> Node.tree.move_node(c_2_2, c_1_1, 'right') >>> print_tree_details([c_2_2]) 7 2 1 2 5 6 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 14 2 1 1 1 2 9 3 2 1 2 3 4 7 2 1 2 5 6 4 2 1 2 7 8 5 1 1 1 10 13 6 5 1 2 11 12 # Undo the move using last-child >>> c_2 = Node.objects.get(pk=c_2.pk) >>> Node.tree.move_node(c_2_2, c_2, 'last-child') >>> print_tree_details([c_2_2]) 7 5 1 2 11 12 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 14 2 1 1 1 2 7 3 2 1 2 3 4 4 2 1 2 5 6 5 1 1 1 8 13 6 5 1 2 9 10 7 5 1 2 11 12 # Move up the tree with descendants using right >>> c_2 = Node.objects.get(pk=c_2.pk) >>> c_1_1 = Node.objects.get(pk=c_1_1.pk) >>> Node.tree.move_node(c_2, c_1_1, 'right') >>> print_tree_details([c_2]) 5 2 1 2 5 10 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 14 2 1 1 1 2 13 3 2 1 2 3 4 5 2 1 2 5 10 6 5 1 3 6 7 7 5 1 3 8 9 4 2 1 2 11 12 # Undo the move using last-child >>> root = Node.objects.get(pk=root.pk) >>> Node.tree.move_node(c_2, root, 'last-child') >>> print_tree_details([c_2]) 5 1 1 1 8 13 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 14 2 1 1 1 2 7 3 2 1 2 3 4 4 2 1 2 5 6 5 1 1 1 8 13 6 5 1 2 9 10 7 5 1 2 11 12 COVERAGE | U1 | U> | D1 | D> ------------+----+----+----+---- first-child | Y | Y | Y | Y last-child | Y | | Y | Y left | | Y | | right | Y | Y | Y | Y # Move down the tree with descendants using left >>> c_1 = Node.objects.get(pk=c_1.pk) >>> c_2_2 = Node.objects.get(pk=c_2_2.pk) >>> Node.tree.move_node(c_1, c_2_2, 'left') >>> print_tree_details([c_1]) 2 5 1 2 5 10 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 14 5 1 1 1 2 13 6 5 1 2 3 4 2 5 1 2 5 10 3 2 1 3 6 7 4 2 1 3 8 9 7 5 1 2 11 12 # Undo the move using first-child >>> root = Node.objects.get(pk=root.pk) >>> Node.tree.move_node(c_1, root, 'first-child') >>> print_tree_details([c_1]) 2 1 1 1 2 7 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 14 2 1 1 1 2 7 3 2 1 2 3 4 4 2 1 2 5 6 5 1 1 1 8 13 6 5 1 2 9 10 7 5 1 2 11 12 # Move down the tree using left >>> c_1_1 = Node.objects.get(pk=c_1_1.pk) >>> c_2_2 = Node.objects.get(pk=c_2_2.pk) >>> Node.tree.move_node(c_1_1, c_2_2, 'left') >>> print_tree_details([c_1_1]) 3 5 1 2 9 10 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 14 2 1 1 1 2 5 4 2 1 2 3 4 5 1 1 1 6 13 6 5 1 2 7 8 3 5 1 2 9 10 7 5 1 2 11 12 # Undo the move using left >>> c_1_2 = Node.objects.get(pk=c_1_2.pk) >>> Node.tree.move_node(c_1_1, c_1_2, 'left') >>> print_tree_details([c_1_1]) 3 2 1 2 3 4 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 14 2 1 1 1 2 7 3 2 1 2 3 4 4 2 1 2 5 6 5 1 1 1 8 13 6 5 1 2 9 10 7 5 1 2 11 12 COVERAGE | U1 | U> | D1 | D> ------------+----+----+----+---- first-child | Y | Y | Y | Y last-child | Y | Y | Y | Y left | Y | Y | Y | Y right | Y | Y | Y | Y I guess we're covered :) ####################### # Inter-Tree Movement # ####################### >>> new_root = Node.objects.create() >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 14 2 1 1 1 2 7 3 2 1 2 3 4 4 2 1 2 5 6 5 1 1 1 8 13 6 5 1 2 9 10 7 5 1 2 11 12 8 - 2 0 1 2 # Moving child nodes between trees ############################################ # Move using default (last-child) >>> c_2 = Node.objects.get(pk=c_2.pk) >>> c_2.move_to(new_root) >>> print_tree_details([c_2]) 5 8 2 1 2 7 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 8 2 1 1 1 2 7 3 2 1 2 3 4 4 2 1 2 5 6 8 - 2 0 1 8 5 8 2 1 2 7 6 5 2 2 3 4 7 5 2 2 5 6 # Move using left >>> c_1_1 = Node.objects.get(pk=c_1_1.pk) >>> c_2 = Node.objects.get(pk=c_2.pk) >>> Node.tree.move_node(c_1_1, c_2, position='left') >>> print_tree_details([c_1_1]) 3 8 2 1 2 3 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 6 2 1 1 1 2 5 4 2 1 2 3 4 8 - 2 0 1 10 3 8 2 1 2 3 5 8 2 1 4 9 6 5 2 2 5 6 7 5 2 2 7 8 # Move using first-child >>> c_1_2 = Node.objects.get(pk=c_1_2.pk) >>> c_2 = Node.objects.get(pk=c_2.pk) >>> Node.tree.move_node(c_1_2, c_2, position='first-child') >>> print_tree_details([c_1_2]) 4 5 2 2 5 6 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 4 2 1 1 1 2 3 8 - 2 0 1 12 3 8 2 1 2 3 5 8 2 1 4 11 4 5 2 2 5 6 6 5 2 2 7 8 7 5 2 2 9 10 # Move using right >>> c_2 = Node.objects.get(pk=c_2.pk) >>> c_1 = Node.objects.get(pk=c_1.pk) >>> Node.tree.move_node(c_2, c_1, position='right') >>> print_tree_details([c_2]) 5 1 1 1 4 11 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 12 2 1 1 1 2 3 5 1 1 1 4 11 4 5 1 2 5 6 6 5 1 2 7 8 7 5 1 2 9 10 8 - 2 0 1 4 3 8 2 1 2 3 # Move using last-child >>> c_1_1 = Node.objects.get(pk=c_1_1.pk) >>> Node.tree.move_node(c_1_1, c_2, position='last-child') >>> print_tree_details([c_1_1]) 3 5 1 2 11 12 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 14 2 1 1 1 2 3 5 1 1 1 4 13 4 5 1 2 5 6 6 5 1 2 7 8 7 5 1 2 9 10 3 5 1 2 11 12 8 - 2 0 1 2 # Moving a root node into another tree as a child node ######################## # Validate exceptions are raised appropriately >>> Node.tree.move_node(root, c_1, position='first-child') Traceback (most recent call last): ... InvalidMove: A node may not be made a child of any of its descendants. >>> Node.tree.move_node(new_root, c_1, position='cheese') Traceback (most recent call last): ... ValueError: An invalid position was given: cheese. >>> new_root = Node.objects.get(pk=new_root.pk) >>> c_2 = Node.objects.get(pk=c_2.pk) >>> new_root.move_to(c_2, position='first-child') >>> print_tree_details([new_root]) 8 5 1 2 5 6 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 16 2 1 1 1 2 3 5 1 1 1 4 15 8 5 1 2 5 6 4 5 1 2 7 8 6 5 1 2 9 10 7 5 1 2 11 12 3 5 1 2 13 14 >>> new_root = Node.objects.create() >>> root = Node.objects.get(pk=root.pk) >>> Node.tree.move_node(new_root, root, position='last-child') >>> print_tree_details([new_root]) 9 1 1 1 16 17 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 18 2 1 1 1 2 3 5 1 1 1 4 15 8 5 1 2 5 6 4 5 1 2 7 8 6 5 1 2 9 10 7 5 1 2 11 12 3 5 1 2 13 14 9 1 1 1 16 17 >>> new_root = Node.objects.create() >>> c_2_1 = Node.objects.get(pk=c_2_1.pk) >>> Node.tree.move_node(new_root, c_2_1, position='left') >>> print_tree_details([new_root]) 10 5 1 2 9 10 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 20 2 1 1 1 2 3 5 1 1 1 4 17 8 5 1 2 5 6 4 5 1 2 7 8 10 5 1 2 9 10 6 5 1 2 11 12 7 5 1 2 13 14 3 5 1 2 15 16 9 1 1 1 18 19 >>> new_root = Node.objects.create() >>> c_1 = Node.objects.get(pk=c_1.pk) >>> Node.tree.move_node(new_root, c_1, position='right') >>> print_tree_details([new_root]) 11 1 1 1 4 5 >>> print_tree_details(Node.tree.all()) 1 - 1 0 1 22 2 1 1 1 2 3 11 1 1 1 4 5 5 1 1 1 6 19 8 5 1 2 7 8 4 5 1 2 9 10 10 5 1 2 11 12 6 5 1 2 13 14 7 5 1 2 15 16 3 5 1 2 17 18 9 1 1 1 20 21 # Making nodes siblings of root nodes ######################################### # Validate exceptions are raised appropriately >>> root = Node.objects.get(pk=root.pk) >>> Node.tree.move_node(root, root, position='left') Traceback (most recent call last): ... InvalidMove: A node may not be made a sibling of itself. >>> Node.tree.move_node(root, root, position='right') Traceback (most recent call last): ... InvalidMove: A node may not be made a sibling of itself. >>> r1 = Tree.objects.create() >>> c1_1 = Tree.objects.create(parent=r1) >>> c1_1_1 = Tree.objects.create(parent=c1_1) >>> r2 = Tree.objects.create() >>> c2_1 = Tree.objects.create(parent=r2) >>> c2_1_1 = Tree.objects.create(parent=c2_1) >>> r3 = Tree.objects.create() >>> c3_1 = Tree.objects.create(parent=r3) >>> c3_1_1 = Tree.objects.create(parent=c3_1) >>> print_tree_details(Tree.tree.all()) 1 - 1 0 1 6 2 1 1 1 2 5 3 2 1 2 3 4 4 - 2 0 1 6 5 4 2 1 2 5 6 5 2 2 3 4 7 - 3 0 1 6 8 7 3 1 2 5 9 8 3 2 3 4 # Target < root node, left sibling >>> r1 = Tree.objects.get(pk=r1.pk) >>> r2 = Tree.objects.get(pk=r2.pk) >>> r2.move_to(r1, 'left') >>> print_tree_details([r2]) 4 - 1 0 1 6 >>> print_tree_details(Tree.tree.all()) 4 - 1 0 1 6 5 4 1 1 2 5 6 5 1 2 3 4 1 - 2 0 1 6 2 1 2 1 2 5 3 2 2 2 3 4 7 - 3 0 1 6 8 7 3 1 2 5 9 8 3 2 3 4 # Target > root node, left sibling >>> r3 = Tree.objects.get(pk=r3.pk) >>> r2.move_to(r3, 'left') >>> print_tree_details([r2]) 4 - 2 0 1 6 >>> print_tree_details(Tree.tree.all()) 1 - 1 0 1 6 2 1 1 1 2 5 3 2 1 2 3 4 4 - 2 0 1 6 5 4 2 1 2 5 6 5 2 2 3 4 7 - 3 0 1 6 8 7 3 1 2 5 9 8 3 2 3 4 # Target < root node, right sibling >>> r1 = Tree.objects.get(pk=r1.pk) >>> r3 = Tree.objects.get(pk=r3.pk) >>> r3.move_to(r1, 'right') >>> print_tree_details([r3]) 7 - 2 0 1 6 >>> print_tree_details(Tree.tree.all()) 1 - 1 0 1 6 2 1 1 1 2 5 3 2 1 2 3 4 7 - 2 0 1 6 8 7 2 1 2 5 9 8 2 2 3 4 4 - 3 0 1 6 5 4 3 1 2 5 6 5 3 2 3 4 # Target > root node, right sibling >>> r1 = Tree.objects.get(pk=r1.pk) >>> r2 = Tree.objects.get(pk=r2.pk) >>> r1.move_to(r2, 'right') >>> print_tree_details([r1]) 1 - 3 0 1 6 >>> print_tree_details(Tree.tree.all()) 7 - 1 0 1 6 8 7 1 1 2 5 9 8 1 2 3 4 4 - 2 0 1 6 5 4 2 1 2 5 6 5 2 2 3 4 1 - 3 0 1 6 2 1 3 1 2 5 3 2 3 2 3 4 # No-op, root left sibling >>> r2 = Tree.objects.get(pk=r2.pk) >>> r2.move_to(r1, 'left') >>> print_tree_details([r2]) 4 - 2 0 1 6 >>> print_tree_details(Tree.tree.all()) 7 - 1 0 1 6 8 7 1 1 2 5 9 8 1 2 3 4 4 - 2 0 1 6 5 4 2 1 2 5 6 5 2 2 3 4 1 - 3 0 1 6 2 1 3 1 2 5 3 2 3 2 3 4 # No-op, root right sibling >>> r1.move_to(r2, 'right') >>> print_tree_details([r1]) 1 - 3 0 1 6 >>> print_tree_details(Tree.tree.all()) 7 - 1 0 1 6 8 7 1 1 2 5 9 8 1 2 3 4 4 - 2 0 1 6 5 4 2 1 2 5 6 5 2 2 3 4 1 - 3 0 1 6 2 1 3 1 2 5 3 2 3 2 3 4 # Child node, left sibling >>> c3_1 = Tree.objects.get(pk=c3_1.pk) >>> c3_1.move_to(r1, 'left') >>> print_tree_details([c3_1]) 8 - 3 0 1 4 >>> print_tree_details(Tree.tree.all()) 7 - 1 0 1 2 4 - 2 0 1 6 5 4 2 1 2 5 6 5 2 2 3 4 8 - 3 0 1 4 9 8 3 1 2 3 1 - 4 0 1 6 2 1 4 1 2 5 3 2 4 2 3 4 # Child node, right sibling >>> r3 = Tree.objects.get(pk=r3.pk) >>> c1_1 = Tree.objects.get(pk=c1_1.pk) >>> c1_1.move_to(r3, 'right') >>> print_tree_details([c1_1]) 2 - 2 0 1 4 >>> print_tree_details(Tree.tree.all()) 7 - 1 0 1 2 2 - 2 0 1 4 3 2 2 1 2 3 4 - 3 0 1 6 5 4 3 1 2 5 6 5 3 2 3 4 8 - 4 0 1 4 9 8 4 1 2 3 1 - 5 0 1 2 # Insertion of positioned nodes ############################################### >>> r1 = Insert.objects.create() >>> r2 = Insert.objects.create() >>> r3 = Insert.objects.create() >>> print_tree_details(Insert.tree.all()) 1 - 1 0 1 2 2 - 2 0 1 2 3 - 3 0 1 2 >>> r2 = Insert.objects.get(pk=r2.pk) >>> c1 = Insert() >>> c1 = Insert.tree.insert_node(c1, r2, commit=True) >>> print_tree_details([c1]) 4 2 2 1 2 3 >>> print_tree_details(Insert.tree.all()) 1 - 1 0 1 2 2 - 2 0 1 4 4 2 2 1 2 3 3 - 3 0 1 2 >>> c1.insert_at(r2) Traceback (most recent call last): ... ValueError: Cannot insert a node which has already been saved. # First child >>> r2 = Insert.objects.get(pk=r2.pk) >>> c2 = Insert() >>> c2 = Insert.tree.insert_node(c2, r2, position='first-child', commit=True) >>> print_tree_details([c2]) 5 2 2 1 2 3 >>> print_tree_details(Insert.tree.all()) 1 - 1 0 1 2 2 - 2 0 1 6 5 2 2 1 2 3 4 2 2 1 4 5 3 - 3 0 1 2 # Left >>> c1 = Insert.objects.get(pk=c1.pk) >>> c3 = Insert() >>> c3 = Insert.tree.insert_node(c3, c1, position='left', commit=True) >>> print_tree_details([c3]) 6 2 2 1 4 5 >>> print_tree_details(Insert.tree.all()) 1 - 1 0 1 2 2 - 2 0 1 8 5 2 2 1 2 3 6 2 2 1 4 5 4 2 2 1 6 7 3 - 3 0 1 2 # Right >>> c4 = Insert() >>> c4 = Insert.tree.insert_node(c4, c3, position='right', commit=True) >>> print_tree_details([c4]) 7 2 2 1 6 7 >>> print_tree_details(Insert.tree.all()) 1 - 1 0 1 2 2 - 2 0 1 10 5 2 2 1 2 3 6 2 2 1 4 5 7 2 2 1 6 7 4 2 2 1 8 9 3 - 3 0 1 2 # Last child >>> r2 = Insert.objects.get(pk=r2.pk) >>> c5 = Insert() >>> c5 = Insert.tree.insert_node(c5, r2, position='last-child', commit=True) >>> print_tree_details([c5]) 8 2 2 1 10 11 >>> print_tree_details(Insert.tree.all()) 1 - 1 0 1 2 2 - 2 0 1 12 5 2 2 1 2 3 6 2 2 1 4 5 7 2 2 1 6 7 4 2 2 1 8 9 8 2 2 1 10 11 3 - 3 0 1 2 # Left sibling of root >>> r2 = Insert.objects.get(pk=r2.pk) >>> r4 = Insert() >>> r4 = Insert.tree.insert_node(r4, r2, position='left', commit=True) >>> print_tree_details([r4]) 9 - 2 0 1 2 >>> print_tree_details(Insert.tree.all()) 1 - 1 0 1 2 9 - 2 0 1 2 2 - 3 0 1 12 5 2 3 1 2 3 6 2 3 1 4 5 7 2 3 1 6 7 4 2 3 1 8 9 8 2 3 1 10 11 3 - 4 0 1 2 # Right sibling of root >>> r2 = Insert.objects.get(pk=r2.pk) >>> r5 = Insert() >>> r5 = Insert.tree.insert_node(r5, r2, position='right', commit=True) >>> print_tree_details([r5]) 10 - 4 0 1 2 >>> print_tree_details(Insert.tree.all()) 1 - 1 0 1 2 9 - 2 0 1 2 2 - 3 0 1 12 5 2 3 1 2 3 6 2 3 1 4 5 7 2 3 1 6 7 4 2 3 1 8 9 8 2 3 1 10 11 10 - 4 0 1 2 3 - 5 0 1 2 # Last root >>> r6 = Insert() >>> r6 = Insert.tree.insert_node(r6, None, commit=True) >>> print_tree_details([r6]) 11 - 6 0 1 2 >>> print_tree_details(Insert.tree.all()) 1 - 1 0 1 2 9 - 2 0 1 2 2 - 3 0 1 12 5 2 3 1 2 3 6 2 3 1 4 5 7 2 3 1 6 7 4 2 3 1 8 9 8 2 3 1 10 11 10 - 4 0 1 2 3 - 5 0 1 2 11 - 6 0 1 2 # order_insertion_by with single criterion #################################### >>> r1 = OrderedInsertion.objects.create(name='games') # Root ordering >>> r2 = OrderedInsertion.objects.create(name='food') >>> print_tree_details(OrderedInsertion.tree.all()) 2 - 1 0 1 2 1 - 2 0 1 2 # Same name - insert after >>> r3 = OrderedInsertion.objects.create(name='food') >>> print_tree_details(OrderedInsertion.tree.all()) 2 - 1 0 1 2 3 - 2 0 1 2 1 - 3 0 1 2 >>> c1 = OrderedInsertion.objects.create(name='zoo', parent=r3) >>> print_tree_details(OrderedInsertion.tree.all()) 2 - 1 0 1 2 3 - 2 0 1 4 4 3 2 1 2 3 1 - 3 0 1 2 >>> r3 = OrderedInsertion.objects.get(pk=r3.pk) >>> c2 = OrderedInsertion.objects.create(name='monkey', parent=r3) >>> print_tree_details(OrderedInsertion.tree.all()) 2 - 1 0 1 2 3 - 2 0 1 6 5 3 2 1 2 3 4 3 2 1 4 5 1 - 3 0 1 2 >>> r3 = OrderedInsertion.objects.get(pk=r3.pk) >>> c3 = OrderedInsertion.objects.create(name='animal', parent=r3) >>> print_tree_details(OrderedInsertion.tree.all()) 2 - 1 0 1 2 3 - 2 0 1 8 6 3 2 1 2 3 5 3 2 1 4 5 4 3 2 1 6 7 1 - 3 0 1 2 # order_insertion_by reparenting with single criterion ######################## # Root -> child >>> r1 = OrderedInsertion.objects.get(pk=r1.pk) >>> r3 = OrderedInsertion.objects.get(pk=r3.pk) >>> r1.parent = r3 >>> r1.save() >>> print_tree_details(OrderedInsertion.tree.all()) 2 - 1 0 1 2 3 - 2 0 1 10 6 3 2 1 2 3 1 3 2 1 4 5 5 3 2 1 6 7 4 3 2 1 8 9 # Child -> root >>> c3 = OrderedInsertion.objects.get(pk=c3.pk) >>> c3.parent = None >>> c3.save() >>> print_tree_details(OrderedInsertion.tree.all()) 6 - 1 0 1 2 2 - 2 0 1 2 3 - 3 0 1 8 1 3 3 1 2 3 5 3 3 1 4 5 4 3 3 1 6 7 # Child -> child >>> c1 = OrderedInsertion.objects.get(pk=c1.pk) >>> c1.parent = c3 >>> c1.save() >>> print_tree_details(OrderedInsertion.tree.all()) 6 - 1 0 1 4 4 6 1 1 2 3 2 - 2 0 1 2 3 - 3 0 1 6 1 3 3 1 2 3 5 3 3 1 4 5 >>> c3 = OrderedInsertion.objects.get(pk=c3.pk) >>> c2 = OrderedInsertion.objects.get(pk=c2.pk) >>> c2.parent = c3 >>> c2.save() >>> print_tree_details(OrderedInsertion.tree.all()) 6 - 1 0 1 6 5 6 1 1 2 3 4 6 1 1 4 5 2 - 2 0 1 2 3 - 3 0 1 4 1 3 3 1 2 3 # Insertion of positioned nodes, multiple ordering criteria ################### >>> r1 = MultiOrder.objects.create(name='fff', size=20, date=date(2008, 1, 1)) # Root nodes - ordering by subsequent fields >>> r2 = MultiOrder.objects.create(name='fff', size=10, date=date(2009, 1, 1)) >>> print_tree_details(MultiOrder.tree.all()) 2 - 1 0 1 2 1 - 2 0 1 2 >>> r3 = MultiOrder.objects.create(name='fff', size=20, date=date(2007, 1, 1)) >>> print_tree_details(MultiOrder.tree.all()) 2 - 1 0 1 2 3 - 2 0 1 2 1 - 3 0 1 2 >>> r4 = MultiOrder.objects.create(name='fff', size=20, date=date(2008, 1, 1)) >>> print_tree_details(MultiOrder.tree.all()) 2 - 1 0 1 2 3 - 2 0 1 2 1 - 3 0 1 2 4 - 4 0 1 2 >>> r5 = MultiOrder.objects.create(name='fff', size=20, date=date(2007, 1, 1)) >>> print_tree_details(MultiOrder.tree.all()) 2 - 1 0 1 2 3 - 2 0 1 2 5 - 3 0 1 2 1 - 4 0 1 2 4 - 5 0 1 2 >>> r6 = MultiOrder.objects.create(name='aaa', size=999, date=date(2010, 1, 1)) >>> print_tree_details(MultiOrder.tree.all()) 6 - 1 0 1 2 2 - 2 0 1 2 3 - 3 0 1 2 5 - 4 0 1 2 1 - 5 0 1 2 4 - 6 0 1 2 # Child nodes >>> r1 = MultiOrder.objects.get(pk=r1.pk) >>> c1 = MultiOrder.objects.create(parent=r1, name='hhh', size=10, date=date(2009, 1, 1)) >>> print_tree_details(MultiOrder.tree.filter(tree_id=r1.tree_id)) 1 - 5 0 1 4 7 1 5 1 2 3 >>> r1 = MultiOrder.objects.get(pk=r1.pk) >>> c2 = MultiOrder.objects.create(parent=r1, name='hhh', size=20, date=date(2008, 1, 1)) >>> print_tree_details(MultiOrder.tree.filter(tree_id=r1.tree_id)) 1 - 5 0 1 6 7 1 5 1 2 3 8 1 5 1 4 5 >>> r1 = MultiOrder.objects.get(pk=r1.pk) >>> c3 = MultiOrder.objects.create(parent=r1, name='hhh', size=15, date=date(2008, 1, 1)) >>> print_tree_details(MultiOrder.tree.filter(tree_id=r1.tree_id)) 1 - 5 0 1 8 7 1 5 1 2 3 9 1 5 1 4 5 8 1 5 1 6 7 >>> r1 = MultiOrder.objects.get(pk=r1.pk) >>> c4 = MultiOrder.objects.create(parent=r1, name='hhh', size=15, date=date(2008, 1, 1)) >>> print_tree_details(MultiOrder.tree.filter(tree_id=r1.tree_id)) 1 - 5 0 1 10 7 1 5 1 2 3 9 1 5 1 4 5 10 1 5 1 6 7 8 1 5 1 8 9 """
Python
""" Template tags for working with lists of model instances which represent trees. """ from django import template from django.db.models import get_model from django.db.models.fields import FieldDoesNotExist from django.utils.encoding import force_unicode from django.utils.translation import ugettext as _ from mptt.utils import tree_item_iterator, drilldown_tree_for_node register = template.Library() class FullTreeForModelNode(template.Node): def __init__(self, model, context_var): self.model = model self.context_var = context_var def render(self, context): cls = get_model(*self.model.split('.')) if cls is None: raise template.TemplateSyntaxError(_('full_tree_for_model tag was given an invalid model: %s') % self.model) context[self.context_var] = cls._tree_manager.all() return '' class DrilldownTreeForNodeNode(template.Node): def __init__(self, node, context_var, foreign_key=None, count_attr=None, cumulative=False): self.node = template.Variable(node) self.context_var = context_var self.foreign_key = foreign_key self.count_attr = count_attr self.cumulative = cumulative def render(self, context): # Let any VariableDoesNotExist raised bubble up args = [self.node.resolve(context)] if self.foreign_key is not None: app_label, model_name, fk_attr = self.foreign_key.split('.') cls = get_model(app_label, model_name) if cls is None: raise template.TemplateSyntaxError(_('drilldown_tree_for_node tag was given an invalid model: %s') % '.'.join([app_label, model_name])) try: cls._meta.get_field(fk_attr) except FieldDoesNotExist: raise template.TemplateSyntaxError(_('drilldown_tree_for_node tag was given an invalid model field: %s') % fk_attr) args.extend([cls, fk_attr, self.count_attr, self.cumulative]) context[self.context_var] = drilldown_tree_for_node(*args) return '' def do_full_tree_for_model(parser, token): """ Populates a template variable with a ``QuerySet`` containing the full tree for a given model. Usage:: {% full_tree_for_model [model] as [varname] %} The model is specified in ``[appname].[modelname]`` format. Example:: {% full_tree_for_model tests.Genre as genres %} """ bits = token.contents.split() if len(bits) != 4: raise template.TemplateSyntaxError(_('%s tag requires three arguments') % bits[0]) if bits[2] != 'as': raise template.TemplateSyntaxError(_("second argument to %s tag must be 'as'") % bits[0]) return FullTreeForModelNode(bits[1], bits[3]) def do_drilldown_tree_for_node(parser, token): """ Populates a template variable with the drilldown tree for a given node, optionally counting the number of items associated with its children. A drilldown tree consists of a node's ancestors, itself and its immediate children. For example, a drilldown tree for a book category "Personal Finance" might look something like:: Books Business, Finance & Law Personal Finance Budgeting (220) Financial Planning (670) Usage:: {% drilldown_tree_for_node [node] as [varname] %} Extended usage:: {% drilldown_tree_for_node [node] as [varname] count [foreign_key] in [count_attr] %} {% drilldown_tree_for_node [node] as [varname] cumulative count [foreign_key] in [count_attr] %} The foreign key is specified in ``[appname].[modelname].[fieldname]`` format, where ``fieldname`` is the name of a field in the specified model which relates it to the given node's model. When this form is used, a ``count_attr`` attribute on each child of the given node in the drilldown tree will contain a count of the number of items associated with it through the given foreign key. If cumulative is also specified, this count will be for items related to the child node and all of its descendants. Examples:: {% drilldown_tree_for_node genre as drilldown %} {% drilldown_tree_for_node genre as drilldown count tests.Game.genre in game_count %} {% drilldown_tree_for_node genre as drilldown cumulative count tests.Game.genre in game_count %} """ bits = token.contents.split() len_bits = len(bits) if len_bits not in (4, 8, 9): raise TemplateSyntaxError(_('%s tag requires either three, seven or eight arguments') % bits[0]) if bits[2] != 'as': raise TemplateSyntaxError(_("second argument to %s tag must be 'as'") % bits[0]) if len_bits == 8: if bits[4] != 'count': raise TemplateSyntaxError(_("if seven arguments are given, fourth argument to %s tag must be 'with'") % bits[0]) if bits[6] != 'in': raise TemplateSyntaxError(_("if seven arguments are given, sixth argument to %s tag must be 'in'") % bits[0]) return DrilldownTreeForNodeNode(bits[1], bits[3], bits[5], bits[7]) elif len_bits == 9: if bits[4] != 'cumulative': raise TemplateSyntaxError(_("if eight arguments are given, fourth argument to %s tag must be 'cumulative'") % bits[0]) if bits[5] != 'count': raise TemplateSyntaxError(_("if eight arguments are given, fifth argument to %s tag must be 'count'") % bits[0]) if bits[7] != 'in': raise TemplateSyntaxError(_("if eight arguments are given, seventh argument to %s tag must be 'in'") % bits[0]) return DrilldownTreeForNodeNode(bits[1], bits[3], bits[6], bits[8], cumulative=True) else: return DrilldownTreeForNodeNode(bits[1], bits[3]) def tree_info(items, features=None): """ Given a list of tree items, produces doubles of a tree item and a ``dict`` containing information about the tree structure around the item, with the following contents: new_level ``True`` if the current item is the start of a new level in the tree, ``False`` otherwise. closed_levels A list of levels which end after the current item. This will be an empty list if the next item is at the same level as the current item. Using this filter with unpacking in a ``{% for %}`` tag, you should have enough information about the tree structure to create a hierarchical representation of the tree. Example:: {% for genre,structure in genres|tree_info %} {% if tree.new_level %}<ul><li>{% else %}</li><li>{% endif %} {{ genre.name }} {% for level in tree.closed_levels %}</li></ul>{% endfor %} {% endfor %} """ kwargs = {} if features: feature_names = features.split(',') if 'ancestors' in feature_names: kwargs['ancestors'] = True return tree_item_iterator(items, **kwargs) def tree_path(items, separator=' :: '): """ Creates a tree path represented by a list of ``items`` by joining the items with a ``separator``. Each path item will be coerced to unicode, so a list of model instances may be given if required. Example:: {{ some_list|tree_path }} {{ some_node.get_ancestors|tree_path:" > " }} """ return separator.join([force_unicode(i) for i in items]) register.tag('full_tree_for_model', do_full_tree_for_model) register.tag('drilldown_tree_for_node', do_drilldown_tree_for_node) register.filter('tree_info', tree_info) register.filter('tree_path', tree_path)
Python
""" Utilities for working with lists of model instances which represent trees. """ import copy import itertools __all__ = ('previous_current_next', 'tree_item_iterator', 'drilldown_tree_for_node') def previous_current_next(items): """ From http://www.wordaligned.org/articles/zippy-triples-served-with-python Creates an iterator which returns (previous, current, next) triples, with ``None`` filling in when there is no previous or next available. """ extend = itertools.chain([None], items, [None]) previous, current, next = itertools.tee(extend, 3) try: current.next() next.next() next.next() except StopIteration: pass return itertools.izip(previous, current, next) def tree_item_iterator(items, ancestors=False): """ Given a list of tree items, iterates over the list, generating two-tuples of the current tree item and a ``dict`` containing information about the tree structure around the item, with the following keys: ``'new_level'` ``True`` if the current item is the start of a new level in the tree, ``False`` otherwise. ``'closed_levels'`` A list of levels which end after the current item. This will be an empty list if the next item is at the same level as the current item. If ``ancestors`` is ``True``, the following key will also be available: ``'ancestors'`` A list of unicode representations of the ancestors of the current node, in descending order (root node first, immediate parent last). For example: given the sample tree below, the contents of the list which would be available under the ``'ancestors'`` key are given on the right:: Books -> [] Sci-fi -> [u'Books'] Dystopian Futures -> [u'Books', u'Sci-fi'] """ structure = {} opts = None for previous, current, next in previous_current_next(items): if opts is None: opts = current._meta current_level = getattr(current, opts.level_attr) if previous: structure['new_level'] = (getattr(previous, opts.level_attr) < current_level) if ancestors: # If the previous node was the end of any number of # levels, remove the appropriate number of ancestors # from the list. if structure['closed_levels']: structure['ancestors'] = \ structure['ancestors'][:-len(structure['closed_levels'])] # If the current node is the start of a new level, add its # parent to the ancestors list. if structure['new_level']: structure['ancestors'].append(unicode(previous)) else: structure['new_level'] = True if ancestors: # Set up the ancestors list on the first item structure['ancestors'] = [] if next: structure['closed_levels'] = range(current_level, getattr(next, opts.level_attr), -1) else: # All remaining levels need to be closed structure['closed_levels'] = range(current_level, -1, -1) # Return a deep copy of the structure dict so this function can # be used in situations where the iterator is consumed # immediately. yield current, copy.deepcopy(structure) def drilldown_tree_for_node(node, rel_cls=None, rel_field=None, count_attr=None, cumulative=False): """ Creates a drilldown tree for the given node. A drilldown tree consists of a node's ancestors, itself and its immediate children, all in tree order. Optional arguments may be given to specify a ``Model`` class which is related to the node's class, for the purpose of adding related item counts to the node's children: ``rel_cls`` A ``Model`` class which has a relation to the node's class. ``rel_field`` The name of the field in ``rel_cls`` which holds the relation to the node's class. ``count_attr`` The name of an attribute which should be added to each child in the drilldown tree, containing a count of how many instances of ``rel_cls`` are related through ``rel_field``. ``cumulative`` If ``True``, the count will be for each child and all of its descendants, otherwise it will be for each child itself. """ if rel_cls and rel_field and count_attr: children = node._tree_manager.add_related_count( node.get_children(), rel_cls, rel_field, count_attr, cumulative) else: children = node.get_children() return itertools.chain(node.get_ancestors(), [node], children)
Python
""" MPTT exceptions. """ class InvalidMove(Exception): """ An invalid node move was attempted. For example, attempting to make a node a child of itself. """ pass
Python
VERSION = (0, 3, 'pre') __all__ = ('register',) class AlreadyRegistered(Exception): """ An attempt was made to register a model for MPTT more than once. """ pass registry = [] def register(model, parent_attr='parent', left_attr='lft', right_attr='rght', tree_id_attr='tree_id', level_attr='level', tree_manager_attr='tree', order_insertion_by=None): """ Sets the given model class up for Modified Preorder Tree Traversal. """ try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.3, 2.4 fallback from django.db.models import signals as model_signals from django.db.models import FieldDoesNotExist, PositiveIntegerField from django.utils.translation import ugettext as _ from mptt import models from mptt.signals import pre_save from mptt.managers import TreeManager if model in registry: raise AlreadyRegistered( _('The model %s has already been registered.') % model.__name__) registry.append(model) # Add tree options to the model's Options opts = model._meta opts.parent_attr = parent_attr opts.right_attr = right_attr opts.left_attr = left_attr opts.tree_id_attr = tree_id_attr opts.level_attr = level_attr opts.tree_manager_attr = tree_manager_attr opts.order_insertion_by = order_insertion_by # Add tree fields if they do not exist for attr in [left_attr, right_attr, tree_id_attr, level_attr]: try: opts.get_field(attr) except FieldDoesNotExist: PositiveIntegerField( db_index=True, editable=False).contribute_to_class(model, attr) # Add tree methods for model instances setattr(model, 'get_ancestors', models.get_ancestors) setattr(model, 'get_children', models.get_children) setattr(model, 'get_descendants', models.get_descendants) setattr(model, 'get_descendant_count', models.get_descendant_count) setattr(model, 'get_next_sibling', models.get_next_sibling) setattr(model, 'get_previous_sibling', models.get_previous_sibling) setattr(model, 'get_root', models.get_root) setattr(model, 'get_siblings', models.get_siblings) setattr(model, 'insert_at', models.insert_at) setattr(model, 'is_child_node', models.is_child_node) setattr(model, 'is_leaf_node', models.is_leaf_node) setattr(model, 'is_root_node', models.is_root_node) setattr(model, 'move_to', models.move_to) # Add a custom tree manager TreeManager(parent_attr, left_attr, right_attr, tree_id_attr, level_attr).contribute_to_class(model, tree_manager_attr) setattr(model, '_tree_manager', getattr(model, tree_manager_attr)) # Set up signal receiver to manage the tree when instances of the # model are about to be saved. model_signals.pre_save.connect(pre_save, sender=model) # Wrap the model's delete method to manage the tree structure before # deletion. This is icky, but the pre_delete signal doesn't currently # provide a way to identify which model delete was called on and we # only want to manage the tree based on the topmost node which is # being deleted. def wrap_delete(delete): def _wrapped_delete(self): opts = self._meta tree_width = (getattr(self, opts.right_attr) - getattr(self, opts.left_attr) + 1) target_right = getattr(self, opts.right_attr) tree_id = getattr(self, opts.tree_id_attr) self._tree_manager._close_gap(tree_width, target_right, tree_id) delete(self) return wraps(delete)(_wrapped_delete) model.delete = wrap_delete(model.delete)
Python
from django.db import models from captcha.conf import settings as captcha_settings import datetime, unicodedata, random, time # Heavily based on session key generation in Django # Use the system (hardware-based) random number generator if it exists. if hasattr(random, 'SystemRandom'): randrange = random.SystemRandom().randrange else: randrange = random.randrange MAX_RANDOM_KEY = 18446744073709551616L # 2 << 63 try: import hashlib # sha for Python 2.5+ except ImportError: import sha # sha for Python 2.4 (deprecated in Python 2.6) hashlib = False class CaptchaStore(models.Model): challenge = models.CharField(blank=False, max_length=32) response = models.CharField(blank=False, max_length=32) hashkey = models.CharField(blank=False, max_length=40, unique=True) expiration = models.DateTimeField(blank=False) def save(self,*args,**kwargs): self.response = self.response.lower() if not self.expiration: self.expiration = datetime.datetime.now() + datetime.timedelta(minutes= int(captcha_settings.CAPTCHA_TIMEOUT)) if not self.hashkey: key_ = unicodedata.normalize('NFKD', str(randrange(0,MAX_RANDOM_KEY)) + str(time.time()) + unicode(self.challenge)).encode('ascii', 'ignore') + unicodedata.normalize('NFKD', unicode(self.response)).encode('ascii', 'ignore') if hashlib: self.hashkey = hashlib.new('sha', key_).hexdigest() else: self.hashkey = sha.new(key_).hexdigest() del(key_) super(CaptchaStore,self).save(*args,**kwargs) def __unicode__(self): return self.challenge def remove_expired(cls): cls.objects.filter(expiration__lte=datetime.datetime.now()).delete() remove_expired = classmethod(remove_expired)
Python
from django.forms.fields import CharField, MultiValueField from django.forms import ValidationError from django.forms.widgets import TextInput, MultiWidget, HiddenInput from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse from captcha.models import CaptchaStore from captcha.conf import settings from captcha.helpers import * import datetime class CaptchaTextInput(MultiWidget): def __init__(self,attrs=None): widgets = ( HiddenInput(attrs), TextInput(attrs), ) for key in ('image','hidden_field','text_field'): if '%%(%s)s'%key not in settings.CAPTCHA_OUTPUT_FORMAT: raise KeyError('All of %s must be present in your CAPTCHA_OUTPUT_FORMAT setting. Could not find %s' %( ', '.join(['%%(%s)s'%k for k in ('image','hidden_field','text_field')]), '%%(%s)s'%key )) super(CaptchaTextInput,self).__init__(widgets,attrs) def decompress(self,value): if value: return value.split(',') return [None,None] def format_output(self, rendered_widgets): hidden_field, text_field = rendered_widgets return settings.CAPTCHA_OUTPUT_FORMAT %dict(image=self.image_and_audio, hidden_field=hidden_field, text_field=text_field) def render(self, name, value, attrs=None): challenge,response= settings.get_challenge()() store = CaptchaStore.objects.create(challenge=challenge,response=response) key = store.hashkey value = [key, u''] self.image_and_audio = '<img src="%s" alt="captcha" class="captcha" />' %reverse('captcha-image',kwargs=dict(key=key)) if settings.CAPTCHA_FLITE_PATH: self.image_and_audio = '<a href="%s" title="%s">%s</a>' %( reverse('captcha-audio', kwargs=dict(key=key)), unicode(_('Play captcha as audio file')), self.image_and_audio) #fields = super(CaptchaTextInput, self).render(name, value, attrs=attrs) return super(CaptchaTextInput, self).render(name, value, attrs=attrs) class CaptchaField(MultiValueField): widget=CaptchaTextInput def __init__(self, *args,**kwargs): fields = ( CharField(show_hidden_initial=True), CharField(), ) if 'error_messages' not in kwargs or 'invalid' not in kwargs.get('error_messages'): if 'error_messages' not in kwargs: kwargs['error_messages'] = dict() kwargs['error_messages'].update(dict(invalid=_('Invalid CAPTCHA'))) super(CaptchaField,self).__init__(fields=fields, *args, **kwargs) def compress(self,data_list): if data_list: return ','.join(data_list) return None def clean(self, value): super(CaptchaField, self).clean(value) response, value[1] = value[1].strip().lower(), '' CaptchaStore.remove_expired() try: store = CaptchaStore.objects.get(response=response, hashkey=value[0], expiration__gt=datetime.datetime.now()) store.delete() except Exception: raise ValidationError(getattr(self,'error_messages',dict()).get('invalid', _('Invalid CAPTCHA'))) return value
Python
from django.conf.urls.defaults import * urlpatterns = patterns('', url(r'test/$','captcha.tests.views.test',name='captcha-test'), url(r'test2/$','captcha.tests.views.test_custom_error_message',name='captcha-test-custom-error-message'), url(r'',include('captcha.urls')), )
Python
from django import forms from captcha.fields import CaptchaField from django.template import Context, RequestContext, loader from django.http import HttpResponse TEST_TEMPLATE = r''' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>captcha test</title> </head> <body> {% if passed %} <p style="color:green">Form validated</p> {% endif %} <form action="{% url captcha-test %}" method="post"> {{form.as_p}} <p><input type="submit" value="Continue &rarr;"></p> </form> </body> </html> ''' def test(request): class CaptchaTestForm(forms.Form): subject = forms.CharField(max_length=100) sender = forms.EmailField() captcha = CaptchaField(help_text='asdasd') if request.POST: form = CaptchaTestForm(request.POST) if form.is_valid(): passed = True else: form = CaptchaTestForm() t = loader.get_template_from_string(TEST_TEMPLATE) return HttpResponse(t.render(RequestContext(request, locals()))) def test_custom_error_message(request): class CaptchaTestForm(forms.Form): captcha = CaptchaField(help_text='asdasd', error_messages=dict(invalid='TEST CUSTOM ERROR MESSAGE')) if request.POST: form = CaptchaTestForm(request.POST) if form.is_valid(): passed = True else: form = CaptchaTestForm() t = loader.get_template_from_string(TEST_TEMPLATE) return HttpResponse(t.render(RequestContext(request, locals())))
Python
# -*- coding: utf-8 -*- from captcha.conf import settings from captcha.models import CaptchaStore from django.core.urlresolvers import reverse from django.test import TestCase from django.utils.translation import ugettext_lazy as _ import datetime class CaptchaCase(TestCase): urls = 'captcha.tests.urls' def setUp(self): self.default_challenge = settings.get_challenge()() self.math_challenge = settings._callable_from_string('captcha.helpers.math_challenge')() self.chars_challenge = settings._callable_from_string('captcha.helpers.random_char_challenge')() self.unicode_challenge = settings._callable_from_string('captcha.helpers.unicode_challenge')() self.default_store, created = CaptchaStore.objects.get_or_create(challenge=self.default_challenge[0],response=self.default_challenge[1]) self.math_store, created = CaptchaStore.objects.get_or_create(challenge=self.math_challenge[0],response=self.math_challenge[1]) self.chars_store, created = CaptchaStore.objects.get_or_create(challenge=self.chars_challenge[0],response=self.chars_challenge[1]) self.unicode_store, created = CaptchaStore.objects.get_or_create(challenge=self.unicode_challenge[0],response=self.unicode_challenge[1]) def testImages(self): for key in (self.math_store.hashkey, self.chars_store.hashkey, self.default_store.hashkey, self.unicode_store.hashkey): response = self.client.get(reverse('captcha-image',kwargs=dict(key=key))) self.failUnlessEqual(response.status_code, 200) self.assertTrue(response.has_header('content-type')) self.assertEquals(response._headers.get('content-type'), ('Content-Type', 'image/png')) def testAudio(self): if not settings.CAPTCHA_FLITE_PATH: return for key in (self.math_store.hashkey, self.chars_store.hashkey, self.default_store.hashkey, self.unicode_store.hashkey): response = self.client.get(reverse('captcha-audio',kwargs=dict(key=key))) self.failUnlessEqual(response.status_code, 200) self.assertTrue(len(response.content) > 1024) self.assertTrue(response.has_header('content-type')) self.assertEquals(response._headers.get('content-type'), ('Content-Type', 'audio/x-wav')) def testFormSubmit(self): r = self.client.get(reverse('captcha-test')) self.failUnlessEqual(r.status_code, 200) hash_ = r.content[r.content.find('value="')+7:r.content.find('value="')+47] try: response = CaptchaStore.objects.get(hashkey=hash_).response except: self.fail() r = self.client.post(reverse('captcha-test'), dict(captcha_0=hash_,captcha_1=response, subject='xxx', sender='asasd@asdasd.com')) self.failUnlessEqual(r.status_code, 200) self.assertTrue(r.content.find('Form validated') > 0) r = self.client.post(reverse('captcha-test'), dict(captcha_0=hash_,captcha_1=response, subject='xxx', sender='asasd@asdasd.com')) self.failUnlessEqual(r.status_code, 200) self.assertFalse(r.content.find('Form validated') > 0) def testWrongSubmit(self): r = self.client.get(reverse('captcha-test')) self.failUnlessEqual(r.status_code, 200) r = self.client.post(reverse('captcha-test'), dict(captcha_0='abc',captcha_1='wrong response', subject='xxx', sender='asasd@asdasd.com')) self.assertFormError(r,'form','captcha',_('Invalid CAPTCHA')) def testDeleteExpired(self): self.default_store.expiration = datetime.datetime.now() - datetime.timedelta(minutes=5) self.default_store.save() hash_ = self.default_store.hashkey r = self.client.post(reverse('captcha-test'), dict(captcha_0=hash_,captcha_1=self.default_store.response, subject='xxx', sender='asasd@asdasd.com')) self.failUnlessEqual(r.status_code, 200) self.assertFalse(r.content.find('Form validated') > 0) # expired -> deleted try: CaptchaStore.objects.get(hashkey=hash_) self.fail() except: pass def testCustomErrorMessage(self): r = self.client.get(reverse('captcha-test-custom-error-message')) self.failUnlessEqual(r.status_code, 200) # Wrong answer r = self.client.post(reverse('captcha-test-custom-error-message'), dict(captcha_0='abc',captcha_1='wrong response')) self.assertFormError(r,'form','captcha','TEST CUSTOM ERROR MESSAGE') # empty answer r = self.client.post(reverse('captcha-test-custom-error-message'), dict(captcha_0='abc',captcha_1='')) self.assertFormError(r,'form','captcha',_('This field is required.')) def testRepeatedChallenge(self): store = CaptchaStore.objects.create(challenge='xxx',response='xxx') try: store2 = CaptchaStore.objects.create(challenge='xxx',response='xxx') except Exception: self.fail() def testRepeatedChallengeFormSubmit(self): settings.CAPTCHA_CHALLENGE_FUNCT = 'captcha.tests.trivial_challenge' r1 = self.client.get(reverse('captcha-test')) r2 = self.client.get(reverse('captcha-test')) self.failUnlessEqual(r1.status_code, 200) self.failUnlessEqual(r2.status_code, 200) hash_1 = r1.content[r1.content.find('value="')+7:r1.content.find('value="')+47] hash_2 = r2.content[r2.content.find('value="')+7:r2.content.find('value="')+47] try: store_1 = CaptchaStore.objects.get(hashkey=hash_1) store_2 = CaptchaStore.objects.get(hashkey=hash_2) except: self.fail() self.assertTrue(store_1.pk != store_2.pk) self.assertTrue(store_1.response == store_2.response) self.assertTrue(hash_1 != hash_2) r1 = self.client.post(reverse('captcha-test'), dict(captcha_0=hash_1,captcha_1=store_1.response, subject='xxx', sender='asasd@asdasd.com')) self.failUnlessEqual(r1.status_code, 200) self.assertTrue(r1.content.find('Form validated') > 0) try: store_2 = CaptchaStore.objects.get(hashkey=hash_2) except: self.fail() r2 = self.client.post(reverse('captcha-test'), dict(captcha_0=hash_2,captcha_1=store_2.response, subject='xxx', sender='asasd@asdasd.com')) self.failUnlessEqual(r2.status_code, 200) self.assertTrue(r2.content.find('Form validated') > 0) def testOutputFormat(self): settings.CAPTCHA_OUTPUT_FORMAT = u'%(image)s<p>Hello, captcha world</p>%(hidden_field)s%(text_field)s' r = self.client.get(reverse('captcha-test')) self.failUnlessEqual(r.status_code, 200) self.assertTrue('<p>Hello, captcha world</p>' in r.content) def testInvalidOutputFormat(self): settings.CAPTCHA_OUTPUT_FORMAT = u'%(image)s' try: r = self.client.get(reverse('captcha-test')) self.fail() except KeyError: pass def trivial_challenge(): return 'trivial','trivial'
Python
from django.conf.urls.defaults import * urlpatterns = patterns('captcha.views', url(r'image/(?P<key>\w+)/$','captcha_image',name='captcha-image'), url(r'audio/(?P<key>\w+)/$','captcha_audio',name='captcha-audio'), )
Python
# -*- coding: utf-8 -*- import random from captcha.conf import settings def math_challenge(): operators = ('+','*','-',) operands = (random.randint(1,10),random.randint(1,10)) operator = random.choice(operators) if operands[0] < operands[1] and '-' == operator: operands = (operands[1],operands[0]) challenge = '%d%s%d' %(operands[0],operator,operands[1]) return u'%s=' %(challenge), unicode(eval(challenge)) def random_char_challenge(): chars,ret = u'abcdefghijklmnopqrstuvwxyz', u'' for i in range(settings.CAPTCHA_LENGTH): ret += random.choice(chars) return ret.upper(),ret def unicode_challenge(): chars,ret = u'äàáëéèïíîöóòüúù', u'' for i in range(settings.CAPTCHA_LENGTH): ret += random.choice(chars) return ret.upper(), ret def word_challenge(): fd = file(settings.CAPTCHA_WORDS_DICTIONARY,'rb') l = fd.readlines() fd.close() while True: word = random.choice(l).strip() if len(word) >= settings.CAPTCHA_DICTIONARY_MIN_LENGTH and len(word) <= settings.CAPTCHA_DICTIONARY_MAX_LENGTH: break return word.upper(), word.lower() def noise_arcs(draw,image): size = image.size draw.arc([-20,-20, size[0],20], 0, 295, fill=settings.CAPTCHA_FOREGROUND_COLOR) draw.line([-20,20, size[0]+20,size[1]-20], fill=settings.CAPTCHA_FOREGROUND_COLOR) draw.line([-20,0, size[0]+20,size[1]], fill=settings.CAPTCHA_FOREGROUND_COLOR) return draw def noise_dots(draw,image): size = image.size for p in range(int(size[0]*size[1]*0.1)): draw.point((random.randint(0, size[0]),random.randint(0, size[1])), fill=settings.CAPTCHA_FOREGROUND_COLOR ) return draw def post_smooth(image): try: import ImageFilter except ImportError: from PIL import ImageFilter return image.filter(ImageFilter.SMOOTH)
Python
from django.core.management.base import BaseCommand, CommandError import sys from optparse import make_option class Command(BaseCommand): help = "Clean up expired captcha hashkeys." def handle(self, **options): from captcha.models import CaptchaStore import datetime verbose = int(options.get('verbosity')) expired_keys = CaptchaStore.objects.filter(expiration__lte=datetime.datetime.now()).count() if verbose >= 1: print "Currently %s expired hashkeys" % expired_keys try: CaptchaStore.remove_expired() except: if verbose >= 1 : print "Unable to delete expired hashkeys." sys.exit(1) if verbose >= 1: if expired_keys > 0: print "Expired hashkeys removed." else: print "No keys to remove."
Python
import os from django.conf import settings CAPTCHA_FONT_PATH = getattr(settings,'CAPTCHA_FONT_PATH', os.path.normpath(os.path.join(os.path.dirname(__file__), '..', 'fonts/Vera.ttf'))) CAPTCHA_FONT_SIZE = getattr(settings,'CAPTCHA_FONT_SIZE', 22) CAPTCHA_LETTER_ROTATION = getattr(settings, 'CAPTCHA_LETTER_ROTATION', (-35,35)) CAPTCHA_BACKGROUND_COLOR = getattr(settings,'CAPTCHA_BACKGROUND_COLOR', '#ffffff') CAPTCHA_FOREGROUND_COLOR= getattr(settings,'CAPTCHA_FOREGROUND_COLOR', '#001100') CAPTCHA_CHALLENGE_FUNCT = getattr(settings,'CAPTCHA_CHALLENGE_FUNCT','captcha.helpers.random_char_challenge') CAPTCHA_NOISE_FUNCTIONS = getattr(settings,'CAPTCHA_NOISE_FUNCTIONS', ('captcha.helpers.noise_arcs','captcha.helpers.noise_dots',)) CAPTCHA_FILTER_FUNCTIONS = getattr(settings,'CAPTCHA_FILTER_FUNCTIONS',('captcha.helpers.post_smooth',)) CAPTCHA_WORDS_DICTIONARY = getattr(settings,'CAPTCHA_WORDS_DICTIONARY', '/usr/share/dict/words') CAPTCHA_FLITE_PATH = getattr(settings,'CAPTCHA_FLITE_PATH',None) CAPTCHA_TIMEOUT = getattr(settings, 'CAPTCHA_TIMEOUT', 5) # Minutes CAPTCHA_LENGTH = int(getattr(settings, 'CAPTCHA_LENGTH', 4)) # Chars CAPTCHA_IMAGE_BEFORE_FIELD = getattr(settings,'CAPTCHA_IMAGE_BEFORE_FIELD', True) CAPTCHA_DICTIONARY_MIN_LENGTH = getattr(settings,'CAPTCHA_DICTIONARY_MIN_LENGTH', 0) CAPTCHA_DICTIONARY_MAX_LENGTH = getattr(settings,'CAPTCHA_DICTIONARY_MAX_LENGTH', 99) if CAPTCHA_IMAGE_BEFORE_FIELD: CAPTCHA_OUTPUT_FORMAT = getattr(settings,'CAPTCHA_OUTPUT_FORMAT', u'%(image)s %(hidden_field)s %(text_field)s') else: CAPTCHA_OUTPUT_FORMAT = getattr(settings,'CAPTCHA_OUTPUT_FORMAT', u'%(hidden_field)s %(text_field)s %(image)s') # Failsafe if CAPTCHA_DICTIONARY_MIN_LENGTH > CAPTCHA_DICTIONARY_MAX_LENGTH: CAPTCHA_DICTIONARY_MIN_LENGTH, CAPTCHA_DICTIONARY_MAX_LENGTH = CAPTCHA_DICTIONARY_MAX_LENGTH, CAPTCHA_DICTIONARY_MIN_LENGTH def _callable_from_string(string_or_callable): if callable(string_or_callable): return string_or_callable else: return getattr(__import__( '.'.join(string_or_callable.split('.')[:-1]), {}, {}, ['']), string_or_callable.split('.')[-1]) def get_challenge(): return _callable_from_string(CAPTCHA_CHALLENGE_FUNCT) def noise_functions(): if CAPTCHA_NOISE_FUNCTIONS: return map(_callable_from_string, CAPTCHA_NOISE_FUNCTIONS) return list() def filter_functions(): if CAPTCHA_FILTER_FUNCTIONS: return map(_callable_from_string, CAPTCHA_FILTER_FUNCTIONS) return list()
Python
from cStringIO import StringIO from captcha.models import CaptchaStore from django.http import HttpResponse, Http404 from django.shortcuts import get_object_or_404 from captcha.conf import settings import re, random try: import Image, ImageDraw, ImageFont, ImageFilter except ImportError: from PIL import Image, ImageDraw, ImageFont, ImageFilter NON_DIGITS_RX = re.compile('[^\d]') def captcha_image(request,key): store = get_object_or_404(CaptchaStore,hashkey=key) text=store.challenge if settings.CAPTCHA_FONT_PATH.lower().strip().endswith('ttf'): font = ImageFont.truetype(settings.CAPTCHA_FONT_PATH,settings.CAPTCHA_FONT_SIZE) else: font = ImageFont.load(settings.CAPTCHA_FONT_PATH) size = font.getsize(text) size = (size[0]*2,size[1]) image = Image.new('RGB', size , settings.CAPTCHA_BACKGROUND_COLOR) try: PIL_VERSION = int(NON_DIGITS_RX.sub('',Image.VERSION)) except: PIL_VERSION = 116 xpos = 2 for char in text: fgimage = Image.new('RGB', size, settings.CAPTCHA_FOREGROUND_COLOR) charimage = Image.new('L', font.getsize(' %s '%char), '#000000') chardraw = ImageDraw.Draw(charimage) chardraw.text((0,0), ' %s '%char, font=font, fill='#ffffff') if settings.CAPTCHA_LETTER_ROTATION: if PIL_VERSION >= 116: charimage = charimage.rotate(random.randrange( *settings.CAPTCHA_LETTER_ROTATION ), expand=0, resample=Image.BICUBIC) else: charimage = charimage.rotate(random.randrange( *settings.CAPTCHA_LETTER_ROTATION ), resample=Image.BICUBIC) charimage = charimage.crop(charimage.getbbox()) maskimage = Image.new('L', size) maskimage.paste(charimage, (xpos, 4, xpos+charimage.size[0], 4+charimage.size[1] )) size = maskimage.size image = Image.composite(fgimage, image, maskimage) xpos = xpos + 2 + charimage.size[0] image = image.crop((0,0,xpos+1,size[1])) draw = ImageDraw.Draw(image) for f in settings.noise_functions(): draw = f(draw,image) for f in settings.filter_functions(): image = f(image) out = StringIO() image.save(out,"PNG") out.seek(0) response = HttpResponse() response['Content-Type'] = 'image/png' response.write(out.read()) return response def captcha_audio(request,key): if settings.CAPTCHA_FLITE_PATH: store = get_object_or_404(CaptchaStore,hashkey=key) text=store.challenge if 'captcha.helpers.math_challenge' == settings.CAPTCHA_CHALLENGE_FUNCT: text = text.replace('*','times').replace('-','minus') else: text = ', '.join(list(text)) import tempfile, os path = str(os.path.join(tempfile.gettempdir(),'%s.wav' %key)) cline = '%s -t "%s" -o "%s"' %(settings.CAPTCHA_FLITE_PATH, text, path) os.popen(cline).read() if os.path.isfile(path): response = HttpResponse() f = open(path,'rb') response['Content-Type'] = 'audio/x-wav' response.write(f.read()) f.close() os.unlink(path) return response raise Http404
Python
VERSION = (0, 1, 7) def get_version(svn=False): "Returns the version as a human-format string." v = '.'.join([str(i) for i in VERSION]) if svn: from django.utils.version import get_svn_revision import os svn_rev = get_svn_revision(os.path.dirname(__file__)) if svn_rev: v = '%s-%s' % (v, svn_rev) return v
Python
# coding: utf-8 # imports import re, os # django imports from django import forms from django.forms.formsets import BaseFormSet from django.utils.translation import ugettext as _ # filebrowser imports from filebrowser.settings import MAX_UPLOAD_SIZE, FOLDER_REGEX from filebrowser.functions import convert_filename alnum_name_re = re.compile(FOLDER_REGEX) class MakeDirForm(forms.Form): """ Form for creating Folder. """ def __init__(self, path, *args, **kwargs): self.path = path super(MakeDirForm, self).__init__(*args, **kwargs) dir_name = forms.CharField(widget=forms.TextInput(attrs=dict({ 'class': 'vTextField' }, max_length=50, min_length=3)), label=_(u'Name'), help_text=_(u'Only letters, numbers, underscores, spaces and hyphens are allowed.'), required=True) def clean_dir_name(self): if self.cleaned_data['dir_name']: # only letters, numbers, underscores, spaces and hyphens are allowed. if not alnum_name_re.search(self.cleaned_data['dir_name']): raise forms.ValidationError(_(u'Only letters, numbers, underscores, spaces and hyphens are allowed.')) # Folder must not already exist. if os.path.isdir(os.path.join(self.path, convert_filename(self.cleaned_data['dir_name']))): raise forms.ValidationError(_(u'The Folder already exists.')) return convert_filename(self.cleaned_data['dir_name']) class RenameForm(forms.Form): """ Form for renaming Folder/File. """ def __init__(self, path, file_extension, *args, **kwargs): self.path = path self.file_extension = file_extension super(RenameForm, self).__init__(*args, **kwargs) name = forms.CharField(widget=forms.TextInput(attrs=dict({ 'class': 'vTextField' }, max_length=50, min_length=3)), label=_(u'New Name'), help_text=_('Only letters, numbers, underscores, spaces and hyphens are allowed.'), required=True) def clean_name(self): if self.cleaned_data['name']: # only letters, numbers, underscores, spaces and hyphens are allowed. if not alnum_name_re.search(self.cleaned_data['name']): raise forms.ValidationError(_(u'Only letters, numbers, underscores, spaces and hyphens are allowed.')) # folder/file must not already exist. if os.path.isdir(os.path.join(self.path, convert_filename(self.cleaned_data['name']))): raise forms.ValidationError(_(u'The Folder already exists.')) elif os.path.isfile(os.path.join(self.path, convert_filename(self.cleaned_data['name']) + self.file_extension)): raise forms.ValidationError(_(u'The File already exists.')) return convert_filename(self.cleaned_data['name'])
Python
# This file is only necessary for the tests to work
Python
# coding: utf-8 # imports import os # django imports from django.db import models from django import forms from django.forms.widgets import Input from django.db.models.fields import Field, CharField from django.utils.encoding import force_unicode from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ # filebrowser imports from filebrowser.settings import * from filebrowser.base import FileObject from filebrowser.functions import url_to_path class FileBrowseWidget(Input): input_type = 'text' class Media: js = (os.path.join(URL_FILEBROWSER_MEDIA, 'js/AddFileBrowser.js'), ) def __init__(self, attrs=None): self.directory = attrs.get('directory', '') self.extensions = attrs.get('extensions', '') self.format = attrs.get('format', '') if attrs is not None: self.attrs = attrs.copy() else: self.attrs = {} def render(self, name, value, attrs=None): if value is None: value = "" final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) final_attrs['search_icon'] = URL_FILEBROWSER_MEDIA + 'img/filebrowser_icon_show.gif' final_attrs['directory'] = self.directory final_attrs['extensions'] = self.extensions final_attrs['format'] = self.format final_attrs['ADMIN_THUMBNAIL'] = ADMIN_THUMBNAIL final_attrs['DEBUG'] = DEBUG if value != "": try: final_attrs['directory'] = os.path.split(value.path_relative_directory)[0] except: pass return render_to_string("filebrowser/custom_field.html", locals()) class FileBrowseFormField(forms.CharField): widget = FileBrowseWidget default_error_messages = { 'extension': _(u'Extension %(ext)s is not allowed. Only %(allowed)s is allowed.'), } def __init__(self, max_length=None, min_length=None, directory=None, extensions=None, format=None, *args, **kwargs): self.max_length, self.min_length = max_length, min_length self.directory = directory self.extensions = extensions if format: self.format = format or '' self.extensions = extensions or EXTENSIONS.get(format) super(FileBrowseFormField, self).__init__(*args, **kwargs) def clean(self, value): value = super(FileBrowseFormField, self).clean(value) if value == '': return value file_extension = os.path.splitext(value)[1].lower() if self.extensions and not file_extension in self.extensions: raise forms.ValidationError(self.error_messages['extension'] % {'ext': file_extension, 'allowed': ", ".join(self.extensions)}) return value class FileBrowseField(Field): __metaclass__ = models.SubfieldBase def __init__(self, *args, **kwargs): self.directory = kwargs.pop('directory', '') self.extensions = kwargs.pop('extensions', '') self.format = kwargs.pop('format', '') return super(FileBrowseField, self).__init__(*args, **kwargs) def to_python(self, value): if not value or isinstance(value, FileObject): return value return FileObject(url_to_path(value)) def get_db_prep_value(self, value): if value is None: return None return unicode(value) def get_manipulator_field_objs(self): return [oldforms.TextField] def get_internal_type(self): return "CharField" def formfield(self, **kwargs): attrs = {} attrs["directory"] = self.directory attrs["extensions"] = self.extensions attrs["format"] = self.format defaults = { 'form_class': FileBrowseFormField, 'widget': FileBrowseWidget(attrs=attrs), 'directory': self.directory, 'extensions': self.extensions, 'format': self.format } defaults.update(kwargs) return super(FileBrowseField, self).formfield(**defaults)
Python
from django.conf.urls.defaults import * urlpatterns = patterns('', # filebrowser urls url(r'^browse/$', 'filebrowser.views.browse', name="fb_browse"), url(r'^mkdir/', 'filebrowser.views.mkdir', name="fb_mkdir"), url(r'^upload/', 'filebrowser.views.upload', name="fb_upload"), url(r'^rename/$', 'filebrowser.views.rename', name="fb_rename"), url(r'^delete/$', 'filebrowser.views.delete', name="fb_delete"), url(r'^versions/$', 'filebrowser.views.versions', name="fb_versions"), url(r'^check_file/$', 'filebrowser.views._check_file', name="fb_check"), url(r'^upload_file/$', 'filebrowser.views._upload_file', name="fb_do_upload"), )
Python
# coding: utf-8 # django imports from django import template from django.utils.encoding import smart_unicode from django.utils.safestring import mark_safe # filebrowser imports from filebrowser.settings import SELECT_FORMATS register = template.Library() @register.inclusion_tag('filebrowser/include/_response.html', takes_context=True) def query_string(context, add=None, remove=None): """ Allows the addition and removal of query string parameters. _response.html is just {{ response }} Usage: http://www.url.com/{% query_string "param_to_add=value, param_to_add=value" "param_to_remove, params_to_remove" %} http://www.url.com/{% query_string "" "filter" %}filter={{new_filter}} http://www.url.com/{% query_string "sort=value" "sort" %} """ # Written as an inclusion tag to simplify getting the context. add = string_to_dict(add) remove = string_to_list(remove) params = context['query'].copy() response = get_query_string(params, add, remove) return {'response': response } def query_helper(query, add=None, remove=None): """ Helper Function for use within views. """ add = string_to_dict(add) remove = string_to_list(remove) params = query.copy() return get_query_string(params, add, remove) def get_query_string(p, new_params=None, remove=None): """ Add and remove query parameters. From `django.contrib.admin`. """ if new_params is None: new_params = {} if remove is None: remove = [] for r in remove: for k in p.keys(): #if k.startswith(r): if k == r: del p[k] for k, v in new_params.items(): if k in p and v is None: del p[k] elif v is not None: p[k] = v return mark_safe('?' + '&'.join([u'%s=%s' % (k, v) for k, v in p.items()]).replace(' ', '%20')) def string_to_dict(string): """ Usage: {{ url|thumbnail:"width=10,height=20" }} {{ url|thumbnail:"width=10" }} {{ url|thumbnail:"height=20" }} """ kwargs = {} if string: string = str(string) if ',' not in string: # ensure at least one ',' string += ',' for arg in string.split(','): arg = arg.strip() if arg == '': continue kw, val = arg.split('=', 1) kwargs[kw] = val return kwargs def string_to_list(string): """ Usage: {{ url|thumbnail:"width,height" }} """ args = [] if string: string = str(string) if ',' not in string: # ensure at least one ',' string += ',' for arg in string.split(','): arg = arg.strip() if arg == '': continue args.append(arg) return args class SelectableNode(template.Node): def __init__(self, filetype, format): self.filetype = template.Variable(filetype) self.format = template.Variable(format) def render(self, context): try: filetype = self.filetype.resolve(context) except template.VariableDoesNotExist: filetype = '' try: format = self.format.resolve(context) except template.VariableDoesNotExist: format = '' if filetype and format and filetype in SELECT_FORMATS[format]: selectable = True elif filetype and format and filetype not in SELECT_FORMATS[format]: selectable = False else: selectable = True context['selectable'] = selectable return '' def selectable(parser, token): try: tag, filetype, format = token.split_contents() except: raise TemplateSyntaxError, "%s tag requires 2 arguments" % token.contents.split()[0] return SelectableNode(filetype, format) register.tag(selectable)
Python
# coding: utf-8 from django.utils.html import escape from django.utils.safestring import mark_safe from django.template import Library register = Library() DOT = '.' @register.inclusion_tag('filebrowser/include/paginator.html', takes_context=True) def pagination(context): page_num = context['page'].number-1 paginator = context['p'] if not paginator.num_pages or paginator.num_pages == 1: page_range = [] else: ON_EACH_SIDE = 3 ON_ENDS = 2 # If there are 10 or fewer pages, display links to every page. # Otherwise, do some fancy if paginator.num_pages <= 10: page_range = range(paginator.num_pages) else: # Insert "smart" pagination links, so that there are always ON_ENDS # links at either end of the list of pages, and there are always # ON_EACH_SIDE links at either end of the "current page" link. page_range = [] if page_num > (ON_EACH_SIDE + ON_ENDS): page_range.extend(range(0, ON_EACH_SIDE - 1)) page_range.append(DOT) page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1)) else: page_range.extend(range(0, page_num + 1)) if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1): page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1)) page_range.append(DOT) page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages)) else: page_range.extend(range(page_num + 1, paginator.num_pages)) return { 'page_range': page_range, 'page_num': page_num, 'results_var': context['results_var'], 'query': context['query'], }
Python
# coding: utf-8 # django imports from django.template import Node from django.template import Library from django.utils.safestring import mark_safe register = Library() class CsrfTokenNode(Node): def render(self, context): csrf_token = context.get('csrf_token', None) if csrf_token: if csrf_token == 'NOTPROVIDED': return mark_safe(u"") else: return mark_safe(u"<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='%s' /></div>" % (csrf_token)) else: # It's very probable that the token is missing because of # misconfiguration, so we raise a warning from django.conf import settings if settings.DEBUG: import warnings warnings.warn("A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.") return u'' def fb_csrf_token(parser, token): return CsrfTokenNode() register.tag(fb_csrf_token)
Python
# coding: utf-8 # imports import os, re from time import gmtime # django imports from django.template import Library, Node, Variable, VariableDoesNotExist, TemplateSyntaxError from django.conf import settings from django.utils.encoding import force_unicode # filebrowser imports from filebrowser.settings import MEDIA_ROOT, MEDIA_URL, VERSIONS from filebrowser.functions import url_to_path, path_to_url, get_version_path, version_generator from filebrowser.base import FileObject register = Library() class VersionNode(Node): def __init__(self, src, version_prefix): self.src = Variable(src) if (version_prefix[0] == version_prefix[-1] and version_prefix[0] in ('"', "'")): self.version_prefix = version_prefix[1:-1] else: self.version_prefix = None self.version_prefix_var = Variable(version_prefix) def render(self, context): try: source = self.src.resolve(context) except VariableDoesNotExist: return None if self.version_prefix: version_prefix = self.version_prefix else: try: version_prefix = self.version_prefix_var.resolve(context) except VariableDoesNotExist: return None try: version_path = get_version_path(url_to_path(str(source)), version_prefix) if not os.path.isfile(os.path.join(MEDIA_ROOT, version_path)): # create version version_path = version_generator(url_to_path(str(source)), version_prefix) elif os.path.getmtime(os.path.join(MEDIA_ROOT, url_to_path(str(source)))) > os.path.getmtime(os.path.join(MEDIA_ROOT, version_path)): # recreate version if original image was updated version_path = version_generator(url_to_path(str(source)), version_prefix, force=True) return path_to_url(version_path) except: return "" def version(parser, token): """ Displaying a version of an existing Image according to the predefined VERSIONS settings (see filebrowser settings). {% version field_name version_prefix %} Use {% version my_image 'medium' %} in order to display the medium-size version of an Image stored in a field name my_image. version_prefix can be a string or a variable. if version_prefix is a string, use quotes. """ try: tag, src, version_prefix = token.split_contents() except: raise TemplateSyntaxError, "%s tag requires 2 arguments" % token.contents.split()[0] if (version_prefix[0] == version_prefix[-1] and version_prefix[0] in ('"', "'")) and version_prefix.lower()[1:-1] not in VERSIONS: raise TemplateSyntaxError, "%s tag received bad version_prefix %s" % (tag, version_prefix) return VersionNode(src, version_prefix) class VersionObjectNode(Node): def __init__(self, src, version_prefix, var_name): self.var_name = var_name self.src = Variable(src) if (version_prefix[0] == version_prefix[-1] and version_prefix[0] in ('"', "'")): self.version_prefix = version_prefix[1:-1] else: self.version_prefix = None self.version_prefix_var = Variable(version_prefix) def render(self, context): try: source = self.src.resolve(context) except VariableDoesNotExist: return None if self.version_prefix: version_prefix = self.version_prefix else: try: version_prefix = self.version_prefix_var.resolve(context) except VariableDoesNotExist: return None try: version_path = get_version_path(url_to_path(str(source)), version_prefix) if not os.path.isfile(os.path.join(MEDIA_ROOT, version_path)): # create version version_path = version_generator(url_to_path(str(source)), version_prefix) elif os.path.getmtime(os.path.join(MEDIA_ROOT, url_to_path(str(source)))) > os.path.getmtime(os.path.join(MEDIA_ROOT, version_path)): # recreate version if original image was updated version_path = version_generator(url_to_path(str(source)), version_prefix, force=True) context[self.var_name] = FileObject(version_path) except: context[self.var_name] = "" return '' def version_object(parser, token): """ Returns a context variable 'version_object'. {% version_object field_name version_prefix %} Use {% version_object my_image 'medium' %} in order to retrieve the medium version of an Image stored in a field name my_image. Use {% version_object my_image 'medium' as var %} in order to use 'var' as your context variable. version_prefix can be a string or a variable. if version_prefix is a string, use quotes. """ try: #tag, src, version_prefix = token.split_contents() tag, arg = token.contents.split(None, 1) except: raise TemplateSyntaxError, "%s tag requires arguments" % token.contents.split()[0] m = re.search(r'(.*?) (.*?) as (\w+)', arg) if not m: raise TemplateSyntaxError, "%r tag had invalid arguments" % tag src, version_prefix, var_name = m.groups() if (version_prefix[0] == version_prefix[-1] and version_prefix[0] in ('"', "'")) and version_prefix.lower()[1:-1] not in VERSIONS: raise TemplateSyntaxError, "%s tag received bad version_prefix %s" % (tag, version_prefix) return VersionObjectNode(src, version_prefix, var_name) class VersionSettingNode(Node): def __init__(self, version_prefix): if (version_prefix[0] == version_prefix[-1] and version_prefix[0] in ('"', "'")): self.version_prefix = version_prefix[1:-1] else: self.version_prefix = None self.version_prefix_var = Variable(version_prefix) def render(self, context): if self.version_prefix: version_prefix = self.version_prefix else: try: version_prefix = self.version_prefix_var.resolve(context) except VariableDoesNotExist: return None context['version_setting'] = VERSIONS[version_prefix] return '' def version_setting(parser, token): """ Get Information about a version setting. """ try: tag, version_prefix = token.split_contents() except: raise TemplateSyntaxError, "%s tag requires 1 argument" % token.contents.split()[0] if (version_prefix[0] == version_prefix[-1] and version_prefix[0] in ('"', "'")) and version_prefix.lower()[1:-1] not in VERSIONS: raise TemplateSyntaxError, "%s tag received bad version_prefix %s" % (tag, version_prefix) return VersionSettingNode(version_prefix) register.tag(version) register.tag(version_object) register.tag(version_setting)
Python
# coding: utf-8 # imports import os # django imports from django.conf import settings from django.utils.translation import ugettext_lazy as _ # settings for django-tinymce try: import tinymce.settings DEFAULT_URL_TINYMCE = tinymce.settings.JS_BASE_URL + '/' DEFAULT_PATH_TINYMCE = tinymce.settings.JS_ROOT + '/' except ImportError: DEFAULT_URL_TINYMCE = settings.ADMIN_MEDIA_PREFIX + "tinymce/jscripts/tiny_mce/" DEFAULT_PATH_TINYMCE = os.path.join(settings.MEDIA_ROOT, 'admin/tinymce/jscripts/tiny_mce/') # Set to True in order to see the FileObject when Browsing. DEBUG = getattr(settings, "FILEBROWSER_DEBUG", False) # Main Media Settings MEDIA_ROOT = getattr(settings, "FILEBROWSER_MEDIA_ROOT", settings.MEDIA_ROOT) MEDIA_URL = getattr(settings, "FILEBROWSER_MEDIA_URL", settings.MEDIA_URL) # Main FileBrowser Directory. This has to be a directory within MEDIA_ROOT. # Leave empty in order to browse all files under MEDIA_ROOT. # DO NOT USE A SLASH AT THE BEGINNING, DO NOT FORGET THE TRAILING SLASH AT THE END. DIRECTORY = getattr(settings, "FILEBROWSER_DIRECTORY", 'uploads/') # The URL/PATH to your filebrowser media-files. URL_FILEBROWSER_MEDIA = getattr(settings, "FILEBROWSER_URL_FILEBROWSER_MEDIA", "/medias/filebrowser/") PATH_FILEBROWSER_MEDIA = getattr(settings, "FILEBROWSER_PATH_FILEBROWSER_MEDIA", os.path.join(settings.MEDIA_ROOT, 'filebrowser/')) # The URL/PATH to your TinyMCE Installation. URL_TINYMCE = getattr(settings, "FILEBROWSER_URL_TINYMCE", DEFAULT_URL_TINYMCE) PATH_TINYMCE = getattr(settings, "FILEBROWSER_PATH_TINYMCE", DEFAULT_PATH_TINYMCE) # Allowed Extensions for File Upload. Lower case is important. # Please be aware that there are Icons for the default extension settings. # Therefore, if you add a category (e.g. "Misc"), you won't get an icon. EXTENSIONS = getattr(settings, "FILEBROWSER_EXTENSIONS", { 'Folder': [''], 'Image': ['.jpg','.jpeg','.gif','.png','.tif','.tiff'], 'Video': ['.mov','.wmv','.mpeg','.mpg','.avi','.rm'], 'Document': ['.pdf','.doc','.rtf','.txt','.xls','.csv'], 'Audio': ['.mp3','.mp4','.wav','.aiff','.midi','.m4p'], 'Code': ['.html','.py','.js','.css'] }) # Define different formats for allowed selections. # This has to be a subset of EXTENSIONS. SELECT_FORMATS = getattr(settings, "FILEBROWSER_SELECT_FORMATS", { 'File': ['Folder','Document',], 'Image': ['Image'], 'Media': ['Video','Sound'], 'Document': ['Document'], # for TinyMCE we can also define lower-case items 'image': ['Image'], 'file': ['Folder','Image','Document',], }) # Directory to Save Image Versions (and Thumbnails). Relative to MEDIA_ROOT. # If no directory is given, versions are stored within the Image directory. # VERSION URL: VERSIONS_BASEDIR/original_path/originalfilename_versionsuffix.extension VERSIONS_BASEDIR = getattr(settings, 'FILEBROWSER_VERSIONS_BASEDIR', '') # Versions Format. Available Attributes: verbose_name, width, height, opts VERSIONS = getattr(settings, "FILEBROWSER_VERSIONS", { 'fb_thumb': {'verbose_name': 'Admin Thumbnail', 'width': 60, 'height': 60, 'opts': 'crop upscale'}, 'sponsor': {'verbose_name': 'Thumbnail Sponsors (80px)', 'width': '', 'height': 80, 'opts': ''}, 'thumbnail': {'verbose_name': 'Thumbnail (140px)', 'width': 140, 'height': 140, 'opts': ''}, 'small': {'verbose_name': 'Small (300px)', 'width': 300, 'height': 300, 'opts': ''}, 'medium': {'verbose_name': 'Medium (460px)', 'width': 460, 'height': '', 'opts': ''}, 'big': {'verbose_name': 'Big (620px)', 'width': 620, 'height': 620, 'opts': ''}, 'cropped': {'verbose_name': 'Cropped (60x60px)', 'width': 60, 'height': 60, 'opts': 'crop'}, 'croppedthumbnail': {'verbose_name': 'Cropped Thumbnail (140x140px)', 'width': 140, 'height': 140, 'opts': 'crop'}, }) # Versions available within the Admin-Interface. ADMIN_VERSIONS = getattr(settings, 'FILEBROWSER_ADMIN_VERSIONS', ['sponsor', 'thumbnail','small', 'medium','big']) # Which Version should be used as Admin-thumbnail. ADMIN_THUMBNAIL = getattr(settings, 'FILEBROWSER_ADMIN_THUMBNAIL', 'fb_thumb') # EXTRA SETTINGS # True to save the URL including MEDIA_URL to your model fields # or False (default) to save path relative to MEDIA_URL. # Note: Full URL does not necessarily means absolute URL. SAVE_FULL_URL = getattr(settings, "FILEBROWSER_SAVE_FULL_URL", True) # If set to True, the FileBrowser will not try to import a mis-installed PIL. STRICT_PIL = getattr(settings, 'FILEBROWSER_STRICT_PIL', False) # PIL's Error "Suspension not allowed here" work around: # s. http://mail.python.org/pipermail/image-sig/1999-August/000816.html IMAGE_MAXBLOCK = getattr(settings, 'FILEBROWSER_IMAGE_MAXBLOCK', 1024*1024) # Exclude files matching any of the following regular expressions # Default is to exclude 'thumbnail' style naming of image-thumbnails. EXTENSION_LIST = [] for exts in EXTENSIONS.values(): EXTENSION_LIST += exts EXCLUDE = getattr(settings, 'FILEBROWSER_EXCLUDE', (r'_(%(exts)s)_.*_q\d{1,3}\.(%(exts)s)' % {'exts': ('|'.join(EXTENSION_LIST))},)) # Max. Upload Size in Bytes. MAX_UPLOAD_SIZE = getattr(settings, "FILEBROWSER_MAX_UPLOAD_SIZE", 10485760) # Convert Filename (replace spaces and convert to lowercase) CONVERT_FILENAME = getattr(settings, "FILEBROWSER_CONVERT_FILENAME", True) # Max. Entries per Page # Loading a Sever-Directory with lots of files might take a while # Use this setting to limit the items shown LIST_PER_PAGE = getattr(settings, "FILEBROWSER_LIST_PER_PAGE", 50) # Default Sorting # Options: date, filesize, filename_lower, filetype_checked DEFAULT_SORTING_BY = getattr(settings, "FILEBROWSER_DEFAULT_SORTING_BY", "date") # Sorting Order: asc, desc DEFAULT_SORTING_ORDER = getattr(settings, "FILEBROWSER_DEFAULT_SORTING_ORDER", "desc") # regex to clean dir names before creation FOLDER_REGEX = getattr(settings, "FILEBROWSER_FOLDER_REGEX", r'^[\sa-zA-Z0-9._/-]+$') # EXTRA TRANSLATION STRINGS # The following strings are not availabe within views or templates _('Folder') _('Image') _('Video') _('Document') _('Audio') _('Code')
Python
# coding: utf-8 # django imports from django.contrib.sessions.models import Session from django.shortcuts import get_object_or_404, render_to_response from django.contrib.auth.models import User from django.template import RequestContext from django.conf import settings def flash_login_required(function): """ Decorator to recognize a user by its session. Used for Flash-Uploading. """ def decorator(request, *args, **kwargs): try: engine = __import__(settings.SESSION_ENGINE, {}, {}, ['']) except: import django.contrib.sessions.backends.db engine = django.contrib.sessions.backends.db session_data = engine.SessionStore(request.POST.get('session_key')) user_id = session_data['_auth_user_id'] # will return 404 if the session ID does not resolve to a valid user request.user = get_object_or_404(User, pk=user_id) return function(request, *args, **kwargs) return decorator
Python
from django.core.management.base import NoArgsCommand class Command(NoArgsCommand): help = "(Re)Generate versions of Images" def handle_noargs(self, **options): import os, re from filebrowser.settings import EXTENSION_LIST, EXCLUDE, MEDIA_ROOT, DIRECTORY, VERSIONS, EXTENSIONS # Precompile regular expressions filter_re = [] for exp in EXCLUDE: filter_re.append(re.compile(exp)) for k,v in VERSIONS.iteritems(): exp = (r'_%s.(%s)') % (k, '|'.join(EXTENSION_LIST)) filter_re.append(re.compile(exp)) path = os.path.join(MEDIA_ROOT, DIRECTORY) # walkt throu the filebrowser directory # for all/new files (except file versions itself and excludes) for dirpath,dirnames,filenames in os.walk(path): for filename in filenames: filtered = False # no "hidden" files (stating with ".") if filename.startswith('.'): continue # check the exclude list for re_prefix in filter_re: if re_prefix.search(filename): filtered = True if filtered: continue (tmp, extension) = os.path.splitext(filename) if extension in EXTENSIONS["Image"]: self.createVersions(os.path.join(dirpath, filename)) def createVersions(self, path): print "generating versions for: ", path from filebrowser.settings import VERSIONS from filebrowser.functions import version_generator for version in VERSIONS: #print " ", version version_generator(path, version, True)
Python
# coding: utf-8 # imports import os, re, datetime from time import gmtime, strftime # django imports from django.conf import settings # filebrowser imports from filebrowser.settings import * from filebrowser.functions import get_file_type, url_join, is_selectable, get_version_path # PIL import if STRICT_PIL: from PIL import Image else: try: from PIL import Image except ImportError: import Image class FileObject(object): """ The FileObject represents a File on the Server. PATH has to be relative to MEDIA_ROOT. """ def __init__(self, path): self.path = path self.url_rel = path.replace("\\","/") self.head = os.path.split(path)[0] self.filename = os.path.split(path)[1] self.filename_lower = self.filename.lower() # important for sorting self.filetype = get_file_type(self.filename) def _filesize(self): """ Filesize. """ if os.path.isfile(os.path.join(MEDIA_ROOT, self.path)) or os.path.isdir(os.path.join(MEDIA_ROOT, self.path)): return os.path.getsize(os.path.join(MEDIA_ROOT, self.path)) return "" filesize = property(_filesize) def _date(self): """ Date. """ if os.path.isfile(os.path.join(MEDIA_ROOT, self.path)) or os.path.isdir(os.path.join(MEDIA_ROOT, self.path)): return os.path.getmtime(os.path.join(MEDIA_ROOT, self.path)) return "" date = property(_date) def _datetime(self): """ Datetime Object. """ return datetime.datetime.fromtimestamp(self.date) datetime = property(_datetime) def _extension(self): """ Extension. """ return u"%s" % os.path.splitext(self.filename)[1] extension = property(_extension) def _filetype_checked(self): if self.filetype == "Folder" and os.path.isdir(self.path_full): return self.filetype elif self.filetype != "Folder" and os.path.isfile(self.path_full): return self.filetype else: return "" filetype_checked = property(_filetype_checked) def _path_full(self): """ Full server PATH including MEDIA_ROOT. """ return u"%s" % os.path.join(MEDIA_ROOT, self.path) path_full = property(_path_full) def _path_relative(self): return self.path path_relative = property(_path_relative) def _path_relative_directory(self): """ Path relative to initial directory. """ directory_re = re.compile(r'^(%s)' % (DIRECTORY)) value = directory_re.sub('', self.path) return u"%s" % value path_relative_directory = property(_path_relative_directory) def _url_relative(self): return self.url_rel url_relative = property(_url_relative) def _url_full(self): """ Full URL including MEDIA_URL. """ return u"%s" % url_join(MEDIA_URL, self.url_rel) url_full = property(_url_full) def _url_save(self): """ URL used for the filebrowsefield. """ if SAVE_FULL_URL: return self.url_full else: return self.url_rel url_save = property(_url_save) def _url_thumbnail(self): """ Thumbnail URL. """ if self.filetype == "Image": return u"%s" % url_join(MEDIA_URL, get_version_path(self.path, 'fb_thumb')) else: return "" url_thumbnail = property(_url_thumbnail) def url_admin(self): if self.filetype_checked == "Folder": directory_re = re.compile(r'^(%s)' % (DIRECTORY)) value = directory_re.sub('', self.path) return u"%s" % value else: return u"%s" % url_join(MEDIA_URL, self.path) def _dimensions(self): """ Image Dimensions. """ if self.filetype == 'Image': try: im = Image.open(os.path.join(MEDIA_ROOT, self.path)) return im.size except: pass else: return False dimensions = property(_dimensions) def _width(self): """ Image Width. """ return self.dimensions[0] width = property(_width) def _height(self): """ Image Height. """ return self.dimensions[1] height = property(_height) def _orientation(self): """ Image Orientation. """ if self.dimensions: if self.dimensions[0] >= self.dimensions[1]: return "Landscape" else: return "Portrait" else: return None orientation = property(_orientation) def _is_empty(self): """ True if Folder is empty, False if not. """ if os.path.isdir(self.path_full): if not os.listdir(self.path_full): return True else: return False else: return None is_empty = property(_is_empty) def __repr__(self): return u"%s" % self.url_save def __str__(self): return u"%s" % self.url_save def __unicode__(self): return u"%s" % self.url_save
Python
# coding: utf-8 # imports import os, re, decimal from time import gmtime, strftime, localtime, mktime, time from urlparse import urlparse # django imports from django.utils.translation import ugettext as _ from django.utils.safestring import mark_safe from django.core.files import File from django.core.files.storage import default_storage # filebrowser imports from filebrowser.settings import * # PIL import if STRICT_PIL: from PIL import Image else: try: from PIL import Image except ImportError: import Image def url_to_path(value): """ Change URL to PATH. Value has to be an URL relative to MEDIA URL or a full URL (including MEDIA_URL). Returns a PATH relative to MEDIA_ROOT. """ mediaurl_re = re.compile(r'^(%s)' % (MEDIA_URL)) value = mediaurl_re.sub('', value) return value def path_to_url(value): """ Change PATH to URL. Value has to be a PATH relative to MEDIA_ROOT. Return an URL relative to MEDIA_ROOT. """ mediaroot_re = re.compile(r'^(%s)' % (MEDIA_ROOT)) value = mediaroot_re.sub('', value) return url_join(MEDIA_URL, value) def dir_from_url(value): """ Get the relative server directory from a URL. URL has to be an absolute URL including MEDIA_URL or an URL relative to MEDIA_URL. """ mediaurl_re = re.compile(r'^(%s)' % (MEDIA_URL)) value = mediaurl_re.sub('', value) directory_re = re.compile(r'^(%s)' % (DIRECTORY)) value = directory_re.sub('', value) return os.path.split(value)[0] def get_version_path(value, version_prefix): """ Construct the PATH to an Image version. Value has to be server-path, relative to MEDIA_ROOT. version_filename = filename + version_prefix + ext Returns a path relative to MEDIA_ROOT. """ if os.path.isfile(os.path.join(MEDIA_ROOT, value)): path, filename = os.path.split(value) filename, ext = os.path.splitext(filename) # check if this file is a version of an other file # to return filename_<version>.ext instead of filename_<version>_<version>.ext tmp = filename.split("_") if tmp[len(tmp)-1] in ADMIN_VERSIONS: # it seems like the "original" is actually a version of an other original # so we strip the suffix (aka. version_perfix) new_filename = filename.replace("_" + tmp[len(tmp)-1], "") # check if the version exists when we use the new_filename if os.path.isfile(os.path.join(MEDIA_ROOT, path, new_filename + "_" + version_prefix + ext)): # our "original" filename seem to be filename_<version> construct # so we replace it with the new_filename filename = new_filename # if a VERSIONS_BASEDIR is set we need to strip it from the path # or we get a <VERSIONS_BASEDIR>/<VERSIONS_BASEDIR>/... construct if VERSIONS_BASEDIR != "": path = path.replace(VERSIONS_BASEDIR + "/", "") version_filename = filename + "_" + version_prefix + ext return os.path.join(VERSIONS_BASEDIR, path, version_filename) else: return None def sort_by_attr(seq, attr): """ Sort the sequence of objects by object's attribute Arguments: seq - the list or any sequence (including immutable one) of objects to sort. attr - the name of attribute to sort by Returns: the sorted list of objects. """ import operator # Use the "Schwartzian transform" # Create the auxiliary list of tuples where every i-th tuple has form # (seq[i].attr, i, seq[i]) and sort it. The second item of tuple is needed not # only to provide stable sorting, but mainly to eliminate comparison of objects # (which can be expensive or prohibited) in case of equal attribute values. intermed = map(None, map(getattr, seq, (attr,)*len(seq)), xrange(len(seq)), seq) intermed.sort() return map(operator.getitem, intermed, (-1,) * len(intermed)) def url_join(*args): """ URL join routine. """ if args[0].startswith("http://"): url = "http://" else: url = "/" for arg in args: arg = unicode(arg).replace("\\", "/") arg_split = arg.split("/") for elem in arg_split: if elem != "" and elem != "http:": url = url + elem + "/" # remove trailing slash for filenames if os.path.splitext(args[-1])[1]: url = url.rstrip("/") return url def get_path(path): """ Get Path. """ if path.startswith('.') or os.path.isabs(path) or not os.path.isdir(os.path.join(MEDIA_ROOT, DIRECTORY, path)): return None return path def get_file(path, filename): """ Get File. """ if not os.path.isfile(os.path.join(MEDIA_ROOT, DIRECTORY, path, filename)) and not os.path.isdir(os.path.join(MEDIA_ROOT, DIRECTORY, path, filename)): return None return filename def get_breadcrumbs(query, path): """ Get breadcrumbs. """ breadcrumbs = [] dir_query = "" if path: for item in path.split(os.sep): dir_query = os.path.join(dir_query,item) breadcrumbs.append([item,dir_query]) return breadcrumbs def get_filterdate(filterDate, dateTime): """ Get filterdate. """ returnvalue = '' dateYear = strftime("%Y", gmtime(dateTime)) dateMonth = strftime("%m", gmtime(dateTime)) dateDay = strftime("%d", gmtime(dateTime)) if filterDate == 'today' and int(dateYear) == int(localtime()[0]) and int(dateMonth) == int(localtime()[1]) and int(dateDay) == int(localtime()[2]): returnvalue = 'true' elif filterDate == 'thismonth' and dateTime >= time()-2592000: returnvalue = 'true' elif filterDate == 'thisyear' and int(dateYear) == int(localtime()[0]): returnvalue = 'true' elif filterDate == 'past7days' and dateTime >= time()-604800: returnvalue = 'true' elif filterDate == '': returnvalue = 'true' return returnvalue def get_settings_var(): """ Get settings variables used for FileBrowser listing. """ settings_var = {} # Main settings_var['DEBUG'] = DEBUG settings_var['MEDIA_ROOT'] = MEDIA_ROOT settings_var['MEDIA_URL'] = MEDIA_URL settings_var['DIRECTORY'] = DIRECTORY # FileBrowser settings_var['URL_FILEBROWSER_MEDIA'] = URL_FILEBROWSER_MEDIA settings_var['PATH_FILEBROWSER_MEDIA'] = PATH_FILEBROWSER_MEDIA # TinyMCE settings_var['URL_TINYMCE'] = URL_TINYMCE settings_var['PATH_TINYMCE'] = PATH_TINYMCE # Extensions/Formats (for FileBrowseField) settings_var['EXTENSIONS'] = EXTENSIONS settings_var['SELECT_FORMATS'] = SELECT_FORMATS # Versions settings_var['VERSIONS_BASEDIR'] = VERSIONS_BASEDIR settings_var['VERSIONS'] = VERSIONS settings_var['ADMIN_VERSIONS'] = ADMIN_VERSIONS settings_var['ADMIN_THUMBNAIL'] = ADMIN_THUMBNAIL # FileBrowser Options settings_var['MAX_UPLOAD_SIZE'] = MAX_UPLOAD_SIZE # Convert Filenames settings_var['CONVERT_FILENAME'] = CONVERT_FILENAME return settings_var def handle_file_upload(path, file): """ Handle File Upload. """ file_path = os.path.join(path, file.name) uploadedfile = default_storage.save(file_path, file) return uploadedfile def get_file_type(filename): """ Get file type as defined in EXTENSIONS. """ file_extension = os.path.splitext(filename)[1].lower() file_type = '' for k,v in EXTENSIONS.iteritems(): for extension in v: if file_extension == extension.lower(): file_type = k return file_type def is_selectable(filename, selecttype): """ Get select type as defined in FORMATS. """ file_extension = os.path.splitext(filename)[1].lower() select_types = [] for k,v in SELECT_FORMATS.iteritems(): for extension in v: if file_extension == extension.lower(): select_types.append(k) return select_types def version_generator(value, version_prefix, force=None): """ Generate Version for an Image. value has to be a serverpath relative to MEDIA_ROOT. """ # PIL's Error "Suspension not allowed here" work around: # s. http://mail.python.org/pipermail/image-sig/1999-August/000816.html if STRICT_PIL: from PIL import ImageFile else: try: from PIL import ImageFile except ImportError: import ImageFile ImageFile.MAXBLOCK = IMAGE_MAXBLOCK # default is 64k try: im = Image.open(os.path.join(MEDIA_ROOT, value)) version_path = get_version_path(value, version_prefix) absolute_version_path = os.path.join(MEDIA_ROOT, version_path) version_dir = os.path.split(absolute_version_path)[0] if not os.path.isdir(version_dir): os.makedirs(version_dir) os.chmod(version_dir, 0775) version = scale_and_crop(im, VERSIONS[version_prefix]['width'], VERSIONS[version_prefix]['height'], VERSIONS[version_prefix]['opts']) try: version.save(absolute_version_path, quality=90, optimize=(os.path.splitext(version_path)[1].lower() != '.gif')) except IOError: version.save(absolute_version_path, quality=90) return version_path except: return None def scale_and_crop(im, width, height, opts): """ Scale and Crop. """ x, y = [float(v) for v in im.size] if width: xr = float(width) else: xr = float(x*height/y) if height: yr = float(height) else: yr = float(y*width/x) if 'crop' in opts: r = max(xr/x, yr/y) else: r = min(xr/x, yr/y) if r < 1.0 or (r > 1.0 and 'upscale' in opts): im = im.resize((int(x*r), int(y*r)), resample=Image.ANTIALIAS) if 'crop' in opts: x, y = [float(v) for v in im.size] ex, ey = (x-min(x, xr))/2, (y-min(y, yr))/2 if ex or ey: im = im.crop((int(ex), int(ey), int(x-ex), int(y-ey))) return im # if 'crop' in opts: # if 'top_left' in opts: # #draw cropping box from upper left corner of image # box = (0, 0, int(min(x, xr)), int(min(y, yr))) # im = im.resize((int(x), int(y)), resample=Image.ANTIALIAS).crop(box) # elif 'top_right' in opts: # #draw cropping box from upper right corner of image # box = (int(x-min(x, xr)), 0, int(x), int(min(y, yr))) # im = im.resize((int(x), int(y)), resample=Image.ANTIALIAS).crop(box) # elif 'bottom_left' in opts: # #draw cropping box from lower left corner of image # box = (0, int(y-min(y, yr)), int(xr), int(y)) # im = im.resize((int(x), int(y)), resample=Image.ANTIALIAS).crop(box) # elif 'bottom_right' in opts: # #draw cropping box from lower right corner of image # (int(x-min(x, xr)), int(y-min(y, yr)), int(x), int(y)) # im = im.resize((int(x), int(y)), resample=Image.ANTIALIAS).crop(box) # else: # ex, ey = (x-min(x, xr))/2, (y-min(y, yr))/2 # if ex or ey: # box = (int(ex), int(ey), int(x-ex), int(y-ey)) # im = im.resize((int(x), int(y)), resample=Image.ANTIALIAS).crop(box) # return im scale_and_crop.valid_options = ('crop', 'upscale') def convert_filename(value): """ Convert Filename. """ if CONVERT_FILENAME: return value.replace(" ", "_").lower() else: return value
Python
# coding: utf-8 # general imports import os, re from time import gmtime, strftime # django imports from django.shortcuts import render_to_response, HttpResponse from django.template import RequestContext as Context from django.http import HttpResponseRedirect from django.contrib.admin.views.decorators import staff_member_required from django.views.decorators.cache import never_cache from django.utils.translation import ugettext as _ from django.conf import settings from django import forms from django.core.urlresolvers import reverse from django.core.exceptions import ImproperlyConfigured from django.dispatch import Signal from django.core.paginator import Paginator, InvalidPage, EmptyPage try: # django SVN from django.views.decorators.csrf import csrf_exempt except: # django 1.1 from django.contrib.csrf.middleware import csrf_exempt # filebrowser imports from filebrowser.settings import * from filebrowser.functions import path_to_url, sort_by_attr, get_path, get_file, get_version_path, get_breadcrumbs, get_filterdate, get_settings_var, handle_file_upload, convert_filename from filebrowser.templatetags.fb_tags import query_helper from filebrowser.base import FileObject from filebrowser.decorators import flash_login_required # Precompile regular expressions filter_re = [] for exp in EXCLUDE: filter_re.append(re.compile(exp)) for k,v in VERSIONS.iteritems(): exp = (r'_%s.(%s)') % (k, '|'.join(EXTENSION_LIST)) filter_re.append(re.compile(exp)) def browse(request): """ Browse Files/Directories. """ # QUERY / PATH CHECK query = request.GET.copy() path = get_path(query.get('dir', '')) directory = get_path('') if path is None: msg = _('The requested Folder does not exist.') request.user.message_set.create(message=msg) if directory is None: # The DIRECTORY does not exist, raise an error to prevent eternal redirecting. raise ImproperlyConfigured, _("Error finding Upload-Folder. Maybe it does not exist?") redirect_url = reverse("fb_browse") + query_helper(query, "", "dir") return HttpResponseRedirect(redirect_url) abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path) # INITIAL VARIABLES results_var = {'results_total': 0, 'results_current': 0, 'delete_total': 0, 'images_total': 0, 'select_total': 0 } counter = {} for k,v in EXTENSIONS.iteritems(): counter[k] = 0 dir_list = os.listdir(abs_path) files = [] for file in dir_list: # EXCLUDE FILES MATCHING VERSIONS_PREFIX OR ANY OF THE EXCLUDE PATTERNS filtered = file.startswith('.') for re_prefix in filter_re: if re_prefix.search(file): filtered = True if filtered: continue results_var['results_total'] += 1 # CREATE FILEOBJECT fileobject = FileObject(os.path.join(DIRECTORY, path, file)) # FILTER / SEARCH append = False if fileobject.filetype == request.GET.get('filter_type', fileobject.filetype) and get_filterdate(request.GET.get('filter_date', ''), fileobject.date): append = True if request.GET.get('q') and not re.compile(request.GET.get('q').lower(), re.M).search(file.lower()): append = False # APPEND FILE_LIST if append: try: # COUNTER/RESULTS if fileobject.filetype == 'Image': results_var['images_total'] += 1 if fileobject.filetype != 'Folder': results_var['delete_total'] += 1 elif fileobject.filetype == 'Folder' and fileobject.is_empty: results_var['delete_total'] += 1 if query.get('type') and query.get('type') in SELECT_FORMATS and fileobject.filetype in SELECT_FORMATS[query.get('type')]: results_var['select_total'] += 1 elif not query.get('type'): results_var['select_total'] += 1 except OSError: # Ignore items that have problems continue else: files.append(fileobject) results_var['results_current'] += 1 # COUNTER/RESULTS if fileobject.filetype: counter[fileobject.filetype] += 1 # SORTING query['o'] = request.GET.get('o', DEFAULT_SORTING_BY) query['ot'] = request.GET.get('ot', DEFAULT_SORTING_ORDER) files = sort_by_attr(files, request.GET.get('o', DEFAULT_SORTING_BY)) if not request.GET.get('ot') and DEFAULT_SORTING_ORDER == "desc" or request.GET.get('ot') == "desc": files.reverse() p = Paginator(files, LIST_PER_PAGE) try: page_nr = request.GET.get('p', '1') except: page_nr = 1 try: page = p.page(page_nr) except (EmptyPage, InvalidPage): page = p.page(p.num_pages) return render_to_response('filebrowser/index.html', { 'dir': path, 'p': p, 'page': page, 'results_var': results_var, 'counter': counter, 'query': query, 'title': _(u'FileBrowser'), 'settings_var': get_settings_var(), 'breadcrumbs': get_breadcrumbs(query, path), 'breadcrumbs_title': "" }, context_instance=Context(request)) browse = staff_member_required(never_cache(browse)) # mkdir signals filebrowser_pre_createdir = Signal(providing_args=["path", "dirname"]) filebrowser_post_createdir = Signal(providing_args=["path", "dirname"]) def mkdir(request): """ Make Directory. """ from filebrowser.forms import MakeDirForm # QUERY / PATH CHECK query = request.GET path = get_path(query.get('dir', '')) if path is None: msg = _('The requested Folder does not exist.') request.user.message_set.create(message=msg) return HttpResponseRedirect(reverse("fb_browse")) abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path) if request.method == 'POST': form = MakeDirForm(abs_path, request.POST) if form.is_valid(): server_path = os.path.join(abs_path, form.cleaned_data['dir_name']) try: # PRE CREATE SIGNAL filebrowser_pre_createdir.send(sender=request, path=path, dirname=form.cleaned_data['dir_name']) # CREATE FOLDER os.mkdir(server_path) os.chmod(server_path, 0775) # POST CREATE SIGNAL filebrowser_post_createdir.send(sender=request, path=path, dirname=form.cleaned_data['dir_name']) # MESSAGE & REDIRECT msg = _('The Folder %s was successfully created.') % (form.cleaned_data['dir_name']) request.user.message_set.create(message=msg) # on redirect, sort by date desc to see the new directory on top of the list # remove filter in order to actually _see_ the new folder # remove pagination redirect_url = reverse("fb_browse") + query_helper(query, "ot=desc,o=date", "ot,o,filter_type,filter_date,q,p") return HttpResponseRedirect(redirect_url) except OSError, (errno, strerror): if errno == 13: form.errors['dir_name'] = forms.util.ErrorList([_('Permission denied.')]) else: form.errors['dir_name'] = forms.util.ErrorList([_('Error creating folder.')]) else: form = MakeDirForm(abs_path) return render_to_response('filebrowser/makedir.html', { 'form': form, 'query': query, 'title': _(u'New Folder'), 'settings_var': get_settings_var(), 'breadcrumbs': get_breadcrumbs(query, path), 'breadcrumbs_title': _(u'New Folder') }, context_instance=Context(request)) mkdir = staff_member_required(never_cache(mkdir)) def upload(request): """ Multipe File Upload. """ from django.http import parse_cookie # QUERY / PATH CHECK query = request.GET path = get_path(query.get('dir', '')) if path is None: msg = _('The requested Folder does not exist.') request.user.message_set.create(message=msg) return HttpResponseRedirect(reverse("fb_browse")) abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path) # SESSION (used for flash-uploading) cookie_dict = parse_cookie(request.META.get('HTTP_COOKIE', '')) engine = __import__(settings.SESSION_ENGINE, {}, {}, ['']) session_key = cookie_dict.get(settings.SESSION_COOKIE_NAME, None) return render_to_response('filebrowser/upload.html', { 'query': query, 'title': _(u'Select files to upload'), 'settings_var': get_settings_var(), 'session_key': session_key, 'breadcrumbs': get_breadcrumbs(query, path), 'breadcrumbs_title': _(u'Upload') }, context_instance=Context(request)) upload = staff_member_required(never_cache(upload)) @csrf_exempt def _check_file(request): """ Check if file already exists on the server. """ from django.utils import simplejson folder = request.POST.get('folder') fb_uploadurl_re = re.compile(r'^.*(%s)' % reverse("fb_upload")) folder = fb_uploadurl_re.sub('', folder) fileArray = {} if request.method == 'POST': for k,v in request.POST.items(): if k != "folder": v = convert_filename(v) if os.path.isfile(os.path.join(MEDIA_ROOT, DIRECTORY, folder, v)): fileArray[k] = v return HttpResponse(simplejson.dumps(fileArray)) # upload signals filebrowser_pre_upload = Signal(providing_args=["path", "file"]) filebrowser_post_upload = Signal(providing_args=["path", "file"]) @csrf_exempt @flash_login_required def _upload_file(request): """ Upload file to the server. """ from django.core.files.move import file_move_safe if request.method == 'POST': folder = request.POST.get('folder') fb_uploadurl_re = re.compile(r'^.*(%s)' % reverse("fb_upload")) folder = fb_uploadurl_re.sub('', folder) abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, folder) if request.FILES: filedata = request.FILES['Filedata'] filedata.name = convert_filename(filedata.name) # PRE UPLOAD SIGNAL filebrowser_pre_upload.send(sender=request, path=request.POST.get('folder'), file=filedata) # HANDLE UPLOAD uploadedfile = handle_file_upload(abs_path, filedata) # MOVE UPLOADED FILE # if file already exists if os.path.isfile(os.path.join(MEDIA_ROOT, DIRECTORY, folder, filedata.name)): old_file = os.path.join(abs_path, filedata.name) new_file = os.path.join(abs_path, uploadedfile) file_move_safe(new_file, old_file) # POST UPLOAD SIGNAL filebrowser_post_upload.send(sender=request, path=request.POST.get('folder'), file=FileObject(os.path.join(DIRECTORY, folder, filedata.name))) return HttpResponse('True') #_upload_file = flash_login_required(_upload_file) # delete signals filebrowser_pre_delete = Signal(providing_args=["path", "filename"]) filebrowser_post_delete = Signal(providing_args=["path", "filename"]) def delete(request): """ Delete existing File/Directory. When trying to delete a Directory, the Directory has to be empty. """ # QUERY / PATH CHECK query = request.GET path = get_path(query.get('dir', '')) filename = get_file(query.get('dir', ''), query.get('filename', '')) if path is None or filename is None: if path is None: msg = _('The requested Folder does not exist.') else: msg = _('The requested File does not exist.') request.user.message_set.create(message=msg) return HttpResponseRedirect(reverse("fb_browse")) abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path) msg = "" if request.GET: if request.GET.get('filetype') != "Folder": relative_server_path = os.path.join(DIRECTORY, path, filename) try: # PRE DELETE SIGNAL filebrowser_pre_delete.send(sender=request, path=path, filename=filename) # DELETE IMAGE VERSIONS/THUMBNAILS for version in VERSIONS: try: os.unlink(os.path.join(MEDIA_ROOT, get_version_path(relative_server_path, version))) except: pass # DELETE FILE os.unlink(os.path.join(abs_path, filename)) # POST DELETE SIGNAL filebrowser_post_delete.send(sender=request, path=path, filename=filename) # MESSAGE & REDIRECT msg = _('The file %s was successfully deleted.') % (filename.lower()) request.user.message_set.create(message=msg) redirect_url = reverse("fb_browse") + query_helper(query, "", "filename,filetype") return HttpResponseRedirect(redirect_url) except OSError: # todo: define error message msg = OSError else: try: # PRE DELETE SIGNAL filebrowser_pre_delete.send(sender=request, path=path, filename=filename) # DELETE FOLDER os.rmdir(os.path.join(abs_path, filename)) # POST DELETE SIGNAL filebrowser_post_delete.send(sender=request, path=path, filename=filename) # MESSAGE & REDIRECT msg = _('The folder %s was successfully deleted.') % (filename.lower()) request.user.message_set.create(message=msg) redirect_url = reverse("fb_browse") + query_helper(query, "", "filename,filetype") return HttpResponseRedirect(redirect_url) except OSError: # todo: define error message msg = OSError if msg: request.user.message_set.create(message=msg) return render_to_response('filebrowser/index.html', { 'dir': dir_name, 'file': request.GET.get('filename', ''), 'query': query, 'settings_var': get_settings_var(), 'breadcrumbs': get_breadcrumbs(query, dir_name), 'breadcrumbs_title': "" }, context_instance=Context(request)) delete = staff_member_required(never_cache(delete)) # rename signals filebrowser_pre_rename = Signal(providing_args=["path", "filename", "new_filename"]) filebrowser_post_rename = Signal(providing_args=["path", "filename", "new_filename"]) def rename(request): """ Rename existing File/Directory. Includes renaming existing Image Versions/Thumbnails. """ from filebrowser.forms import RenameForm # QUERY / PATH CHECK query = request.GET path = get_path(query.get('dir', '')) filename = get_file(query.get('dir', ''), query.get('filename', '')) if path is None or filename is None: if path is None: msg = _('The requested Folder does not exist.') else: msg = _('The requested File does not exist.') request.user.message_set.create(message=msg) return HttpResponseRedirect(reverse("fb_browse")) abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path) file_extension = os.path.splitext(filename)[1].lower() if request.method == 'POST': form = RenameForm(abs_path, file_extension, request.POST) if form.is_valid(): relative_server_path = os.path.join(DIRECTORY, path, filename) new_filename = form.cleaned_data['name'] + file_extension new_relative_server_path = os.path.join(DIRECTORY, path, new_filename) try: # PRE RENAME SIGNAL filebrowser_pre_rename.send(sender=request, path=path, filename=filename, new_filename=new_filename) # DELETE IMAGE VERSIONS/THUMBNAILS # regenerating versions/thumbs will be done automatically for version in VERSIONS: try: os.unlink(os.path.join(MEDIA_ROOT, get_version_path(relative_server_path, version))) except: pass # RENAME ORIGINAL os.rename(os.path.join(MEDIA_ROOT, relative_server_path), os.path.join(MEDIA_ROOT, new_relative_server_path)) # POST RENAME SIGNAL filebrowser_post_rename.send(sender=request, path=path, filename=filename, new_filename=new_filename) # MESSAGE & REDIRECT msg = _('Renaming was successful.') request.user.message_set.create(message=msg) redirect_url = reverse("fb_browse") + query_helper(query, "", "filename") return HttpResponseRedirect(redirect_url) except OSError, (errno, strerror): form.errors['name'] = forms.util.ErrorList([_('Error.')]) else: form = RenameForm(abs_path, file_extension) return render_to_response('filebrowser/rename.html', { 'form': form, 'query': query, 'file_extension': file_extension, 'title': _(u'Rename "%s"') % filename, 'settings_var': get_settings_var(), 'breadcrumbs': get_breadcrumbs(query, path), 'breadcrumbs_title': _(u'Rename') }, context_instance=Context(request)) rename = staff_member_required(never_cache(rename)) def versions(request): """ Show all Versions for an Image according to ADMIN_VERSIONS. """ # QUERY / PATH CHECK query = request.GET path = get_path(query.get('dir', '')) filename = get_file(query.get('dir', ''), query.get('filename', '')) if path is None or filename is None: if path is None: msg = _('The requested Folder does not exist.') else: msg = _('The requested File does not exist.') request.user.message_set.create(message=msg) return HttpResponseRedirect(reverse("fb_browse")) abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path) return render_to_response('filebrowser/versions.html', { 'original': path_to_url(os.path.join(DIRECTORY, path, filename)), 'query': query, 'title': _(u'Versions for "%s"') % filename, 'settings_var': get_settings_var(), 'breadcrumbs': get_breadcrumbs(query, path), 'breadcrumbs_title': _(u'Versions for "%s"') % filename }, context_instance=Context(request)) versions = staff_member_required(never_cache(versions))
Python
# coding: utf-8 from django.shortcuts import render_to_response from django.http import Http404, HttpResponse from django.template import Context, Template from django.contrib.contenttypes.models import ContentType from django.utils.html import strip_tags, fix_ampersands, escape from django.utils.encoding import force_unicode from django.utils.safestring import mark_safe JSON_TEMPLATE = u"[{% for obj in objects %}{contentTypeId:'{{ obj.content_type_id }}',contentTypeText:'{{ obj.content_type_text }}',objectId:'{{ obj.object_id }}',objectText:'{{ obj.object_text|urlencode }}'}{% if not forloop.last %},{% endif %}{% endfor %}]" def get_obj(content_type_id, object_id): content_type = ContentType.objects.get(pk=content_type_id) try: obj = content_type.get_object_for_this_type(pk=object_id) except: obj = None content_type_text = unicode(content_type) if obj: object_text = unicode(obj) else: object_text = "Not Found" return { 'content_type_text': content_type_text, 'content_type_id': content_type_id, 'object_text':strip_tags(object_text), 'object_id': object_id } def generic_lookup(request): if request.method == 'GET': objects = [] if request.GET.has_key('content_type') and request.GET.has_key('object_id'): obj = get_obj(request.GET['content_type'], request.GET['object_id']) objects = (obj, ) elif request.GET.has_key('lookup'): objs = eval(request.GET['lookup']) for obj in objs: objects.append(get_obj(obj[0], obj[1])) if objects: t = Template(JSON_TEMPLATE) c = Context({'objects': objects}) return HttpResponse(t.render(c), mimetype='text/plain; charset=utf-8')
Python
# coding: utf-8 from django.shortcuts import render_to_response from django.template import RequestContext from django.shortcuts import get_object_or_404 from django.contrib.admin.views.decorators import staff_member_required from django.utils.translation import ugettext as _ from grappelli.models.help import Help, HelpItem def detail(request, object_id): """ CMS Help (Detail). """ obj = get_object_or_404(HelpItem, pk=object_id) menu = Help.objects.filter(helpitem__isnull=False).distinct() return render_to_response('grappelli/help/help_detail.html', { 'object': obj, 'menu': menu, 'title': obj.title, }, context_instance=RequestContext(request) ) detail = staff_member_required(detail) def help(request): """ CMS Help (Overview). """ menu = Help.objects.filter(helpitem__isnull=False).distinct() return render_to_response('grappelli/help/help.html', { 'menu': menu, 'title': _('Help'), }, context_instance=RequestContext(request) ) help = staff_member_required(help)
Python
# coding: utf-8 from django.http import HttpResponse from django.db import models def related_lookup(request): if request.method == 'GET': if request.GET.has_key('object_id') and request.GET.has_key('app_label') and request.GET.has_key('model_name'): object_id = request.GET.get('object_id') app_label = request.GET.get('app_label') model_name = request.GET.get('model_name') if object_id: try: model = models.get_model(app_label, model_name) obj = model.objects.get(pk=object_id) obj_text = unicode(obj) except: obj_text = "Not Found" else: obj_text = "" else: obj_text = "Error" else: obj_text = "Error" return HttpResponse(obj_text, mimetype='text/plain; charset=utf-8') def m2m_lookup(request): obj_text = [] if request.method == 'GET': if request.GET.has_key('object_id') and request.GET.has_key('app_label') and request.GET.has_key('model_name'): object_ids = request.GET.get('object_id').split(',') app_label = request.GET.get('app_label') model_name = request.GET.get('model_name') for obj_id in object_ids: try: model = models.get_model(app_label, model_name) obj = model.objects.get(pk=obj_id) obj_text.append(unicode(obj)) except: obj_text.append("Not Found") else: obj_text.append("Error") else: obj_text.append("Error") obj_text = ", ".join(obj_text) return HttpResponse(obj_text, mimetype='text/plain; charset=utf-8')
Python
# -*- coding: utf-8 -*- # imports import urllib # django imports from django.shortcuts import HttpResponse, render_to_response from django.http import HttpResponseRedirect from django.contrib.admin.views.decorators import staff_member_required from django.utils.translation import ugettext as _ # grappelli imports from grappelli.models.bookmarks import Bookmark, BookmarkItem from grappelli.settings import ADMIN_TITLE, ADMIN_URL try: # django SVN from django.views.decorators.csrf import csrf_exempt except: # django 1.1 from django.contrib.csrf.middleware import csrf_exempt @csrf_exempt def add_bookmark(request): """ Add Site to Bookmarks. """ if request.method == 'POST': if request.POST.get('path') and request.POST.get('title'): next = urllib.unquote(request.POST.get('path')) try: bookmark = Bookmark.objects.get(user=request.user) except Bookmark.DoesNotExist: bookmark = Bookmark(user=request.user) bookmark.save() try: bookmarkitem = BookmarkItem.objects.get(bookmark=bookmark, link=urllib.unquote(request.POST.get('path'))) msg = ['error', _('Site is already bookmarked.')] except BookmarkItem.DoesNotExist: try: bookmarkitem = BookmarkItem(bookmark=bookmark, title=request.POST.get('title'), link=urllib.unquote(request.POST.get('path'))) bookmarkitem.save() msg = ['success', _('Site was added to Bookmarks.')] except: msg = ['error', _('Site could not be added to Bookmarks.')] else: msg = ['error', _('Site could not be added to Bookmarks.')] next = request.POST.get('path') else: msg = ['error', _('Site could not be added to Bookmarks.')] next = ADMIN_URL # MESSAGE & REDIRECT if not request.session.get('grappelli'): request.session['grappelli'] = {} request.session['grappelli']['message'] = msg request.session.modified = True return HttpResponseRedirect(next) add_bookmark = staff_member_required(add_bookmark) def remove_bookmark(request): """ Remove Site from Bookmarks. """ if request.GET: if request.GET.get('path'): next = urllib.unquote(request.GET.get('path')) try: bookmarkitem = BookmarkItem.objects.get(bookmark__user=request.user, link=urllib.unquote(request.GET.get('path'))) bookmarkitem.delete() msg = ['success', _('Site was removed from Bookmarks.')] except BookmarkItem.DoesNotExist: msg = ['error', _('Site could not be removed from Bookmarks.')] else: msg = ['error', _('Site could not be removed from Bookmarks.')] next = ADMIN_URL else: msg = ['error', _('Site could not be removed from Bookmarks.')] # MESSAGE & REDIRECT if not request.session.get('grappelli'): request.session['grappelli'] = {} request.session['grappelli']['message'] = msg request.session.modified = True return HttpResponseRedirect(next) remove_bookmark = staff_member_required(remove_bookmark) def get_bookmark(request): """ Get Bookmarks for the currently logged-in User (AJAX request). """ if request.method == 'GET': if request.GET.get('path'): object_list = BookmarkItem.objects.filter(bookmark__user=request.user).order_by('order') #print urllib.unquote(request.GET.get('path')) try: bookmark = Bookmark.objects.get(user=request.user) except Bookmark.DoesNotExist: bookmark = Bookmark(user=request.user) bookmark.save() try: BookmarkItem.objects.get(bookmark__user=request.user, link=urllib.unquote(request.GET.get('path'))) is_bookmark = True except BookmarkItem.DoesNotExist: is_bookmark = False else: object_list = "" is_bookmark = "" else: object_list = "" is_bookmark = "" return render_to_response('admin/includes_grappelli/bookmarks.html', { 'object_list': object_list, 'bookmark': bookmark, 'is_bookmark': is_bookmark, 'admin_title': ADMIN_TITLE, 'path': request.GET.get('path', ''), }) get_bookmark = staff_member_required(get_bookmark)
Python
"""Beautiful Soup Elixir and Tonic "The Screen-Scraper's Friend" http://www.crummy.com/software/BeautifulSoup/ Beautiful Soup parses a (possibly invalid) XML or HTML document into a tree representation. It provides methods and Pythonic idioms that make it easy to navigate, search, and modify the tree. A well-formed XML/HTML document yields a well-formed data structure. An ill-formed XML/HTML document yields a correspondingly ill-formed data structure. If your document is only locally well-formed, you can use this library to find and process the well-formed part of it. Beautiful Soup works with Python 2.2 and up. It has no external dependencies, but you'll have more success at converting data to UTF-8 if you also install these three packages: * chardet, for auto-detecting character encodings http://chardet.feedparser.org/ * cjkcodecs and iconv_codec, which add more encodings to the ones supported by stock Python. http://cjkpython.i18n.org/ Beautiful Soup defines classes for two main parsing strategies: * BeautifulStoneSoup, for parsing XML, SGML, or your domain-specific language that kind of looks like XML. * BeautifulSoup, for parsing run-of-the-mill HTML code, be it valid or invalid. This class has web browser-like heuristics for obtaining a sensible parse tree in the face of common HTML errors. Beautiful Soup also defines a class (UnicodeDammit) for autodetecting the encoding of an HTML or XML document, and converting it to Unicode. Much of this code is taken from Mark Pilgrim's Universal Feed Parser. For more than you ever wanted to know about Beautiful Soup, see the documentation: http://www.crummy.com/software/BeautifulSoup/documentation.html Here, have some legalese: Copyright (c) 2004-2009, Leonard Richardson All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the the Beautiful Soup Consortium and All Night Kosher Bakery nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE, DAMMIT. """ from __future__ import generators __author__ = "Leonard Richardson (leonardr@segfault.org)" __version__ = "3.1.0.1" __copyright__ = "Copyright (c) 2004-2009 Leonard Richardson" __license__ = "New-style BSD" import codecs import markupbase import types import re from HTMLParser import HTMLParser, HTMLParseError try: from htmlentitydefs import name2codepoint except ImportError: name2codepoint = {} try: set except NameError: from sets import Set as set #These hacks make Beautiful Soup able to parse XML with namespaces markupbase._declname_match = re.compile(r'[a-zA-Z][-_.:a-zA-Z0-9]*\s*').match DEFAULT_OUTPUT_ENCODING = "utf-8" # First, the classes that represent markup elements. def sob(unicode, encoding): """Returns either the given Unicode string or its encoding.""" if encoding is None: return unicode else: return unicode.encode(encoding) class PageElement: """Contains the navigational information for some part of the page (either a tag or a piece of text)""" def setup(self, parent=None, previous=None): """Sets up the initial relations between this element and other elements.""" self.parent = parent self.previous = previous self.next = None self.previousSibling = None self.nextSibling = None if self.parent and self.parent.contents: self.previousSibling = self.parent.contents[-1] self.previousSibling.nextSibling = self def replaceWith(self, replaceWith): oldParent = self.parent myIndex = self.parent.contents.index(self) if hasattr(replaceWith, 'parent') and replaceWith.parent == self.parent: # We're replacing this element with one of its siblings. index = self.parent.contents.index(replaceWith) if index and index < myIndex: # Furthermore, it comes before this element. That # means that when we extract it, the index of this # element will change. myIndex = myIndex - 1 self.extract() oldParent.insert(myIndex, replaceWith) def extract(self): """Destructively rips this element out of the tree.""" if self.parent: try: self.parent.contents.remove(self) except ValueError: pass #Find the two elements that would be next to each other if #this element (and any children) hadn't been parsed. Connect #the two. lastChild = self._lastRecursiveChild() nextElement = lastChild.next if self.previous: self.previous.next = nextElement if nextElement: nextElement.previous = self.previous self.previous = None lastChild.next = None self.parent = None if self.previousSibling: self.previousSibling.nextSibling = self.nextSibling if self.nextSibling: self.nextSibling.previousSibling = self.previousSibling self.previousSibling = self.nextSibling = None return self def _lastRecursiveChild(self): "Finds the last element beneath this object to be parsed." lastChild = self while hasattr(lastChild, 'contents') and lastChild.contents: lastChild = lastChild.contents[-1] return lastChild def insert(self, position, newChild): if (isinstance(newChild, basestring) or isinstance(newChild, unicode)) \ and not isinstance(newChild, NavigableString): newChild = NavigableString(newChild) position = min(position, len(self.contents)) if hasattr(newChild, 'parent') and newChild.parent != None: # We're 'inserting' an element that's already one # of this object's children. if newChild.parent == self: index = self.find(newChild) if index and index < position: # Furthermore we're moving it further down the # list of this object's children. That means that # when we extract this element, our target index # will jump down one. position = position - 1 newChild.extract() newChild.parent = self previousChild = None if position == 0: newChild.previousSibling = None newChild.previous = self else: previousChild = self.contents[position-1] newChild.previousSibling = previousChild newChild.previousSibling.nextSibling = newChild newChild.previous = previousChild._lastRecursiveChild() if newChild.previous: newChild.previous.next = newChild newChildsLastElement = newChild._lastRecursiveChild() if position >= len(self.contents): newChild.nextSibling = None parent = self parentsNextSibling = None while not parentsNextSibling: parentsNextSibling = parent.nextSibling parent = parent.parent if not parent: # This is the last element in the document. break if parentsNextSibling: newChildsLastElement.next = parentsNextSibling else: newChildsLastElement.next = None else: nextChild = self.contents[position] newChild.nextSibling = nextChild if newChild.nextSibling: newChild.nextSibling.previousSibling = newChild newChildsLastElement.next = nextChild if newChildsLastElement.next: newChildsLastElement.next.previous = newChildsLastElement self.contents.insert(position, newChild) def append(self, tag): """Appends the given tag to the contents of this tag.""" self.insert(len(self.contents), tag) def findNext(self, name=None, attrs={}, text=None, **kwargs): """Returns the first item that matches the given criteria and appears after this Tag in the document.""" return self._findOne(self.findAllNext, name, attrs, text, **kwargs) def findAllNext(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns all items that match the given criteria and appear after this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.nextGenerator, **kwargs) def findNextSibling(self, name=None, attrs={}, text=None, **kwargs): """Returns the closest sibling to this Tag that matches the given criteria and appears after this Tag in the document.""" return self._findOne(self.findNextSiblings, name, attrs, text, **kwargs) def findNextSiblings(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns the siblings of this Tag that match the given criteria and appear after this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.nextSiblingGenerator, **kwargs) fetchNextSiblings = findNextSiblings # Compatibility with pre-3.x def findPrevious(self, name=None, attrs={}, text=None, **kwargs): """Returns the first item that matches the given criteria and appears before this Tag in the document.""" return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs) def findAllPrevious(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns all items that match the given criteria and appear before this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.previousGenerator, **kwargs) fetchPrevious = findAllPrevious # Compatibility with pre-3.x def findPreviousSibling(self, name=None, attrs={}, text=None, **kwargs): """Returns the closest sibling to this Tag that matches the given criteria and appears before this Tag in the document.""" return self._findOne(self.findPreviousSiblings, name, attrs, text, **kwargs) def findPreviousSiblings(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns the siblings of this Tag that match the given criteria and appear before this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.previousSiblingGenerator, **kwargs) fetchPreviousSiblings = findPreviousSiblings # Compatibility with pre-3.x def findParent(self, name=None, attrs={}, **kwargs): """Returns the closest parent of this Tag that matches the given criteria.""" # NOTE: We can't use _findOne because findParents takes a different # set of arguments. r = None l = self.findParents(name, attrs, 1) if l: r = l[0] return r def findParents(self, name=None, attrs={}, limit=None, **kwargs): """Returns the parents of this Tag that match the given criteria.""" return self._findAll(name, attrs, None, limit, self.parentGenerator, **kwargs) fetchParents = findParents # Compatibility with pre-3.x #These methods do the real heavy lifting. def _findOne(self, method, name, attrs, text, **kwargs): r = None l = method(name, attrs, text, 1, **kwargs) if l: r = l[0] return r def _findAll(self, name, attrs, text, limit, generator, **kwargs): "Iterates over a generator looking for things that match." if isinstance(name, SoupStrainer): strainer = name else: # Build a SoupStrainer strainer = SoupStrainer(name, attrs, text, **kwargs) results = ResultSet(strainer) g = generator() while True: try: i = g.next() except StopIteration: break if i: found = strainer.search(i) if found: results.append(found) if limit and len(results) >= limit: break return results #These Generators can be used to navigate starting from both #NavigableStrings and Tags. def nextGenerator(self): i = self while i: i = i.next yield i def nextSiblingGenerator(self): i = self while i: i = i.nextSibling yield i def previousGenerator(self): i = self while i: i = i.previous yield i def previousSiblingGenerator(self): i = self while i: i = i.previousSibling yield i def parentGenerator(self): i = self while i: i = i.parent yield i # Utility methods def substituteEncoding(self, str, encoding=None): encoding = encoding or "utf-8" return str.replace("%SOUP-ENCODING%", encoding) def toEncoding(self, s, encoding=None): """Encodes an object to a string in some encoding, or to Unicode. .""" if isinstance(s, unicode): if encoding: s = s.encode(encoding) elif isinstance(s, str): if encoding: s = s.encode(encoding) else: s = unicode(s) else: if encoding: s = self.toEncoding(str(s), encoding) else: s = unicode(s) return s class NavigableString(unicode, PageElement): def __new__(cls, value): """Create a new NavigableString. When unpickling a NavigableString, this method is called with the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be passed in to the superclass's __new__ or the superclass won't know how to handle non-ASCII characters. """ if isinstance(value, unicode): return unicode.__new__(cls, value) return unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING) def __getnewargs__(self): return (unicode(self),) def __getattr__(self, attr): """text.string gives you text. This is for backwards compatibility for Navigable*String, but for CData* it lets you get the string without the CData wrapper.""" if attr == 'string': return self else: raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr) def encode(self, encoding=DEFAULT_OUTPUT_ENCODING): return self.decode().encode(encoding) def decodeGivenEventualEncoding(self, eventualEncoding): return self class CData(NavigableString): def decodeGivenEventualEncoding(self, eventualEncoding): return u'<![CDATA[' + self + u']]>' class ProcessingInstruction(NavigableString): def decodeGivenEventualEncoding(self, eventualEncoding): output = self if u'%SOUP-ENCODING%' in output: output = self.substituteEncoding(output, eventualEncoding) return u'<?' + output + u'?>' class Comment(NavigableString): def decodeGivenEventualEncoding(self, eventualEncoding): return u'<!--' + self + u'-->' class Declaration(NavigableString): def decodeGivenEventualEncoding(self, eventualEncoding): return u'<!' + self + u'>' class Tag(PageElement): """Represents a found HTML tag with its attributes and contents.""" def _invert(h): "Cheap function to invert a hash." i = {} for k,v in h.items(): i[v] = k return i XML_ENTITIES_TO_SPECIAL_CHARS = { "apos" : "'", "quot" : '"', "amp" : "&", "lt" : "<", "gt" : ">" } XML_SPECIAL_CHARS_TO_ENTITIES = _invert(XML_ENTITIES_TO_SPECIAL_CHARS) def _convertEntities(self, match): """Used in a call to re.sub to replace HTML, XML, and numeric entities with the appropriate Unicode characters. If HTML entities are being converted, any unrecognized entities are escaped.""" x = match.group(1) if self.convertHTMLEntities and x in name2codepoint: return unichr(name2codepoint[x]) elif x in self.XML_ENTITIES_TO_SPECIAL_CHARS: if self.convertXMLEntities: return self.XML_ENTITIES_TO_SPECIAL_CHARS[x] else: return u'&%s;' % x elif len(x) > 0 and x[0] == '#': # Handle numeric entities if len(x) > 1 and x[1] == 'x': return unichr(int(x[2:], 16)) else: return unichr(int(x[1:])) elif self.escapeUnrecognizedEntities: return u'&amp;%s;' % x else: return u'&%s;' % x def __init__(self, parser, name, attrs=None, parent=None, previous=None): "Basic constructor." # We don't actually store the parser object: that lets extracted # chunks be garbage-collected self.parserClass = parser.__class__ self.isSelfClosing = parser.isSelfClosingTag(name) self.name = name if attrs == None: attrs = [] self.attrs = attrs self.contents = [] self.setup(parent, previous) self.hidden = False self.containsSubstitutions = False self.convertHTMLEntities = parser.convertHTMLEntities self.convertXMLEntities = parser.convertXMLEntities self.escapeUnrecognizedEntities = parser.escapeUnrecognizedEntities def convert(kval): "Converts HTML, XML and numeric entities in the attribute value." k, val = kval if val is None: return kval return (k, re.sub("&(#\d+|#x[0-9a-fA-F]+|\w+);", self._convertEntities, val)) self.attrs = map(convert, self.attrs) def get(self, key, default=None): """Returns the value of the 'key' attribute for the tag, or the value given for 'default' if it doesn't have that attribute.""" return self._getAttrMap().get(key, default) def has_key(self, key): return self._getAttrMap().has_key(key) def __getitem__(self, key): """tag[key] returns the value of the 'key' attribute for the tag, and throws an exception if it's not there.""" return self._getAttrMap()[key] def __iter__(self): "Iterating over a tag iterates over its contents." return iter(self.contents) def __len__(self): "The length of a tag is the length of its list of contents." return len(self.contents) def __contains__(self, x): return x in self.contents def __nonzero__(self): "A tag is non-None even if it has no contents." return True def __setitem__(self, key, value): """Setting tag[key] sets the value of the 'key' attribute for the tag.""" self._getAttrMap() self.attrMap[key] = value found = False for i in range(0, len(self.attrs)): if self.attrs[i][0] == key: self.attrs[i] = (key, value) found = True if not found: self.attrs.append((key, value)) self._getAttrMap()[key] = value def __delitem__(self, key): "Deleting tag[key] deletes all 'key' attributes for the tag." for item in self.attrs: if item[0] == key: self.attrs.remove(item) #We don't break because bad HTML can define the same #attribute multiple times. self._getAttrMap() if self.attrMap.has_key(key): del self.attrMap[key] def __call__(self, *args, **kwargs): """Calling a tag like a function is the same as calling its findAll() method. Eg. tag('a') returns a list of all the A tags found within this tag.""" return apply(self.findAll, args, kwargs) def __getattr__(self, tag): #print "Getattr %s.%s" % (self.__class__, tag) if len(tag) > 3 and tag.rfind('Tag') == len(tag)-3: return self.find(tag[:-3]) elif tag.find('__') != 0: return self.find(tag) raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__, tag) def __eq__(self, other): """Returns true iff this tag has the same name, the same attributes, and the same contents (recursively) as the given tag. NOTE: right now this will return false if two tags have the same attributes in a different order. Should this be fixed?""" if not hasattr(other, 'name') or not hasattr(other, 'attrs') or not hasattr(other, 'contents') or self.name != other.name or self.attrs != other.attrs or len(self) != len(other): return False for i in range(0, len(self.contents)): if self.contents[i] != other.contents[i]: return False return True def __ne__(self, other): """Returns true iff this tag is not identical to the other tag, as defined in __eq__.""" return not self == other def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING): """Renders this tag as a string.""" return self.decode(eventualEncoding=encoding) BARE_AMPERSAND_OR_BRACKET = re.compile("([<>]|" + "&(?!#\d+;|#x[0-9a-fA-F]+;|\w+;)" + ")") def _sub_entity(self, x): """Used with a regular expression to substitute the appropriate XML entity for an XML special character.""" return "&" + self.XML_SPECIAL_CHARS_TO_ENTITIES[x.group(0)[0]] + ";" def __unicode__(self): return self.decode() def __str__(self): return self.encode() def encode(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0): return self.decode(prettyPrint, indentLevel, encoding).encode(encoding) def decode(self, prettyPrint=False, indentLevel=0, eventualEncoding=DEFAULT_OUTPUT_ENCODING): """Returns a string or Unicode representation of this tag and its contents. To get Unicode, pass None for encoding.""" attrs = [] if self.attrs: for key, val in self.attrs: fmt = '%s="%s"' if isString(val): if (self.containsSubstitutions and eventualEncoding is not None and '%SOUP-ENCODING%' in val): val = self.substituteEncoding(val, eventualEncoding) # The attribute value either: # # * Contains no embedded double quotes or single quotes. # No problem: we enclose it in double quotes. # * Contains embedded single quotes. No problem: # double quotes work here too. # * Contains embedded double quotes. No problem: # we enclose it in single quotes. # * Embeds both single _and_ double quotes. This # can't happen naturally, but it can happen if # you modify an attribute value after parsing # the document. Now we have a bit of a # problem. We solve it by enclosing the # attribute in single quotes, and escaping any # embedded single quotes to XML entities. if '"' in val: fmt = "%s='%s'" if "'" in val: # TODO: replace with apos when # appropriate. val = val.replace("'", "&squot;") # Now we're okay w/r/t quotes. But the attribute # value might also contain angle brackets, or # ampersands that aren't part of entities. We need # to escape those to XML entities too. val = self.BARE_AMPERSAND_OR_BRACKET.sub(self._sub_entity, val) if val is None: # Handle boolean attributes. decoded = key else: decoded = fmt % (key, val) attrs.append(decoded) close = '' closeTag = '' if self.isSelfClosing: close = ' /' else: closeTag = '</%s>' % self.name indentTag, indentContents = 0, 0 if prettyPrint: indentTag = indentLevel space = (' ' * (indentTag-1)) indentContents = indentTag + 1 contents = self.decodeContents(prettyPrint, indentContents, eventualEncoding) if self.hidden: s = contents else: s = [] attributeString = '' if attrs: attributeString = ' ' + ' '.join(attrs) if prettyPrint: s.append(space) s.append('<%s%s%s>' % (self.name, attributeString, close)) if prettyPrint: s.append("\n") s.append(contents) if prettyPrint and contents and contents[-1] != "\n": s.append("\n") if prettyPrint and closeTag: s.append(space) s.append(closeTag) if prettyPrint and closeTag and self.nextSibling: s.append("\n") s = ''.join(s) return s def decompose(self): """Recursively destroys the contents of this tree.""" contents = [i for i in self.contents] for i in contents: if isinstance(i, Tag): i.decompose() else: i.extract() self.extract() def prettify(self, encoding=DEFAULT_OUTPUT_ENCODING): return self.encode(encoding, True) def encodeContents(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0): return self.decodeContents(prettyPrint, indentLevel).encode(encoding) def decodeContents(self, prettyPrint=False, indentLevel=0, eventualEncoding=DEFAULT_OUTPUT_ENCODING): """Renders the contents of this tag as a string in the given encoding. If encoding is None, returns a Unicode string..""" s=[] for c in self: text = None if isinstance(c, NavigableString): text = c.decodeGivenEventualEncoding(eventualEncoding) elif isinstance(c, Tag): s.append(c.decode(prettyPrint, indentLevel, eventualEncoding)) if text and prettyPrint: text = text.strip() if text: if prettyPrint: s.append(" " * (indentLevel-1)) s.append(text) if prettyPrint: s.append("\n") return ''.join(s) #Soup methods def find(self, name=None, attrs={}, recursive=True, text=None, **kwargs): """Return only the first child of this Tag matching the given criteria.""" r = None l = self.findAll(name, attrs, recursive, text, 1, **kwargs) if l: r = l[0] return r findChild = find def findAll(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs): """Extracts a list of Tag objects that match the given criteria. You can specify the name of the Tag and any attributes you want the Tag to have. The value of a key-value pair in the 'attrs' map can be a string, a list of strings, a regular expression object, or a callable that takes a string and returns whether or not the string matches for some custom definition of 'matches'. The same is true of the tag name.""" generator = self.recursiveChildGenerator if not recursive: generator = self.childGenerator return self._findAll(name, attrs, text, limit, generator, **kwargs) findChildren = findAll # Pre-3.x compatibility methods. Will go away in 4.0. first = find fetch = findAll def fetchText(self, text=None, recursive=True, limit=None): return self.findAll(text=text, recursive=recursive, limit=limit) def firstText(self, text=None, recursive=True): return self.find(text=text, recursive=recursive) # 3.x compatibility methods. Will go away in 4.0. def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0): if encoding is None: return self.decodeContents(prettyPrint, indentLevel, encoding) else: return self.encodeContents(encoding, prettyPrint, indentLevel) #Private methods def _getAttrMap(self): """Initializes a map representation of this tag's attributes, if not already initialized.""" if not getattr(self, 'attrMap'): self.attrMap = {} for (key, value) in self.attrs: self.attrMap[key] = value return self.attrMap #Generator methods def recursiveChildGenerator(self): if not len(self.contents): raise StopIteration stopNode = self._lastRecursiveChild().next current = self.contents[0] while current is not stopNode: yield current current = current.next def childGenerator(self): if not len(self.contents): raise StopIteration current = self.contents[0] while current: yield current current = current.nextSibling raise StopIteration # Next, a couple classes to represent queries and their results. class SoupStrainer: """Encapsulates a number of ways of matching a markup element (tag or text).""" def __init__(self, name=None, attrs={}, text=None, **kwargs): self.name = name if isString(attrs): kwargs['class'] = attrs attrs = None if kwargs: if attrs: attrs = attrs.copy() attrs.update(kwargs) else: attrs = kwargs self.attrs = attrs self.text = text def __str__(self): if self.text: return self.text else: return "%s|%s" % (self.name, self.attrs) def searchTag(self, markupName=None, markupAttrs={}): found = None markup = None if isinstance(markupName, Tag): markup = markupName markupAttrs = markup callFunctionWithTagData = callable(self.name) \ and not isinstance(markupName, Tag) if (not self.name) \ or callFunctionWithTagData \ or (markup and self._matches(markup, self.name)) \ or (not markup and self._matches(markupName, self.name)): if callFunctionWithTagData: match = self.name(markupName, markupAttrs) else: match = True markupAttrMap = None for attr, matchAgainst in self.attrs.items(): if not markupAttrMap: if hasattr(markupAttrs, 'get'): markupAttrMap = markupAttrs else: markupAttrMap = {} for k,v in markupAttrs: markupAttrMap[k] = v attrValue = markupAttrMap.get(attr) if not self._matches(attrValue, matchAgainst): match = False break if match: if markup: found = markup else: found = markupName return found def search(self, markup): #print 'looking for %s in %s' % (self, markup) found = None # If given a list of items, scan it for a text element that # matches. if isList(markup) and not isinstance(markup, Tag): for element in markup: if isinstance(element, NavigableString) \ and self.search(element): found = element break # If it's a Tag, make sure its name or attributes match. # Don't bother with Tags if we're searching for text. elif isinstance(markup, Tag): if not self.text: found = self.searchTag(markup) # If it's text, make sure the text matches. elif isinstance(markup, NavigableString) or \ isString(markup): if self._matches(markup, self.text): found = markup else: raise Exception, "I don't know how to match against a %s" \ % markup.__class__ return found def _matches(self, markup, matchAgainst): #print "Matching %s against %s" % (markup, matchAgainst) result = False if matchAgainst == True and type(matchAgainst) == types.BooleanType: result = markup != None elif callable(matchAgainst): result = matchAgainst(markup) else: #Custom match methods take the tag as an argument, but all #other ways of matching match the tag name as a string. if isinstance(markup, Tag): markup = markup.name if markup is not None and not isString(markup): markup = unicode(markup) #Now we know that chunk is either a string, or None. if hasattr(matchAgainst, 'match'): # It's a regexp object. result = markup and matchAgainst.search(markup) elif (isList(matchAgainst) and (markup is not None or not isString(matchAgainst))): result = markup in matchAgainst elif hasattr(matchAgainst, 'items'): result = markup.has_key(matchAgainst) elif matchAgainst and isString(markup): if isinstance(markup, unicode): matchAgainst = unicode(matchAgainst) else: matchAgainst = str(matchAgainst) if not result: result = matchAgainst == markup return result class ResultSet(list): """A ResultSet is just a list that keeps track of the SoupStrainer that created it.""" def __init__(self, source): list.__init__([]) self.source = source # Now, some helper functions. def isList(l): """Convenience method that works with all 2.x versions of Python to determine whether or not something is listlike.""" return ((hasattr(l, '__iter__') and not isString(l)) or (type(l) in (types.ListType, types.TupleType))) def isString(s): """Convenience method that works with all 2.x versions of Python to determine whether or not something is stringlike.""" try: return isinstance(s, unicode) or isinstance(s, basestring) except NameError: return isinstance(s, str) def buildTagMap(default, *args): """Turns a list of maps, lists, or scalars into a single map. Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and NESTING_RESET_TAGS maps out of lists and partial maps.""" built = {} for portion in args: if hasattr(portion, 'items'): #It's a map. Merge it. for k,v in portion.items(): built[k] = v elif isList(portion) and not isString(portion): #It's a list. Map each item to the default. for k in portion: built[k] = default else: #It's a scalar. Map it to the default. built[portion] = default return built # Now, the parser classes. class HTMLParserBuilder(HTMLParser): def __init__(self, soup): HTMLParser.__init__(self) self.soup = soup # We inherit feed() and reset(). def handle_starttag(self, name, attrs): if name == 'meta': self.soup.extractCharsetFromMeta(attrs) else: self.soup.unknown_starttag(name, attrs) def handle_endtag(self, name): self.soup.unknown_endtag(name) def handle_data(self, content): self.soup.handle_data(content) def _toStringSubclass(self, text, subclass): """Adds a certain piece of text to the tree as a NavigableString subclass.""" self.soup.endData() self.handle_data(text) self.soup.endData(subclass) def handle_pi(self, text): """Handle a processing instruction as a ProcessingInstruction object, possibly one with a %SOUP-ENCODING% slot into which an encoding will be plugged later.""" if text[:3] == "xml": text = u"xml version='1.0' encoding='%SOUP-ENCODING%'" self._toStringSubclass(text, ProcessingInstruction) def handle_comment(self, text): "Handle comments as Comment objects." self._toStringSubclass(text, Comment) def handle_charref(self, ref): "Handle character references as data." if self.soup.convertEntities: data = unichr(int(ref)) else: data = '&#%s;' % ref self.handle_data(data) def handle_entityref(self, ref): """Handle entity references as data, possibly converting known HTML and/or XML entity references to the corresponding Unicode characters.""" data = None if self.soup.convertHTMLEntities: try: data = unichr(name2codepoint[ref]) except KeyError: pass if not data and self.soup.convertXMLEntities: data = self.soup.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref) if not data and self.soup.convertHTMLEntities and \ not self.soup.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref): # TODO: We've got a problem here. We're told this is # an entity reference, but it's not an XML entity # reference or an HTML entity reference. Nonetheless, # the logical thing to do is to pass it through as an # unrecognized entity reference. # # Except: when the input is "&carol;" this function # will be called with input "carol". When the input is # "AT&T", this function will be called with input # "T". We have no way of knowing whether a semicolon # was present originally, so we don't know whether # this is an unknown entity or just a misplaced # ampersand. # # The more common case is a misplaced ampersand, so I # escape the ampersand and omit the trailing semicolon. data = "&amp;%s" % ref if not data: # This case is different from the one above, because we # haven't already gone through a supposedly comprehensive # mapping of entities to Unicode characters. We might not # have gone through any mapping at all. So the chances are # very high that this is a real entity, and not a # misplaced ampersand. data = "&%s;" % ref self.handle_data(data) def handle_decl(self, data): "Handle DOCTYPEs and the like as Declaration objects." self._toStringSubclass(data, Declaration) def parse_declaration(self, i): """Treat a bogus SGML declaration as raw data. Treat a CDATA declaration as a CData object.""" j = None if self.rawdata[i:i+9] == '<![CDATA[': k = self.rawdata.find(']]>', i) if k == -1: k = len(self.rawdata) data = self.rawdata[i+9:k] j = k+3 self._toStringSubclass(data, CData) else: try: j = HTMLParser.parse_declaration(self, i) except HTMLParseError: toHandle = self.rawdata[i:] self.handle_data(toHandle) j = i + len(toHandle) return j class BeautifulStoneSoup(Tag): """This class contains the basic parser and search code. It defines a parser that knows nothing about tag behavior except for the following: You can't close a tag without closing all the tags it encloses. That is, "<foo><bar></foo>" actually means "<foo><bar></bar></foo>". [Another possible explanation is "<foo><bar /></foo>", but since this class defines no SELF_CLOSING_TAGS, it will never use that explanation.] This class is useful for parsing XML or made-up markup languages, or when BeautifulSoup makes an assumption counter to what you were expecting.""" SELF_CLOSING_TAGS = {} NESTABLE_TAGS = {} RESET_NESTING_TAGS = {} QUOTE_TAGS = {} PRESERVE_WHITESPACE_TAGS = [] MARKUP_MASSAGE = [(re.compile('(<[^<>]*)/>'), lambda x: x.group(1) + ' />'), (re.compile('<!\s+([^<>]*)>'), lambda x: '<!' + x.group(1) + '>') ] ROOT_TAG_NAME = u'[document]' HTML_ENTITIES = "html" XML_ENTITIES = "xml" XHTML_ENTITIES = "xhtml" # TODO: This only exists for backwards-compatibility ALL_ENTITIES = XHTML_ENTITIES # Used when determining whether a text node is all whitespace and # can be replaced with a single space. A text node that contains # fancy Unicode spaces (usually non-breaking) should be left # alone. STRIP_ASCII_SPACES = { 9: None, 10: None, 12: None, 13: None, 32: None, } def __init__(self, markup="", parseOnlyThese=None, fromEncoding=None, markupMassage=True, smartQuotesTo=XML_ENTITIES, convertEntities=None, selfClosingTags=None, isHTML=False, builder=HTMLParserBuilder): """The Soup object is initialized as the 'root tag', and the provided markup (which can be a string or a file-like object) is fed into the underlying parser. HTMLParser will process most bad HTML, and the BeautifulSoup class has some tricks for dealing with some HTML that kills HTMLParser, but Beautiful Soup can nonetheless choke or lose data if your data uses self-closing tags or declarations incorrectly. By default, Beautiful Soup uses regexes to sanitize input, avoiding the vast majority of these problems. If the problems don't apply to you, pass in False for markupMassage, and you'll get better performance. The default parser massage techniques fix the two most common instances of invalid HTML that choke HTMLParser: <br/> (No space between name of closing tag and tag close) <! --Comment--> (Extraneous whitespace in declaration) You can pass in a custom list of (RE object, replace method) tuples to get Beautiful Soup to scrub your input the way you want.""" self.parseOnlyThese = parseOnlyThese self.fromEncoding = fromEncoding self.smartQuotesTo = smartQuotesTo self.convertEntities = convertEntities # Set the rules for how we'll deal with the entities we # encounter if self.convertEntities: # It doesn't make sense to convert encoded characters to # entities even while you're converting entities to Unicode. # Just convert it all to Unicode. self.smartQuotesTo = None if convertEntities == self.HTML_ENTITIES: self.convertXMLEntities = False self.convertHTMLEntities = True self.escapeUnrecognizedEntities = True elif convertEntities == self.XHTML_ENTITIES: self.convertXMLEntities = True self.convertHTMLEntities = True self.escapeUnrecognizedEntities = False elif convertEntities == self.XML_ENTITIES: self.convertXMLEntities = True self.convertHTMLEntities = False self.escapeUnrecognizedEntities = False else: self.convertXMLEntities = False self.convertHTMLEntities = False self.escapeUnrecognizedEntities = False self.instanceSelfClosingTags = buildTagMap(None, selfClosingTags) self.builder = builder(self) self.reset() if hasattr(markup, 'read'): # It's a file-type object. markup = markup.read() self.markup = markup self.markupMassage = markupMassage try: self._feed(isHTML=isHTML) except StopParsing: pass self.markup = None # The markup can now be GCed. self.builder = None # So can the builder. def _feed(self, inDocumentEncoding=None, isHTML=False): # Convert the document to Unicode. markup = self.markup if isinstance(markup, unicode): if not hasattr(self, 'originalEncoding'): self.originalEncoding = None else: dammit = UnicodeDammit\ (markup, [self.fromEncoding, inDocumentEncoding], smartQuotesTo=self.smartQuotesTo, isHTML=isHTML) markup = dammit.unicode self.originalEncoding = dammit.originalEncoding self.declaredHTMLEncoding = dammit.declaredHTMLEncoding if markup: if self.markupMassage: if not isList(self.markupMassage): self.markupMassage = self.MARKUP_MASSAGE for fix, m in self.markupMassage: markup = fix.sub(m, markup) # TODO: We get rid of markupMassage so that the # soup object can be deepcopied later on. Some # Python installations can't copy regexes. If anyone # was relying on the existence of markupMassage, this # might cause problems. del(self.markupMassage) self.builder.reset() self.builder.feed(markup) # Close out any unfinished strings and close all the open tags. self.endData() while self.currentTag.name != self.ROOT_TAG_NAME: self.popTag() def isSelfClosingTag(self, name): """Returns true iff the given string is the name of a self-closing tag according to this parser.""" return self.SELF_CLOSING_TAGS.has_key(name) \ or self.instanceSelfClosingTags.has_key(name) def reset(self): Tag.__init__(self, self, self.ROOT_TAG_NAME) self.hidden = 1 self.builder.reset() self.currentData = [] self.currentTag = None self.tagStack = [] self.quoteStack = [] self.pushTag(self) def popTag(self): tag = self.tagStack.pop() # Tags with just one string-owning child get the child as a # 'string' property, so that soup.tag.string is shorthand for # soup.tag.contents[0] if len(self.currentTag.contents) == 1 and \ isinstance(self.currentTag.contents[0], NavigableString): self.currentTag.string = self.currentTag.contents[0] #print "Pop", tag.name if self.tagStack: self.currentTag = self.tagStack[-1] return self.currentTag def pushTag(self, tag): #print "Push", tag.name if self.currentTag: self.currentTag.contents.append(tag) self.tagStack.append(tag) self.currentTag = self.tagStack[-1] def endData(self, containerClass=NavigableString): if self.currentData: currentData = u''.join(self.currentData) if (currentData.translate(self.STRIP_ASCII_SPACES) == '' and not set([tag.name for tag in self.tagStack]).intersection( self.PRESERVE_WHITESPACE_TAGS)): if '\n' in currentData: currentData = '\n' else: currentData = ' ' self.currentData = [] if self.parseOnlyThese and len(self.tagStack) <= 1 and \ (not self.parseOnlyThese.text or \ not self.parseOnlyThese.search(currentData)): return o = containerClass(currentData) o.setup(self.currentTag, self.previous) if self.previous: self.previous.next = o self.previous = o self.currentTag.contents.append(o) def _popToTag(self, name, inclusivePop=True): """Pops the tag stack up to and including the most recent instance of the given tag. If inclusivePop is false, pops the tag stack up to but *not* including the most recent instqance of the given tag.""" #print "Popping to %s" % name if name == self.ROOT_TAG_NAME: return numPops = 0 mostRecentTag = None for i in range(len(self.tagStack)-1, 0, -1): if name == self.tagStack[i].name: numPops = len(self.tagStack)-i break if not inclusivePop: numPops = numPops - 1 for i in range(0, numPops): mostRecentTag = self.popTag() return mostRecentTag def _smartPop(self, name): """We need to pop up to the previous tag of this type, unless one of this tag's nesting reset triggers comes between this tag and the previous tag of this type, OR unless this tag is a generic nesting trigger and another generic nesting trigger comes between this tag and the previous tag of this type. Examples: <p>Foo<b>Bar *<p>* should pop to 'p', not 'b'. <p>Foo<table>Bar *<p>* should pop to 'table', not 'p'. <p>Foo<table><tr>Bar *<p>* should pop to 'tr', not 'p'. <li><ul><li> *<li>* should pop to 'ul', not the first 'li'. <tr><table><tr> *<tr>* should pop to 'table', not the first 'tr' <td><tr><td> *<td>* should pop to 'tr', not the first 'td' """ nestingResetTriggers = self.NESTABLE_TAGS.get(name) isNestable = nestingResetTriggers != None isResetNesting = self.RESET_NESTING_TAGS.has_key(name) popTo = None inclusive = True for i in range(len(self.tagStack)-1, 0, -1): p = self.tagStack[i] if (not p or p.name == name) and not isNestable: #Non-nestable tags get popped to the top or to their #last occurance. popTo = name break if (nestingResetTriggers != None and p.name in nestingResetTriggers) \ or (nestingResetTriggers == None and isResetNesting and self.RESET_NESTING_TAGS.has_key(p.name)): #If we encounter one of the nesting reset triggers #peculiar to this tag, or we encounter another tag #that causes nesting to reset, pop up to but not #including that tag. popTo = p.name inclusive = False break p = p.parent if popTo: self._popToTag(popTo, inclusive) def unknown_starttag(self, name, attrs, selfClosing=0): #print "Start tag %s: %s" % (name, attrs) if self.quoteStack: #This is not a real tag. #print "<%s> is not real!" % name attrs = ''.join(map(lambda(x, y): ' %s="%s"' % (x, y), attrs)) self.handle_data('<%s%s>' % (name, attrs)) return self.endData() if not self.isSelfClosingTag(name) and not selfClosing: self._smartPop(name) if self.parseOnlyThese and len(self.tagStack) <= 1 \ and (self.parseOnlyThese.text or not self.parseOnlyThese.searchTag(name, attrs)): return tag = Tag(self, name, attrs, self.currentTag, self.previous) if self.previous: self.previous.next = tag self.previous = tag self.pushTag(tag) if selfClosing or self.isSelfClosingTag(name): self.popTag() if name in self.QUOTE_TAGS: #print "Beginning quote (%s)" % name self.quoteStack.append(name) self.literal = 1 return tag def unknown_endtag(self, name): #print "End tag %s" % name if self.quoteStack and self.quoteStack[-1] != name: #This is not a real end tag. #print "</%s> is not real!" % name self.handle_data('</%s>' % name) return self.endData() self._popToTag(name) if self.quoteStack and self.quoteStack[-1] == name: self.quoteStack.pop() self.literal = (len(self.quoteStack) > 0) def handle_data(self, data): self.currentData.append(data) def extractCharsetFromMeta(self, attrs): self.unknown_starttag('meta', attrs) class BeautifulSoup(BeautifulStoneSoup): """This parser knows the following facts about HTML: * Some tags have no closing tag and should be interpreted as being closed as soon as they are encountered. * The text inside some tags (ie. 'script') may contain tags which are not really part of the document and which should be parsed as text, not tags. If you want to parse the text as tags, you can always fetch it and parse it explicitly. * Tag nesting rules: Most tags can't be nested at all. For instance, the occurance of a <p> tag should implicitly close the previous <p> tag. <p>Para1<p>Para2 should be transformed into: <p>Para1</p><p>Para2 Some tags can be nested arbitrarily. For instance, the occurance of a <blockquote> tag should _not_ implicitly close the previous <blockquote> tag. Alice said: <blockquote>Bob said: <blockquote>Blah should NOT be transformed into: Alice said: <blockquote>Bob said: </blockquote><blockquote>Blah Some tags can be nested, but the nesting is reset by the interposition of other tags. For instance, a <tr> tag should implicitly close the previous <tr> tag within the same <table>, but not close a <tr> tag in another table. <table><tr>Blah<tr>Blah should be transformed into: <table><tr>Blah</tr><tr>Blah but, <tr>Blah<table><tr>Blah should NOT be transformed into <tr>Blah<table></tr><tr>Blah Differing assumptions about tag nesting rules are a major source of problems with the BeautifulSoup class. If BeautifulSoup is not treating as nestable a tag your page author treats as nestable, try ICantBelieveItsBeautifulSoup, MinimalSoup, or BeautifulStoneSoup before writing your own subclass.""" def __init__(self, *args, **kwargs): if not kwargs.has_key('smartQuotesTo'): kwargs['smartQuotesTo'] = self.HTML_ENTITIES kwargs['isHTML'] = True BeautifulStoneSoup.__init__(self, *args, **kwargs) SELF_CLOSING_TAGS = buildTagMap(None, ['br' , 'hr', 'input', 'img', 'meta', 'spacer', 'link', 'frame', 'base']) PRESERVE_WHITESPACE_TAGS = set(['pre', 'textarea']) QUOTE_TAGS = {'script' : None, 'textarea' : None} #According to the HTML standard, each of these inline tags can #contain another tag of the same type. Furthermore, it's common #to actually use these tags this way. NESTABLE_INLINE_TAGS = ['span', 'font', 'q', 'object', 'bdo', 'sub', 'sup', 'center'] #According to the HTML standard, these block tags can contain #another tag of the same type. Furthermore, it's common #to actually use these tags this way. NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del'] #Lists can contain other lists, but there are restrictions. NESTABLE_LIST_TAGS = { 'ol' : [], 'ul' : [], 'li' : ['ul', 'ol'], 'dl' : [], 'dd' : ['dl'], 'dt' : ['dl'] } #Tables can contain other tables, but there are restrictions. NESTABLE_TABLE_TAGS = {'table' : [], 'tr' : ['table', 'tbody', 'tfoot', 'thead'], 'td' : ['tr'], 'th' : ['tr'], 'thead' : ['table'], 'tbody' : ['table'], 'tfoot' : ['table'], } NON_NESTABLE_BLOCK_TAGS = ['address', 'form', 'p', 'pre'] #If one of these tags is encountered, all tags up to the next tag of #this type are popped. RESET_NESTING_TAGS = buildTagMap(None, NESTABLE_BLOCK_TAGS, 'noscript', NON_NESTABLE_BLOCK_TAGS, NESTABLE_LIST_TAGS, NESTABLE_TABLE_TAGS) NESTABLE_TAGS = buildTagMap([], NESTABLE_INLINE_TAGS, NESTABLE_BLOCK_TAGS, NESTABLE_LIST_TAGS, NESTABLE_TABLE_TAGS) # Used to detect the charset in a META tag; see start_meta CHARSET_RE = re.compile("((^|;)\s*charset=)([^;]*)", re.M) def extractCharsetFromMeta(self, attrs): """Beautiful Soup can detect a charset included in a META tag, try to convert the document to that charset, and re-parse the document from the beginning.""" httpEquiv = None contentType = None contentTypeIndex = None tagNeedsEncodingSubstitution = False for i in range(0, len(attrs)): key, value = attrs[i] key = key.lower() if key == 'http-equiv': httpEquiv = value elif key == 'content': contentType = value contentTypeIndex = i if httpEquiv and contentType: # It's an interesting meta tag. match = self.CHARSET_RE.search(contentType) if match: if (self.declaredHTMLEncoding is not None or self.originalEncoding == self.fromEncoding): # An HTML encoding was sniffed while converting # the document to Unicode, or an HTML encoding was # sniffed during a previous pass through the # document, or an encoding was specified # explicitly and it worked. Rewrite the meta tag. def rewrite(match): return match.group(1) + "%SOUP-ENCODING%" newAttr = self.CHARSET_RE.sub(rewrite, contentType) attrs[contentTypeIndex] = (attrs[contentTypeIndex][0], newAttr) tagNeedsEncodingSubstitution = True else: # This is our first pass through the document. # Go through it again with the encoding information. newCharset = match.group(3) if newCharset and newCharset != self.originalEncoding: self.declaredHTMLEncoding = newCharset self._feed(self.declaredHTMLEncoding) raise StopParsing pass tag = self.unknown_starttag("meta", attrs) if tag and tagNeedsEncodingSubstitution: tag.containsSubstitutions = True class StopParsing(Exception): pass class ICantBelieveItsBeautifulSoup(BeautifulSoup): """The BeautifulSoup class is oriented towards skipping over common HTML errors like unclosed tags. However, sometimes it makes errors of its own. For instance, consider this fragment: <b>Foo<b>Bar</b></b> This is perfectly valid (if bizarre) HTML. However, the BeautifulSoup class will implicitly close the first b tag when it encounters the second 'b'. It will think the author wrote "<b>Foo<b>Bar", and didn't close the first 'b' tag, because there's no real-world reason to bold something that's already bold. When it encounters '</b></b>' it will close two more 'b' tags, for a grand total of three tags closed instead of two. This can throw off the rest of your document structure. The same is true of a number of other tags, listed below. It's much more common for someone to forget to close a 'b' tag than to actually use nested 'b' tags, and the BeautifulSoup class handles the common case. This class handles the not-co-common case: where you can't believe someone wrote what they did, but it's valid HTML and BeautifulSoup screwed up by assuming it wouldn't be.""" I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS = \ ['em', 'big', 'i', 'small', 'tt', 'abbr', 'acronym', 'strong', 'cite', 'code', 'dfn', 'kbd', 'samp', 'strong', 'var', 'b', 'big'] I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS = ['noscript'] NESTABLE_TAGS = buildTagMap([], BeautifulSoup.NESTABLE_TAGS, I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS, I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS) class MinimalSoup(BeautifulSoup): """The MinimalSoup class is for parsing HTML that contains pathologically bad markup. It makes no assumptions about tag nesting, but it does know which tags are self-closing, that <script> tags contain Javascript and should not be parsed, that META tags may contain encoding information, and so on. This also makes it better for subclassing than BeautifulStoneSoup or BeautifulSoup.""" RESET_NESTING_TAGS = buildTagMap('noscript') NESTABLE_TAGS = {} class BeautifulSOAP(BeautifulStoneSoup): """This class will push a tag with only a single string child into the tag's parent as an attribute. The attribute's name is the tag name, and the value is the string child. An example should give the flavor of the change: <foo><bar>baz</bar></foo> => <foo bar="baz"><bar>baz</bar></foo> You can then access fooTag['bar'] instead of fooTag.barTag.string. This is, of course, useful for scraping structures that tend to use subelements instead of attributes, such as SOAP messages. Note that it modifies its input, so don't print the modified version out. I'm not sure how many people really want to use this class; let me know if you do. Mainly I like the name.""" def popTag(self): if len(self.tagStack) > 1: tag = self.tagStack[-1] parent = self.tagStack[-2] parent._getAttrMap() if (isinstance(tag, Tag) and len(tag.contents) == 1 and isinstance(tag.contents[0], NavigableString) and not parent.attrMap.has_key(tag.name)): parent[tag.name] = tag.contents[0] BeautifulStoneSoup.popTag(self) #Enterprise class names! It has come to our attention that some people #think the names of the Beautiful Soup parser classes are too silly #and "unprofessional" for use in enterprise screen-scraping. We feel #your pain! For such-minded folk, the Beautiful Soup Consortium And #All-Night Kosher Bakery recommends renaming this file to #"RobustParser.py" (or, in cases of extreme enterprisiness, #"RobustParserBeanInterface.class") and using the following #enterprise-friendly class aliases: class RobustXMLParser(BeautifulStoneSoup): pass class RobustHTMLParser(BeautifulSoup): pass class RobustWackAssHTMLParser(ICantBelieveItsBeautifulSoup): pass class RobustInsanelyWackAssHTMLParser(MinimalSoup): pass class SimplifyingSOAPParser(BeautifulSOAP): pass ###################################################### # # Bonus library: Unicode, Dammit # # This class forces XML data into a standard format (usually to UTF-8 # or Unicode). It is heavily based on code from Mark Pilgrim's # Universal Feed Parser. It does not rewrite the XML or HTML to # reflect a new encoding: that happens in BeautifulStoneSoup.handle_pi # (XML) and BeautifulSoup.start_meta (HTML). # Autodetects character encodings. # Download from http://chardet.feedparser.org/ try: import chardet # import chardet.constants # chardet.constants._debug = 1 except ImportError: chardet = None # cjkcodecs and iconv_codec make Python know about more character encodings. # Both are available from http://cjkpython.i18n.org/ # They're built in if you use Python 2.4. try: import cjkcodecs.aliases except ImportError: pass try: import iconv_codec except ImportError: pass class UnicodeDammit: """A class for detecting the encoding of a *ML document and converting it to a Unicode string. If the source encoding is windows-1252, can replace MS smart quotes with their HTML or XML equivalents.""" # This dictionary maps commonly seen values for "charset" in HTML # meta tags to the corresponding Python codec names. It only covers # values that aren't in Python's aliases and can't be determined # by the heuristics in find_codec. CHARSET_ALIASES = { "macintosh" : "mac-roman", "x-sjis" : "shift-jis" } def __init__(self, markup, overrideEncodings=[], smartQuotesTo='xml', isHTML=False): self.declaredHTMLEncoding = None self.markup, documentEncoding, sniffedEncoding = \ self._detectEncoding(markup, isHTML) self.smartQuotesTo = smartQuotesTo self.triedEncodings = [] if markup == '' or isinstance(markup, unicode): self.originalEncoding = None self.unicode = unicode(markup) return u = None for proposedEncoding in overrideEncodings: u = self._convertFrom(proposedEncoding) if u: break if not u: for proposedEncoding in (documentEncoding, sniffedEncoding): u = self._convertFrom(proposedEncoding) if u: break # If no luck and we have auto-detection library, try that: if not u and chardet and not isinstance(self.markup, unicode): u = self._convertFrom(chardet.detect(self.markup)['encoding']) # As a last resort, try utf-8 and windows-1252: if not u: for proposed_encoding in ("utf-8", "windows-1252"): u = self._convertFrom(proposed_encoding) if u: break self.unicode = u if not u: self.originalEncoding = None def _subMSChar(self, match): """Changes a MS smart quote character to an XML or HTML entity.""" orig = match.group(1) sub = self.MS_CHARS.get(orig) if type(sub) == types.TupleType: if self.smartQuotesTo == 'xml': sub = '&#x'.encode() + sub[1].encode() + ';'.encode() else: sub = '&'.encode() + sub[0].encode() + ';'.encode() else: sub = sub.encode() return sub def _convertFrom(self, proposed): proposed = self.find_codec(proposed) if not proposed or proposed in self.triedEncodings: return None self.triedEncodings.append(proposed) markup = self.markup # Convert smart quotes to HTML if coming from an encoding # that might have them. if self.smartQuotesTo and proposed.lower() in("windows-1252", "iso-8859-1", "iso-8859-2"): smart_quotes_re = "([\x80-\x9f])" smart_quotes_compiled = re.compile(smart_quotes_re) markup = smart_quotes_compiled.sub(self._subMSChar, markup) try: # print "Trying to convert document to %s" % proposed u = self._toUnicode(markup, proposed) self.markup = u self.originalEncoding = proposed except Exception, e: # print "That didn't work!" # print e return None #print "Correct encoding: %s" % proposed return self.markup def _toUnicode(self, data, encoding): '''Given a string and its encoding, decodes the string into Unicode. %encoding is a string recognized by encodings.aliases''' # strip Byte Order Mark (if present) if (len(data) >= 4) and (data[:2] == '\xfe\xff') \ and (data[2:4] != '\x00\x00'): encoding = 'utf-16be' data = data[2:] elif (len(data) >= 4) and (data[:2] == '\xff\xfe') \ and (data[2:4] != '\x00\x00'): encoding = 'utf-16le' data = data[2:] elif data[:3] == '\xef\xbb\xbf': encoding = 'utf-8' data = data[3:] elif data[:4] == '\x00\x00\xfe\xff': encoding = 'utf-32be' data = data[4:] elif data[:4] == '\xff\xfe\x00\x00': encoding = 'utf-32le' data = data[4:] newdata = unicode(data, encoding) return newdata def _detectEncoding(self, xml_data, isHTML=False): """Given a document, tries to detect its XML encoding.""" xml_encoding = sniffed_xml_encoding = None try: if xml_data[:4] == '\x4c\x6f\xa7\x94': # EBCDIC xml_data = self._ebcdic_to_ascii(xml_data) elif xml_data[:4] == '\x00\x3c\x00\x3f': # UTF-16BE sniffed_xml_encoding = 'utf-16be' xml_data = unicode(xml_data, 'utf-16be').encode('utf-8') elif (len(xml_data) >= 4) and (xml_data[:2] == '\xfe\xff') \ and (xml_data[2:4] != '\x00\x00'): # UTF-16BE with BOM sniffed_xml_encoding = 'utf-16be' xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8') elif xml_data[:4] == '\x3c\x00\x3f\x00': # UTF-16LE sniffed_xml_encoding = 'utf-16le' xml_data = unicode(xml_data, 'utf-16le').encode('utf-8') elif (len(xml_data) >= 4) and (xml_data[:2] == '\xff\xfe') and \ (xml_data[2:4] != '\x00\x00'): # UTF-16LE with BOM sniffed_xml_encoding = 'utf-16le' xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8') elif xml_data[:4] == '\x00\x00\x00\x3c': # UTF-32BE sniffed_xml_encoding = 'utf-32be' xml_data = unicode(xml_data, 'utf-32be').encode('utf-8') elif xml_data[:4] == '\x3c\x00\x00\x00': # UTF-32LE sniffed_xml_encoding = 'utf-32le' xml_data = unicode(xml_data, 'utf-32le').encode('utf-8') elif xml_data[:4] == '\x00\x00\xfe\xff': # UTF-32BE with BOM sniffed_xml_encoding = 'utf-32be' xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8') elif xml_data[:4] == '\xff\xfe\x00\x00': # UTF-32LE with BOM sniffed_xml_encoding = 'utf-32le' xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8') elif xml_data[:3] == '\xef\xbb\xbf': # UTF-8 with BOM sniffed_xml_encoding = 'utf-8' xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8') else: sniffed_xml_encoding = 'ascii' pass except: xml_encoding_match = None xml_encoding_re = '^<\?.*encoding=[\'"](.*?)[\'"].*\?>'.encode() xml_encoding_match = re.compile(xml_encoding_re).match(xml_data) if not xml_encoding_match and isHTML: meta_re = '<\s*meta[^>]+charset=([^>]*?)[;\'">]'.encode() regexp = re.compile(meta_re, re.I) xml_encoding_match = regexp.search(xml_data) if xml_encoding_match is not None: xml_encoding = xml_encoding_match.groups()[0].decode( 'ascii').lower() if isHTML: self.declaredHTMLEncoding = xml_encoding if sniffed_xml_encoding and \ (xml_encoding in ('iso-10646-ucs-2', 'ucs-2', 'csunicode', 'iso-10646-ucs-4', 'ucs-4', 'csucs4', 'utf-16', 'utf-32', 'utf_16', 'utf_32', 'utf16', 'u16')): xml_encoding = sniffed_xml_encoding return xml_data, xml_encoding, sniffed_xml_encoding def find_codec(self, charset): return self._codec(self.CHARSET_ALIASES.get(charset, charset)) \ or (charset and self._codec(charset.replace("-", ""))) \ or (charset and self._codec(charset.replace("-", "_"))) \ or charset def _codec(self, charset): if not charset: return charset codec = None try: codecs.lookup(charset) codec = charset except (LookupError, ValueError): pass return codec EBCDIC_TO_ASCII_MAP = None def _ebcdic_to_ascii(self, s): c = self.__class__ if not c.EBCDIC_TO_ASCII_MAP: emap = (0,1,2,3,156,9,134,127,151,141,142,11,12,13,14,15, 16,17,18,19,157,133,8,135,24,25,146,143,28,29,30,31, 128,129,130,131,132,10,23,27,136,137,138,139,140,5,6,7, 144,145,22,147,148,149,150,4,152,153,154,155,20,21,158,26, 32,160,161,162,163,164,165,166,167,168,91,46,60,40,43,33, 38,169,170,171,172,173,174,175,176,177,93,36,42,41,59,94, 45,47,178,179,180,181,182,183,184,185,124,44,37,95,62,63, 186,187,188,189,190,191,192,193,194,96,58,35,64,39,61,34, 195,97,98,99,100,101,102,103,104,105,196,197,198,199,200, 201,202,106,107,108,109,110,111,112,113,114,203,204,205, 206,207,208,209,126,115,116,117,118,119,120,121,122,210, 211,212,213,214,215,216,217,218,219,220,221,222,223,224, 225,226,227,228,229,230,231,123,65,66,67,68,69,70,71,72, 73,232,233,234,235,236,237,125,74,75,76,77,78,79,80,81, 82,238,239,240,241,242,243,92,159,83,84,85,86,87,88,89, 90,244,245,246,247,248,249,48,49,50,51,52,53,54,55,56,57, 250,251,252,253,254,255) import string c.EBCDIC_TO_ASCII_MAP = string.maketrans( \ ''.join(map(chr, range(256))), ''.join(map(chr, emap))) return s.translate(c.EBCDIC_TO_ASCII_MAP) MS_CHARS = { '\x80' : ('euro', '20AC'), '\x81' : ' ', '\x82' : ('sbquo', '201A'), '\x83' : ('fnof', '192'), '\x84' : ('bdquo', '201E'), '\x85' : ('hellip', '2026'), '\x86' : ('dagger', '2020'), '\x87' : ('Dagger', '2021'), '\x88' : ('circ', '2C6'), '\x89' : ('permil', '2030'), '\x8A' : ('Scaron', '160'), '\x8B' : ('lsaquo', '2039'), '\x8C' : ('OElig', '152'), '\x8D' : '?', '\x8E' : ('#x17D', '17D'), '\x8F' : '?', '\x90' : '?', '\x91' : ('lsquo', '2018'), '\x92' : ('rsquo', '2019'), '\x93' : ('ldquo', '201C'), '\x94' : ('rdquo', '201D'), '\x95' : ('bull', '2022'), '\x96' : ('ndash', '2013'), '\x97' : ('mdash', '2014'), '\x98' : ('tilde', '2DC'), '\x99' : ('trade', '2122'), '\x9a' : ('scaron', '161'), '\x9b' : ('rsaquo', '203A'), '\x9c' : ('oelig', '153'), '\x9d' : '?', '\x9e' : ('#x17E', '17E'), '\x9f' : ('Yuml', ''),} ####################################################################### #By default, act as an HTML pretty-printer. if __name__ == '__main__': import sys soup = BeautifulSoup(sys.stdin) print soup.prettify()
Python
# coding: utf-8 from django.db import connection, models from django.db.models.signals import post_delete, post_save qn = connection.ops.quote_name class PositionField(models.IntegerField): """A model field to manage the position of an item within a collection. By default all instances of a model are treated as one collection; if the ``unique_for_field`` argument is used, each value of the specified field is treated as a distinct collection. ``PositionField`` values work like list indices, including the handling of negative values. A value of ``-2`` will be cause the position to be set to the second to last position in the collection. The implementation differs from standard list indices in that values that are too large or too small are converted to the maximum or minimum allowed value respectively. When the value of a ``PositionField`` in a model instance is modified, the positions of other instances in the same collection are automatically updated to reflect the change. Assigning a value of ``None`` to a ``PositionField`` will cause the instance to be moved to the end of the collection (or appended to the collection, in the case of a new instance). """ def __init__(self, verbose_name=None, name=None, unique_for_field=None, *args, **kwargs): # blank values are used to move an instance to the last position kwargs.setdefault('blank', True) # unique constraints break the ability to execute a single query to # increment or decrement a set of positions; they also require the use # of temporary placeholder positions which result in undesirable # additional queries unique = kwargs.get('unique', False) if unique: raise TypeError( '%s cannot have a unique constraint' % self.__class__.__name__ ) # TODO: raise exception if position field appears in unique_together super(PositionField, self).__init__(verbose_name, name, *args, **kwargs) self.unique_for_field = unique_for_field def contribute_to_class(self, cls, name): super(PositionField, self).contribute_to_class(cls, name) # use this object as the descriptor for field access setattr(cls, self.name, self) # adjust related positions in response to a delete or save post_delete.connect(self._on_delete, sender=cls) post_save.connect(self._on_save, sender=cls) def get_internal_type(self): # all values will be positive after pre_save return 'PositiveIntegerField' def pre_save(self, model_instance, add): current, updated = self._get_instance_cache(model_instance) # existing instance, position not modified; no cleanup required if current is not None and updated is None: self._reset_instance_cache(model_instance, current) return current count = self._get_instance_peers(model_instance).count() if current is None: max_position = count else: max_position = count - 1 min_position = 0 # new instance; appended; no cleanup required if current is None and (updated == -1 or updated >= max_position): self._reset_instance_cache(model_instance, max_position) return max_position if max_position >= updated >= min_position: # positive position; valid index position = updated elif updated > max_position: # positive position; invalid index position = max_position elif abs(updated) <= (max_position + 1): # negative position; valid index # add 1 to max_position to make this behave like a negative list # index. -1 means the last position, not the last position minus 1 position = max_position + 1 + updated else: # negative position; invalid index position = min_position # instance inserted; cleanup required on post_save self._set_instance_cache(model_instance, position) return position def __get__(self, instance, owner): if instance is None: raise AttributeError('%s must be accessed via instance' % self.name) current, updated = self._get_instance_cache(instance) if updated is None: return current return updated def __set__(self, instance, value): if instance is None: raise AttributeError('%s must be accessed via instance' % self.name) self._set_instance_cache(instance, value) def _get_instance_cache(self, instance): try: current, updated = getattr(instance, self.get_cache_name()) except (AttributeError, TypeError): current, updated = None, None return current, updated def _reset_instance_cache(self, instance, value): try: delattr(instance, self.get_cache_name()) except AttributeError: pass setattr(instance, self.get_cache_name(), (value, None)) def _set_instance_cache(self, instance, value): # TODO: Find a more robust way to determine if instance exists in # the db; this is necessary because the position field won't be # initialized to None when models.Manager.create is called with an # explicit position. # FIXME: This breaks pre-newforms-admin when setting a position gt the # maximum possible position -- something about how models are # instantiated keeps this method from doing the right thing. # Fortunately it works on newforms-admin, so it will be moot soon. has_pk = bool(getattr(instance, instance._meta.pk.attname)) # default to None for existing instances; -1 for new instances #updated = None if has_pk else -1 if has_pk: updated = None else: updated = -1 try: current = getattr(instance, self.get_cache_name())[0] except (AttributeError, TypeError): if has_pk: current = value else: current = None if value is not None: updated = value else: if value is None: updated = -1 elif value != current: updated = value setattr(instance, self.get_cache_name(), (current, updated)) def _get_instance_peers(self, instance): # return a queryset containing all instances of the model that belong # to the same collection as instance; either all instances of a model # or all instances with the same value in unique_for_field filters = {} if self.unique_for_field: unique_for_field = instance._meta.get_field(self.unique_for_field) unique_for_value = getattr(instance, unique_for_field.attname) if unique_for_field.null and unique_for_value is None: filters['%s__isnull' % unique_for_field.name] = True else: filters[unique_for_field.name] = unique_for_value return instance.__class__._default_manager.filter(**filters) def _on_delete(self, sender, instance, **kwargs): current, updated = self._get_instance_cache(instance) # decrement positions gt current operations = [self._get_operation_sql('-')] conditions = [self._get_condition_sql('>', current)] cursor = connection.cursor() cursor.execute(self._get_update_sql(instance, operations, conditions)) self._reset_instance_cache(instance, None) def _on_save(self, sender, instance, **kwargs): current, updated = self._get_instance_cache(instance) # no cleanup required if updated is None: return None if current is None: # increment positions gte updated operations = [self._get_operation_sql('+')] conditions = [self._get_condition_sql('>=', updated)] elif updated > current: # decrement positions gt current and lte updated operations = [self._get_operation_sql('-')] conditions = [ self._get_condition_sql('>', current), self._get_condition_sql('<=', updated) ] else: # increment positions lt current and gte updated operations = [self._get_operation_sql('+')] conditions = [ self._get_condition_sql('<', current), self._get_condition_sql('>=', updated) ] # exclude instance from the update conditions.append('%(pk_field)s != %(pk)s' % { 'pk': getattr(instance, instance._meta.pk.attname), 'pk_field': qn(instance._meta.pk.column) }) cursor = connection.cursor() cursor.execute(self._get_update_sql(instance, operations, conditions)) self._reset_instance_cache(instance, updated) def _get_update_sql(self, instance, operations=None, conditions=None): operations = operations or [] conditions = conditions or [] # TODO: add params and operations to update auto_now date(time)s params = { 'position_field': qn(self.column), 'table': qn(instance._meta.db_table), } if self.unique_for_field: unique_for_field = instance._meta.get_field(self.unique_for_field) unique_for_value = getattr(instance, unique_for_field.attname) params['unique_for_field'] = qn(unique_for_field.column) # this field is likely to be indexed; put it first if unique_for_field.null and unique_for_value is None: conditions.insert(0, '%(unique_for_field)s IS NULL') else: params['unique_for_value'] = unique_for_value conditions.insert(0, '%(unique_for_field)s = %(unique_for_value)s') query = 'UPDATE %(table)s' query += ' SET %s' % ', '.join(operations) query += ' WHERE %s' % ' AND '.join(conditions) return query % params def _get_condition_sql(self, gt_or_lt, position): return '%%(position_field)s %(gt_or_lt)s %(position)s' % { 'gt_or_lt': gt_or_lt, 'position': position } def _get_operation_sql(self, plus_or_minus): return """ %%(position_field)s = (%%(position_field)s %(plus_or_minus)s 1)""" % { 'plus_or_minus': plus_or_minus }
Python
# coding: utf-8 from django.db import models, transaction from django.utils.translation import ugettext as _ from grappelli.fields import PositionField class Help(models.Model): """ Help Entry. """ title = models.CharField(_('Title'), max_length=50) # order order = PositionField(_('Order')) class Meta: app_label = "grappelli" verbose_name = _('Help') verbose_name_plural = _('Help') ordering = ['order'] def __unicode__(self): return u"%s" % (self.title) save = transaction.commit_on_success(models.Model.save) class HelpItem(models.Model): """ Help Entry Item. """ help = models.ForeignKey(Help, verbose_name=_('Help')) title = models.CharField(_('Title'), max_length=200) link = models.CharField(_('Link'), max_length=200, help_text=_('The Link should be relative, e.g. /admin/blog/.')) body = models.TextField(_('Body')) # order order = PositionField(_('Order'), unique_for_field='help') class Meta: app_label = "grappelli" verbose_name = _('Help Entry') verbose_name_plural = _('Help Entries') ordering = ['help', 'order'] def __unicode__(self): return u"%s" % (self.title) def get_body(self): body = self.body.replace('<h2>', '</div><div class="module"><h2>') return body save = transaction.commit_on_success(models.Model.save)
Python
from grappelli.models.navigation import Navigation, NavigationItem from grappelli.models.bookmarks import Bookmark, BookmarkItem from grappelli.models.help import Help, HelpItem
Python
# coding: utf-8 from django.db import models, transaction from django.utils.translation import ugettext as _ from grappelli.fields import PositionField class Bookmark(models.Model): """ Bookmark. """ user = models.ForeignKey('auth.User', limit_choices_to={'is_staff': True}, verbose_name=_('User'), related_name="admin_bookmark_set") class Meta: app_label = "grappelli" verbose_name = _('Bookmark') verbose_name_plural = _('Bookmarks') ordering = ['user',] def __unicode__(self): return u"%s" % (self.user) save = transaction.commit_on_success(models.Model.save) class BookmarkItem(models.Model): """ Bookmark Item. """ bookmark = models.ForeignKey(Bookmark, verbose_name=_('Bookmark')) title = models.CharField(_('Title'), max_length=80) link = models.CharField(_('Link'), max_length=200, help_text=_('The Link should be relative, e.g. /admin/blog/.')) # order order = PositionField(_('Order'), unique_for_field='bookmark') class Meta: app_label = "grappelli" verbose_name = _('Bookmark Item') verbose_name_plural = _('Bookmark Items') ordering = ['order'] def __unicode__(self): return u"%s" % (self.title) save = transaction.commit_on_success(models.Model.save)
Python
# coding: utf-8 from django.db import models, transaction from django.utils.translation import ugettext as _ from grappelli.fields import PositionField ITEM_CATEGORY_CHOICES = ( ('1', 'internal'), ('2', 'external'), ) class Navigation(models.Model): """ Sidebar-Navigation on the Admin Index-Site. """ title = models.CharField(_('Title'), max_length=30) # order order = PositionField(_('Order')) class Meta: app_label = "grappelli" verbose_name = _('Navigation') verbose_name_plural = _('Navigation') ordering = ['order',] def __unicode__(self): return u"%s" % (self.title) save = transaction.commit_on_success(models.Model.save) class NavigationItem(models.Model): """ Navigation Item. """ navigation = models.ForeignKey(Navigation, verbose_name=_('Navigation')) title = models.CharField(_('Title'), max_length=30) link = models.CharField(_('Link'), max_length=200, help_text=_('The Link should be relative, e.g. /admin/blog/.')) category = models.CharField(_('Category'), max_length=1, choices=ITEM_CATEGORY_CHOICES) # users users = models.ManyToManyField('auth.User', limit_choices_to={'is_staff': True}, verbose_name=_('Users'), blank=True, related_name="admin_navigation_users") groups = models.ManyToManyField('auth.Group', verbose_name=_('Groups'), blank=True, related_name="admin_navigation_groups") # order order = PositionField(_('Order'), unique_for_field='navigation') class Meta: app_label = "grappelli" verbose_name = _('Navigation Item') verbose_name_plural = _('Navigation Items') ordering = ['navigation', 'order'] def __unicode__(self): return u"%s" % (self.title) save = transaction.commit_on_success(models.Model.save)
Python
# coding: utf-8 from django.conf.urls.defaults import * urlpatterns = patterns('', # BOOKMARKS url(r'^bookmark/add/$', 'grappelli.views.bookmarks.add_bookmark', name="grp_bookmark_add"), url(r'^bookmark/remove/$', 'grappelli.views.bookmarks.remove_bookmark', name="grp_bookmark_remove"), url(r'^bookmark/get/$', 'grappelli.views.bookmarks.get_bookmark', name="grp_bookmark_get"), # HELP url(r'^help/(?P<object_id>\d+)/$', 'grappelli.views.help.detail', name="grp_help_detail"), url(r'^help', 'grappelli.views.help.help', name="grp_help"), # GENERIC url(r'^obj_lookup/$', 'grappelli.views.generic.generic_lookup', name="grp_generic_lookup"), # FOREIGNKEY LOOKUP url(r'^related_lookup/$', 'grappelli.views.related.related_lookup', name="grp_related_lookup"), url(r'^m2m_lookup/$', 'grappelli.views.related.m2m_lookup', name="grp_m2m_lookup") # AUTOCOMPLETE LOOKUP #url(r'^autocomplete_lookup/$', 'grappelli.views.related.autocomplete_lookup', name="grp_autocomplete_lookup"), #url(r'^autocomplete_lookup_id/$', 'grappelli.views.related.autocomplete_lookup_id', name="grp_autocomplete_lookup_id"), # M2M AUTOCOMPLETE LOOKUP #url(r'^m2m_autocomplete_lookup/$', 'grappelli.views.related.m2m_autocomplete_lookup', name="grp_m2m_autocomplete_lookup"), #url(r'^m2m_autocomplete_lookup_id/$', 'grappelli.views.related.m2m_autocomplete_lookup_id', name="grp_m2m_autocomplete_lookup_id"), )
Python
# coding: utf-8 # django imports from django.template import Node from django.template import Library from django.utils.safestring import mark_safe register = Library() class CsrfTokenNode(Node): def render(self, context): csrf_token = context.get('csrf_token', None) if csrf_token: if csrf_token == 'NOTPROVIDED': return mark_safe(u"") else: return mark_safe(u"<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='%s' /></div>" % (csrf_token)) else: # It's very probable that the token is missing because of # misconfiguration, so we raise a warning from django.conf import settings if settings.DEBUG: import warnings warnings.warn("A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.") return u'' def grp_csrf_token(parser, token): return CsrfTokenNode() register.tag(grp_csrf_token)
Python