django-modeltranslation:如何禁用显示没有翻译的语言的对象(例如帖子)?
django-modeltranslation: how to disable showing objects (e.g. posts) for the languages that it doesn't have translation?
我正在开发一个 django 多语言应用程序并使用 django-modeltranslation 来翻译模型。它工作正常,除了一件事:当翻译不可用特定语言时,它仍然显示对象(比方说帖子)。我有一些帖子在塔吉克语中可用,但在俄语中不可用,反之亦然。
我的目标是禁止以我没有翻译的语言显示帖子。可能是通过显示 404 或任何其他方式,但它根本不应该显示帖子,而不是部分
这是我的设置:
settings.py
LANGUAGES = [
('ru', _('Russian')),
('tg', _('Tajik')),
# ('en', _('English')),
]
EXTRA_LANG_INFO = {
'tg': {
'bidi': False,
'code': 'tg',
'name': 'Tajik',
'name_local': u'Тоҷикӣ',
},
}
# Add custom languages not provided by Django
LANG_INFO = dict(list(django.conf.locale.LANG_INFO.items()) + list(EXTRA_LANG_INFO.items()))
django.conf.locale.LANG_INFO = LANG_INFO
global_settings.LANGUAGES = global_settings.LANGUAGES + [("tg", 'Tajik')]
LANGUAGE_CODE = 'ru'
# from modeltranslation.settings import ENABLE_REGISTRATIONS
MODELTRANSLATION_LANGUAGES = ('tg','ru')
MODELTRANSLATION_DEFAULT_LANGUAGE = ('tg')
MODELTRANSLATION_FALLBACK_LANGUAGES = ('ru', 'tg')
transation.py
from modeltranslation.translator import translator, TranslationOptions
from blog.models import Post, Matlab
class BlogPostTranslationOptions(TranslationOptions):
fields = ('Title', 'ShortDesc', 'Content')
translator.register(Post, BlogPostTranslationOptions)
models.py:
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Черновик'),
('published', 'Опубликованно'),
)
POST_TYPE_CHOICES = (
('image', 'Image'),
('video', 'Video'),
)
Title = models.CharField("Заголовок публикации", blank=True, max_length=250, help_text="Введите заголовок публикации")
Slug = models.SlugField(max_length=250, blank=True, unique=True, help_text="Введите ссылку публикации. Нап.: eto-publikaciya")
ShortDesc = models.TextField("Короткое Описание", blank=True, help_text="Введите короткое описание публикации")
Content = RichTextUploadingField("Полное Описание", blank=True, help_text="Введите контент публикации")
# author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
avtor = models.ForeignKey(Specialist, on_delete=models.SET_NULL, null=True, default=None, blank=True)
posttype = models.CharField(max_length=10, choices=POST_TYPE_CHOICES, default='image')
Image = ProcessedImageField(upload_to='blog/%Y/%m/%d/',
processors=[ResizeToFill(1200, 768)],
format='JPEG',
options={'quality': 60}, blank=False)
image_thumbnail = ImageSpecField(source='Image',
processors=[ResizeToFill(768, 500)],
format='JPEG',
# options={'quality': 60}
)
VideoEmbedCode = models.TextField("Embed код видео", blank=True, help_text="Введите Embed код публикации")
# published = models.DateTimeField(auto_now=True)
tags = TaggableManager(through=TaggedPost, blank=True)
allow_commenting = models.BooleanField("Разрешить комментирование", default=True)
hide_comments = models.BooleanField("Скрыть комментариев", default=False)
Created = models.DateTimeField(auto_now_add=True)
Updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published')
我的views.py:
def blog_list(request):
template = 'blog/blog_index.html'
posts = Post.objects.filter(status='published')
common_tags = Post.tags.most_common()[:4]
recent_posts = Post.objects.filter(status='published').order_by("-Created")[:3]
#Paginator
paginator = Paginator(posts, 3) # Show n posts per page
page = request.GET.get('page')
posts = paginator.get_page(page)
# allTags = Tag.objects.all() #All tags
allBlogTags = Post.tags.all() #[:2]
# categories = Category.objects.all()
args = {
'posts': posts,
'common_tags':common_tags,
'recent_posts': recent_posts,
'allBlogTags':allBlogTags,
}
return render(request, template, args)
我对模型翻译有什么设置不对吗?
如何禁止显示俄语(或塔吉克语)不可用的帖子?
基本上,我放置了一个 if 语句,用于检查字段是否为空。如果是,则排除该对象。
def blog_list(request):
# translation.activate('tg')
template = 'blog/blog_index.html'
posts = Post.objects.filter(status='published')
if request.LANGUAGE_CODE == 'ru':
posts = posts.exclude(ShortDesc_ru__exact='')
elif request.LANGUAGE_CODE == 'tg':
posts = posts.exclude(ShortDesc_tg__exact='')
common_tags = Post.tags.most_common()[:4]
recent_posts = Post.objects.filter(status='published').order_by("-Created")[:3]
#Paginator
paginator = Paginator(posts, 6) # Show n posts per page
page = request.GET.get('page')
posts = paginator.get_page(page)
# allTags = Tag.objects.all() #All tags
allBlogTags = Post.tags.all() #[:2]
# categories = Category.objects.all()
args = {
'posts': posts,
'common_tags':common_tags,
'recent_posts': recent_posts,
'allBlogTags':allBlogTags,
}
return render(request, template, args)
或者,更短:
posts = Post.objects.filter(status='published').exclude(ShortDesc__exact=None)
可能有不同的更有效的方法来做到这一点。
我正在开发一个 django 多语言应用程序并使用 django-modeltranslation 来翻译模型。它工作正常,除了一件事:当翻译不可用特定语言时,它仍然显示对象(比方说帖子)。我有一些帖子在塔吉克语中可用,但在俄语中不可用,反之亦然。
我的目标是禁止以我没有翻译的语言显示帖子。可能是通过显示 404 或任何其他方式,但它根本不应该显示帖子,而不是部分
这是我的设置: settings.py
LANGUAGES = [
('ru', _('Russian')),
('tg', _('Tajik')),
# ('en', _('English')),
]
EXTRA_LANG_INFO = {
'tg': {
'bidi': False,
'code': 'tg',
'name': 'Tajik',
'name_local': u'Тоҷикӣ',
},
}
# Add custom languages not provided by Django
LANG_INFO = dict(list(django.conf.locale.LANG_INFO.items()) + list(EXTRA_LANG_INFO.items()))
django.conf.locale.LANG_INFO = LANG_INFO
global_settings.LANGUAGES = global_settings.LANGUAGES + [("tg", 'Tajik')]
LANGUAGE_CODE = 'ru'
# from modeltranslation.settings import ENABLE_REGISTRATIONS
MODELTRANSLATION_LANGUAGES = ('tg','ru')
MODELTRANSLATION_DEFAULT_LANGUAGE = ('tg')
MODELTRANSLATION_FALLBACK_LANGUAGES = ('ru', 'tg')
transation.py
from modeltranslation.translator import translator, TranslationOptions
from blog.models import Post, Matlab
class BlogPostTranslationOptions(TranslationOptions):
fields = ('Title', 'ShortDesc', 'Content')
translator.register(Post, BlogPostTranslationOptions)
models.py:
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Черновик'),
('published', 'Опубликованно'),
)
POST_TYPE_CHOICES = (
('image', 'Image'),
('video', 'Video'),
)
Title = models.CharField("Заголовок публикации", blank=True, max_length=250, help_text="Введите заголовок публикации")
Slug = models.SlugField(max_length=250, blank=True, unique=True, help_text="Введите ссылку публикации. Нап.: eto-publikaciya")
ShortDesc = models.TextField("Короткое Описание", blank=True, help_text="Введите короткое описание публикации")
Content = RichTextUploadingField("Полное Описание", blank=True, help_text="Введите контент публикации")
# author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
avtor = models.ForeignKey(Specialist, on_delete=models.SET_NULL, null=True, default=None, blank=True)
posttype = models.CharField(max_length=10, choices=POST_TYPE_CHOICES, default='image')
Image = ProcessedImageField(upload_to='blog/%Y/%m/%d/',
processors=[ResizeToFill(1200, 768)],
format='JPEG',
options={'quality': 60}, blank=False)
image_thumbnail = ImageSpecField(source='Image',
processors=[ResizeToFill(768, 500)],
format='JPEG',
# options={'quality': 60}
)
VideoEmbedCode = models.TextField("Embed код видео", blank=True, help_text="Введите Embed код публикации")
# published = models.DateTimeField(auto_now=True)
tags = TaggableManager(through=TaggedPost, blank=True)
allow_commenting = models.BooleanField("Разрешить комментирование", default=True)
hide_comments = models.BooleanField("Скрыть комментариев", default=False)
Created = models.DateTimeField(auto_now_add=True)
Updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published')
我的views.py:
def blog_list(request):
template = 'blog/blog_index.html'
posts = Post.objects.filter(status='published')
common_tags = Post.tags.most_common()[:4]
recent_posts = Post.objects.filter(status='published').order_by("-Created")[:3]
#Paginator
paginator = Paginator(posts, 3) # Show n posts per page
page = request.GET.get('page')
posts = paginator.get_page(page)
# allTags = Tag.objects.all() #All tags
allBlogTags = Post.tags.all() #[:2]
# categories = Category.objects.all()
args = {
'posts': posts,
'common_tags':common_tags,
'recent_posts': recent_posts,
'allBlogTags':allBlogTags,
}
return render(request, template, args)
我对模型翻译有什么设置不对吗? 如何禁止显示俄语(或塔吉克语)不可用的帖子?
基本上,我放置了一个 if 语句,用于检查字段是否为空。如果是,则排除该对象。
def blog_list(request):
# translation.activate('tg')
template = 'blog/blog_index.html'
posts = Post.objects.filter(status='published')
if request.LANGUAGE_CODE == 'ru':
posts = posts.exclude(ShortDesc_ru__exact='')
elif request.LANGUAGE_CODE == 'tg':
posts = posts.exclude(ShortDesc_tg__exact='')
common_tags = Post.tags.most_common()[:4]
recent_posts = Post.objects.filter(status='published').order_by("-Created")[:3]
#Paginator
paginator = Paginator(posts, 6) # Show n posts per page
page = request.GET.get('page')
posts = paginator.get_page(page)
# allTags = Tag.objects.all() #All tags
allBlogTags = Post.tags.all() #[:2]
# categories = Category.objects.all()
args = {
'posts': posts,
'common_tags':common_tags,
'recent_posts': recent_posts,
'allBlogTags':allBlogTags,
}
return render(request, template, args)
或者,更短:
posts = Post.objects.filter(status='published').exclude(ShortDesc__exact=None)
可能有不同的更有效的方法来做到这一点。