如何修复从视图到 html 的传递变量

阿卜杜勒·贾

我在将变量“res”从视图传递到 index.html 时遇到问题,它返回 html 页面中的最后一个结果

查看文件:

def index(request):

    posts = Layout.objects.all()
    urlpost = SiteUrls.objects.all()[:20]


    field_value = SiteUrls.objects.values_list('site_url', flat=True)

    for site_url in field_value:
        print(site_url)
        res = os.system("ping -n 1 " + site_url )

        if res == 0:
            res = "connected"
        else:
            res = "not connected"

    context = {
        'posts':posts,
        'urlpost':urlpost,
        'res': res
    }

    return render (request, 'posts/index.html', context)

html文件:

      <table>
        <tbody>
            {% for SiteUrls in urlpost %}
          <tr>
            <td>{{SiteUrls.site_title}}</td>
            <td>{{SiteUrls.site_url}}</td>

            <td> {{res}} </td>

            <td><a style="margin-bottom:10px" class="waves-effect waves-light btn">open Site</a></td>
          </tr>
            {% endfor %}
        </tbody>
      </table>

我想取回每一行的具体结果

丹尼尔·赫珀

不要使用.values_list(). 改为使用对象并将您的值添加为附加属性。

请注意,在您的代码中,您将SiteUrls查询限制为 20 个对象,但随后您 pingSiteUrls数据库中的所有对象我假设您只想 ping 这些 20 SiteUrls

def index(request):

    posts = Layout.objects.all()
    urlpost = list(SiteUrls.objects.all()[:20])

    for site_url in urlpost:
        print(site_url.site_url)
        res = os.system("ping -n 1 " + site_url.site_url )

        if res == 0:
            site_url.res = "connected"
        else:
            site_url.res = "not connected"

    context = {
        'posts':posts,
        'urlpost':urlpost,
    }

    return render (request, 'posts/index.html', context)

模板:

  <table>
    <tbody>
        {% for SiteUrls in urlpost %}
      <tr>
        <td>{{SiteUrls.site_title}}</td>
        <td>{{SiteUrls.site_url}}</td>

        <td> {{SiteUrls.res}} </td>

        <td><a style="margin-bottom:10px" class="waves-effect waves-light btn">open Site</a></td>
      </tr>
        {% endfor %}
    </tbody>
  </table>

此外,像您在这里所做的那样,在 Web 请求中调用这样的系统进程通常被认为是一个坏主意。一旦你开始使用它,我鼓励你研究任务队列的概念。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章