Display query and result on the same page

70 views
Skip to first unread message

Oberdan Santos

unread,
Nov 22, 2023, 4:34:47 PM11/22/23
to pylons-discuss
Hello!!! I'm trying to make the code below work as follows.
When filling out the data entry, click on the query button.

# template/pac_recepx. jinja2

<div class="form">    
        <div class="row g-2 mt-3">      
            <h3><span class="font-semi-bold">Consultar cadastro do paciente</span></h3>
        </div>
        <form class="form-inline my-2 my-lg-0" action="http://localhost:6543/queryx" method="GET">
            <label for="cpf">Digite o CPF (11 números)</label>
            <input class="form-control mr-sm-2" type="text" id="cpf" name="cpf" required maxlength="11" value=''>
            <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Consultar</button>
        </form>
    </div>

In this view, using the code below, it shows all registered patients. 

@view_config(route_name='queryp', renderer='piprdc:templates/pac_query.jinja2')
def queryp(request):
   rows = request.dbsession.query(Paciente).all()
   pacientes=[]
   for row in rows:
      pacientes.append({"id":row.id, "name":row.name, "idade":row.idade, "data_nascimento":row.data_nascimento, "sexo":row.sexo,
                        "raca":row.raca, "fone":row.fone, "endereco":row.endereco, "cpf":row.cpf, "cns":row.cns})
   return{'pacientes':pacientes}

The question is, how do I make it show only the patient I requested the appointment with? I've looked at a lot of content, but I can't create a logic for it to take the past information (cpf), compare it and display it.

Every help is welcome.

Oberdan costa



Mike Orr

unread,
Nov 22, 2023, 6:33:04 PM11/22/23
to pylons-...@googlegroups.com
The simplest way is:

```
cpf = request.params["cpf"]
rows = request.dbsession.query(Paciente).filter(cpf=cpf),all()
```

This doesn't do any validation or graceful error reporting on the
input value, so you may want to use Colander or FormEncode for that. I
use FormEncode. Otherwise invalid input may lead to a Python exception
and an Internal Server Error for the user, and 'cpf' will be a string
even if the database field is integer.
> --
> You received this message because you are subscribed to the Google Groups "pylons-discuss" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to pylons-discus...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/pylons-discuss/25b36bc3-0c71-4587-b79f-dfb26e83e7f7n%40googlegroups.com.



--
Mike Orr <slugg...@gmail.com>

Oberdan Santos

unread,
Nov 23, 2023, 10:03:28 AM11/23/23
to pylons-discuss

The simplest way is:
```
cpf = request.params["cpf"]
rows = request.dbsession.query(Paciente).filter(cpf=cpf),all()
```
O codigo no formato acima não executou, apresentou erro, mas foi de grande valia,  muito obrigado). Fiz uma pequena alteração e deu certo. 
Funcionou assim:
cpf = request.params["cpf"]
   rows = request.dbsession.query(Paciente).filter(Paciente.cpf==cpf).all()

Você deve notado  no enuciado do assunto, que além da consulta, tenho o problema do resultado ser publicado em outra pagina.  

codigo da pagina de consulta
# templates/pac_recepx.jinja2

<div class="form">    
        <div class="row g-2 mt-3">      
            <h3><span class="font-semi-bold">Consultar cadastro do paciente</span></h3>
        </div>
        <form class="form-inline my-2 my-lg-0" action="http://localhost:6543/queryx" method="GET">
            <label for="cpf">Digite o CPF (11 números)</label>
            <input class="form-control mr-sm-2" type="text" id="cpf" name="cpf" required maxlength="11" value=''>
            <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Consultar</button>
        </form>
    </div>


O resultado  esta indo para ...

Como faço para levar esse resultado para dentro da mesma  da pagina que esta fazendo a  consulta (templates/pac_recepx.jinja2 ), ou seja, coloca-lo abaixo da consulta?

Desde já agradeço seu apoio.

Oberdan Costa

Mike Orr

unread,
Nov 23, 2023, 2:08:49 PM11/23/23
to pylons-...@googlegroups.com
On Thu, Nov 23, 2023 at 7:03 AM Oberdan Santos <sc.ob...@gmail.com> wrote:
> O codigo no formato acima não executou, apresentou erro, mas foi de grande valia, muito obrigado). Fiz uma pequena alteração e deu certo.
> Funcionou assim:
> cpf = request.params["cpf"]
> rows = request.dbsession.query(Paciente).filter(Paciente.cpf==cpf).all()

I remembered that after I wrote the comment, that it's
`filtey(Paciente.cpf==cpf)` and `filter_by(cpf=cpf)`. And `filter_by'
may not be supported in SQLAlchemy 2.0? I'm still on 1.4/1.3.

I'm afraid I don't know enough Portuguese to understand the rest of the message.

Laurent Daverio

unread,
Nov 23, 2023, 2:19:16 PM11/23/23
to pylons-...@googlegroups.com
Hi Mike,

.filter() and .filter_by() are still both valid in SQLAlchemy 2.x. I think .filter() is a synonym of .where().

Note : what is deprecated, but still available, is the "query syntax". I even think it's no longer documented. Recommended syntaxes are here:

https://docs.sqlalchemy.org/en/20/changelog/migration_20.html#migration-orm-usage

It's a bit more verbose, but closer to SQL :)

Laurent.

--
You received this message because you are subscribed to the Google Groups "pylons-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pylons-discus...@googlegroups.com.

Oberdan Santos

unread,
Nov 23, 2023, 2:50:54 PM11/23/23
to pylons-discuss
You should note in the subject statement that in addition to the query, I have the problem of the result being published on another page.
query page code
# templates/pac_recepx.jinja2

<div class="form">    
        <div class="row g-2 mt-3">      
            <h3><span class="font-semi-bold">Consultar cadastro do paciente</span></h3>
        </div>
        <form class="form-inline my-2 my-lg-0" action="http://localhost:6543/queryx" method="GET">
            <label for="cpf">Digite o CPF (11 números)</label>
            <input class="form-control mr-sm-2" type="text" id="cpf" name="cpf" required maxlength="11" value=''>
            <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Consultar</button>
        </form>
    </div>

The result is going to...

How do I take this result to the same page as the query (templates/pac_recepx.jinja2), that is, place it below the query?

Thank you in advance for your support.

Oberdan Costa

Laurent Daverio

unread,
Nov 23, 2023, 4:16:30 PM11/23/23
to pylons-...@googlegroups.com
Well, to be honest, it's not a question about Pyramid, it's a question about an absolutely basic pattern in web programming. I was doing that with Perl CGI scripts 25 years ago, when Python was still in infancy, and Pyramid didn't exist.

The problem is actually very simple : you use *one* view, not two, i.e. the form must call its own URL (e.g. action="#") 

The view tests if a non-null parameter "cpf" had been provided. If that's the case, you compute the results (SQL query), and you send the two values to the template (cpf, and the rows).

The template tests if it receives a "cpf" parameter. If so, it auto-fills the form, and displays the rows (using a combination of {%if ...}, {%for ...} etc. as appropriate).

Again, it's not a Pyramid question, or a Pyramid solution, I would have given you exactly the same answer with FastAPI, PHP, Rails, Flask, etc.

Mike Orr

unread,
Nov 23, 2023, 4:26:37 PM11/23/23
to pylons-...@googlegroups.com
On Thu, Nov 23, 2023 at 11:50 AM Oberdan Santos <sc.ob...@gmail.com> wrote:
>
> You should note in the subject statement that in addition to the query, I have the problem of the result being published on another page.
> query page code
> # templates/pac_recepx.jinja2
>
> <div class="form">
> <div class="row g-2 mt-3">
> <h3><span class="font-semi-bold">Consultar cadastro do paciente</span></h3>
> </div>
> <form class="form-inline my-2 my-lg-0" action="http://localhost:6543/queryx" method="GET">
> <label for="cpf">Digite o CPF (11 números)</label>
> <input class="form-control mr-sm-2" type="text" id="cpf" name="cpf" required maxlength="11" value=''>
> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Consultar</button>
> </form>
> </div>
>
> The result is going to...
> action="http://localhost:6543/queryx
>
> How do I take this result to the same page as the query (templates/pac_recepx.jinja2), that is, place it below the query?

There are two approaches.

SERVER-SIDE ONLY:

Remove the form `action` attribute. The form will post back to the
same view that contained the form. In the view, add an `if` stanza to
distinguish whether there's form input or not:

```
cpf = request.params.get("cpf", "") # User input, or "" if no input.
error = "" # Validation error
message, or None if no error.
rows = None # Result rows, or None
if no valid input, or [] if valid input but zero results.
if cpf: # If value is not "" or None.
if CPF_IS_VALID:
rows = request.dbsession...
else:
error = "Input is invalid."
return {"cpf": cpf, "error": error, "rows": rows}
```

Then your template might always show the form, but only show the
results section if there was input, and only show the results table if
there was at least one result, and only show the error message if
there was a user error. I use Mako templating so I'll write it that
way.

```
## page.mako
<form method="GET" class="...">
% if error:
<div>${error}</div>
%endif
<input name="cpf" value="${cpf}" ... />
</form>

% if results is not None: # If there was valid user input.
<h2>Results</h2>
% if results: # If there was at least one result.
<table>
<th>Header</th>...
% for r in results:
<tr>...</tr>
% endfor
% else: # Else there were zero results.
<p><em>No results.</em></p>
% endif
```

CLIENT-SIDE ALTERNATIVE:

Write Javascript to intercept the Submit click. Send an AJAX request
to the server to get the results in a JSON array. Use Javascript to
populate the results table. That's beyond the scope of this mailing
list. In this case you'd have a view that processes the AJAX request
and converts the rows list to JSON before returning it.

Oberdan Santos

unread,
Nov 30, 2023, 12:00:10 PM11/30/23
to pylons-discuss
Hi Mike. I tried many things, including beyond your tip, but I can't make any progress. I think it's something simple. Attached is my last attempt. If you can help I would appreciate it.

pac_recepx.txt
pac_query.txt
view.txt
Reply all
Reply to author
Forward
0 new messages