Setting a default image on new record in database

Hi

I have created a new column in users, called UserImage. I want to set up that column so that a default profile image is set in that field when a new user signs up.
When creating a user I tried adding a field to the login code UserImages = 'blankprofile.png' but it causes an error.

I have uploaded that image to assets on anvil, should the path be assets/blankprofile.png or what should it be? I want to add it to this row. Like this.
user = app_tables.users.add_row(email=email, enabled=True, Firstname=Firstname, UserImage='blankprofile.png', Surname=Surname,password_hash=pwhash)

What is the type of the UserImage column? If it’s text, what you’re doing should work.

If it’s Media, then you have to give it a Media object, not a text string. Here’s an example of getting a file into a Media object: Accessing .txt asset from client module - #3

You wouldn’t do the get_bytes part of that, you’d just put the entire Media object into your data table field.

I set the type as media object. So in their example

url = anvil.server.get_app_origin() + "/_/theme/my_file.txt"
file_contents = URLMedia(url).get_bytes()

I’d do this, without the getbytes part?

url = anvil.server.get_app_origin() + "/_/travevo/blankprofile.png"
file_contents = URLMedia(url)

And then in my line of code I’d put:

user = app_tables.users.add_row(email=email, enabled=True, Firstname=Firstname, UserImage=file_contents, Surname=Surname,password_hash=pwhash)

It would be:

url = anvil.server.get_app_origin() + "/_/theme/blankprofile.png"

Unless you have created a folder named travevo in your Assets section, in which case it would be:

url = anvil.server.get_app_origin() + "/_/theme/travevo/blankprofile.png"

The /_/theme/ portion is the root of your Assets section.

2 Likes

Ahh got you, thanks for that.

I just set it up and am getting this error

NameError: name 'URLMedia' is not defined

  • at logincode, line 84

On my code is this, originally I had UserImage=file_contents, that came up with the same error, so I commented out file_contents and put URLMedia(url) as I figured this should also return the url. It did produce the same result e.g. an error, but I’m not sure how to fix it, since isnt URLMedia already defined in Anvil???:-

  def add_user_if_missing():
    user = app_tables.users.get(email=email)
    url = anvil.server.get_app_origin() + "/_/theme/blankprofile.png"
   # file_contents = URLMedia(url)
    if user is None:
      user = app_tables.users.add_row(email=email, enabled=True, Firstname=Firstname, UserImage=URLMedia(url), Surname=Surname,password_hash=pwhash)
      return user

Server modules generally don’t do from anvil import *, so you have to specify anvil.URLMedia or do the import from anvil import URLMedia

2 Likes

Thanks Jay, that worked perfectly!!!

1 Like