from django.utils.translation import ugettext as _ from django.db import models from tinymce import models as tinymce_models from django.conf import settings from django.utils import translation #from tinymce.widgets import TinyMCE # Create your models here. class Information(models.Model): def __unicode__(self): return InformationLocale.get_heading_with_fallback(self.id) def __str__(self): return InformationLocale.get_heading_with_fallback(self.id) parent_information = models.ForeignKey('self', blank=True, null=True, related_name='children', verbose_name=_("Parent information"),on_delete=models.CASCADE) main_illustration = models.ImageField(upload_to='images/information', blank=True, verbose_name=_("Main illustration") ) ordering = models.IntegerField(default=0, verbose_name=_("Ordering")) class Meta: ordering = ["ordering"] class InformationIllustration(models.Model): information = models.ForeignKey(Information,on_delete=models.CASCADE) illustration = models.ImageField(upload_to='images/information', blank=True, verbose_name=_("Illustration")) class InformationAttachment(models.Model): information = models.ForeignKey(Information,on_delete=models.CASCADE) attachment = models.FileField(upload_to='attachments/information', blank=True, verbose_name=_("Attachment")) class InformationLocale(models.Model): information = models.ForeignKey(Information,on_delete=models.CASCADE) headline = models.CharField(max_length=200, verbose_name=_("Headline")) lead_paragraph = models.TextField(verbose_name=_("Lead paragraph")) body = tinymce_models.HTMLField(verbose_name=_("Body text")) language_code = models.CharField(max_length=2, verbose_name=_("Language code")) @staticmethod def get_information_locale_with_fallback(information_id, language_code=translation.get_language()): if information_id == None: return None # Try with user's preferred locale first try: return InformationLocale.objects.get( information=Information.objects.get(pk=information_id), language_code=language_code ) except: # Try with site's default language try: return InformationLocale.objects.get( information=Information.objects.get(pk=information_id), language_code=settings.LANGUAGE_CODE ) except: # Try with English try: return InformationLocale.objects.get( information=Information.objects.get(pk=information_id), language_code="en" ) except: # Use the first and best return InformationLocale.objects.filter(information=Information.objects.get(pk=information_id))[0] @staticmethod def get_heading_with_fallback(information_id, language_code=translation.get_language()): information_locale = InformationLocale.get_information_locale_with_fallback(information_id, language_code) if information_locale == None: return "" else: return InformationLocale.get_information_locale_with_fallback(information_id, language_code).headline