A
A
Alexander Proshchenkov2018-05-29 18:20:04
Django
Alexander Proshchenkov, 2018-05-29 18:20:04

How to properly display data from db?

I want to display data from a db table on an html page
. There are three classes of models, people: a student's class and a date (the status in it is a mark, a person came or not):

class school_class(models.Model):
  school_class = models.CharField(max_length=10, help_text = 'Класс')
  def __str__(self):
    return self.school_class

class people(models.Model):
  first_name = models.CharField(max_length=100, help_text = 'Имя учащегося')
  last_name = models.CharField(max_length=100, help_text = 'Фамилия учащегося')
  school_class = models.ManyToManyField(school_class, help_text = 'Класс ученика')
  def __str__(self):
    return '{} {}'.format(self.first_name, self.last_name)

class date(models.Model):
  id = models.UUIDField(primary_key=True, default=uuid.uuid4)
  date = models.DateField(help_text = 'Дата')
  status = models.CharField(max_length=10, choices = (
    ('+', '+'),
    ('-', '-')
    ))
  people = models.ForeignKey(people, help_text = 'Фамилия, имя учащегося', on_delete = models.SET_NULL, null=True)

  def __str__(self):
    return '{} {}'.format(self.date, self.people.__str__())

  def get_absolute_url(self):
    return reverse('date-detail', args=[str(self.id)])

  class Meta:
    ordering = ['date', 'people']

How it should look on the site:
5b0d6ed0265e9310195887.png
generic database file:
<!DOCTYPE html>
<html lang="en">
<head>
  
  {% block title %}<title>Local Library</title>{% endblock %}
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  {% load static %}
  <link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>

<body>

  <div class="container-fluid">

    <div class="row">
      <div class="col-sm-2">
      {% block sidebar %}
      <ul class="sidebar-nav">
          <li><a href="{% url 'index' %}">Home</a></li>
          <li><a href="{% url 'date' %}">Date</a></li>
          <li><a href="">Nothing!</a></li>
      </ul>
     {% endblock %}
      </div>
      <div class="col-sm-10 ">
      {% block content %}{% endblock %}
      </div>
    </div>

  </div>
</body>
</html>

Here is the current page:
{% extends "base_generic.html" %}

{% block content %}
<h1>Date List</h1>

  {% if date_list %}
    <table>
      <tr>
        <td>
          People/Date
        </td>
        {% for date in date_list%}
          <td>{{ date.date}}</td>
        {% endfor %}
      </tr>
      {% for stat in date_list %}
        <tr>
          <td>
            {{ stat.people }}
          </td>
          {% for date in stat %}
            <td>
              {% if date.status %}{{ date.status }}{% else %}?{% endif %}
            </td>
          {% endfor %}
        </tr>
      {% endfor %}
    </table>
  {% else %}
    <p>Данных нет!</p>
  {% endif %}
{% endblock %}

When going to the page, it gives an error: 'date' object is not iterable
How to display the data concisely?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nick V, 2018-05-29
@Keltor

Alexander Proshenkov
_

models.py
from django.db import models
from django.utils.translation import ugettext_lazy as _


class SchoolClass(models.Model):
    name = models.CharField(
        _('Класс'),
        max_length=10,
        db_index=True,
        unique=True,
        help_text=_('Название класса.'),
    )

    class Meta:
        verbose_name = _('Класс')
        verbose_name_plural = _('Классы')

    def __str__(self):
        return self.name


class Pupil(models.Model):
    first_name = models.CharField(
        _('Имя'),
        max_length=100,
        db_index=True,
        help_text=_('Имя учащегося.'),
    )
    last_name = models.CharField(
        _('Фамилия'),
        max_length=100,
        db_index=True,
        help_text=_('Фамилия учащегося.'),
    )
    school_class = models.ForeignKey(
        to=SchoolClass, on_delete=models.CASCADE,
        verbose_name=_('Класс'), related_name='pupils',
        help_text=_('Название класса.'),
    )

    class Meta:
        verbose_name = _('Ученик')
        verbose_name_plural = _('Ученики')
        indexes = (
            models.Index(fields=['first_name', 'last_name']),
        )

    def __str__(self):
        return self.full_name

    @property
    def full_name(self):
        return '{} {}'.format(self.first_name, self.last_name)


class Schedule(models.Model):
    ATTEND = 'attend'
    ABSENT = 'absent'
    STATUS_CHOICES = (
        (ATTEND, 'Присутствовал'),
        (ABSENT, 'Отсутствовал'),
    )

    pupil = models.ForeignKey(
        to=Pupil, on_delete=models.CASCADE,
        verbose_name=_('Ученик'), related_name='schedules',
        help_text=_('Фамилия и имя учащегося.')
    )
    date = models.DateField(
        _('Дата'),
        db_index=True,
        help_text=_('Дата.')
    )
    status = models.CharField(
        _('Статус'), max_length=10,
        choices=STATUS_CHOICES, default=ABSENT,
        db_index=True,
        help_text=_('Статус.')
    )

    class Meta:
        verbose_name = _('Расписание')
        verbose_name_plural = _('Расписания')
        indexes = (
            models.Index(fields=['date', 'status']),
        )
        unique_together = ('pupil', 'date',)

admin.py
from django.contrib import admin

from schedule.models import (
    SchoolClass,
    Pupil,
    Schedule
)


class PupilInLIne(admin.TabularInline):
    model = Pupil
    fields = ('first_name', 'last_name')
    extra = 1


class ScheduleInLIne(admin.TabularInline):
    model = Schedule
    fields = ('date', 'status')
    extra = 1


@admin.register(SchoolClass)
class SchoolClassAdmin(admin.ModelAdmin):
    list_display = ('name',)
    list_display_links = ('name',)
    inlines = (PupilInLIne,)
    list_filter = ('name',)
    search_fields = ('name',)


@admin.register(Pupil)
class PupilAdmin(admin.ModelAdmin):
    list_display = ('full_name', 'school_class')
    list_display_links = ('full_name',)
    inlines = (ScheduleInLIne,)
    raw_id_fields = ('school_class',)
    list_select_related = ('school_class',)
    search_fields = ('first_name', 'last_name', 'school_class__name')
    list_filter = ('school_class__name',)

The view will be something like this
views.py
class PupilScheduleDetailView(DetailView):
    model = Pupil
    template_name = 'pupil_schedule_detail.html'

    def get_context_data(self, **kwargs):
        context_data = super().get_context_data(**kwargs)
        schedule_queryset = self.object.schedules.all().select_related(
            'pupil'
        ).values(
            'pupil__first_name',
            'pupil__last_name',
            'date', 'status'
        )
        context_data.update({
            'schedules': schedule_queryset
        })
        return context_data

pupil_schedule_detail.html
{% if schedules %}
  <table>

    {% for schedule in schedules %}
      <tr>
        <td>{{ schedule.pupil__first_name }} {{ schedule.pupil__last_name }}</td>
        <td>{{ schedule.date }}</td>
        <td>{{ schedule.status }}</td>
      </tr>
    {% endfor %}

  </table>
{% else %}
  <p>Данных нет!</p>
{% endif %}

In general, xs, of course, look here for yourself .. I don’t know your implementation, think for yourself.
Z.Y. I haven’t worked with regular django views and templates for a long time, so maybe something is wrong, sorry here ¯\_(ツ)_/¯

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question