2 types of products in the same view

0

How can I list 2 product types in index (Pizzas and Drinks) by defining an order by and dividing% divs of the pizzas), follow what I have:

class IndexListView(ListView):
    model = Product
    template_name = 'inicio.html'
    context_object_name = 'products'
    paginate_by = 5

I would like an explanation of what would be the best way to do this.

    
asked by anonymous 21.04.2017 / 17:37

1 answer

0

The "best way to do this" is a little subjective, it essentially depends on the context. Let's create a small application to try to solve the problem, I'll report the steps (my environment is Linux):

1) Create a project called pizza, and an app called core:

$ django-admin startproject pizza
$ cd pizza
$ ./manage.py startapp core 

2) Edit the core models file (core / models.py) and make it the following content:

from django.db import models

class Pizza(models.Model):
    codigo = models.CharField(max_length=5)
    descricao = models.CharField(max_length=100)
    preco = models.DecimalField(verbose_name='preço',decimal_places=2, max_digits=9)

    def __str__(self):
        return self.descricao

class Bebida(models.Model):
    codigo = models.CharField(max_length=5)
    descricao = models.CharField(max_length=100)
    preco = models.DecimalField(verbose_name='preço', decimal_places=2, max_digits=9)

    def __str__(self):
        return self.descricao

3) Edit core / views.py:

from .models import Pizza, Bebida
from django.views.generic.list import ListView

class IndexView(ListView):
    template_name = 'core/index.html'
    model = Pizza

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['bebidas'] = Bebida.objects.all()

        return context

4) Edit pizza / url.py:

from django.conf.urls import url
from django.contrib import admin
from core.views import IndexView

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'$', IndexView.as_view(), name='index'),

]

5) Edit core / templates / core / index.html

<div id = "pizzas">
  <ul>
    {% for objl in object_list %}
       <li>{{ objl}}</li>
    {% endfor %}
  </ul>
</div>


<div id = "bebida">
  <ul>
    {% for b in bebidas %}
       <li>{{ b }}</li>
    {% endfor %}
  </ul>
</div>    

6) Edit core / admin.py

from django.contrib import admin
from .models import Pizza, Bebida

admin.site.register(Pizza)
admin.site.register(Bebida)

7) Run the project and, through admin, add some intens in pizza and drink.

8) Point the browse to the index page and you will see the pizzas and the drinks that you included in their respective divs.

    
22.04.2017 / 21:56