GithubHelp home page GithubHelp logo

infoportugal / wagtail-modeltranslation Goto Github PK

View Code? Open in Web Editor NEW
149.0 12.0 117.0 1.16 MB

Simple app to patch modeltranslation (https://github.com/deschler/django-modeltranslation) into Wagtail CMS.

Python 88.75% JavaScript 8.13% CSS 1.59% Makefile 0.86% HTML 0.68%

wagtail-modeltranslation's Introduction

Wagtail Modeltranslation

This app is built using core features of django-modeltranslation: https://github.com/deschler/django-modeltranslation

It's an alternative approach for i18n support on Wagtail CMS websites.

The wagtail-modeltranslation application is used to translate dynamic content of existing Wagtail models to an arbitrary number of languages, without having to change the original model classes. It uses a registration approach (comparable to Django's admin app) to add translations to existing or new projects and is fully integrated into the Wagtail admin UI.

The advantage of a registration approach is the ability to add translations to models on a per-app basis. You can use the same app in different projects, whether or not they use translations, and without touching the original model class.

https://github.com/infoportugal/wagtail-modeltranslation/blob/master/screenshot.png?raw=true

Features

  • Add translations without changing existing models or views
  • Translation fields are stored in the same table (no expensive joins)
  • Supports inherited models (abstract and multi-table inheritance)
  • Handle more than just text fields
  • Wagtail admin integration
  • Flexible fallbacks, auto-population and more!
  • Default Page model fields has translatable fields by default
  • StreamFields are now supported!

Caveats

wagtail-modeltranslation patches Wagtail's Page model with translation fields title_xx, slug_xx, seo_title_xx, search_description_xx and url_path_xx where "xx" represents the language code for each translated language. This is done without migrations through command sync_page_translation_fields. Since Page model belongs to Wagtail it's within the realm of possibility that one day Wagtail may add a conflicting field to Page thus interfering with wagtail-modeltranslation.

Wagtail's slugurl tag does not work across languages. wagtail-modeltranslation provides a drop-in replacement named slugurl_trans which by default takes the slug parameter in the default language.

Quick start

  1. Install wagtail-modeltranslation:

    pip install wagtail-modeltranslation
    
  2. Add 'wagtail_modeltranslation' to your INSTALLED_APPS setting like this (before all apps that you want to translate):

    INSTALLED_APPS = (
        ...
        'wagtail_modeltranslation',
        'wagtail_modeltranslation.makemigrations',
        'wagtail_modeltranslation.migrate',
    )
    
  3. Add 'django.middleware.locale.LocaleMiddleware' to MIDDLEWARE on your settings.py:

    MIDDLEWARE = (
        ...
        'django.middleware.locale.LocaleMiddleware',  # should be after SessionMiddleware and before CommonMiddleware
    )
    
  4. Enable i18n on settings.py:

    USE_I18N = True
    
  5. Define available languages on settings.py:

    from django.utils.translation import gettext_lazy as _
    
    LANGUAGES = (
        ('pt', _('Portuguese')),
        ('es', _('Spanish')),
        ('fr', _('French')),
    )
    
  6. Create translation.py inside the root folder of the app where the model you want to translate exists:

    from .models import Foo
    from modeltranslation.translator import TranslationOptions
    from modeltranslation.decorators import register
    
    @register(Foo)
    class FooTR(TranslationOptions):
        fields = (
            'body',
        )
    
  7. Run python manage.py makemigrations followed by python manage.py migrate (repeat every time you add a new language or register a new model)

  8. Run python manage.py sync_page_translation_fields (repeat every time you add a new language)

  9. If you're adding wagtail-modeltranslation to an existing site run python manage.py update_translation_fields

Supported versions

Title
wagtail-modeltranslation release Compatible Wagtail versions Compatible Django versions Compatible Python versions
0.10 >= 1.12, < 2.12 >= 1.11 2.7, 3.4, 3.5, 3.6
0.11 >= 2.13, < 3.0 >= 3.0 3.6, 3.7, 3.8, 3.9
0.12 >= 3.0, < 4.0 >= 3.2 3.7, 3.8, 3.9, 3.10
0.13 >= 4.0, < 5.0 >= 3.2 3.7, 3.8, 3.9, 3.10
0.14 >= 5.0, < 6.0 >= 3.2 3.8, 3.9, 3.10, 3.11
0.15 >= 5.2 >= 4.2 3.8, 3.9, 3.10, 3.11, 3.12

Upgrade considerations (v0.10.8)

  • Template tag change_lang now needs a second parameter, page

Upgrade considerations (v0.8)

This version includes breaking changes as some key parts of the app have been re-written:

  • The most important change is that Page is now patched with translation fields.
  • WAGTAILMODELTRANSLATION_ORIGINAL_SLUG_LANGUAGE setting has been deprecated.

To upgrade to this version you need to:

  • Replace the WagtailTranslationOptions with TranslationOptions in all translation.py files
  • Run python manage.py sync_page_translation_fields at least once to create Page's translation fields
  • Replace any usages of Wagtail's {% slugurl ... %} for wagtail-modeltranslation's own {% slugurl_trans ... %}
  • While optional it's recommended to add 'wagtail_modeltranslation.makemigrations' to your INSTALLED_APPS. This will override Django's makemigrations command to avoid creating spurious Page migrations.

Upgrade considerations (v0.6)

This version has some important changes as there was a refactoring to include django-modeltranslation as a dependency instead of duplicating their code in our version. This allow us to focus on Wagtail admin integration features as django-modeltranslation is very well mantained and is very quickly to fix problems with the latest Django versions. This way we also keep all the django-modeltranslation features (if you want you can also customize django-admin, for example). We also provide a new class to create the translation options classes: WagtailTranslationOptions Most of the changes are related to imports as they change from wagtail-modeltranslation to modeltranslation.

To upgrade to this version you need to:

  • Replace the TranslationOptions with WagtailTranslationOptions in all translation.py files
  • The import of the register decorator is now from modeltranslation.decorators import register
  • The import of translator is now from modeltranslation.translator import translator

Project Home

https://github.com/infoportugal/wagtail-modeltranslation

Documentation

http://wagtail-modeltranslation.readthedocs.io/

wagtail-modeltranslation's People

Contributors

agelinas avatar andreasnuesslein avatar ashwoods avatar benjaoming avatar buczek avatar chaahk avatar dependabot[bot] avatar diogomarques29 avatar dmarcelino avatar dpratter avatar dwasyl avatar easherma avatar jaimenms avatar jomiq avatar jorenham avatar kakulukia avatar lloyderino avatar msilva94 avatar msilvapor avatar nulopes avatar olivierdalang avatar pomax avatar saeed617 avatar stuaxo avatar tiagofmc avatar timtan avatar tissieres avatar tomdyson avatar tuerlefl avatar v1kku avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wagtail-modeltranslation's Issues

Add translation of streamfield to a Multifield-Panel breaks Javascript

I wanted to add a collapcollapsible Multifield-Panel for each language which works fine except for the fact that the streamfield does not open when clicking on the plus button or any of the available block-icons buttons. I get an error in the javascript which says: Uncaught TypeError: Cannot read property 'innerHTML' of undefined (copy_stream_fields.js: 20).

It seems that the script is looking for a h2 that is not there.

0.5.x Python3 compatibility

wagtail-modeltranslation-0.4.2 is python3 compatible,

wagtail-modeltranslation-0.5.0a0 is not in wagtail-modeltranslation/patch_wagtailadmin.py

  File "/home/uer/code/hzk/lib/python3.5/site-packages/wagtail_modeltranslation/patch_wagtailadmin.py", line 92, in __init__
    for related_name, formset in form.formsets.iteritems():
AttributeError: 'dict' object has no attribute 'iteritems'

URL property return None

Hi guys,

I installed your app yesterday and since that I am still trying to get it work. I have a big trouble with getting correct URL for all my pages. Page.url return None instead of correct URL string. I found that the problem is in cache mechanism.

These steps folow my problem:

  1. start webserver
  2. http://localhost:7000/cs/
  3. all links to subpages are OK
  4. switching language to "en" ... http://localhost:7000/en/
  5. all links to subpages are broken = http://localhost:7000/en/None
  6. since that "cs" is OK, "en" is not OK till the cache is rebuild
    def url(self):
        root_paths = Site.get_site_root_paths()
        for (id, root_path, root_url) in root_paths:
            if self.url_path.startswith(root_path):
                return ('' if len(root_paths) == 1 else root_url) + reverse('wagtail_serve', args=(self.url_path[len(root_path):],))

I found where is the problem. In the Page.url ... Site.get_site_root_paths() always return the root_path of the first initialized language (f.e. "cs"). That is because get_site_root_paths is using cache here:

    def get_site_root_paths():
        result = cache.get('wagtail_site_root_paths')
        return result

I know couple workarounds howto figure it out. But I don't think that is is OK.

MODELTRANSLATION_DEFAULT_LANGUAGE not in LANGUAGES setting.

I see all info in the documentation but i haven't idea what's the problem.
ccct - -run-media-salahaddin-data-proyectos-trabajo-ccct - -ccct-ccct-settings-base py - pycharm 5 0 3_025

'es' are in settings.LANGUAGE, so, what's the problem?

I don't understand: i want put es as default language and en tr as translatable languages, what settings i need?

Ok, i believe that i solve this:
ccct - -run-media-salahaddin-data-proyectos-trabajo-ccct - -ccct-ccct-settings-base py - pycharm 5 0 3_026

But if you cant see i have other error:
I built a new migration and make it, delete all es fields. But, when i try edit a page, i have these error:
fielderror at -admin-pages-28-edit- - mozilla firefox_027

Why? I suppose that es fields is the primary fields. So, why i have this error?

Ok, I delete the second option and put the first, migrate and getback es fields and all is well, but:
phppgadmin - mozilla firefox_028
wagtail - editando nuevo - mozilla firefox_029
If i have info in original fields why es field haven't these info?

I mean, i understand that if i put a default language, when i writter information for these language, original field have this information, right?

Issue with page translated fields migrations

I added a translatable field to a model that I previously defined. When I run makemigrations of my app, It creates these migrations:

Migrations for 'wagtailcore':
  0020_auto_20150930_1205.py:
    - Add field search_description_ca to page
    - Add field search_description_en to page
    - Add field search_description_es to page
    - Add field seo_title_ca to page
    - Add field seo_title_en to page
    - Add field seo_title_es to page
    - Add field slug_ca to page
    - Add field slug_en to page
    - Add field slug_es to page
    - Add field title_ca to page
    - Add field title_en to page
    - Add field title_es to page
    - Add field url_path_ca to page
    - Add field url_path_en to page
    - Add field url_path_es to page

that seems a default behaviour of wagtail-modeltranslation. This is not quite good because if I have to deploy this project these migrations won't be deployed as are located in my local site-packages.

A common solution for this is specifying in setings.py that migrations would be on my app:

    MIGRATION_MODULES = {'wagtailcore': 'cms.migrations_wagtail'}

But this its seem that it isn't working properly:

django.db.migrations.graph.NodeNotFoundError: Migration wagtailredirects.0001_initial dependencies reference nonexistent parent node ('wagtailcore', '0002_initial_data')

Any idea of how to fix this?

Error when using InlinePanel

wagtail-modeltranslation is working rather well for me with the exception of handling InlinePanel in torchbox/wagtail-torchbox setup I have customized. Also, I'm wondering if the new wagtail streamfield can be used with modeltranslation?

Here is some sample code with InlinePanel which triggers an error (I placed an arrow next to one of the lines triggering an error):

BlogPage.content_panels = [
FieldPanel('title', classname="full title"),
--> InlinePanel(BlogPage, 'related_author', label="Author"),
FieldPanel('author_left'),
FieldPanel('date'),
FieldPanel('intro', classname="full"),
FieldPanel('body', classname="full"),

StreamFieldPanel('streamfield'),

InlinePanel(BlogPage, 'related_links', label="Related links"),

InlinePanel(BlogPage, 'tags', label="Tags")

]
(I had to comment out StreamFieldPanel and all InlinePanels to get rid of error message)

Here are a few significant lines from the debugging screen:

AttributeError at /admin/pages/new/core/blogpage/3/

type object 'BlogPage' has no attribute 'panels'

(...)

Exception Location: /var/www/htac/htacweb/wagtail_modeltranslation/models.py in _patch_inlinepanel, line 216

It's great having modeltranslation working for Wagtail! Thank you|

Integration with wagtailmodeladmin

When a snippet is registered with wagtailmodeladmin the default edit and create view uses a different edit_handler that wasn't patched by wagtail-modeltranslation.

Need an example language switcher in template

It would be good to add an example of a language switcher in the Documentation. It has been removed in README.1st and I'm sure it would be quite helpfull. I would need it myself.

I will add it in the Documentation ...

Thank you

Alain

Problem on python shell

On the python shell when we try "Model".objects.all or "Model".objects.first to get the pages that returns an "bound method NewMultilingualManager."all or first" of wagtail_modeltranslation.translator.NewMultilingualManager object".

- inside language code cause error

2015-11-16 6 53 35

I find inside wagtail-modeltranslation/models.py . we should replace all "-" to "_" in language code. due to wagtail model translation produce model in the form "file_language_code" while django make migration.

it may cause problem while using language code such as zh-hant

while accessing language code to get the real field name. use build_localized_fieldname may be better

volunteer to work on documentation

Hi Rui,

I can help with the documentation, just let me know how I can help. I've started getting acquainted on how to create documentation with Readthedocs. Maybe Rui you have already something started which we could help with knowing that you are rather busy.

I greatly appreciate wagtail-modeltranslation!

url_path translation field

Override set_url_path() method in order to populate url_path for each language. This way we can get translatable urls based on already supported translated slugs.

Copying content of streamfields fails with 500

Copy content of streamfields

Recently I've noticed that the function to copy content of a streamfield does not work in my project. In the traceback (see attached) I saw that the request failed with the error code 500.
The streamfield is registered for translation and in the admin interface the streamfields for every language are visible. When one of the language buttons are clicked, the request fails and nothing happens.

Is this a bug or could be something wrong with my setup?

Additionally, it would be nice to hide these buttons if the streamfield is not registered for translation.

Using:

  • Django 1.8.5
  • wagtail 1.1
  • wagtail-modeltranslation 0.3.2
Request Method: GET
Request URL: /admin/pages/5/edit/copy_translation_content?origin_field_name=page_de&target_field_name=page_content&serializedOriginField=%5B%5D HTTP/1.1" 500 15117

ERROR django.request handle_uncaught_exception(256): Internal Server Error: /admin/pages/5/edit/copy_translation_content
Traceback (most recent call last):
  File "<PATH_TO_VIRTUALENV>/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "<PATH_TO_VIRTUALENV>/lib/python2.7/site-packages/django/views/decorators/cache.py", line 43, in _cache_controlled
    response = viewfunc(request, *args, **kw)
  File "<PATH_TO_VIRTUALENV>/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 22, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "<PATH_TO_VIRTUALENV>/lib/python2.7/site-packages/wagtail_modeltranslation/wagtail_hooks.py", line 75, in return_translation_target_field_rendered_html
    q_data, {}, target_field_name)
  File "<PATH_TO_VIRTUALENV>/lib/python2.7/site-packages/wagtail/wagtailcore/blocks/stream_block.py", line 135, in value_from_datadict
    count = int(data['%s-count' % prefix])
  File "<PATH_TO_VIRTUALENV>/lib/python2.7/site-packages/django/utils/datastructures.py", line 322, in __getitem__
    raise MultiValueDictKeyError(repr(key))
MultiValueDictKeyError: "u'page_content-count'"

Problems migrating existing models to new modeltranslation installation

Hi guys, i was working with wagtail 8.0 and i have many page in my db.
I migrating all models to 1.0 and modeltranslation and i have this issue:
no titulos

Where are titles?

Now i have a problem, in all pages that i try to edit or create i get screen of this type:
problemas translation

What is the problem? i need help urgently!

Wagtail 1.4 issue

I'm testing Wagtail 1.4 and i have this bug with model translatio:

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f695eab8d90>
Traceback (most recent call last):
  File "/run/media/salahaddin/Datos/Proyectos/Trabajo/adkm/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "/run/media/salahaddin/Datos/Proyectos/Trabajo/adkm/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
    autoreload.raise_last_exception()
  File "/run/media/salahaddin/Datos/Proyectos/Trabajo/adkm/lib/python3.5/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception
    six.reraise(*_exception)
  File "/run/media/salahaddin/Datos/Proyectos/Trabajo/adkm/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/run/media/salahaddin/Datos/Proyectos/Trabajo/adkm/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "/run/media/salahaddin/Datos/Proyectos/Trabajo/adkm/lib/python3.5/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/run/media/salahaddin/Datos/Proyectos/Trabajo/adkm/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/run/media/salahaddin/Datos/Proyectos/Trabajo/adkm/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "/run/media/salahaddin/Datos/Proyectos/Trabajo/adkm/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 662, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/run/media/salahaddin/Datos/Proyectos/Trabajo/adkm/anadolu/core/models.py", line 20, in <module>
    from wagtail_modeltranslation.models import TranslationMixin
  File "/run/media/salahaddin/Datos/Proyectos/Trabajo/adkm/lib/python3.5/site-packages/wagtail_modeltranslation/models.py", line 16, in <module>
    from wagtail.wagtailadmin.views.pages import get_page_edit_handler,\
ImportError: cannot import name 'get_page_edit_handler'

This bug makes Wagtail Model translation useless, we couldn't use when official release will be release.

Other idioms in new tab

Hello,
It could be possible to have:

CONTENT [EN] | CONTENT [ES] | CONTENT [FR]

Instead the actual:
Tittle [es]
Tittle [en]

I could help with that if any give me some direction.

Problem with slugs

When a page is register for translation the verification of uniqueness of the slug field doesn't work. So, that allows to have different pages with same slugs, and gives error in template because returns two pages to the same template.

AttributeError: No attribute 'panels' when using InlinePanel

When I tried to use an InlinePanel for a cluster of ImageChoosers as content_panel in my Page-class, an AttributeError-exception is thrown.

class VenueArticle(TranslationMixin, ArticlePage):
    address = models.CharField(max_length=255, blank=True, null=True)

    content_panels = Page.content_panels + [
        FieldPanel('author'),
        FieldPanel('bodytext', classname='full'),
        MultiFieldPanel([
            ImageChooserPanel('hero_image_small'),
            ImageChooserPanel('hero_image_large'),
            FieldPanel('hero_image_title'),
        ], heading="header_image"),
        InlinePanel('gallery_images', label='images'),
    ]

class GalleryImage(models.Model):
    image_ref = models.ForeignKey('wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+',)
    panels = [
        ImageChooserPanel('image_ref')
    ]
    imageLink = ParentalKey('VenueArticle', related_name='gallery_images')

Exception-Value:
type object 'FooPage' has no attribute 'panels'
Source of this exception seems to be following line in the wagtail_modeltranslation/models.py on line 352:
inline_panels = getattr( instance.__class__, panel.relation_name).related.model.panels
model is a Page-object, that has obviously no panels attribute

I tried the following workaround: defining an empty list as fallback value for panels, which seems to work:

relation = getattr(instance.__class__, panel.relation_name)
inline_panels = getattr(relation.related.model, 'panels', [])

I'm using:
wagtail==1.0
wagtail-modeltranslation==0.2.2

Environment:


Request Method: GET
Request URL: http://localhost:8000/admin/pages/new/<appname>/venuearticle/1/

Django Version: 1.8.4
Python Version: 2.7.10
Installed Applications:
('wagtail_modeltranslation',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'taggit',
 'compressor',
 'modelcluster',
 'wagtail.wagtailcore',
 'wagtail.wagtailadmin',
 'wagtail.wagtailsearch',
 'wagtail.wagtailimages',
 'wagtail.wagtaildocs',
 'wagtail.wagtailsnippets',
 'wagtail.wagtailusers',
 'wagtail.wagtailsites',
 'wagtail.wagtailembeds',
 'wagtail.wagtailredirects',
 'wagtail.wagtailforms',
 'search',
 'home',
 '<appname>')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.locale.LocaleMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'wagtail.wagtailcore.middleware.SiteMiddleware',
 'wagtail.wagtailredirects.middleware.RedirectMiddleware')


