django - Django使用复选框小部件从视图中运行python函数
问题描述
我正在创建一个 Django 项目。我的数据库中有很多数据,我正在通过表格将其呈现到我的模板中。每列对应于我的数据库中的字段。除此之外,我的应用程序允许用户对选定的数据执行一些操作。我希望用户能够通过views
单击按钮来运行这些操作(通过 中的函数)。
很明显,让用户为每一行单击一个按钮会很乏味。所以我认为最好让他们点击相应行的复选框,然后让他们点击一个按钮来运行我项目中的特定功能。
原谅我,但我不知道如何处理这种设置。我已经阅读了有关复选框小部件的信息,但是如果它们选中了复选框,我该如何对 HTML 模板上呈现的一组对象运行函数。
感谢您的指导!
这是我所拥有的模板片段:
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col">Major</th>
<th scope="col">Promote</th>
</tr>
</thead>
<tbody>
{% for s in list %}
<tr>
<th scope="row">{{s.student_id}}</th>
<td>{{s.user.username}}</td>
<td>{{s.user.email}}</td>
<td>{{s.major}}</td>
<td><a type="button" class="btn btn-success" href="{% url 'emailPage' s.student_id%}">Make Tutor</a></td>
</tr>
</tbody>
</table>
试图将每一行按钮替换为一键单击系统。我从我的观点通过 masterList 。
模型.py
class masterList(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="student")
student_id = models.IntegerField(primary_key=True, null=False, validators=[MaxValueValidator(999999), MinValueValidator(100000)])
phone = PhoneField(blank=False, help_text='best number to contact you')
major = models.CharField(max_length=500, blank=False)
eof = models.BooleanField(blank=False, choices = [(True, 'Yes'), (False, 'No')])
arc = models.BooleanField(blank=False, choices = [(True, 'Yes'), (False, 'No')])
class Meta():
verbose_name = 'Student Info'
def __str__(self):
return self.user.username
解决方案
我绝不是这方面的专家,我见过人们通过实时重新加载和视图之外的逻辑来做到这一点(我听说这被忽视了)但这是我通常为这样的事情串起来的一般格式:
# models.py
class ListModel(models.Model):
. . .
student_id = models.Field()
# views.py
if request.POST.get('expel_all_students'):
for student_id in table:
expelled_students_id = str(request.POST.get('expelled_student'))
expelled_student_instance = ListModel.objects.get(id = expelled_students_id)
student_id.rm(expelled_student_instance)
# templates.py
<button type="submit" value='expel_all_students' name="expel_all_students"> Expel all students </button>
<table>
. . .
这里的关键是按钮值由视图中的 if 语句拾取,当单击提交按钮时触发函数的操作。这就是我朋友的魔法。
推荐阅读
- javascript - Paypal 智能按钮 – 延迟触发“onApproval”会导致问题
- docker - Windows 10 企业版 Docker 安装失败
- excel - 如何从excel单元格中提取文本
- python - 如何使用python检测相同颜色的相邻线以检测损坏区域?
- android - 为什么回收站视图项目没有重新排列?
- c# - 使用 dotnet test 运行标记为 [Explicit] 的测试
- python - 如何将存储为字符串/日期时间(两者)的日期转换为 MongoDB 中的仅日期时间?
- html - Flexbox 对齐 - 每行两个,然后一个
- r - 将数据框中的值重新排列并提取到 R 中的特定列
- continuous-integration - 如何在 GitHub Actions CI 的主目录中添加路径?