0

我无法仅访问模板中的 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 = "library/page/library_page.html" 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

它是这样显示的: 错误图片

这是模型:

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 中,在显示标题的四个空对象之后,我不想显示空对象,并且在上面我上传了找不到图像 url 的图像,因此我需要在模板中检查空对象或我必须添加的视图模型翻译的正确过滤器

>>> 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>
4

0 回答 0