Traceback:
File "/Users/<username>/.virtualenvs/<virtualenv_name>/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/<username>/.virtualenvs/<virtualenv_name>/lib/python2.7/site-packages/django/views/decorators/cache.py" in _cache_controlled
  43.             response = viewfunc(request, *args, **kw)
File "/Users/<username>/.virtualenvs/<virtualenv_name>/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  22.                 return view_func(request, *args, **kwargs)
File "/Users/<username>/.virtualenvs/<virtualenv_name>/lib/python2.7/site-packages/wagtail/wagtailadmin/views/pages.py" in create
  144.     page = page_class(owner=request.user)
File "/Users/<username>/.virtualenvs/<virtualenv_name>/lib/python2.7/site-packages/wagtail_modeltranslation/translator.py" in new_init
  218.         old_init(self, *args, **kwargs)
File "/Users/<username>/.virtualenvs/<virtualenv_name>/lib/python2.7/site-packages/wagtail_modeltranslation/models.py" in __init__
  137.                 trtab = TranslationMixin._patch_panel(self, panel)
File "/Users/<username>/.virtualenvs/<virtualenv_name>/lib/python2.7/site-packages/wagtail_modeltranslation/models.py" in _patch_panel
  208.             TranslationMixin._patch_inlinepanel(instance, panel)
