Django 1.6:在另一个模板中显示特定模型对象

时间:2014-12-15 13:30:22

标签: python django django-models django-views

在一个应用程序上工作我有一对多的关系,我有很多产品,一些特定的产品只与一个网站有关。

在我的主页上,我从网站模型显示我列出的网站。我想展示产品,当用户点击我的主页上的任何一个slu to时,会重定向到一个产品页面(另一个模板),我将产品型号相关的所有对象都显示在该特定网站上。

以下是我的用户流程

主页 - >点击网站(' / browse / website_slug')--->转到 - >产品页面(仅填充相关点击的产品对象)

我的product_extend应用程序中的Models.py

产品型号:

class Product(models.Model):
    """
    The product structure for the application, the products we scrap from sites will model this and save directly into the tables.
    """

    product_name = models.CharField(max_length=254, verbose_name=_('Name'), null=True, blank=True)
    product_price = CurrencyField( verbose_name=_('Unit price') )
    product_slug_url = models.URLField(max_length=200,  null=True, blank=True)
    product_category = models.CharField(max_length=254, blank=True, null=True)
    product_img = models.ImageField('Product Image', upload_to='product_images', null=True, blank=True) 
    product_website_url = models.URLField(max_length=200,  null=True, blank=True) 
    product_website_name = models.CharField(max_length=254, blank=True, null=True)

    #For Admin Purposes, to keep track of new and old items in the database by administrative users
    date_added = models.DateTimeField(auto_now_add=True, null=True, blank=True, verbose_name=_('Date added'))
    last_modified = models.DateTimeField(auto_now=True, null=True, blank=True, verbose_name=_('Last modified') )

    #For Admin Purposes, to make sure an item is active by administrative users
    active = models.BooleanField(default=True, verbose_name=_('Active') )

    # Foreign Key
    website = models.ForeignKey(Website, null=True, related_name='website_to_product')

网站模型

class Website(models.Model):
    name = models.CharField(max_length=254, blank=True, null=True, unique=True)
    description = models.TextField(null=True, blank=True)
    website_slug = models.SlugField(verbose_name=_('Website Slug'), unique=True)
    site_logo = models.ImageField('Websites Logo', upload_to='website_logo_images', null=True, blank=True) 

    menswear = models.BooleanField(default=False, verbose_name=_('Menswear'))
    womenswear = models.BooleanField(default=False, verbose_name=_('Womenswear'))


    active = models.BooleanField(default=True, verbose_name=_('Active'))

我的product_extend应用程序中的视图

view.py

 class ProductView(ListView):

    context_object_name = 'product_list'
    template_name = 'product_extend/_productlist.html'
    # queryset = ProductExtend.objects.filter(id=1)
    model = Product

    def get_context_data(self, **kwargs):
        context = super(ProductView, self).get_context_data(**kwargs)
        return context

class WebsiteView(ListView):

context_object_name = 'home'
template_name = 'homepage.html'
queryset = Website.objects.order_by('name')
model = Website

def get_context_data(self, **kwargs):
    context = super(WebsiteView, self).get_context_data(**kwargs)
    return context

模板

Homepage.html

  {% for object in home %}
        <li class="page_tiles-home home-website-reveal"> 
            <a href="browse/website_slug" data-title="{{object.name}}" data-description="{{object.description}}">
                <img alt="{{object.name}}" src="{{MEDIA_URL}}{{object.site_logo}}" />
            </a> 
        </li>  
    {% endfor %}

Product.html

{% for object in product_list %}
    <li class="col n-4">
        <figure class="rollover site">
            <div class="scrap-likes"><span class="icon-heart"></span></div>
            <img src="{{object.product_img}}" width="470" height="700">
           <!--  <div class="scrap-from"> Scrapped from:<a class="scrap-site" target="_blank" href="{{object.product_website_url}}">{{object.product_website_name}}</a></div> -->
            <div class="scrap-designer"> Scrapped from: <a class="scrap-site" target="_blank" href="{{object.product_website_url}}">{{object.product_website_name}}</a></div>
            <div class="scrap-title">{{object.product_name }}, <span class="scrap-price">${{object.product_price}}</span></div>
            <a class="scrap-buy" target="_blank" href="{{object.product_slug_url}}">View Item</a>
        </figure>
    </li>
    {% endfor %}

网址

我的应用urls.py

  urlpatterns = patterns('',
     url(r"^$", WebsiteView.as_view(), name="home"),
     url(r'^browse/', include('product_extend.urls')),
    )

我的应用product_extend urls.py

  urlpatterns = patterns('',
     ??? No clue what to put ???
   )

2 个答案:

答案 0 :(得分:2)

您可以在 product_extend urls.py

中添加此内容
urlpatterns = patterns('',
    url(r'^(?P<website_slug>[\w]+)$', ProductView.as_view(), name='products_list'),
)

然后在ProductView覆盖get_queryset方法,使用website_slug过滤查询集:

class ProductView(ListView):

    context_object_name = 'product_list'
    template_name = 'product_extend/_productlist.html'
    # queryset = ProductExtend.objects.filter(id=1)
    model = Product

    def get_context_data(self, **kwargs):
        context = super(ProductView, self).get_context_data(**kwargs)
        return context

    def get_queryset(self):
        qs = super(ProductView, self).get_queryset()
        return qs.filter(website__website_slug__exact=self.kwargs['website_slug'])

答案 1 :(得分:0)

读完两次后,想想你想要的是:

url(r'^product/website/(?P<slug>)$', "your_view_to_peform_product_search_for_slug_website_here"),

并在您的视图“HTML”

href="product/website/{{ website.slug }}"
像这样......