我正在使用Parler来本地化我的模型。
Django Admin 工作正常,但现在我想在前端重新创建管理表单。
到目前为止,我可以创建一个新模型,但它始终以默认语言创建。现在的问题是,我该如何设置语言?
最好的情况是,我可以<select>
在表单中选择语言,但默认值将由 get 参数设置,language=iso_code
或者如果使用 Django Admin 中的语言选项卡更容易。
编辑:问题似乎出在表单类的某个地方。
模型
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']