File "/Users/<username>/.virtualenvs/<virtualenv_name>/lib/python2.7/site-packages/wagtail_modeltranslation/models.py" in _patch_inlinepanel
  356.             instance.__class__, panel.relation_name).related.model.panels

Exception Type: AttributeError at /admin/pages/new/<appname>/venuearticle/1/
Exception Value: type object 'VenueArticle' has no attribute 'panels'

Template tags missing from pip install

Thanks for creating this app!

Unless I'm misunderstanding something, the templatetags directory is not included from pip install wagtail-modeltranslation

~/.virtualenvs/wagtail.trans/lib/python2.7/site-packages/wagtail_modeltranslation
$: ls -l
-rw-rw-r-- 1 pymarco pymarco   335 Aug  7 15:05 apps.py
-rw-rw-r-- 1 pymarco pymarco   837 Aug  7 15:05 decorators.py
-rw-rw-r-- 1 pymarco pymarco 16968 Aug  7 15:05 fields.py
-rw-rw-r-- 1 pymarco pymarco  1353 Aug  7 15:05 forms.py
-rw-rw-r-- 1 pymarco pymarco   213 Aug  7 15:05 __init__.py
drwxrwxr-x 3 pymarco pymarco  4096 Aug  7 15:05 management
-rw-rw-r-- 1 pymarco pymarco 20995 Aug  7 15:05 manager.py
-rw-rw-r-- 1 pymarco pymarco 15422 Aug  7 15:05 models.py
-rw-rw-r-- 1 pymarco pymarco  2891 Aug  7 15:05 settings.py
drwxrwxr-x 3 pymarco pymarco  4096 Aug  7 15:05 static
-rw-rw-r-- 1 pymarco pymarco   356 Aug  7 15:05 translation.py
-rw-rw-r-- 1 pymarco pymarco 24296 Aug  7 15:05 translator.py
-rw-rw-r-- 1 pymarco pymarco  5539 Aug  7 15:05 utils.py
-rw-rw-r-- 1 pymarco pymarco   676 Aug  7 15:05 wagtail_hooks.py
-rw-rw-r-- 1 pymarco pymarco  4065 Aug  7 15:05 widgets.py

