Django parler的翻译标签未显示在视图中

lnlaulya  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(154)

我正在使用Django parler来翻译我的模型。现在我正在创建一个自定义的管理面板,我有一个创建和更新内容的视图。我正在使用一个基于类的视图,继承自“视图”的创建和更新视图,所以我不能使用TranslatableCreateView和TranslatableUpdateView。我在Django parler的代码中看到,使用TranslatableModelFormMixin,你可以添加翻译支持到基于类的视图。我使用了这个mixin,但仍然无法访问语言选项卡。
这里是Views.py:

class ContentCreateUpdateView(TranslatableModelFormMixin, TemplateResponseMixin, View):
module = None
model = None
obj = None
template_name = 'content-form.html'

def get_model(self, model_name):
    if model_name in ['text', 'video', 'image', 'file']:
        return apps.get_model(app_label='courses', model_name=model_name)
    return None

def get_form(self, model, *args, **kwargs):
    Form = modelform_factory(model, exclude=['owner',
                                             'order',
                                             'created',
                                             'updated'])
    return Form(*args, **kwargs)

def dispatch(self, request, module_id, model_name, id=None):
    self.module = get_object_or_404(Module, id=module_id, course__owner=request.user)
    self.model = self.get_model(model_name)
    if id:
        self.obj = get_object_or_404(self.model,
                                     id=id,
                                     owner=request.user)
    return super().dispatch(request, module_id, model_name, id)

def get(self, request, module_id, model_name, id=None):
    form = self.get_form(self.model, instance=self.obj,)
    return self.render_to_response({'form': form, 'object': self.obj})

def post(self, request, module_id, model_name, id=None):
    form = self.get_form(self.model, instance=self.obj, data=request.POST, files=request.FILES)
    if form.is_valid():
        obj = form.save(commit=False)
        obj.owner = request.user
        obj.save()
        if not id:
            # new content
            Content.objects.create(module=self.module, item=obj)
        return redirect('module_content_list', self.module.id)
    return self.render_to_response({'form': form, 'object': self.obj})

模板:

{% extends '_base.html' %}
{% load crispy_forms_tags %}
{% load crispy_forms_filters %}

{% block content %}
<div class="col-md-12">
    <!-- Horizontal Form -->
    <div class="card card-primary">
        <div class="card-header ">
            {% if object %}
                <h3 class="card-title mb-0 float-left"> Edit Content "{{ object.title }}"</h3>
            {% else %}
                <h3 class="card-title mb-0 float-left"> Add New Content</h3>
            {% endif %}
        </div>
        <!-- /.card-header -->
        <!-- form start -->
        <div class="card-body">
            <form method="post" enctype="multipart/form-data">
                <div class="row">
                    <div class="col-12">
                        {% if language_tabs %}
                            <ul class="nav nav-tabs">
                                {% for url,name,code,status in language_tabs %}
                                    {% if status == 'current' %}
                                        <input type="hidden" class="language_button selected" name="{{ code }}"/>
                                        <li class="nav-item">
                                            <a class="current nav-link active"
                                               aria-selected="true">{{ name }}</a>
                                        </li>
                                    {% else %}
                                        <li class="nav-item">
                                            <a class="{{ status }} nav-link"
                                               href="{{ url }}"
                                               aria-selected="false">{{ name }}</a>
                                        </li>
                                    {% endif %}
                                {% endfor %}
                            </ul>
                        {% endif %}
                    </div>

                    <div class="col-6">
                        
                        {{ form }}

                    </div>
                </div>
                {% csrf_token %}
                <div class="col-6">
                    <button class="btn btn-success">Save Content</button>
                </div>
            </form>
        </div>
    </div>
</div>
<!-- /.card -->

{%结束块%}
下面是django parler的源代码:

class TranslatableModelFormMixin(LanguageChoiceMixin):
"""
Mixin to add translation support to class based views.

For example, adding translation support to django-oscar::

    from oscar.apps.dashboard.catalogue import views as oscar_views
    from parler.views import TranslatableModelFormMixin

    class ProductCreateUpdateView(TranslatableModelFormMixin, oscar_views.ProductCreateUpdateView):
        pass
"""

def get_form_class(self):
    """
    Return a ``TranslatableModelForm`` by default if no form_class is set.
    """
    super_method = super().get_form_class
    # no "__func__" on the class level function in python 3
    default_method = getattr(
        ModelFormMixin.get_form_class, "__func__", ModelFormMixin.get_form_class
    )
    if not (super_method.__func__ is default_method):
        # Don't get in your way, if you've overwritten stuff.
        return super_method()
    else:
        # Same logic as ModelFormMixin.get_form_class, but using the right form base class.
        if self.form_class:
            return self.form_class
        else:
            model = _get_view_model(self)
            if self.fields:
                fields = self.fields
                return modelform_factory(model, form=TranslatableModelForm, fields=fields)
            else:
                return modelform_factory(model, form=TranslatableModelForm)

def get_form_kwargs(self):
    """
    Pass the current language to the form.
    """
    kwargs = super().get_form_kwargs()
    # The TranslatableAdmin can set form.language_code, because the modeladmin always creates a fresh subclass.
    # If that would be done here, the original globally defined form class would be updated.
    kwargs["_current_language"] = self.get_form_language()
    return kwargs

# Backwards compatibility
# Make sure overriding get_current_language() affects get_form_language() too.
def get_form_language(self):
    return self.get_current_language()

选项卡应如下所示:

但现在看起来是这样的:

如果有人有类似的经验,请随时写你的意见

htrmnn0y

htrmnn0y1#

在settings.py档案中,找到PARLER_LANGUAGES设定,并将“无”变更为SITE_ID。

PARLER_LANGUAGES = {
    1: (
        {'code': 'en', },  # English
        {'code': 'ru', },  # Russian
    ),
    'default': {
        'fallbacks': ['en'],
        'hide_untranslated': False,
    }
}

相关问题