py4web posting to db

119 views
Skip to first unread message

Maurice Waka

unread,
Feb 28, 2020, 1:29:01 PM2/28/20
to web2py-users
I'm still learning a lot from py4web.....especially not being a programmer myself, and I appreciate a lot from the help I get from you ALL. 

Anyway, I managed o create the tables and controller functions but I note that I'm not able to post to the database, at the same time, I cant see the messages on the index page..this code works well in web2py. I hope I have posted all relevant info.

My codes are as follows:
Controller:


import requests
from . common import *
from pydal.validators import *
from datetime import datetime, timedelta, date
from py4web.utils.auth import Auth
from py4web.utils.form import Form, FormStyleBulma
from py4web.utils.publisher import Publisher, ALLOW_ALL_POLICY
from .common import db, session, T, cache, auth, logger, authenticated, unauthenticated
from py4web import action, request, DAL, Field, Session, Cache, user_in, abort, redirect, URL, Translator
from pydal.validators import IS_NOT_EMPTY, IS_INT_IN_RANGE, IS_IN_SET, IS_IN_DB, IS_EMAIL, IS_MATCH
from yatl.helpers import A, TEXTAREA, INPUT, TR, TD, TABLE, DIV, LABEL, FORM, SELECT, OPTION, P, H1, H2, H3, H4, H5, HTML, BODY, META


auth
= Auth(session, db)
# (configure here)
auth
.enable()


@authenticated()
@action.uses(db, session, T, auth.user)
def index():
    codes
= []
   
del codes[:]
    r
= []
    yesterday
= datetime.utcnow() - timedelta(days=1)
    db
(db.answers.modified_on < yesterday).delete()
    form
= FORM(INPUT(_name='message'), INPUT(_type='submit'))
   
if request.POST.vars:
        r
.append(request.POST.message)
        codes
.append(r[0])
       
#db.posts.insert(message=codes[0])
        rows
= db(db.posts.author== auth.user_id).select()
       
for row in rows:
            row
.update_record(message=codes[0])
   
...more code
    reports
= 'wellness_main.report()' #data from modules
    name3
= request.POST.message #string from user
    db
.answers.insert(quest=name3, message = report())

    replies
= db(db.answers.author == auth.user_id).select(db.answers.ALL, orderby=db.answers.created_on)[-7:-1] # show the last few posts from the table
   
return dict(name3=name3, reports=reports, replies=replies)

Models:

from datetime import datetime, timedelta, date
from py4web import action, request, DAL, Field, Session, Cache, user_in
from py4web.utils.auth import Auth
from py4web import action, request, abort, redirect, URL, Field
from py4web.utils.form import Form, FormStyleBulma
from py4web.utils.publisher import Publisher, ALLOW_ALL_POLICY
from pydal.validators import IS_NOT_EMPTY, IS_INT_IN_RANGE, IS_IN_SET, IS_IN_DB, IS_EMAIL, IS_MATCH
from yatl.helpers import INPUT, H1, HTML, BODY, A
from pydal.validators import *
from . common import db, session, T, cache, authenticated, unauthenticated, Field




# exposes services necessary to access the db.thing via ajax
publisher
= Publisher(db, policy=ALLOW_ALL_POLICY)
# define session and cache objects
session
= Session(secret="some secret")
cache
= Cache(size=1000)


auth
= Auth(session, db)

# (configure here)
auth
.enable()


db
.define_table('posts',
               
Field('author', 'reference auth_user', default=auth.user_id, writable=False, readable=False),
               
Field("message", 'text', requires=IS_NOT_EMPTY(), notnull=False),
                auth
.signature

               
)
db
.define_table('answers',
               
Field('author', 'reference auth_user', default=auth.user_id, readable=False, writable=False),
               
Field('quest', 'text', requires=IS_NOT_EMPTY(),),
               
Field("message", 'text', requires=IS_NOT_EMPTY(),),
               
Field('posted_on','datetime', default=datetime.utcnow()),
                auth
.signature
               
)

View...index.html

N/B
This is part of a long html, js code:

<ul class="messages">
    [[for reply in replies:]]
   
<li class="message right appeared">
       
<div>[[=reply.modified_on]]</div>
       
<div class="text_wrapper">
           
<div class="text">[[=XML(reply.quest, sanitize=True)]]</div>                    
       
</div>
   
</li>
   
<li class="message left appeared">
       
<div>[[=reply.posted_on]]</div>
       
<div class="col-md-1 col-lg-2"></div>
       
<div class = "col-md-10 col-lg-8">
           
<div class="text_wrapper">
               
<!--div class="readmore"-->                                
               
<div style="font-family: 'Josefin Slab';font-size: 1.2em; color: black;">
                   
<a href="#" id="[[=reply.id]]-show" class="showLink" style=" color:#38D9D6;font-size:18px;"onclick="showHide('[[=reply.id]]');return false;">Read answer</a>
                   
<div id="[[=reply.id]]" style="background: #EFF2F2; height: 0px; overflow: hidden; transition: height 2s; -moz-transition: height 2s; -webkit-transition: height 2s; -o-transition: height 2s;"class="more">                                    
                       
<div id="text-content"style="text-align: justify; font-weight: lighter; line-height:1.4; hyphens: manual; word-wrap: break-word;color:black;font-size: 16px;">[[=XML(reply.message, sanitize=True)]]
                       
</div>
                       
                   
</div>
                   
               
</div>
                [[pass]]
           
</div>
       
</div>
       
<div class="col-md-1 col-lg-2"></div>
   
</li>
</ul>

Maurice Waka

unread,
Mar 3, 2020, 5:08:27 AM3/3/20
to web2py-users
Any help on this please ?

Dave S

unread,
Mar 3, 2020, 4:46:36 PM3/3/20
to web2py-users


On Tuesday, March 3, 2020 at 2:08:27 AM UTC-8, Maurice Waka wrote:
Any help on this please ?

On Friday, February 28, 2020 at 9:29:01 PM UTC+3, Maurice Waka wrote:
I'm still learning a lot from py4web.....especially not being a programmer myself, and I appreciate a lot from the help I get from you ALL. 

Anyway, I managed o create the tables and controller functions but I note that I'm not able to post to the database, at the same time, I cant see the messages on the index page..this code works well in web2py. I hope I have posted all relevant info.


[much snipped]

Okay, you've posted what you don't see happening.  What happens instead?  Are there errors?  Unexpected output?  Have you examined the response using the browser tools?  Have you added any logging on the server side?

If there are any relevant screen shots, it would be okay to include those.

Oh, and since you say this works with web2py, are you using the same client-side code in both cases?  That the difference is all server side?

/dps

Maurice Waka

unread,
Mar 4, 2020, 5:30:09 AM3/4/20
to web2py-users
I've done some look up into the code, did some changes and checked how it behaves.

I noted, that using the same code....something is not right with the author field.
See the screen shot, the author is not posting but the rest of info is posting. I used the sqlite browser to check the messages.
This is the current error i'm now getting with the same code.
def index():
    ...code here...
    r = []#info will be posted here
    codes = []
    del codes[:]

    form = FORM(INPUT(_name='message'), INPUT(_type='submit'))
    if request.POST.vars:
        r.append(request.POST.message)
        codes.append(r[0])
        rows = db(db.posts.author== auth.user_id).select()
        for row in rows:
            row.update_record(message=codes[0])
    name3 = request.GET.message 
    db.answers.insert(quest=name3, message = report())#, file=photos)
    db.posts.insert(message = report())
    ####>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>RETRIEVE MESSAGES<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    ##replies = db(db.answers.author == auth.user_id).select(orderby=~db.answers.created_on, limitby=(0,10))
    replies = db(db.answers).select(orderby=~db.answers.created_by, limitby=(0,10))
    return dict(name3=name3, replies=replies)

template:
[[extend 'layout.html']]
[[import datetime]]
[[from yatl.helpers import A, TEXTAREA, INPUT, TR, TD, TABLE, DIV, LABEL, FORM, SELECT, OPTION, P, H1, H2, H3, H4, H5, HTML, BODY, META]]

<body>    
    <div class="chat_window" id="a2">
        <ul class="messages">
            [[for reply in replies:]]
            <li class="message right appeared">
                <div>[[=reply.modified_on]]</div>
                <div class="text_wrapper">
                    <div class="text">[[=XML(reply.quest, sanitize=True)]]</div>
                    
                </div>
            </li>
Error message:
Traceback (most recent call last):
  File "/home/maurice/py4web/py4web/core.py", line 551, in wrapper
    ret = func(*func_args, **func_kwargs)
  File "/home/maurice/py4web/py4web/core.py", line 514, in wrapper
    ret = obj.transform(ret)
  File "/home/maurice/py4web/py4web/core.py", line 300, in transform
    reader=Template.reader,
  File "/home/maurice/.local/lib/python3.6/site-packages/yatl/template.py", line 968, in render
    exec(code, context)
  File "<string>", line 39, in <module>
TypeError: URL() got an unexpected keyword argument 'args'


--
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
---
You received this message because you are subscribed to a topic in the Google Groups "web2py-users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/web2py/cneqSQXGacE/unsubscribe.
To unsubscribe from this group and all its topics, send an email to web2py+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/web2py/9fa18a69-4d5c-4339-896e-41ce795c2e96%40googlegroups.com.

Lovedie JC

unread,
Mar 4, 2020, 6:34:30 AM3/4/20
to web...@googlegroups.com
I just found out that the error was because I was having a null variable instead of an image in one of the lines.
I still can't figure out how I can't have the Field(author, reference auth_user
work. 

You received this message because you are subscribed to the Google Groups "web2py-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to web2py+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/web2py/CALkNK57StytFMf05toP5E1-tMVYDQqnEzkYC7zRMHXAC57simA%40mail.gmail.com.
Reply all
Reply to author
Forward
0 new messages