首页 > 解决方案 > /'int'对象的AttributeError没有属性'get',试图通过for循环获取对象ID

问题描述

我正在开发一个基于 IP 显示正常运行时间的项目。该代码应该从模型属性中提取 IP,ping IP 地址,并返回 0 或 1,这将被传递到 HTML 并在那里进行检查。

我已经在 python shell 中运行了这些步骤并获得了所需的数据,但是在运行我的测试服务器时,我收到了这个错误:

AttributeError at /
'int' object has no attribute 'get'
Request Method: GET
Request URL:    http://localhost:8000/
Django Version: 3.2.2
Exception Type: AttributeError
Exception Value:    
'int' object has no attribute 'get'

这是我的代码,如果有人可以帮助它,不胜感激!!!!

视图.py:

from django.shortcuts import render
from django.http import HttpResponse
from .models import NewServer
import os

# Create your views here.

def index(request):
    servers = NewServer.objects.order_by('id')
    #this should ping the server!!!!
    #loop through all NewServer objects, storing each
    #count in ids
    for ids in servers:
        #for every loop, set get_server to the
        #current NewServer objects via the id
        get_server = NewServer.objects.get(id=ids.id)
        #create the ping command with the ip
        #gotten through the 'ip' attribute
        #in the model
        ping = "ping -c 1 " + get_server.ip + " > /dev/null" 
        #store the whole command in the status_code variable
        status_code = os.system(ping)
        #each time status_code is ran, it should either return
        #a 0 (success), or 1 (failure)
        return status_code
    context = {'servers':servers, 'status_code': status_code} 
    return render(request, 'monitor/index.html', context)

模型.py:

from django.db import models

# Create your models here.

class NewServer(models.Model):
    name = models.CharField(max_length=50)
    ip = models.CharField(max_length=200)

    def __str__(self):
        return self.ip
        return self.name

索引.html:

{% extends 'monitor/base.html' %}

{% block content %}
<table>
    <tr>
        <th> Server Name: </th>
        <th> Status: </th> 
    </tr>
    {% for server in servers %}
        <tr>
        <td>{{server.name}}</td>    
        {% if status_code == 0  %}
            <td> Up</td>
        {% else %}
            <td> Down </td>
        {% endif %}
        </tr>
    {%empty%}
        <p> Hmm... there's no servers. </p>
    {% endfor %}
</table>
{% endblock content %}

标签: pythondjango

解决方案


将需要进行一些更改。您可以相应地放置逻辑。您收到此错误的主要原因是因为您只返回了status_code内部 for 循环。我把它改成了这样,它工作了。

def index(request):
    servers = NewServer.objects.order_by('id')
    status_code = '201'
    context = {'servers':servers, 'status_code': status_code} 
    for ids in servers:
        get_server = NewServer.objects.get(id=ids.id)
        ping = "ping -c 1 " + get_server.ip + " > /dev/null" 
        status_code = os.system(ping)
        return render(request, 'home.html', context)
    return render(request, 'home.html', context)

那不是您需要的正确逻辑。但是您可以创建逻辑来将每个服务器及其状态代码存储在上下文中。但肯定的原因是只status_code在 for 循环内部返回。


推荐阅读