Information does not appear in the form when editing

Asked

Viewed 42 times

-1

With the primary key ID, work with the information in the views, but it does not appear in the edit(html), the fields sector and company appears.

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)

HTML that is called to do the editing, I am passing the id(primary key of the extension )

<section class="container w-auto bgcolor_cad">
        <form action="submit" method="POST">{% csrf_token %}
         <input type="number" name="id_ramal" value="{{ i.id }}" hidden>
           <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.email }}">
                  </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>

Models

class Setores(models.Model):
    setor = models.CharField(max_length=150, unique=True)

    class Meta:
        db_table = 'setores'

    def __str__(self):
        return self.setor

class Empresas(models.Model):
    nome_emp = models.CharField(max_length=250,verbose_name='Empresa')
    cnpj = models.CharField(max_length=21, verbose_name='CNPJ')
    insc_estadual= models.CharField(max_length=13, blank=True, verbose_name='Inscrição Estadual')
    telefone_emp = models.CharField(max_length=13, verbose_name='Telefone')
    rua = models.CharField(max_length=500, verbose_name='Endereço')
    numero = models.CharField(max_length=6, verbose_name='Número')
    complemento = models.CharField(max_length=150, blank=True, verbose_name='Complemento')
    bairro = models.CharField(max_length=150, verbose_name='Bairro')
    cep = models.CharField(max_length=9, verbose_name='CEP')

    class Meta:
        db_table = 'empresas'

    def __str__(self):
        return self.nome_emp


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)

    def get_data_criacao(self):
        return self.data_criacao.strftime('%d/%m/%Y')

1 answer

1


Hey, your code had some problems, I don’t know if you’re doing the same in the rest of html here with more details and suggestions. I fixed your code, but it will only show the data you want if you pass the url url? id={id_ramal}. You still don’t understand how it works to send values through the Django context to the template. Where does {{ i.email }} come from if you define it in your view and send it in the context {...'email': i_mail...} in the template would be {{ email }}, does i come from an iteration of a for? Where is he? Server side, you were doing multiple queries to get data from db, two of them unnecessary. Well without realizing what you want, your information in the doubts are not very clear, but here is the solution of the problems.

NOTE: In practice I changed the query of extensions = Ramais.objects.filter(id=id_ramal) to extensions = Ramais.objects.get(id=id_ramal), so it does not return a queryset but the object and accessible through the value extensions passed by the context, to access your data just do extensions id., for example. On the id_ramal line = request.GET.get('id'), you will only get the id if you pass on the route, that is, as I explained before, url? id={id_ramal}.

I hope I made it clear why I didn’t show data in your template.

py views.

@login_required(login_url='/login/')
def ed_ramal(request):
    template_name = 'ramal.html'
    context = {}
    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:
        ramais = Ramais.objects.get(id=id_ramal)
        setor = Setores.objects.filter(id=id_setor[0]['setor_ramais'])
        empresa= Empresas.objects.filter(id=id_empresa[0]['empresa_ramais'])
        context = { 'ramais': ramais, 'setores': setor, 'empresas': empresa}
    else:
        empresa = Empresas.objects.all()
        setor = Setores.objects.all()
        context = {'empresas': empresa, 'setores': setor}
    return render(request, template_name, context)

html extension.

<form action="submit" method="POST">{% csrf_token %}
         <input type="number" name="id_ramal" value="{{ ramais.id }}" hidden>
           <div class="form-row">
                <div class="form-group col-md-4">

                    <label>Ramal:</label>
                    <input type="number" name="ramal" class="form-control" value="{{ ramais.id }}"  >
                </div>
                <div class=" col-md-4">
                    <label>Responsável:</label>
                    <input type="text" name="responsavel"  class="form-control" value="{{ ramais.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="{{ ramais.email }}">
                  </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/" class="btn btn-info">ADICIONAR</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/" class="btn btn-danger">CANCELAR</a>
        </form>
  • Thanks, it’s working. I don’t know how to use this query in db, I know how to do it through the tools. And in the case of i.ramais in the template, I didn’t know how to send the data and I thought it would be "i.ramais" as a "for", but I understood that you put "extensions.id" would be "extensions" of the database, right?

  • Hi, when going through the context the object 'extensions', it has several attributes and one of them the id, to access this via template just that, extensions.id.

  • thank you very much. It helped me a lot and this is my first system. I will not miss but these details.

Browser other questions tagged

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