AttributeError at / ‘int’ object has no attribute ‘get’, trying to get object id via for loop

  django, python

I’m working on a project that’ll display uptime based on an IP. The code is supposed to pull the IP from a model attribute, ping the IP address, and return either a 0 or a 1, which’ll be passed to the HTML and checked for there.

I’ve ran the steps through in the python shell and got the data needed, but when running my test server, I get this error:

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'

Here’s my code, if someone can help it’s greatly appreciated!!!!

views.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)

models.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

index.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 %}

Source: Python Questions

LEAVE A COMMENT