2017-01-28 5 views
1

На главной странице сайта, который я создаю, я пытаюсь извлечь данные из двух приложений: «Блог и портфолио». Блог работает отлично, но портфолио не появляется. Я предполагаю, что это потому, что у меня есть внешние ключи в моей модели. Я выбрал эту структуру проекта, потому что сайт является преимущественно блогом, но я хочу, чтобы главная страница показывала некоторые недавние работы с портфолио на боковой панели. Как вы можете видеть, для шаблона index.html не требуется вся информация из модели Portfolio.portfolio, поэтому я попытался импортировать только некоторые из полей. Как включить отношение внешнего ключа в мой шаблон, чтобы данные могли проходить через приложения?Внешний вид Django в шаблоне

Шаблон - 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 
+0

Вы только разоблачил 'portfolio_list' шаблону, поэтому, вероятно,' {% для портфеля in portfolio_list%} ... '? – thebjorn

+0

Вы уже вытащили запрос, содержащий экземпляры портфолио, в ваш контекст шаблона. Вы просто должны правильно использовать его. – trixn

ответ

0

Оказывается, мне пришлось добавить импорт для «portfolio.models», и изменить вокруг некоторых из синтаксиса. После этого он отображает данные из кросс-приложений. В качестве эффекта я смог удалить все материалы IndexPortfolio, которые у меня были в блоге/models.py, потому что в этот момент это было необязательно после того, как я понял правильный способ импортировать модель другого приложения.

блог/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 %} 
+0

Итак, мой ответ вам поможет? Я редактирую импорт, как вы предлагаете. Вы можете принять ответ, если она решила вашу проблему. Рад помочь вам – Wilfried

1

блог/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 %} 
Смежные вопросы