Django外键在模板中

时间:2017-01-28 20:58:55

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

在我正在构建的网站的主页上,我正在尝试从两个应用程序,博客和投资组合中提取数据。博客运作良好,但投资组合没有出现。我认为这是因为我的模型中有外键。我选择了这个项目结构,因为该网站主要是一个博客,但我希望主页能够在侧栏上显示最近的一些投资组合。如您所见,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

博客/ 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

博客/ 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,
                  }
    )

组合/ 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

2 个答案:

答案 0 :(得分: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 %}

答案 1 :(得分:0)

事实证明,我必须为'portfolio.models'添加导入,并改变一些语法。之后,它显示来自跨应用程序模型的数据。实际上,我能够删除我在blog / models.py中发生的所有IndexPortfolio内容,因为在我找到导入其他应用程序模型的正确方法后,此时没有必要。

<强>博客/ views.py

{% 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 %}

模板 - index.html

<body> 
    <o-premeiro-demo></o-premeiro-demo> 
  </body>