django修改数据库对象

时间:2018-07-07 08:06:24

标签: python django templates models

我正在开发一种考勤管理系统。我想修改学生的出勤率。

class Subject(models.Model):
    subject_name = models.CharField(max_length=20)
    #attendance = models.ForeignKey(Attendance, on_delete = models.DO_NOTHING)
    attendance = models.IntegerField(default=0)
    def __str__(self):
        return self.subject_name


class Section(models.Model):
    section_name = models.CharField(max_length=20)
    subject = models.ManyToManyField(Subject)
    def __str__(self):
        return self.section_name


class Student(models.Model):
    rollno = models.IntegerField()
    name = models.CharField(max_length=20)
    section = models.ForeignKey(Section, on_delete = models.DO_NOTHING, default=0)
    def __str__(self):
        return str(self.rollno) + self.name 

这是我的模板。 (Student.html)

{% for i in data %}  
                <tr>
                    <td>{{ i.rollno }}</td>
                    <td>{{ i.name }}</td>
                    <td> <button class='btn btn-danger' id='{{i.rollno}}' on click = "{{ i.section.subject.get(subject_name='java').attendance)|add:1 }}"> 
                    </td>
                </tr>
{% endfor %}

在模板中使用.get()方法时出现错误。我想在按钮点击时增加(+1)出席人数。

1 个答案:

答案 0 :(得分:1)

我强烈建议您通过Django Tutorial。您将学习Django MVC概念,并能够轻松实现您的要求。以下代码将帮助您入门。

views.py

def increment_attendance(request, subject_id):
  """Increment Attendance for a Subject"""

    subject = Subject.objects.get(id=subject_id)
    # check if record exists
    if not subject:
        raise Http404("Invalid subject_id")

    # can also use only get_object_or_404(Subject, pk=subject_id)

    # increment attendance
    subject.attendance += 1
    # save / commit to database
    subject.save()

    # redirec to 'some' page or previous page?
    return redirect('top')

将此路径添加到您的urls.py

  path('subject/<int:day>/increment_attendance', views.increment_attendance, name='increment_attendance')

模板

  <a class="btn btn-danger" id="{{i.rollno}}" href="{% url 'increment_attendance' subject_id=subject_id" %}"></a>