首页 > 解决方案 > 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'

标签: djangodjango-modelsdjango-templatesdjango-views

解决方案


您的代码中有几个问题使其不正确:

  • 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}}

推荐阅读