django - Ouput ping status on django template
问题描述
I have a model that contains domain names which I need to ping. I was able to create the view but I couldn't figure out how to output it on the template.
def index(request, page):
template = "home.html"
if request.method == 'POST':
csv_file = request.FILES['file']
if not csv_file.name.endswith('.csv'):
messages.error(request, 'Please upload a .csv file.')
data_set = csv_file.read().decode('ISO-8859-1')
io_string = io.StringIO(data_set)
next(io_string)
for column in csv.reader(io_string, delimiter=','):
_, created = Table.objects.update_or_create(
page=column[0],
keyword=column[1],
interval=column[2],
email=column[3],
notes=column[4],
billing=column[5],
)
page_object = get_object_or_404(Table, page=page)
try:
subprocess.check_call(['ping', '-c', '1', page_object.page])
except subprocess.CalledProcessError:
host_online = False
else:
host_online = True
context = {
'tables': Table.objects.all(),
'online': host_online,
'page': page
}
return render(request, template, context)
the model
class Table(models.Model):
page = models.URLField(verbose_name=None)
and this is how I call it on the template
{% if online %}
<i class="small material-icons green-text">check_circle</i>
{% else %}
<i class="small material-icons red-text">close</i>
{% endif %}
Can anyone guide me?
It's returning data_upload() missing 1 required positional argument: 'page'
解决方案
您的代码中有几个问题使其不正确:
domain = Table.objects.filter(page)
将失败。你应该做domain = Table.objects.filter(page=page)
- 您实际上并没有 ping 一个域,因为
domain
它只是代码中的一个字符串subprocess.check_call(['ping', '-c', '1', "domain"])
- 您没有使用上下文:如果要在模板中访问它,则需要将其传递给
render
调用return render(request, 'home.html', context
:)
更重要的是,Django 的过滤器函数返回一个queryset
对象,而不是单个实体。
我的建议是按如下方式修复您的代码:
视图.py
from django.shortcuts import get_object_or_404
def pingDomain(request, page):
page_object = get_object_or_404(Table, page=page)
try:
subprocess.check_call(['ping', '-c', '1', page_object.page])
except subprocess.CalledProcessError:
host_online = False
else:
host_online = True
context = {
'online': host_online
}
return render(request, 'home.html', context)
然后在您的模板中,您可以简单地通过online
密钥访问它:
{{online}}
推荐阅读
- c++ - C++ 将函数对象作为左值和/或右值传递
- javascript - 在完成 node.js 中的第一次执行之前,第二次调用相同的异步函数会发生什么
- mongodb - MongoDB Atlas 副本集名称
- symfony - 如何为 Symfony 4 配置 KnpPaginatorBundle
- reactjs - 如何将图标/图像添加到 react.js 中的选择选项?
- bash - xargs 命令在 bash 别名中使用时会静默失败
- python - Plotly:基于属性的不同强度级别的分类着色
- r - R 在两个向量的连续值上应用函数
- python - 熊猫 to_datetime 月份读取不正确
- android - Android NavigationBarColor 不会变为黑色(仅变为黑色)