Home > other >  How to display django model column values horizontally on django template
How to display django model column values horizontally on django template

Time:01-14

my issue is displaying the model data on django template horizontally. I have a model named "Main" with 3 columns. When I display on the template it looks like this-

enter image description here

I want to filter it by category that will look like this-

Main.objects.filter(category='food')

enter image description here

My goal is to show the category name on the template with the price horizontally on the side with plus signs. It should look something like this-

food= 8 10 11

I tried for...in loop both on template and on views.py both failed. Tried something like this- print(f"{i.category}={i.price} ") with for loop. Didn't work.

output =f'{i.price} ' with a for loop, holding it in a variable and display that variable on template. Different combinations of those, all failed.

Since = is mainly for integers, I tried with i.price without turning it into a string, failed.

Most answers I found here on "displaying model data horizontally on Django template" are about using css to display form elements side by side,which I know how to do and not exactly my problem.

Can anyone point me to the right direction?

Here is my models.py

class Main(models.Model):
    name = models.CharField(max_length = 60, blank = True)
    category = models.CharField(max_length = 60, blank = True)
    price = models.CharField(max_length = 60, blank = True)

    def __str__(self):
        return self.name

views.py -

def products(request):
    products = Main.objects.all()
    context = {'products':products}
    return render(request, 'myapp/index.html', context)

and the HTML template -

<div >
   <table >
      <tr>
         <th>Product</th>
         <th>Category</th>
         <th>Price</th>
      </tr>
      {% for i in products %}
      <tr>
         <td>{{i.name}}</td>
         <td>{{i.category}}</td>
         <td>{{i.price}}</td>
      </tr>
      {% endfor %}
   </table>
</div>

Not the entire template but you get the idea. Very basic.

CodePudding user response:

You can do it like this:

views.py:

def products(request):
    foods = Main.objects.filter(category='food').values_lis('category', flat=True)
    return render(request, 'myapp/index.html', {'foods': foods})

index.html:

<div >
  <p> food:  
     <span> 
       {% for food in foods %}
         {{ food }} {% if not forloop.last %} {% endif %}
       {% endfor %}
     </span>
  </p>
</div>
  •  Tags:  
  • Related