如何访问模板中的Django模型转换字段?

时间:2016-04-09 13:10:08

标签: python django django-modeltranslation

我无法只访问模板中的Django Translated字段,只要它在模板中返回Null,就会显示它。 以下是我的模板代码示例:

{% for book in books %}
        <div class="item">
            <a href="/{{ lang }}/{% get_attr book 'file_' lang %}" title="{% get_attr book 'title_' lang %}">
                <img src="/media/{% get_attr book 'file_preview_' lang %}"/>
            </a>
        </div>
    {% empty %}
        <h3>Empty</h3>
    {% endfor %}

这是我的视图代码示例:

类BooksView(TemplateView):     template_name =&#34; library / page / library_page.html&#34;     model = Book

def get_context_data(self, **kwargs):
    context = super(BooksView, self).get_context_data(**kwargs)
    context.update(modules.standard(self.request, kwargs))
    context['books'] = Book.objects.filter(published=True, )

    return context

它显示如下: Error pictures

这是模特:

class Book(models.Model):
    title = models.CharField(max_length=100)
    file = models.FileField(upload_to='library/file/%Y/%m/%d')
    file_preview = models.FileField(upload_to='library/file_preview/%Y/%m/%d')
    publishedTime = UnixDateTimeField(auto_now=True)
    published = models.BooleanField(default=True)


    def __unicode__(self):
        return self.title

在django shell中,在显示标题的四个空对象之后,我不想显示NULL对象,上面我上传了无法找到图片网址的图片,因此我需要在模板中查看null对象或视图我必须为modeltranslation添加正确的过滤器

>>> l = Book.objects.order_by('pk')
>>> l
[<Book: Book 1 en>, <Book: Second book en>, <Book: Third book 3>, <Book: Fourth book en>, <Book: Fifth book en>]
>>> for x in l:
...     print x.pk,"-",x.title_ru
... 
1 - 
2 - 
3 - 
4 - 
5 - Pyataya kniga ru


<div class="books">
    <div class="item">
      <a href="/ru/" title="">
        <img src="/media/">
      </a>
    </div>
    <div class="item">
      <a href="/ru/" title="">
        <img src="/media/">
      </a>
   </div>
   <div class="item">
      <a href="/ru/" title="">
         <img src="/media/">
      </a>
   </div>
   <div class="item">
      <a href="/ru/" title="">
         <img src="/media/">
      </a>
   </div>
   <div class="item">
      <a href="/ru/library/file/2016/04/08/Computer_Glossary.pdf" title="Pyataya kniga ru">
        <img src="/media/library/file_preview/2016/04/08/pdf_2.jpg" style="
width: 100px;
height: 100px; ">
      </a>
   </div>
 </div>

0 个答案:

没有答案