简体   繁体   中英

rendering array on django template

I have following view

def deals(request):
    usr=UserProfile.objects.get(user_id=request.user.id)
    merchant=MerchantProfile.objects.get(user_id=usr.id)
    dealItems=MerchantDeal.objects.filter(merchant_id=merchant.id)
    stateText = {1 : 'Created',
                  2 : 'Activated',
                  3 : 'Completed'}

    return render_to_response('deals.html',locals(),context_instance=RequestContext(request))

In the model MerchantDeal i have one field state_id with three ids 1,2,3 for created, completed and used respectively

I have following template

<table>
                  <tr>
                    <th>Deals</th>
                    <th>Status</th>
                    <th>Start date </th>
                    <th>End date </th>
                    <th>Used</th>
                    <th>Edit</th>
                  </tr>
                  {% for Item in dealItems %}
                  <tr class="gray">
                    <td>{{Item.title|capfirst}} </td>
                    <td >{{Item.current_state}}</td>
                    <td>{{Item.start_date}}</td>
                    <td>{{Item.end_date}}</td>
                    <td width="90">{{Item.used}}</td>
                    <td width="92"><a class="ajax cboxElement" href="/ajax/item?id={{foodItem.id}}">edit</a></td>
                  </tr>
                  {%endfor%}
                </table>

This is show current_state as 1,2,3 instead of created,completed and used. I have defined stateText array too

stateText = {1 : 'Created',
             2 : 'Activated',
             3 : 'Completed'}

How to render that for 1,2,3 which comes from database?

In your MerchantDeal model:

STATE_CHOICES = ((1,'Created'),(2,'Activated'),(3,'Completed'))

class MerchantDeal(models.Model):
    # .. your various other fields
    current_state = models.IntegerField(choices=STATE_CHOICES)

Then in your template:

<td>{{ Item.get_current_state.display }}</td>

The documentation details how this works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM