Search problem using Django queryset when editing

Asked

Viewed 108 times

0

I am glad for the help, because I am not able to carry out this search, even performing the search, returns me the right id (id_sector and id_company) but Django does not recognize or I am doing something wrong.

Error "The Queryset value for an Exact lookup must be Limited to one result using slicing"

Views

@login_required(login_url='/login/')
def ed_ramal(request):
    id_ramal = request.GET.get('id')
    id_setor = Ramais.objects.filter(id=id_ramal).values('setor_ramais')
    id_empresa = Ramais.objects.filter(id=id_ramal).values('empresa_ramais')

    if id_ramal:
        ed_ramal = Ramais.objects.filter(id=id_ramal).values('ramal')
        i_resp = Ramais.objects.filter(id=id_ramal).values('nome_resp')
        i_mail = Ramais.objects.filter(id=id_ramal).values('email')
        setor = Setores.objects.filter(id=id_setor[0]['setor_ramais'])
        empresa= Empresas.objects.filter(id=id_empresa[0]['empresa_ramais'])
        dados = {'ramal': ed_ramal, 'responsavel': i_resp, 'email': i_mail, 'setores': setor, 'empresas': empresa}
    else:
        empresa = Empresas.objects.all()
        setor = Setores.objects.all()
        dados = {'empresas': empresa, 'setores': setor}
    return render(request, 'ramal.html', dados)

Models

    class Ramais(models.Model):
        ramal = models.CharField(max_length=4, verbose_name='Ramal')
        nome_resp = models.CharField(max_length=30, verbose_name='Responsavél')
        email = models.EmailField(max_length=60)
        setor_ramais = models.ForeignKey(Setores, on_delete= models.DO_NOTHING, verbose_name='Setor')
        empresa_ramais = models.ForeignKey(Empresas,on_delete= models.DO_NOTHING, verbose_name='Empresa')
        data_criacao = models.DateTimeField(auto_now=True)


        class Meta:
            db_table = 'ramais'

        def __str__(self):
            return self.ramal + str(self.setor_ramais)+ str(self.empresa_ramais)

Html code before editing:

{% extends "parciais/base.html" %}
{% block content %}
        <nav class="navbar center">
           <form class="form-inline" method="GET">
                <input class="form-control mr-sm-2 "type="text" name="search" id="buscar">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Consulta</button>
           </form>
       </nav>
            <section id="lista_ramais">
                <div class="container-fluid lista_ramais">
                    <p>LISTA DE RAMAIS</p>
                </div>
            </section>
        <section class="container-fluid margin">
            <div class="table-responsive-lg">
                <table class="table table-xl table-striped">
                    <thead class="claro" align="center">
                        <tr>
                        <th scope="col">RAMAL</th>
                        <th scope="col">RESPONSAVÉL</th>
                        <th scope="col">SETOR</th>
                        <th scope="col">EMPRESA</th>
                        {% if request.user.is_authenticated %}
                            <th scope="col">EDIÇÃO
                              <a href="edicao/">
                                <button type="button" class="btn btn-light">ADICIONAR</button>
                              </a>
                            </th>
                        {% endif %}
                        </tr>
                    </thead>
                    <tbody>
                           {% for i in ramais %}
                                <tr>
                                <th>{{i.ramal}}</th>
                                <td>{{ i.nome_resp | upper }}</td>
                                <td>{{ i.setor_ramais | upper }}</td>
                                <td>{{ i.empresa_ramais }}</td>
                                {% if request.user.is_authenticated %}
                                     <td>
                                        <a href="edicao/?id={{ i.id }}">
                                         <button type="button" class="btn btn-warning">EDITAR</button>
                                        <!/a>
                                         <a href="/delete/{{ i.id }}">
                                         <button type="button" class="btn btn-danger">EXCLUIR</button>
                                        </a>
                                     </td>
                                {% endif %}
                                </tr>
                           {% endfor %}
                      </tbody>
                </table>
                <nav aria-label="Navegação de página exemplo">
                    <ul class="pagination">
                      {% for pagina in ramais.paginator.page_range %}
                        {% if ramais.number == pagina %}
                            <li class="page-item active"><a class="page-link" href="?page={{ pagina }}">{{ pagina }}</a></li>
                        {% else %}
                           <li class="page-item"><a class="page-link" href="?page={{ pagina }}">{{ pagina }}</a></li>
                        {% endif %}
                      {% endfor %}
                    </ul>
                </nav>
            </div>
            <div align="right">
                <button type="button" onclick="window.print()" class="btn btn-outline-secondary">Imprimir</button>
            </div>
        </section>
{% endblock %}

