skip to Main Content

I have a table myuser with two columns (id serial primary, username varchar(20) unique not null). I am trying to make a Tkinter gui that takes "username" from a form and inserts it in the postgres table myuser.

I want to generate a warning when "username" field is left empty (or any other invalid requests) in the gui. How to do that ? Could not find any suitable answers in psycopg error lists.

I tried the following, but if I keep the username field in the gui empty, I don’t see any warning, and the program runs without error. I expected to see a warning with this if condition.

Also, if there are other types of invalidity (> 20 characters), my solution would not work. So, what would be the best way for doing this ?

name = namefield.get() 
try:
    c.execute('''INSERT INTO myuser (username)
        VALUES (%s)''', (name,)
        )
    if name == None:
       print('Please insert a valid username')
    
except psycopg2.IntegrityError:
   conn.rollback()
else:
   conn.commit()

Many thanks for your help!

2

Answers


  1. Go with the checks on backend side. Check for null value for username and show a proper prompt.

    Something like this:

     if not name://i.e., if null
         messagebox.showwarning('Warning', 'Please insert a valid username')
     else:
         //insert to database
    
    Login or Signup to reply.
  2. just to check 2 cases in python and then try to execute sql query.

    name = namefield.get() 
    if not name or len(name) > 20:
        print('Please insert a valid username')
    else:
        try:
            c.execute('''INSERT INTO myuser (username) VALUES (%s)''', (name,))
        except psycopg2.IntegrityError:
            conn.rollback()
        else:
            conn.commit()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search