【问题标题】:Django foreign key in template模板中的Django外键
【发布时间】:2017-06-14 08:41:49
【问题描述】:

在我正在构建的网站的主页上,我试图从两个应用程序中提取数据,博客和投资组合。博客运行良好,但投资组合没有出现。我认为这是因为我的模型中有外键。我选择这个项目结构是因为该站点主要是一个博客,但我希望主页在侧栏上显示一些最近的作品集。如您所见,index.html 模板不需要 Portfolio.portfolio 模型中的所有信息,因此我尝试仅导入部分字段。 如何在我的模板中包含外键关系,以便数据可以遍历应用程序?

模板 - index.html

{% for i in IndexPortfolio %}
    <div class="col-xs-12 col-sm-6 thumb">
        <a class="thumbnail" href="{{ IndexPortfolio.get_absolute_url }}">
            <img class="img-responsive" src="{{ IndexPortfolio.cover_image.url }}" alt="">
            <p>{{ portfolio.title }}/{{ portfolio.client_name }}</p>
        </a>
    </div>
{% endfor %}

项目结构

mysite/
blog/
   templates/
        blog/
            blog_list.html
            blog_detail.html
        index.html
        bio.html
        resume.html
   models.py
   views.py
portfolio/
    templates/
        portfolio_list.html
        portfolio_detail.html
    models.py
    views.py

blog/models.py

from django.db import models
from datetime import date
from django.urls import reverse  # Used to generate URLs by reversing the URL patterns

class IndexPortfolio(models.Model):
    title = models.ForeignKey('portfolio.Portfolio', related_name='ip_title')
    client_name = models.ForeignKey("portfolio.Portfolio", related_name='ip_client_name')
    post_date = models.ForeignKey("portfolio.Portfolio", related_name='ip_post_date')
    cover_image = models.ForeignKey("portfolio.Portfolio",  related_name='ip_cover_image')

    class Meta:
        ordering = ["post_date"]
        verbose_name_plural = "Homepage Highlights - Best Portfolio Pieces"

    def ip_get_absolute_url(self):
    """
    Returns the url to access a particular portfolio piece instance.
    """
        return reverse('portfolio-detail', args=[str(self.id)])

    def __str__(self):
    """
        String for representing the Model object.
    """
        return self.ip_title

blog/views.py

from django.shortcuts import render
from django.views import generic
from .models import Blog, IndexPortfolio


def index(request):
"""
View function for home page of site.
"""
# Generate most recent blog and portfolio post
    portfolio_list = IndexPortfolio.objects.all().order_by('-post_date')[0:6]
    blog_list = Blog.objects.all().order_by('-post_date')[0:15]
# Render the HTML template index.html with the data in the context variable.

    return render(
         request,
         'index.html',
         context={'portfolio_list': portfolio_list,
                  'blog_list': blog_list,
                  }
    )

portfolio/models.py

from django.db import models
from datetime import date
from django.urls import reverse  # Used to generate URLs by reversing the URL patterns


    class Portfolio(models.Model):
"""
Model representing a portfolio piece.
"""
    title = models.CharField(max_length=200)
    client_name = models.CharField(max_length=200, blank=True)
    content = models.TextField(max_length=4000)
    post_date = models.DateField(default=date.today)
    cover_image = models.ImageField(null=True, blank=True)
    image = models.ImageField(null=True, blank=True)

    CLIENT_TYPES = (
        ('a', 'agency'),
        ('p', 'personal project'),
        ('f', 'freelance'),
        ('n', 'nonprofit'),
   )

    client_type = models.CharField(max_length=1, choices=CLIENT_TYPES, blank=True, default='p', help_text='Client type')

    class Meta:
        ordering = ["post_date"]
        verbose_name_plural = "Portfolio Pieces"

    def get_absolute_url(self):
    """
    Returns the url to access a particular portfolio piece instance.
    """
        return reverse('portfolio-detail', args=[str(self.id)])

    def __str__(self):
    """
    String for representing the Model object.
    """
        return self.title

【问题讨论】:

  • 您只将portfolio_list 暴露给模板,所以可能{% for portfolio in portfolio_list %}...?
  • 您已经将包含投资组合实例的查询集拉入您的模板上下文中。你只需要正确使用它。

标签: django django-models django-templates django-views


【解决方案1】:

blog/views.py:使用Portfolio模型,初始化portfolio_list

from django.shortcuts import render
from django.views import generic
from .models import Blog
from portfolio.models import Portfolio


def index(request):
    """
    View function for home page of site.
    """
    # Generate most recent blog and portfolio post
    portfolio_list = Portfolio.objects.all().order_by('-post_date')[0:6]
    blog_list = Blog.objects.all().order_by('-post_date')[0:15]
    # Render the HTML template index.html with the data in the context variable.

    return render(
         request,
         'index.html',
         context={'portfolio_list': portfolio_list,
                  'blog_list': blog_list,
                  }
    )

模板 - index.html:知道,在你的循环中使用portfolio_list

{% for p in portfolio_list %}
    <div class="col-xs-12 col-sm-6 thumb">
        <a class="thumbnail" href="{{ p.get_absolute_url }}">
            <img class="img-responsive" src="{{ p.cover_image.url }}" alt="">
            <p>{{ p.title }}/{{ p.client_name }}</p>
        </a>
    </div>
{% endfor %}

【讨论】:

    【解决方案2】:

    事实证明,我必须为“portfolio.models”添加导入,并更改一些语法。之后,它显示来自跨应用模型的数据。结果,我能够删除我在 blog/models.py 中进行的所有 IndexPortfolio 内容,因为在我找到了导入其他应用程序模型的正确方法之后,那时就没有必要了。

    blog/views.py

    from django.shortcuts import render
    from django.views import generic
    from .models import Blog
    from portfolio.models import Portfolio
    
    
    def index(request):
        """
        View function for home page of site.
        """
        # Generate most recent blog and portfolio post
        portfolio_list = Portfolio.objects.all().order_by('-post_date')[0:6]
        blog_list = Blog.objects.all().order_by('-post_date')[0:15]
        # Render the HTML template index.html with the data in the context variable.
    
        return render(
             request,
            'index.html',
             context={'portfolio_list': portfolio_list,
                      'blog_list': blog_list,
                     }
        )
    

    模板 - index.html

    {% for portfolio in portfolio_list %}
        <div class="col-xs-12 col-sm-6 thumb">
            <a class="thumbnail" href="{{ portfolio.get_absolute_url }}">
                <img class="img-responsive" src="{{ portfolio.cover_image.url }}" alt="">
                <p>{{ portfolio.title }}/{{ portfolio.client_name }}</p>
            </a>
        </div>
    {% endfor %}
    

    【讨论】:

    • 所以我的回答对你有帮助吗?我按照您的建议编辑导入。如果她解决了您的问题,您可以接受答案。很高兴为您提供帮助
    猜你喜欢
    • 2011-11-04
    • 2012-08-30
    • 2015-02-21
    • 2021-07-12
    • 2020-09-02
    • 2019-07-31
    • 2016-09-14
    相关资源
    最近更新 更多