简体   繁体   中英

Django template doesn't output values to HTML table cells

I have the following template:

 <table>
     <tr>
         <th>Monday</th>
        <th>Tuesday</th>
        <th>Wednesday</th>
        <th>Thursday</th>
        <th>Friday</th>
        <th>Saturday</th>
        <th>Sunday</th>
    </tr>

    {% for row in table %}
    <tr>
        {% for i in week_length %}
        <td>{{row.i}}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>

And the following view:

def calendar(request):
    template_name = 'workoutcal/calendar.html'

    today_date = timezone.now()
    today_year = today_date.year
    today_month = today_date.month
    today_day = today_date.day

    table = maketable(today_date) # Creates something like: [[None, 1, 2, 3, 4, 5, 6],[7, 8, ...],...,[28, 29, 30, 31, None, None, None]]

    template = loader.get_template('workoutcal/calendar.html')

    #Workout.objects.filter("Workouts lie between certain dates")
    context = {
        'workout_list': Workout.objects.filter(date__year = today_year, date__month = today_month, date__day = today_day),
        'table': table, # The calendar
        'week_length': range(7),
    }
    return HttpResponse(template.render(context, request))

When I access the page ( localhost:8000/workoutcal ), nothing except for the table headers is output. It looks like this:

桌子

检查对象

I can't figure out why Django is not putting my output into the cell. I want no output for elements of the list that are None , and then simply the element content (all are strings) in for all other elements. Any ideas?

You're iterating over the wrong thing. Your calendar is a list of lists; you should iterate over each row, then each column in that row. week_length is completely irrelevant.

{% for week in table %}
<tr>
    {% for day in week %}
    <td>{{ week }}</td>
    {% endfor %}
</tr>
{% endfor %}

You are not accessing the items in the row object correctly. They are at index i not at the attribute named i .

You could just do the following:

{% for i in row %}
    <td>{{ i }}</td>
{% endfor %}

Because row is the list of elements you want to access. This would avoid the need to pass the week_length variable.

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