When I use git to clone the app from GitHub, the file structure includes a templatetags directory

~/Downloads/wagtail_modeltranslation
[master] $: ls -l 
-rwxrwxr-x 1 pymarco pymarco   335 Aug  7 16:41 apps.py
-rwxrwxr-x 1 pymarco pymarco   837 Aug  7 16:41 decorators.py
-rwxrwxr-x 1 pymarco pymarco 16968 Aug  7 16:41 fields.py
-rwxrwxr-x 1 pymarco pymarco  1353 Aug  7 16:41 forms.py
-rwxrwxr-x 1 pymarco pymarco   213 Aug  7 16:41 __init__.py
drwxrwxr-x 3 pymarco pymarco  4096 Aug  7 16:41 management
-rwxrwxr-x 1 pymarco pymarco 20995 Aug  7 16:41 manager.py
-rwxrwxr-x 1 pymarco pymarco 15422 Aug  7 16:41 models.py
-rw-rw-r-- 1 pymarco pymarco  8015 Aug  7 16:41 models.pyc
-rwxrwxr-x 1 pymarco pymarco  2891 Aug  7 16:41 settings.py
drwxrwxr-x 4 pymarco pymarco  4096 Aug  7 16:41 static
drwxrwxr-x 2 pymarco pymarco  4096 Aug  7 16:41 templatetags <--- Template tags directory
-rw-rw-r-- 1 pymarco pymarco    16 Aug  7 16:41 tests.py
-rw-rw-r-- 1 pymarco pymarco   356 Aug  7 16:41 translation.py
-rwxrwxr-x 1 pymarco pymarco 24296 Aug  7 16:41 translator.py
-rwxrwxr-x 1 pymarco pymarco  5539 Aug  7 16:41 utils.py
-rw-rw-r-- 1 pymarco pymarco   676 Aug  7 16:41 wagtail_hooks.py
-rwxrwxr-x 1 pymarco pymarco  4065 Aug  7 16:41 widgets.py

