如何:Django Parler CRUD 表单

How to: Django Parler CRUD Forms

我正在使用 Parler 来本地化我的模型。

Django Admin 工作正常,但现在我想在前端重新创建管理表单。

到目前为止,我可以创建一个新模型,但它总是以默认语言创建。 现在的问题是,如何设置语言?

最好的情况是,我可以通过表单中的 <select> select 语言,但默认值将由 get param language=iso_code 设置,或者如果它使用 Django Admin 中的语言选项卡更容易。

编辑: 问题似乎出在 class.

形式的某处

型号

class Category(MPTTModel, TranslatableModel):
    title = TranslatedField(any_language=True)
    description = TranslatedField()
    slug = TranslatedField()
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children',
                            db_index=True)

    objects = CategoryManager()

    def save(self, *args, **kwargs):
        super(Category, self).save(*args, **kwargs)


class CategoryTranslation(TranslatedFieldsModel):
    title = models.CharField(max_length=200)
    description = models.TextField(null=True)
    slug = models.SlugField()

    master = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='translations')

    class Meta:
        unique_together = (
            ('language_code', 'slug'),
        )

查看

@method_decorator(login_required, name='dispatch')
class CategoriesCreateView(TranslatableCreateView):
    model = Category
    context_object_name = 'categories'
    template_name = 'categories/update.html'
    form_class = CategoryForm
    object = Category()

    def get(self, request, *args, **kwargs):
        request.DEFAULT_LANGUAGE = LANGUAGE_CODE
        request.meta_title = _('Create Category')
        return super().get(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        request.DEFAULT_LANGUAGE = LANGUAGE_CODE
        request.meta_title = _('Create Category')
        return super().post(request, *args, **kwargs)

表格

class CategoryForm(TranslatableModelForm):
    use_required_attribute = False

    title = TranslatedField()
    description = TranslatedField()
    slug = TranslatedField()
    parent = TreeNodeChoiceField(queryset=Category.objects.all())

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.form_action = '.'
        self.helper.form_class = 'form-horizontal form-bordered'
        self.helper.label_class = 'col-lg-3'
        self.helper.field_class = 'col-lg-8'

        self.helper.layout = self.__get_layout()
        super().__init__(*args, **kwargs)
        self.fields['parent'].required = False

    @staticmethod
    def __get_layout():
        layout = Layout(
            Field('parent'),
            Field('title'),
            Field('slug'),
            Field('description'),
            ButtonHolder(
                Submit('submit', _('Save'))
            )
        )
        return layout

    class Meta:
        model = Category
        fields = ['title', 'description', 'slug', 'parent']

当然该死的解决方案非常简单。

问题是,self.helper.form_action = '.' 覆盖了所有获取参数,其中包括 language/translation。