I am developing a django multilingual app and using django-modeltranslation to translate the models. It works fine except one thing: when translation is not available in a specific language, it still shows the objects (let's say posts). I have some posts that are available in tajik while not available in russian, and vice versa.

My goal is to disable showing the posts in the language which I do not have translation. May be by showing 404 or any other way, but it should not show the posts at all, not partially

Here are my settings: 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')

My 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)

Is there anything I am setting wrong with modeltranslation? How can I disable showing posts that are not available in Russian (or tajik)?

1

There are 1 answers

0
Saidmamad On BEST ANSWER

So basically, I have put an if statement, which checks if a field is empty. If so, that it excludes the object.

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)

Or, more shorter:

posts = Post.objects.filter(status='published').exclude(ShortDesc__exact=None)

Probably there are different more efficient ways to do that.