Copy page does not creates slugs for all languages

Hi there,

When copying a page, the slug field doesn't get created for all languages. Imagine we have a page with both title_pt and title_en and we want to copy a page "teste" giving it the name "teste 2" and slug "teste-2", it will create the new page with the fields title_pt "teste", title_en "teste 2", slug_pt "teste" and slug_en "teste-2". So in conclusion it will only creates the fields for the current browser language (mine is en).

best regards,
Diogo Marques

Step 5 of the read me is unclear

In step 5 of the introduction you write:

In order to update pages url_path field use "set_translation_url_paths" instead of original "set_url_paths"

It's unclear to me what you mean with this. Where should I do this? Could you provide an example or so?

Active wagtail admin language is used to save translated fields on Page (eg. title, slug)

Wagtail admin uses LocaleMiddleware to detect browser language.

Imagine a custom page model translating the title field. When using the wagtail admin in eg German, the value set on the title_de field will also be written to the title field of Page (the wagtail built in root model) when saving. When using the admin in eg. English, the Page.title will contain the English value after saving.

When editors with different language operating systems/browsers use the admin (which is not uncommon when operating a multi-language site), the languages of the title fields of the various pages stored will vary.

This has a number of problematic side effects:

  • The Page.title field is used in the list views of wagtail admin. So the list will show a mix of all kinds of languages and make it difficult for editors to find the articles they are looking for.
  • Speaking of "finding things": when using the basic wagtail setup with DB search backend, the translated fields cannot be searched. This is a wagtail limitation, only fields on the Page model can be searched with this backend.
    However, that would not be a problem, if the titles on the Page model would stay consistent eg. "always in English". Imagine using the word "district" in the title for eg a page describing a location: you'd have to search for "bezirk" if the last saving editor happened used a German browser, "quartier" if they were using French etc. You just never know what to search for.