Editing HTML code / add

{% extends "parciais/base.html" %}

{% block content %}
{% load static %}
    <link rel= "stylesheet" type="text/css" href= "{% static '/bootstrap/css/bootstrap.min.css' %}" >
    <link rel= "stylesheet" type="text/css" href= "{% static '/style.css' %}" >

<section>
    <div class="container w-auto lista">
        <p>RAMAL</p>
    </div>
</section>

<section class="container w-auto bgcolor_cad">
        <form action="submit" method="POST">{% csrf_token %}
         <input type="number" name="id_ramal" value="{{ i.id }}">
           <div class="form-row">
                <div class="form-group col-md-4">

                  <label>Ramal:</label>
                  <input type="number" name="ramal" class="form-control" value="{{ i.ramal  }}"  >
                </div>
                <div class=" col-md-4">
                  <label>Responsável:</label>
                  <input type="text" name="responsavel"  class="form-control" value="{{ i.nome_resp }}" >
                </div>
          </div>
            <div class="form-row">
                  <div class="col-md-4">
                    <label>Email:</label>
                    <input type="email" name="email"  class="form-control" value="{{ i.emal }}">
                  </div>
                    <div class="col-md-4">
                      <label >Setor:</label>
                      <select id="inputState" name="setor" class="form-control">
                        {% for s in setores %}
                            <option  value="{{ s.id }}" name="pk_setor">{{ s.setor }}</option>
                        {% endfor %}
                      </select>
                        <a href="/ramais/edicao/setor/">
                            <button type="button" class="btn btn-info">ADICIONAR</button>
                        </a>
                    </div>
            </div>
            <div class="form-row">
                    <div class="form-group col-md-4">
                      <label for="inputState">Empresa:</label>
                      <select id="inputState01" name="empresa"  class="form-control">
                        {% for e in empresas %}
                            <option  value="{{ e.id }}" name="pk_empresa">{{ e.nome_emp }}</option>
                        {% endfor %}
                      </select>
                    </div>
            </div>
            <button type="submit" class="btn btn-success">SALVAR</button>
            <a href="/ramais/">
                <button type="button" class="btn btn-danger">CANCELAR</button>
            </a>
        </form>
</section>
        <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
{% endblock %}

Full code on my Github: https://github.com/cristianpaes/RAMAIS

1 answer

1


with the filter you get a queryset, so the result is not id, for id_sector and id_company, use something like this:

@login_required(login_url='/login/')
    def ed_ramal(request):

        id_ramal = request.GET.get('id')
        id_setor = Ramais.objects.filter(id=id_ramal).values('setor_ramais')
        id_empresa = Ramais.objects.filter(id=id_ramal).values('empresa_ramais')

        if id_ramal:
            ramal = Ramais.objects.filter(id=id_ramal)
            setor = Setores.objects.filter(id=id_setor[0]['setor_ramais'])
            empresa= Empresas.objects.filter(id=id_empresa[0]['empresa_ramais'])
            dados = {'empresas': empresa, 'setores': setor, 'ramal':ramal}

        else:
            empresa = Empresas.objects.all()
            setor = Setores.objects.all()
            dados = {'empresas': empresa, 'setores': setor}
        return render(request, 'ramal.html', dados)
  • I made the change you reported, but it still gives type error. Typeerror: Field 'id' expected a number but got {'setor_ramais': 1}.

  • Fix the fix, validate now.

  • Now gave another error: 'Sectors' Object is not iterable.

  • Now I assume you have another html problem iterating sectors, you’re looking at that HTML, that you didn’t share. You can’t expect help without sharing the code here.

  • I put the HTML where I take the ID and have my github, to check all html and full code. I just can’t solve it.

  • Fixed in the code I shared, in your HTML no problem, but in the function ed_ramal, Since I didn’t have access to that code, I couldn’t figure out how you present it in the template. What is the problem here, you can not pass to a for loop in the template one and only instance of the Object Sectors or Companies, (the latter would give error to serguir after correcting the Sectors), is what happens when doing *.objects.get(), you have to use *.filter()In this way the ORM of Django returns a Queryset of this object and eternal, even being only one, I do not know if this is the goal with the if id_ramal:. have a dropdown.

  • Thank you very much. It worked and it was silly stuff. I’m learning and this happens.

  • Can you help me, to bring the values of Ramal, responsible and email. And could you leave interactive the sectors and Company? my idea would be to change if the person is transferred.

  • I think you should close this issue, open a new one, your doubt here is resolved. Put the code and detail the problem very well, "my idea would be to change if the person is transferred", only this is not enough. Try to be as objective as possible.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.