【问题标题】:django modifying database objectdjango修改数据库对象
【发布时间】:2018-12-15 16:50:30
【问题描述】:

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

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 

这是我的模板。 (学生.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) 出勤率。

【问题讨论】:

  • 但这根本不是你可以在模板中做的事情,即使抛开语法问题。像这样的事情必须在视图中完成。
  • 感谢您的回复。请帮我。什么应该作为参数传递给视图以及如何传递?我是 Django 的新手。 @丹尼尔罗斯曼

标签: python django templates models


【解决方案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>

【讨论】:

  • 谢谢@Zekoi。你能评论我的models.py吗?这是我的第一个项目,我不确定我制作的数据库。
猜你喜欢
  • 2021-04-23
  • 1970-01-01
  • 2018-12-15
  • 2023-03-05
  • 1970-01-01
  • 2016-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多