The "translation overloaded" fields of Page should always contain the same language, probably best to use settings.LANGUAGE_CODE.

change_lang returns None

I'm using the wagtail demo and I have made the HomePage translatable according your instructions. In the admin this works fine.

Now I amended the home_page.html template with this:

{% load modeltranslation %}
<li class="dropdown">
    <a data-toggle="dropdown" class="dropdown-toggle" data-hover="dropdown" href="#">{{     LANGUAGE_CODE }}<i class="fa fa-angle-down ml5"></i></a>
    <ul class="dropdown-menu" id="language-dropdown">
        {% for lang in languages %}
            {% if lang.0 != LANGUAGE_CODE %}
                <li tabindex="-1"><a href="{% change_lang lang.0 %}">{{ lang.1 }}</a></li>
            {% endif %}
        {% endfor %}
   </ul>
</li>

To make sure that languages has a value I wrote a tiny context processor:

from django.conf import settings

def languages(request):

    return {'languages': settings.LANGUAGES}

And settings.LANGUAGES is defined like this (in compliance with the instructions from django-model-translation):
gettext = lambda s: s
LANGUAGES = (
('en', gettext('English')),
('nl', gettext('Dutch')),
('bg', gettext('Bulgarian')),
)

Unfortunately this doesn't seem the way to do it, because the returned urls are None, for example:

<li tabindex="-1"><a href="None">Dutch</a></li>
<li tabindex="-1"><a href="None">Bulgarian</a></li>

What am I doing wrong?

Are the advanced settings in the Documentation implemented

I'm the one who has created the documentation based on django-modeltranslation. I have included the advanced settings.

Today I have tried some of the advanced settings, such as

  • MODELTRANSLATION_DEFAULT_LANGUAGE = 'fr',
  • MODELTRANSLATION_AUTO_POPULATE = True,
  • etc.

I am wondering if the advanced settings are implemented in wagtail-modeltranslation? If not, I will remove that section so no one is going to be misled by the documentation.

Thank you,
Alain

Update descendant URL paths not implemented: moving pages & changing slugs broken

When moving a page or changing the slug of a page with descendants, all the descendant's url_paths must be updated to reflect the new slug (new slugs in every language to be precise) of the parent.

Currently the patched Page.move() method does this for the moved page. The call to set_url_path() (wagtail_modeltranslation/models.py:450) makes sure the url_path of the moved page is updated. However, if that page has descendants, those url_paths will be broken.

This is because Page._update_descendant_url_paths() (wagtail/wagtailcore/models.py:506) is not patched and in the original implementation is using raw sql and operates only on the Page table (and therefore the untranslated url_path), not the specific model which carries the translated slugs.

The same Page._update_descendant_url_paths() is called by Page.save() (currently not patched by modeltranslate) to propagare slug/url_path changes of parents to to their descendants. This means, that changing the slug of any parent page, breaks the children's url_paths.

Unstable behaviour at the level of wagtailadmin display

When I add TranslationMixin to my translatable page, it adds always correctly the multi-language fields to the database, but it does always display them all in the Wagtail admin page. Let's consider the following code:

class HomePage(Page, TranslatablePageMixin):
    claim = models.CharField(
        verbose_name='claim',
        max_length=255,
        blank=True
    )

    header_image = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+'
    )


HomePage.content_panels = [
    FieldPanel('title', classname="full title"),
    FieldPanel('claim', classname="full title"),
    ImageChooserPanel('header_image')
]


class SubmitFormField(AbstractFormField):
    page = ParentalKey('SubmitFormPage', related_name='form_fields')


class SubmitFormPage(WagtailCaptchaEmailForm, TranslationMixin):
    body = RichTextField(blank=True, help_text='Edit the content you want to see before the form.')
    thank_you_text = RichTextField(blank=True, help_text='Set the message users will see after submitting the form.')


SubmitFormPage.content_panels = Page.content_panels + [
    MultiFieldPanel([
        FieldPanel('to_address'),
        FieldPanel('from_address'),
        FieldPanel('subject'),
    ], "Email"),
    FieldPanel('body', classname="full"),
    FieldPanel('thank_you_text', classname="full"),
    # InlinePanel('form_fields', label="Form fields")
]

If we consider that for both pages I added the translatable attributes to their correspondent Translation classes in translation.py the result is as follow:

SubmitFormPage : (works correctly)

snapshot2

HomePage : (does not work as expected)

snapshot1

In order to fix the problem I had to rewrite the HomePage.content_panels and add all the fields manually which is not the way it is intended to be used:

HomePage.content_panels = [
    FieldPanel('title_en', classname="full title"),
    FieldPanel('title_de', classname="full title"),
    FieldPanel('claim_en', classname="full title"),
    FieldPanel('claim_de', classname="full title"),
    ImageChooserPanel('header_image')
]

ImageChooserPanel is not translated

Hi,

Inside my translation.py one fields tuple includes an ImageChooserPanel field, but this is the unique field isn't translated.
Are ImageChooserPanel supported or only FieldPanel?

Thanks

Release a Wagtail-1.4.1-compatible version on PyPI

The current release on PyPI, 0.4.4 is incompatible with the recently released Wagtail version 1.4.1:

from wagtail_modeltranslation.models import TranslationMixin
  File "<python>/site-packages/wagtail_modeltranslation/models.py", line 16, in <module>
    from wagtail.wagtailadmin.views.pages import get_page_edit_handler,\
ImportError: cannot import name 'get_page_edit_handler'

Language switcher

We are trying out wagtail and wagtail-modeltranslation. It works fine using djangos i18n_patterns and all. However, we have one problem. We wanna be able to switch language, and it should switch to the same page (if it exist) in the swapped language.

How to map a page url to the same page url in the other language? It is not as simple as just replacing the /en/ with /sv/, as for example the slug could be different if one is using that. Any standard way to do this? Any helper methods?

After saving 'Page' url_path of non default languages is broken

I'm playing with this module trying to evaluate it for next project. I build small demo site, a blog to test building multi lingual website.

So the problem that I found is:
After editing and saving page that have nested url_path like:
url_path_en = /home/predrags-blog/first-blog/
url_path_sr = /home/predragov-blog/prvi-blog/

it changes url_paths to:
url_path_en = /home/predragov-blog/first-blog/
url_path_sr = /home/predragov-blog/prvi-blog/

my default language is sr and it seams that url_path of non default languages is changed to contain parent path of default language + sulg of current document in appropriate language.

This get fixed after running /manage.py set_translation_url_paths, but it is not practical for me to run it every time when I change something on website.

I make a quick fix, I hope it will be some use for you before you finding more elegant solution.

in wagtail_modeltranslation/models.py

       def set_url_path(self, parent):
        """
        This method override populates url_path for each specified language.
        This way we can get different urls for each language, defined
        by page slug.
        """
       # quick fix start ( line 422)
        if parent:
            parent = parent.content_type.model_class().objects.get(pk=parent.pk)
       # quick fix end

        for lang in settings.LANGUAGES:
            if parent:

All best

Problem with data migrations

Hi,
Imagine we have a model class MyModel(TranslationMixin, Page) with field 'description' and migrate the database. Then, we create a migration that creates a new instance of that class and run the migration. No problems so far. After this, we add a new field to the class 'name' and migrate the database.
Now the problem is when we recreate the database and run migrations, django runs the data migration and it gives an error saying the field 'name' does not exists.

In the code of 'models.py' of wagtail_modeltranslation there is a 'if' at the start of TranslationMixin init that solves this problem, but that is not a good solution because when creating a page, wagtail_modeltranslation will not patch the fields for all languages.

Anyone has any ideias of how to solve this problem?

The model "Page" is not registered for translation

After following the setup instructions I am experiencing a;
wagtail_modeltranslation.translator.NotRegistered: The model "Page" is not registered for translation

When running; manage.py makemigrations

Setup is;
Python==3.4
wagtail==1.2
wagtail-modeltranslation==0.3.4
Django==1.8.7

Wagtail project is a basic setup from the wagtail documentation (creating your first app)

The model is question is just;

class HomePage(TranslationMixin, Page):
    body = RichTextField(blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('body', classname="full")
    ]

[Feature] Form Page translation

Hi guys, i have a problem trying translate a Form page:

typeerror at -admin-pages-3-edit- - mozilla firefox_019
typeerror at -admin-pages-3-edit- - mozilla firefox_020

I think that this happen because model translation wants translate all form fields childs; why? because i have other FormPage but this haven't formfields childs, have a custom form.
wagtail - new affiliate registration s page - mozilla firefox_063
As you can see here aren't problem for form fields.

Can anyone help with this?

Thank you.

Changing title shouldn't change slug on live pages

Changing the title of a live page also changes its slug, without warning and with usability/SEO implications.

This was also the case in wagtail itself, fixed with wagtail/wagtail#1810 for wagtail/wagtail#528 preventing a slug change when the page is live.

The fix for wagtail-modeltranslation should be in wagtail_translated_slugs.js:9

