2 types of products in the same view

Asked

Viewed 169 times

0

How could I list 2 types of products on index (Pizzas and Drinks) Defining a order by and dividing into divs different (div of drinks, div of the pizzas), follows what I have:

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

I’d like an explanation of what would be the best way to do that.

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 will 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 stick to 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 intense pizza and drink.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.