if ($('body').hasClass('create') || (!$('#id_slug_'+lang_code).data('previous-val').length || cleanForSlug($('#id_title_'+lang_code).data('previous-val')) === $('#id_slug_'+lang_code).data('previous-val'))) {
// only update slug if the page is being created from scratch, if slug is completely blank, or if title and slug prior to typing were identical

Not sure why the last check "if title and slug prior to typing were identical" is required/sensible?

[CleandUP] [Optionally]Promote panels ordering

Do not misunderstand me friend, I really find it a very useful alternative multilanguage Wagtail, django-cms uses the same type of fields to multi-language pages, and the same is to get reports, to help and ideas.

I think about promote panels that should be more tidy and elegant:
promote panels tr

As you can see in the picture, all the fields appear one after the other, and it looks pretty bad, I think it best to put the fields in each language in separate panels and the end panel of the image is separated, thisIt gives more order and stilo page.

promote panels fin

InlinePanels not being patched

The panels on inlines are not being patched even when that model is registered. This happens because the patching method is getting the panels of the parent page instead of the inline model itself.

[Feature] Snippets translation

Hi guys, how are you?

I want talk about something a few important: translate snippets.

Isn't very important at first view but it's simple thing, snippets, at least wagtail demo snippets have some unique field for translation: text. I think that will be ugly have all weg site translate except a snippet, don't it?

Ok, i try to translate a snippet and i have the next problem with it:
attributeerror at -admin-snippets-core-advert- - mozilla firefox_059
seleccion_060
seleccion_061

Can do you anithing for solve it? Thanks.

PD: I can verify what happen if i try add new snippet:
attributeerror at -admin-snippets-core-advert-add- - mozilla firefox_062

Problem with language_code setting

I try fix the other issue and one time i can see this problem:
'Page' haven't the 'slug_es-co' .

And the traceback show this:

for lang in settings.LANGUAGES:
            if parent:
                tr_slug = getattr(self, 'slug_'+lang[0])
                if not tr_slug:
                    tr_slug = getattr(self, 'slug_'+settings.LANGUAGE_CODE)

I have this in settings:

LANGUAGE_CODE = 'es-co'  # Por defecto'en-us'
LANGUAGES = (
    ('es',  _('Spanish')),
    ('en',  _('English')),
    ('tr',  _('Turkish')),
)

I think this see in my db and i can't fine this slug: slug_es-co, why?
Then, i delete '-co' and works.

The problem is get the LANGUAGE_CODE completly, i think that will good strip this characters for fix this problem :D

Inline not working

in my translation.py:

class HomePageCarouselImageTR(TranslationOptions):
    fields = ('featured_phrase',)

translator.register(HomePageCarouselImage, HomePageCarouselImageTR)

in my models.py:

class HomePageCarouselImage(TranslationMixin, Orderable, ImageBasedModel):
    featured_phrase = RichTextField(
        blank=True, null=True,
        verbose_name=u'Frase de destaque', max_length=120)
    page = ParentalKey('core.HomePage', related_name='carousel_images')

    panels = [
        ImageChooserPanel('image'),
        FieldPanel('featured_phrase', classname='full'),
    ]

error:
Internal Server Error: /admin/pages/new/core/homepage/1/
Traceback (most recent call last):
File "/home/diogo/Projects/django-minhoin/virtualenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
response = wrapped_callback(request, _callback_args, *_callback_kwargs)
File "/home/diogo/Projects/django-minhoin/virtualenv/local/lib/python2.7/site-packages/django/views/decorators/cache.py", line 38, in _cache_controlled
response = viewfunc(request, _args, *_kw)
File "/home/diogo/Projects/django-minhoin/virtualenv/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
return view_func(request, _args, *_kwargs)
File "/home/diogo/Projects/django-minhoin/virtualenv/local/lib/python2.7/site-packages/wagtail/wagtailadmin/views/pages.py", line 144, in create
page = page_class(owner=request.user)
File "/home/diogo/Projects/django-minhoin/virtualenv/local/lib/python2.7/site-packages/modeltranslation/translator.py", line 218, in new_init
old_init(self, _args, *_kwargs)
File "/home/diogo/Projects/django-minhoin/minhoin/apps/wagtail_modeltranslation/models.py", line 62, in init
form = edit_handler_class.get_form_class(self.class)
File "/home/diogo/Projects/django-minhoin/virtualenv/local/lib/python2.7/site-packages/wagtail/wagtailadmin/edit_handlers.py", line 200, in get_form_class
formsets=cls.required_formsets(), widgets=cls.widget_overrides())
File "/home/diogo/Projects/django-minhoin/virtualenv/local/lib/python2.7/site-packages/wagtail/wagtailadmin/edit_handlers.py", line 316, in required_formsets
formsets.update(handler_class.required_formsets())
File "/home/diogo/Projects/django-minhoin/virtualenv/local/lib/python2.7/site-packages/wagtail/wagtailadmin/edit_handlers.py", line 316, in required_formsets
formsets.update(handler_class.required_formsets())
File "/home/diogo/Projects/django-minhoin/virtualenv/local/lib/python2.7/site-packages/wagtail/wagtailadmin/edit_handlers.py", line 601, in required_formsets
child_edit_handler_class = cls.get_child_edit_handler_class()
File "/home/diogo/Projects/django-minhoin/virtualenv/local/lib/python2.7/site-packages/wagtail/wagtailadmin/edit_handlers.py", line 595, in get_child_edit_handler_class
cls._child_edit_handler_class = MultiFieldPanel(panels, heading=cls.heading).bind_to_model(get_related_model(cls.related))
File "/home/diogo/Projects/django-minhoin/virtualenv/local/lib/python2.7/site-packages/wagtail/wagtailadmin/edit_handlers.py", line 409, in bind_to_model
'children': [child.bind_to_model(model) for child in self.children],
AttributeError: 'dict' object has no attribute 'bind_to_model'

Add Admin screenshot

I think that in order to have a good understand of what this app could do. A screenshot of the admin panel would help with that.

Working on wagtail-modeltranslation Documentation

You can take a look in the wiki (left sidebar) where I have started working on the wagtail-modeltranslation documentation.

If you can help in any way, it would be greatly appreciated.

Suggestions and corrections are also welcomed.

I plan on having it hosted on readthedocs.org later.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.