#web-development

2 messages Β· Page 47 of 1

rustic pebble
#

Yea

#

But it still doesnt work for me

#
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)

# DB STUFF
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://myurlhere'
app.secret_key = '3904-39034-094-3290-'
db = SQLAlchemy(app)

from controllers.database import Idea
from helpers.user_post import Post
Idea.initiate()
sly canyon
#

very strange

#

I'm actually not sure

rustic pebble
#

yea

sly canyon
#

I'd try to change the way you're organizing the app

#

For consistency, I always organize it as Miguel Grinberg suggests

#

But I really can't catch why is this occuring to you

#

I'm also not sure if you have to name your models file as models.py

rustic pebble
#

I dont think I need

sly canyon
#

Maybe that's a constriction in Flask

rustic pebble
#

hmm

#

I will try and do this on linux

native tide
#
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg',
                              upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        # Resize Image
        basewidth = 300
        img = Image.open(self.image.path)
        wpercent = (basewidth / float(img.size[0]))
        hsize = int((float(img.size[1]) * float(wpercent)))
        img = img.resize((basewidth, hsize), Image.ANTIALIAS)
        img.save(self.image.path)

This was the example from my practicve project that used it. I'm giving up Django to learn Flask I think though so Im probably nto going any further with it.

#

I would use Django if I was making a full featured blog that I needed to just be a blog that has everything a blog has. Otherwise Im tired of dealing with modifyuing it. Id rather just start from the bottom.

native tide
#

@rustic pebble Do you use flask-bootstrap or do you just do it manually? I think im gonna skip this for now.

rustic pebble
#

I do it manually

#

Every time

#

I usually take a template and change the shit out of it

#

I am just bored to build the foundation

native tide
#

I just saw this extension and foudn that it overly complicates using bootstrap which is already just simple af

#

So if theres no reason to use this extention I wont

#

What are Blueprints?

#

Im probably getting ahead

rustic pebble
#

Hmm

#

I cant really explain how blueprints work tbh

rustic pebble
#

Can someone tell me why this isnt working as it should?

#
        for (item in postsbody) {
            if (!(postsbody[item].innerText in posts_in_dom)) {
                if (postsbody[item].innerText) {
                    posts_in_dom.push(postsbody[item].innerText)
                }
            }
        }
native tide
#

The save method is essential if you want to make any changes to the image before you save it.

#

Which you typically do because otherwise people will upload 4k images lol

rustic pebble
#

and I can benefit off that
took me around 2 hours

manic siren
#

Anybody here know any good tools/libraries etc... to help me make user post feed which also connects between my react front end and flask backend?

fresh dock
#

@manic siren you trying to connect flask to your data source?

#

I suggest sqlalchemy to interact with your db

manic siren
#

@fresh dock Well right now Im just trying to figure out the React part and how exactly to do this. I've been using React for about 2 weeks and things are very confusing. I tried asking in the React discord but nobody really helped me so I thought I'd try here

fresh dock
#

@manic siren never used react myself but I'm literally building an indie social network platform startup on flask and sqlalchemy so I can probably answer all your other questions

#

Oh god react looks like a strictly worse jinja2

#

Kill it

#

Kill it with fire

manic siren
#

I freaking hate it

#

I hate javascript too

fresh dock
#

@manic siren are you constrained to using react or can you switch to an actual templating engine like jinja2 which comes pre packaged with flask

manic siren
#

@fresh dock Im only allowed to use React since thats what we've been learnining in my bootcamp and just in case I have issues my instructors will be able to help me

fresh dock
#

Ah

manic siren
#

@fresh dock I'll definitely have some backend questions for Feed stuff so I'll def come to you

#

I appreciate it!

#

Right now I'm trying to build a morning commuter app. The feed idea is basically similar to what we have on discord. To the left, you have your different channels which in this case would be my trains. Then the Feed which hosts the comments made by users and a comment box below the feed where the user can post a comment.

fresh dock
#

@manic siren so I'm a back end guy. Do you have your flask app connected to your data source yet or no?

manic siren
#

Not yet, I was gonna format my front end first then go to the backend since the front end stuff is what I have most trouble with

#

At least doing this project gives me a sense of what area of development I'd like to be in lol

fresh dock
#

Ah

#

Yeah

#

Front end is a bunch of witchcraft to me

#

Back end is a bunch of black magic to my front end business partner so...

#

We work well together

#

It lets you turn db columns into object properties and automagically handles all the sql in between

manic siren
#

Ahhh interesting

#

Up until now I've been manually doing it sqlite3

#

Thanks! definitely gonna take a look into it

fresh dock
#

@manic siren yikes. If your thing is gonna take any kind of user generated input, then you definitely want something like sqlalchemy to handle all the sql

#

Otherwise every function is 1) an opportunity to fuck up, and 2) an opportunity to not properly sanitize

manic siren
#

By sanitize what do you mean exactly?

fresh dock
#

@manic siren basically, if you fuck up escaping while inserting your user-generated input into an sql query, you end up with the db executing that text as sql code

manic siren
#

Ahhh I see

fresh dock
#

If you use a package like sqlalchemy, it takes care of all that for you and you never have to worry about it

manic siren
#

Well by manual I mean, I have a function that inputs the user for me

#

Ill show you an example

fresh dock
#

In the comic, the school server fails to escape the ' in Bobby Tables's name

#

Which makes the db think "end of name input string"

#

Followed by a ); to close out the query and then it proceeds to execute DROP TABLE Students

#

There are several other tricks that can be exploited in other ways

manic siren
#

lolllll thats hysterical

#

def save(self):     #saves file
        if self.pk is None:
            self._insert()
        else:
            self._update()

    def _insert(self):
        with sqlite3.connect(self.dbpath) as conn:
            cur = conn.cursor()
            sql = """
            INSERT INTO {} (username, encrypted_password, f_name, l_name,  email)
            VALUES(?,?,?,?,?);
            """.format(self.tablename)

            values = (self.username, self.encrypted_password, self.f_name, self.l_name, self.email)
            cur.execute(sql, values)

    def _update(self):
        with sqlite3.connect(self.dbpath) as conn:
            cur = conn.cursor()
            sql = """UPDATE {} SET
                     username = ?, f_name = ?, l_name = ?, crypted_password = ?, email = ?
                     WHERE pk = ?;
            """.format(self.tablename)
            values = (self.username, self.encrypted_password, self.f_name, self.l_name, self.email, self.pk)
            cur.execute(sql, values)




#

I was told the ? prevent sql injections

fresh dock
#

Not that particular implementation unfortunately

#

Also you don't want to be making and killing connections all the time

#

That's sloooo

#

@manic siren ^

#

Also are you encrypting passwords? Or hashing them?

#

Werkzeug (which comes packaged with flask) has a proper function for pw hashing and verifying

#

Salts and hashes and all that in one function call

rustic pebble
#

Does anyone know whether I can link a function when creating a new element?

#

Basically I am creating a button and I want to add an onclick function to that new button

#

but I am getting objectpromise whenever I try to set it

#
            downvote.setAttribute('onclick', update_votes('downvotes'));
#

oh nvm found it

manic siren
#

@fresh dock Im using bcrypt to encrypt my passwords. Makes for checking them so much easier lol

native tide
#

I'm a little worried about the SQL part of flask. But I'll have a look at sqlalchemy when I get to it.

#

Im so far liking it more than Django.

rustic pebble
#

@native tide You will find it very easy

#

You just define classes

#

And then just update objects

#

Nothing more

#

Nothing less

native tide
#

I want to edit bootstrap colors. I think I need to learn how to compile scss down to css to do that effeciently.

#

I could just change the colors around at the top under :root {} but...

#

these colors and variations of them are referenced too many times not using var(--color)

#

That I basically need to learn scss to do this.

#

I could do a global find and replace... but...

#

There is going to be a mess when I get the colors slightly off, which they will be at first.

#

Dude Im looking at how sass can adjust your colors for you

#

and im sold

#

I have to learn this

rustic pebble
#

sass is good

#

But I will never put the effort to learn i

#

it

native tide
#

yeah... I enjoy CSS. The part of front end that I dont like is JS. But thats only because im not very good at it yet.

#

So Im not going to deviate to learn it now

#

But eventually need to

#

sass that is

#

I just found a program to generates the variations in colors for you for now haha

rustic pebble
#

The only part about frontend I enjoy is css

#

x

#

d

native tide
#

Well, overall, sass appears to just make css easier for you if you ever have a very specific color scheme in mind or something like that.

#

Its just one of the other million things i need to learn that i can only do one at a time

rustic pebble
#

I only learn things I need

#

So idk

#

I usually just buy/use and fully customize templates

#

setting up servers is so hard

native tide
#

My first websites were before the age of bootstrap, and back then I put a lot more effort into just laying out a page. This is back when I was a kid. (getting back into this kind of thing is kind of my midlife crisis if you didnt know that)

These days I dont typically use an entire template. But I do look at the documentation for how to show this kind of thing, and then I piece together small templates into something bigger... made up of templates.

#

Its a lot less work. Frankly, I think it makes the entire Internet look exactly the same but...

#

I also know that its a level of polish that the average user expects today.

#

It is what it is

#

We see bootrstrap and we immediately realize, "ah, that's the bootstrappiest thing ive ever seen"

#

An end user sees anything that inst bootstrap and they think, "What is this the 1990s?"

#

shrug. lol. Its less work for me

rustic pebble
#

Well that is why I heavily mod everything

#

And xD i am 18 I still have a lot to learn

#

And I don’t really think that people mind if you use bootstrap as long as you are creative about it

native tide
#

I was this kind of thing from age 13-18. At age 18, when I was free of my house, I spent significantly less time on my computer and went in a different direction at school.

#

Funny that Im back into what I was into when I was a kid now

rustic pebble
#

Eh idk

#

I love coding

#

But I also have a very active social life

#

It is very strange since devs have been given a bad reputation concerning socialization

#

I want to study CS

#

But unis here are hard asf to get into

#

Those who get are only those who can remember whole books and not actually people who are worth it

#

I got to school and I teach my professor about programming haha

native tide
#

See, I wasnt a programmer as a kid. I put together pages in HTML and CSS. I didnt know JavaScript at all. It wasnt like a thing I was a good at. It was a thing I did because at that time, all your little friends at school would have stupid little geocities pages.

#

But a year or two ago

#

I felt something was missing in my life and I needed a hobby

#

And I happened to get a lot more into it than I was as a kid

rustic pebble
#

Well jt might be the understanding you have

#

Before I started using js/python/c#/etc

#

I was afraid of anything that had to do with backend

#

But then I just took a brave decision to learn python

#

And it naturally hit me I need more knowledge on others as well

native tide
#

I just didnt have access to the concept of backend. I remember knowing that if I ran my own server or could afford hosting that I could use PHP to do things you couldnt do without PHP.

#

At the time that was the in web lang

#

But I didnt have access to that stuff

#

I do now

rustic pebble
#

I really cant even afford to buy a domain

#

Right now

native tide
#

lol it happens

rustic pebble
#

And I have like 4 projects on delay

native tide
#

Back then they did not have simple web servers that opened up in your IDE

rustic pebble
#

But eh, idgaf I will get a job in summer

native tide
#

It took... it took more to be exposed to these things back then

#

Now almost anyone can learn.

rustic pebble
#

True

#

But also not true

#

People in school think I should be working in Nasa rn but the truth is that 80% of people here are better than me

#

Its all about perspective

native tide
#

Hm, I suppose. What I'm saying is that... the best programmers are the ones whose family are educated and have a lot of computers around and get them started very early. Today almost any kid can be like, "I want to be a programmer" and download some IDE and is on his way.

#

At one time you needed books.

#

You needed servers.

#

Real onmes

#

And the list goes on.

#

Its easier to get into today.

rustic pebble
#

Hmm well actually I was exposed to computers very early

native tide
#

You dont even neeed a college educatiuon anymore.

#

lol

rustic pebble
#

And I was also prompted to be the creator not the user

#

So I sort of grew up with the mind scheme of developing

native tide
#

yeah. Well it was definitely always a potential thing in me that I didnt pursue heavily until later.

rustic pebble
#

Well coding was considered a hard thing 20 years ago

#

And btw I dont agree with your Ide approach, IDEs can help disorientate new programmers because of their infinite features

#

How are you going to explain Git to someone who can barely print hello world

#

What about file structuring, pep8

#

Etc

native tide
#

I pretty much agree. I know a kid who is like 15 taking college courses and he just failed his first test because he relies on the IDE

#

you're preaching to the choir lol

rustic pebble
#

I am happy I learned coding on sublime

#

Yea idk

native tide
#

I think that it becomes a useful productivity tool but while learning Im grateful I became a drilled typist.

#

Hey I have a question for you if you know the answer, othewise Ill search

rustic pebble
#

Sure

#

If it has to do with django I cannot rly answer

native tide
#

I dont want my login form to have field labels. I want it say grayed out, inside the form while its blank: "Email" and "Password" and when you select it and start typing it replaces it with darker normal text.

#

Flask.

#

Im fully on Flask now.

#

Its much better for me.

rustic pebble
#

That is placeholdwe

#

Placeholder

#

And replacing with dark is css

#

But if you want to add a background text

native tide
#

Cool. Is that an HTML attribute of the form?

#

I'll look it up

rustic pebble
#

You just do <input placeholder=β€œtext”></input>

#

Replace text with the value you want and you got it

native tide
#

Right.

rustic pebble
#

Flask is perfect

native tide
#

Got it, thats much easier than i thought haha

rustic pebble
#

I made a website for posting ideas

#

In 4 hours today

native tide
#

So hold on though

#

I just realized Im not using input tags like normal

#

I have this

rustic pebble
#

Let me see

native tide
#
@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        flash(f"Account created for {form.email.data}", 'purple')
        return redirect(url_for('home'))
    return render_template("register.html",
                           title="Register",
                           form=form)

and that goes to this

   <legend class="border-bottom mb-4">Join Today</legend>
        <div class="form-group">
          {{ form.email.label(class="form-control-label") }}
          {{ form.email(class="form-control form-control-lg") }}
        </div>
        <div class="form-group">
          {{ form.password.label(class="form-control-label") }}
          {{ form.password(class="form-control form-control-lg") }}
        </div>

Where can I put that placeholder prop?

rustic pebble
#

You wouldnt want that

#

Just create a normal form

#

With inputs

native tide
#
class RegisterForm(FlaskForm):
    email = StringField("E-mail",
                        validators=[DataRequired(),
                                    Length(min=4, max=32),
                                    Email()])
    password = PasswordField("Password",
                             validators=[DataRequired(),
                                         Length(min=8)])
    password_confirm = PasswordField("Confirm Password",
                                     validators=[DataRequired(),
                                                 EqualTo('password')])
    submit = SubmitField('Sign Up')

#

forgot that part

rustic pebble
#

Aaaah

#

You are doing it the hard way

native tide
#

am I? lol

rustic pebble
#

Fck its 6:40 am

#

Let me open my pc

native tide
#

Sorry, do what you got to do

rustic pebble
#

Well I havent slept so im ok

native tide
#

haha I do that a lot.

#

its 1130pm for me

rustic pebble
#

I really shouldnt

native tide
#

same

rustic pebble
#

I suppose you have a db model?

native tide
#

Not yet, that's next. I dont even have a database yet.

#

I do but its not in the flask app

#

I was just curious about this appearance thing

#

boom

#

so you dont use wtforms?

rustic pebble
#
   <legend class="border-bottom mb-4">Join Today</legend>
         <form action='/register' method='post'>
          <div class="form-group">
            <label class='form-control-label'></label>
            <input placeholder='E-Mail' name='email'>
          </div>
          <div class="form-group">
            <label class="form-control-label"></label>
            <input placeholder='Password' name='password'>
          </div>
        </form>
#

This should be html

#

this should be python

native tide
#

Right, if I was writing it all as HTML, I could do that.

#

Do you write custom validation?

#

and csrf?

rustic pebble
#
@app.route('/python', methods=['POST'])
def register():
  data = request.form
  email = data['email']
  password = data['password']
native tide
#

hrm

rustic pebble
#

Ehm

#

I deal with this differently

native tide
#

Word.

rustic pebble
#

btw

#

You should never be saving passwords

#

as passwords

native tide
#

haha, yeah I know that. Thats another thing Im concerned about is that Django takes all of this for you. Im happy to learn to do it manually but. yeah

#

Im aware of that

rustic pebble
#

Usually what you would want is a hash

native tide
#

For sure.

rustic pebble
#

Also what have you considered to implement for sessions?

#

I use JWTs

native tide
#

Havent got that far, another thing Django does for you.

#

I'll get there. Im a pretty thorough studier though.

rustic pebble
#

Well tbh

#

You should just try to do things the simple way

#

Utilizing jinja is ok

#

But as you see it is not optimal

native tide
#

No thanks.

rustic pebble
#

I never utilize jinja

native tide
#

No thanks. But thank you.

rustic pebble
#

Sure

#

But you arent going to get live updates

#

with that

#

That is true, but js allows you to do

#

50 times more things

#

with the data you get

#

Like I usually create diagrams, analytics, etc on my websites for the admins

#

How are you going to do that with jinja

#

And also server side rendering doesnt allow responsiveness to occur

#

Whereas you can just refresh elements with js

native tide
#

Im not trying to say I'll never learn to use JavaScript. Its just not what Im focused on right now. I started playing with React a little bit but then I found myself more intersted in learning Flask. I intend to make full use of Flask. I like Python more than JavaScript. Infinitely more.

#

I know that I will have to use it sometimes.

#

But I dont need to rely on it.

#

You call it the easy way and maybe thats how you feel but templates are not difficult.

#

Using JavaScript when yopu dont need it is like taking a flamethrower to a cock roach.

#

But I get that there are times its the only thing that can do the thing

rustic pebble
#

You are right

#

But then again I don’t agree entirely haha

#

Lets just agree to disagree

native tide
#

that's cool, nothing wrong with that.

#

We agree about Flask at least. I like it as much as you do haha.

#

I think its possible I will be missing some features that Django has but one thing I like about that is...

#
  1. learning to do them myself
#
  1. not having to deal with the bloat when Im done
#

When you learn to do Django, theres a huge part of it that feels like, "Well damn, I couldnt have done any of that by myself."

#

Its literally all done for you. If you're cool with default, its already done. lol

#

The problem is, I find it easier to just build from the bottom that try to adjust default behavior constantly

#

Its possible, but its annoying.

#

So yeah

vestal hound
#

the main reason I use Django is the ORM

sharp briar
#

How can I emit an event in a flask route using flask_socketio? I can't seem to get a response to my client

fresh dock
#

@manic siren you should be bashing passwords and comparing the hashes. Werkzeug.security has a great function for this

native tide
#

The ORM is nice. I might look at other ORMs after seeing it in action.

vagrant adder
#

I'm thinking of using peewee for a project i have in mind

#

The creator of it very active on reddit

bleak bobcat
#

@vestal hound agreed. Django's ORM is awesome. I even have a stripped down version of django where only the ORM (and migrations) works because I find it far superior to SQLAlchemy

native tide
#

That's interesting. You use Django just to migrate to your database?

#

Django's ORM is probably the best thing about it.

#

I have this looking all decent. Now to actually connect it to a database. I might do this part tomorrow. This is Flask.

#

I have yet to see what its like doing the database part with Flask yet.

native tide
#

I just started the SQL Alchemy lessons. It seems like its pretty similar... At least so far

short venture
#

Hello all,

I have just completed my first project ever. I have made a simple Stock Management API. Since i have never deployed a project to the production environment before by my own, i don't know how to do. Can you guys tell me how to do it? I want to deploy it to Heroku. Project link:

https://github.com/Ksenofanex/stock-management-api

rustic pebble
#

@native tide sorry for not replying I actually just died on my pc haha

#

@native tide as I said SQL part of Flask is almost identical to classes

#

Let me give you an example

#

After conntecting to your db you need to somehow create a table

#
class Idea(db.Model):
    __tablename__ = "ideas"

    id = db.Column(db.Integer, primary_key=True)
    title= db.Column(db.String(50))
    post_body = db.Column(db.String(50))
    author = db.Column(db.String(50))
    upvotes = db.Column(db.Integer)
    downvotes = db.Column(db.Integer)

    def __init__(self, title: str, post_body: str, author: str, upvotes: int, downvotes: int):
        self.title = title
        self.post_body = post_body
        self.author = author
        self.upvotes = upvotes
        self.downvotes = downvotes
#

This creates a table and adds the items you see as db.Column as columns

#

Then if you want to update a row, you just need to query the table by doing:

ideas = Idea.query.all()
#

This will give you a list of objects that are essentially the rows of the table

#

And you can access them directly as if they were just normal objects

#

If you want to update a row you can just do:

ideas = Idea.query.all()
for idea in ideas:
   if idea.title == 'MyTitle':
    new_idea = Idea(idea.title, post_body='updated post body', author=idea.author, upvotes=idea.upvotes, downvotes=idea.downvotes)
    db.session.add(new_idea)
    db.session.commit()
#

And that is essentially the core elements of SQL with flask

native tide
#

Best possible way to override the indexview of Flask Admin without running into collision whole time ?

elfin solstice
#

Here is my conf file, in /etc/apache2/sites-enabled:

<VirtualHost *:80>
 ServerName artybot.xyz
 DocumentRoot /home/artemisweb/artemisweb
 WSGIScriptAlias / /home/artemisweb/artemisweb/artemisbots/wsgi.py
 
 WSGIDaemonProcess artybot.xyz processes=2 threads=15 display-name=%{GROUP} python-home=/home/artemisweb/artemisweb/venv/lib/python3.8
 WSGIProcessGroup artybot.xyz
 
 <directory /home/artemisweb/artemisweb>
   AllowOverride all
   Require all granted
   Options FollowSymlinks
 </directory>
 
 Alias /static/ /home/artemisweb/artemisweb/main/static/
 
 <Directory /home/artemisweb/artemisweb/main/static>
  Require all granted
 </Directory>
</VirtualHost>

However, when I attempt to access the website, it just times out. What am I doing wrong? I have recently purged and reinstalled apache2

magic blade
#

i'm struggling with django-storages S3 backend, running django1.11 and python3.6 (long road towards getting the whole system up to date...)

#

we have some components that generate files and save them to FileFields; currently using storages.S3Boto3Backend i can't successfully save these FileFields. if i manually create an S3Boto3BackendFile and do model.file_field = s3file_object it says the file is there, but calling either model.file_field.save(filename, s3file_object) or model.save() resets me to FileField: None

#

the file does appear to get uploaded to s3 successfully, but the model doesn't know where to find it!

#

@elfin solstice - anything in the logs for apache? is this a plain wsgi app?

magic blade
#

ok. fiddled around and found something that worked but it doesn't seem to match the intended behavior, and based on my limited understanding of the code i don't understand why this is the only way that works, but for my case, if you create the file separately, then do model.file_field.name = filename and model.save() ... it works properly.

elfin solstice
#

@magic blade
Couldn't find any logs. It's django

sharp briar
#

Any reason why I can't make any post or get requests to my flask routes when I have an open socket? (using flask and flask_socketio together)

native tide
#

So, import hell is apparently a common problem in Flask? Or have they found a modern solution and agreed upon best practice? It seems there are a variety of approaches to it.

rustic pebble
#

@native tide what do you mean?

native tide
#

I havent had the problem yet myself but Ive heard at least two people talk about it.
https://tracy.dev/how-to-mitigate-import-hell-in-flask/
https://www.youtube.com/watch?v=44PvX0Yv368

While that video says its about package structure, what its about is refactoring package structure due to import errors.

In this Python Flask Tutorial, we will be learning how to restructure our application into a package rather than running from a single module. This has major benefits in terms of importing modules across our application. Let's get started...

The code for this series can be fo...

β–Ά Play video
#

What Im asking is, these problems seem like the might be something that has been fixed.

#

And Im wondering if there is best practice now

rustic pebble
#

I have been having import problems

#

for ages

#

on flask

native tide
#

mm yeah it apparently common

rustic pebble
#

But its ok

native tide
#

Yeah, it's a thing I'll just have to learn when I get one

rustic pebble
#

Yup

#

Basically on more complex structures you are going to get that problem

native tide
#

Alright so this is where I am in my models...

# Models
class UserAccount(db.Model):
    """
    Account Holding User
    """
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default="static/default.jpg")
    password = db.Column(db.String(60), nullable=False)
    account_created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    agree_over_18 = db.Column(db.Boolean, nullable=False)

    def __repr__(self):
        return f"User('{self.id}', '{self.email}'>"

class PlayerProfile(db.Model):
    """
    Each user gets a player profile with which to make characters
    and save progress in various Campaigns
    """
    id = db.Column(db.Integer, primary_key=True)

It doesn't really make sense to have the primary key be another id when the PlayerProfile is essentially an extention of the UserAccount -- the only reason I have them as different models is because there are different types of profiles, for the Game MasterProfile (the person who writes the campaign) and its just easier to separate into different places.

But I'm not sure how connect them in the most normalized way.

Is this maybe a question for #databases ?

#

Or does it?

#

I guess the ids dont have to match

#

its not like they will be front facing

#

and while every UserAccount will have a PlayerProfile, not everone will have a GameMasterProfile

#

So I will have to get used to those ids being not the same anyway

native tide
#
sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship GameMasterProfile.campaigns - there are no foreign keys linking these tables.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.

So relationship needs a foreign key. I dont really get this entirely. You need a ForeignKey and a relationship

#

!paste

lavish prismBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

native tide
#

I tried to docstring the models so that you could see what Im ideally going for.

native tide
#

So it basically just seems like like every Foreign key needs an inverse relationship line from the model it comes from

#

Just having OneToOne, OneToMany, and ManyToMany would be bae af

#

So this is the most updated version

class UserAccount(db.Model):
    """
    Account Holding User
    """
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default="static/default.jpg")
    password = db.Column(db.String(60), nullable=False)
    account_created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    agree_over_18 = db.Column(db.Boolean, default=False)
    player_profile = db.relationship('PlayerProfile', backref="player", lazy=True)

    def __repr__(self):
        return f"User('{self.id}', '{self.email}')"

class PlayerProfile(db.Model):
    """
    Each user gets a player profile with which to make characters
    and save progress in various Campaigns
    """
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user_account.id'), nullable=False)
user = UserAccount.query.get(1)
>>> user
User('1', 'asdfasfsd@asdfdsfds.com')
>>> user.player
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'UserAccount' object has no attribute 'player'
#

What am I doing wrong?

#
>>> user_player = PlayerProfile()
>>> user_player
<PlayerProfile (transient 139645120491088)>
>>> db.session.add(user_player)
>>> db.session.commit()
Traceback (most recent call last):
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: player_profile.user_id
[SQL: INSERT INTO player_profile (user_id) VALUES (?)]
[parameters: (None,)]
#

OneToOne. It's a pretty awesome idea.

#

Just cant figure out how to do it.

weary arrow
#

try
user_id = db.Column(db.Integer, db.ForeignKey('useraccount.id'), nullable=False)

#

PlayerProfile requires a UserAccount id,
id = 1
new_player = PlayerProfile(user_id = id)
db.session.add(new_player)

native tide
#

that causes it to error at creating a new user.

sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship UserAccount.player_profile - there are no foreign keys linking these tables.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.

I think user_account is the table name that it would build based on UserAccount class. I could specify the table name I think by __table__ = 'user_account' to be sure

#

I got it to save a user and player.

#

By giving it an id like you said, specifically the id of the user.

#

But I still cant do user.player.some_player_prop

#

Which is what I need

#

I think this has what i need

#

I really wish this was the Django ORM lol

weary arrow
#

yeah I'd double check your table names

native root
#

For the relationship in sqlalchemy you're looking for you must specify BOTH a relationship attribute, and a separate linking ID attribute which is a foreign key

#

It will the (attempt) to link the two properties together for you

native tide
#

Thank you, that sort of makes me fee like what Ive come to is going to maybe work

#
class UserAccount(db.Model):
    """
    Account Holding User
    """
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default="static/default.jpg")
    password = db.Column(db.String(60), nullable=False)
    account_created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    agree_over_18 = db.Column(db.Boolean, default=False)

    player_profile = db.relationship('PlayerProfile', uselist=False, back_populates="user")

    def __repr__(self):
        return f"User('{self.id}', '{self.email}')"

    # def __init__(self, **kwargs):
    #     super(Foo, self).__init__(**kwargs)
    #     # do custom stuff

class PlayerProfile(db.Model):
    """
    Each user gets a player profile with which to make characters
    and save progress in various Campaigns
    """
    __tablename__ = 'player'
    id = db.Column(db.Integer, primary_key=True)
    
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    user = db.relationship('UserAccount', back_populates="player")

    def __repr__(self):
        return f"PlayerProfile({self.id}, {self.user})"

I'm about to test this, but I have to take a shower real quick. I'm going to enjoy the time in the shower believing that this will work.

#

I have to say if that is the correct way to do it, that is overly confusing. I need a better ORM lol

native root
#

You shouldn't have the "player_profile" relationship

#

back_populates should create a "player" attribute on UserAccount for you

#

If you need to put a relationship there, it should match, so be put into an attribute named "player" and back_populate user

#

as it is now it has two names, which might break the pairing

native tide
native root
#

"back_populates" refers to the reverse of the property--so, for PlayerProfile.user, it would be UserAccount.player (like you have above)

#

I'm pretty sure "uselist" means that it will use a list representation rather than a set

native tide
#

I see.

native root
#

Welp, that's not right

#

the uselist flag indicates the placement of a scalar attribute instead of a collection on the β€œmany” side of the relationshi

#

so basically, one to one instead of one to many

native tide
#

Its weird that they dont just use those terms which im more familair with but im sure once i learn this it will be nothing

native root
#

It is a weird name that makes me want to double check my own code

#

So, for clarity:

#
class Dog(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  owner_id = db.Column(db.Integger, db.ForeignKey('owner.id'))
  owner = db.relationship('Owner', back_populates='pets')

class Owner(db.Model):
  id = db.Column(db.Integer...)
  dogs = db.relationship('Dog', back_populates='owner', uselist=True)
#

is for a many-one, one owner, many doggs

#

The two are linked in the database via the owner_id foreignkey, but linked in python via the owner <-> dogs relationship.

#

If, for whatever reason, each owner could only have one dog, you'd change the uselist on dogs to false so that it knows there can only be one

#

Since in the database, many dogs technically could have the same owner id--but unique=True on owner_id in the Dog model could work

#

That is, to say, the columns generated by my example are:

Table Dog:
id    | owner_id |
1     | 1

Table Owner:
id    |
1     |
native tide
#

Oh, cool thanks for writing this out. Let me catch up.

native root
#

and accessing Owner.get(1).dogs generates something like:
SELECT * FROM dogs WHERE owner_id = 1

native tide
#

You differentiating between python and the db helps me understand the difference

#

I think I get it now.

#

Thats why they gave you the helper role haha

#

So you essentially always use uselist on the 1 end

native root
#

If I remember correctly, models have an _metadata attribute you can use to actually print out their table representations

native tide
#

what a terrible name for that kwarg

native root
#

yeah

#

Ah, it's just .metadata, and it has all the tables for the current database via metadata.tables. Each model also has __table__ as well

native tide
#

Right so, it gave me this error when I tried the code above as is
sqlalchemy.exc.InvalidRequestError: Mapper 'mapped class UserAccount->user' has no property 'player'

I'm going to try to remove the one you suggest as opposed to that one.

#

player_profile under UserAccount that is, I'll try it with that commented out

native root
#

So something like:

for table in Dog.metadata.tables:
  print(table.name)
  for column in table.columns:
    print(column.key, column.type_)

( Not sure if this works )

native tide
#

yeah it doesnt like this
sqlalchemy.exc.InvalidRequestError: Mapper 'mapped class UserAccount->user' has no property 'player'
that is on attempt to instantiate a UserAccount.

btw
I'll snippet save that so that I remember that. Right now I have nothing in my tables haha pystrong

native root
#

So I guess it has to be double sided then >.<

native tide
#

Well even with both of them it doesnt like it.

rustic pebble
#

What are you trying to do TLS?

native root
#

What's the error (assuming the names match)

#

They need to point at each other, eg, one assigns to "player" and backrefs "user", and the other is assigned to "user" and backrefs "player"

native tide
#

backref is another word I dont really get. How is that different from back_populates

#

I'm trying to get have a User Account have a one to one relationship with a Player Profile.

rustic pebble
#

Oh ok

#

And where are you having trouble?

native root
#

sorry, I meant back populates there

#

backref is a different syntactical way of doing it

native tide
#

ah okay, so now might be a good time to just learn all the meanings of these kwargs

#

Because Im literally just copying other peoples code and being like, "uh, ok"

native root
#

What's your current code?

native tide
#

Current code:
https://paste.pythondiscord.com/ebifapuroy.py

The place where Im having trouble is that it either...
on instantiation of one of these objects...

>>> user = UserAccount(email="me@mail.com", password="password")
Traceback (most recent call last):

...

sqlalchemy.exc.InvalidRequestError: Mapper 'mapped class UserAccount->user' has no property 'player'

or... before I got here, the problem was that though I could instantiate a PlayerProfile and a UserAccount I had no way of accessing one through the other.

ie
user.player.some_player_prop = "this"

I think Im going to spend some time reading the docs.

native root
#

player_profile = db.relationship('PlayerProfile', uselist=False, back_populates="user") needs to be changed

#

user = db.relationship('UserAccount', back_populates="player") because this here wants it to be named player not player_profile

#

or well, you could change the second one to match, they just need to be the same

native tide
#

Ahhh

rustic pebble
#

^^

native tide
#

soo...

#

as opposed to user = db.relationship('UserAccount', back_populates="player")

should it be user = db.relationship('UserAccount', back_populates=player_profile)

then? Or literally the variable name as a string passed to back_populates?

native root
#

literally the variable name as a string passed to back_populates
cuneiform_this

native tide
#

weird

native root
#

It's so that sqlalchemy can look at the class and figure out where to attach to

#

You tell it to initialize the models, and it goes through all the defined model classes and their attributes. Each class gets assigned a single table (usually), and each attribute that's defined as a column a column with a type and name. Then it sets up the code it needs to fetch across properties--so you can do, say user.profile, or profile.user and keeps track of them, and (might check them?).

Whenever you create/query for an object of that class, it eagerly goes and fetches the related objects with an extra SQL query. When it does so, it attempts to put them in the list/attribute that was specified in the relationship--so that in all cases where you have a UserProfile, it's .player attribute has a PlayerProfile already present. If the attribute doesn't exist, it throws that error

native tide
#

Should I have the primary key of PlayerProfile be a new id?

#

Kind of unrelated but

#

Is that the most normalized way to do this as a 1to1

native root
#

You could, but it really depends on what you're doing

#

Why do you need two different models in the first place?

native tide
#

GameMasterProfile is another type of profile for creating the campaigns that players can join, and users can be either/or/both

native root
#

Oh

#

Then I think the best case would be using the foreignkey column as a primary key as well

native tide
#

Thats what i was thinking

native root
#

It should be as easy as removing the id column from PlayerProfile and adding primary_key=True to the user_id foreignkey column declaration

native tide
#

right

native root
#

That enforces single-key single-concern, and probably also uniqueness per user

native tide
#

Thats how it should be

#

Thanks guys, its working

#

I'm gonna check out that table display script you had when I have some data in these.

native root
#

πŸ‘

#

It just displays the details... probably.. not the actual data, but I'm sure you could work it to the data too

native tide
#

ohh, just the fields on the table? Still, thats good to know.

#

I'm going to have to study this syntax before I really understand how to write these from memory

#

Do you find yourself referencing docs to do your models?

#

Even once you know it well

native root
#

I don't use sqlalchemy often enough to memorize the api properly

#

just the pain points

#

but if I did I'd be able to remember it

#

you're using flask-sqlalchemy though, so the api is slightly different i think

native tide
#

yeah. the code looks nicer with normal sqlalchemy it because you dont have to have db. in front of everything

#

So here is the one problem I have left

#

well, maybe thats optimistic but

#
>>> user = UserAccount.query.get(1)
>>> user
User('1', 'mail@me.com')
>>> player = PlayerProfile()
>>> player
PlayerProfile(None, None)
>>> player.id
>>> player.user
>>> user.player_profile

As you can see at the end, it creates the connection where something should be... but I'm not sure how to connect them.

#

I cant instantiate the PlayerProfile anymore with anything because all of its parameters are foreign

#
class PlayerProfile(db.Model):
    """
    Each user gets a player profile with which to make characters
    and save progress in various Campaigns
    """
    __tablename__ = 'player'

    id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False, primary_key=True)
    user = db.relationship('UserAccount', back_populates="player_profile")
#

It wont remain that way but I figure I need to get the relationship figured out first

#

user.player_profile = player might be as simple as that?

native root
#

You should be able to instantiate it via PlayerProfile(id=user.id) or PlayerProfile(user=user)

native tide
#

ahhh I was using positional arguments like an idiot

#

Do you think its dangerous to use auto incrementing ids for users? Or no if they are not front facing at all?

#

Dangerous in the sense that users will be accessible from other data if I use those numbers in urls and stuff

#

Which I guess I answered my own question.

native root
#

Well

#

Normally users shouldn't be able to access each other if you don't want them to by controlling access in general, so even if you do know a user id you can't get anything from it

#

but an autoincrementing user ID does leak how many user id's you have

native tide
#

Yeahh

#

uuid maybe

native root
#

In my opinion its often not a particularly important consideration, but if you are very concerned about security you should use uuids, yeah

native tide
#

I enjoy best practices in that regard but I will probably not focus on it atm

#

since everything is test data it doesnt matter

native root
#

I went and refined that printer thing

#
for table in Base.metadata.tables.values():
    print(f"Table `{table.name}`:")
    columns = {}
    for column in table.columns:
        column_format = f"{column.key} ({column.type})"
        columns[column.key] = column_format
        print(f"{column_format:>6}", end=" | ")
    print()
    for obj in session.query(table).all():
        for prop, column_format in columns.items():
            print(f"{getattr(obj, prop):>{len(column_format)}}", end=" | ")
        print()
    print()
native tide
#

niceee

#

let me get the classes with it I forgot those

#
class Dog(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  owner_id = db.Column(db.Integger, db.ForeignKey('owner.id'))
  owner = db.relationship('Owner', back_populates='pets')

class Owner(db.Model):
  id = db.Column(db.Integer...)
  dogs = db.relationship('Dog', back_populates='owner', uselist=True)
native root
#

Paste, had a missing line

#

Here's the full working example:

#
from sqlalchemy import Column, Integer, String, ForeignKey, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker


Base = declarative_base()

class Dog(Base):
    __tablename__ = "dog"
    id = Column(Integer, primary_key=True)
    name = Column(String)
    owner_id = Column(Integer, ForeignKey('owner.id'))
    owner = relationship('Owner', back_populates='dogs')

class Owner(Base):
    __tablename__ = "owner"
    id = Column(Integer, primary_key=True)
    name = Column(String)
    dogs = relationship('Dog', back_populates='owner', uselist=True)

engine = create_engine('sqlite:///:memory:')

Base.metadata.create_all(engine)

# create a configured "Session" class
Session = sessionmaker(bind=engine)

# create a Session
session = Session()

# work with sess
bob = Owner(name="Bob")
sally = Owner(name="Sally")

spark = Dog(name="Spark", owner=bob)

session.add_all([bob, sally, spark])
session.commit()


for table in Base.metadata.tables.values():
    print(f"Table `{table.name}`:")
    columns = {}
    for column in table.columns:
        column_format = f"{column.key} ({column.type})"
        columns[column.key] = column_format
        print(f"{column_format:>6}", end=" | ")
    print()
    for obj in session.query(table).all():
        for prop, column_format in columns.items():
            print(f"{getattr(obj, prop):>{len(column_format)}}", end=" | ")
        print()
    print()
#

Produces this:

#
Table `dog`:
id (INTEGER) | name (VARCHAR) | owner_id (INTEGER) | 
           1 |          Spark |                  1 | 

Table `owner`:
id (INTEGER) | name (VARCHAR) | 
           1 |            Bob | 
           2 |          Sally | 
native tide
#

that is pretty cool.

#

I forgot you could pass sqlite:///:memory:

#

what is the declarative_base about

native root
#

something flask-sqlalchemy does for you

native tide
#

It seems like it sets up the base class.

#

I see how you are using things that are in flask-sqlalchemy, like session and etc, from another source. Im sure thats how it all works under the hood.

#

Do you think I could start just using normal sqlachemy?

#

I think the code looks cleaner

#

I have heard people say if you are using flask to just use it so I did

native root
#

If you like it you can use it

fresh dock
#

@native tide yes use sqlalchemy if you can

#

It's a bit of a learning curve but once you are over that, it makes everything way easier

#

It also takes care of sanitization for you

#

So no sql injection

native tide
#

Hrm. Nice. I will definitely look at it. I think while learning I will just do this so there are less curveballs, but I like the look of that code a lot better.

native root
#

I think the biggest things flask-sqlalchemy provides is a good interface to flasks configuration and similar

#

But both are flexible, and flask-sqlalchemy basically does what I did internally for you when you create it anyway

native tide
#

yeah

turbid glen
#

ok so im just start learning html, why <img src="C:\Users\User\Desktop/SW1.png"\> doesnt create the image on the website? My html file is stored inside C:\Users\User\Desktop\Language\HTML\Playground.html btw

rustic pebble
#

@turbid glen You don't close the img with /> instead just use >

turbid glen
fresh dock
#

@turbid glen I'm gonna guess it's browser security not letting pages access assets from the user's (your) computer

turbid glen
#

ohhh make sense, since the picture works if i put the pic in the same file as the html file

#

how do i change it?

rustic pebble
#

Are you using an online editor?

turbid glen
#

im using vscode with its live server

rustic pebble
#

hmm

#

Try putting the image next to the .html file

turbid glen
#

yes it works that way

rustic pebble
#

And link src as ./filename.png

#

It might be a permission thing

turbid glen
#

if i put them in the same file, <img src="SW1.png"> this alone works

rustic pebble
#

Yup

turbid glen
#

btw its better to put those image together with the html file right? like best practice

rustic pebble
#

Optimally you should have a folder called static

#

which contains subdirectories

#

like css, img, js

#

to categorize your files

turbid glen
#

alright, i will keep that in mind when i learning css and js

#

ty

rustic pebble
#

Np πŸ˜„

elfin solstice
#

(reposting as buried)
Here is my conf file, in /etc/apache2/sites-enabled:

<VirtualHost *:80>
 ServerName artybot.xyz
 DocumentRoot /home/artemisweb/artemisweb
 WSGIScriptAlias / /home/artemisweb/artemisweb/artemisbots/wsgi.py
 
 WSGIDaemonProcess artybot.xyz processes=2 threads=15 display-name=%{GROUP} python-home=/home/artemisweb/artemisweb/venv/lib/python3.8
 WSGIProcessGroup artybot.xyz
 
 <directory /home/artemisweb/artemisweb>
   AllowOverride all
   Require all granted
   Options FollowSymlinks
 </directory>
 
 Alias /static/ /home/artemisweb/artemisweb/main/static/
 
 <Directory /home/artemisweb/artemisweb/main/static>
  Require all granted
 </Directory>
</VirtualHost>

However, when I attempt to access the website, it just times out. What am I doing wrong? I have recently purged and reinstalled apache2, and I'm using a django app in /home/artemisweb/artemisweb, called artemisbots with only one project, main. I can't find the logs.

rustic pebble
elfin solstice
#

OK tq

rustic pebble
#

πŸ˜„

native tide
#

I could help if it was nginx

#

You might also try unix.

#

Those guys are more into that side of thing than the average person here.

rustic pebble
#

I can help but I am in class rn

turbid glen
#

i just view the google.com html source and that shit almost blow my head up

#

xD

short venture
#

How can i run bash commands such as "touch, heroku create" etc. in Pycharm terminal in W10? I was able to run these commands in Pycharm in my old laptop which was using W7.

trim grail
#

Have you tried running them?
If they worked on W7, they should work on win10

short venture
#

Of course i did. They aren't workin'.

jagged lark
#

Are you in the terminal or the python console?

short venture
#

Pycharm terminal.

#

I'm trying to deploy my project to Heroku.

jagged lark
#

Can you send a screenshot?

short venture
#

But neither "touch" nor "heroku create" works.

#

Hold on.

#

(venv) D:\Python Projects\Django\API\Stock Management>touch dafuq.txt
'touch' is not recognized as an internal or external command,
operable program or batch file.

jagged lark
#

What does echo %PATH% give you?

short venture
#

D:\Python Projects\Django\API\Stock Management\venv\Scripts;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Windows\System32\OpenSSH;D:
Git\cmd;C:\Users\Burak\AppData\Local\Programs\Python\Python38\Scripts;C:\Users\Burak\AppData\Local\Programs\Python\Python38;C:\Users\Burak\AppData\Local\Microsoft\WindowsApps;D:\PyCharm\bin;
;D:\heroku\bin

#

So, any ideas?

native tide
rustic pebble
#

Haha

jagged lark
#

I mean

#

Why not?

short venture
#

@jagged lark ?

limber laurel
#

So I want to use .login_view( from flask-login), but I am not reallt sure what I need to set in it, do I set the route or what?

jagged lark
limber laurel
#

This is what it says in the docs, I would be happy if someone could expalain what exactly is being set in the .login_view

Edit: Nvm, found my answer, had to enter the name of the route

short venture
#

@jagged lark Thanks.

native tide
#

Should i be using flask-login?

jagged lark
#

It is decent from what I heard

rustic pebble
#

I have heard that it has security issues

#

I usually make my own decorators

vagrant adder
#

@short venture touch doesn't work on heroku because heroku dynos have non-persistent filesystem

#

so if you touch a file and restart a dyno, touched file will disappear

#

the main reason for that is non-persistent filesystem

#

i had the same problem

short venture
#

I didn't ask it for Heroku.

#

Asked for Pycharm.

vagrant adder
#

you want to know how to ssh into your heroku dyno?

#

heroku ps:exec -a appnamehere

hexed crater
#

hey
i have flask project and i using flask_login and i want to add roles (admin,user,...) with permission in every view and can be change by client side is there good library ?

shy holly
#

use django brainmon

fringe solar
#

Hey, anyone has an idea on how to logout a user with oauth2 of discord using: https://discordapp.com/api/oauth2/token/revoke this url ? can't find any documentation on it

solar hatch
#

Hi I am new to web dev I am trying to make a tic tac toe game with flask
What is the best way to make the bored

grizzled harness
#

easiest is a html table

native tide
#

Doesnt that sound pretty insecure to you, mjed?

solar hatch
#

@grizzled harness how about buttons

#

How do I input ???

#

X and o

#

code <div style="position:fixed; bottom:70%; left:42%">
<button>#</button>
<button>#</button>
<button>#</button>
</div>

<div style="position:fixed; bottom:60%; left:42%">
    <button>#</button>
    <button>#</button>
    <button>#</button>
</div>

<div style="position:fixed; bottom:50%; left:42%">
    <button>#</button>
    <button>#</button>
    <button>#</button>
</div>
native tide
#

Personally, I would learn how to make this first make python tic tac toe
https://pencilprogrammer.com/python-programs/tic-tac-toe-python/

They have plenty of others if you search python tic tac toe

The thing is, they are all going to be command line tutorials, and almost anything you find on making a web tic tac toe is going to be in JavaScript. As much as I usually say JavaScript is over used, this is a situation where it might be pretty called for.

But if you're just trying to teach yourself Flask and Python with a practice project, it can be done, and it will work very similarly to the command line version. If you learn that first, as much as you may want to skip it, it will make all of this easier for you.

After you understand that, you'll basically do it the same way. You wil store which is X, O, or unselected in a data structure. You'll have the same code that determines how the board should be displayed.

The main difference will be that instead of rendering in command line, you'll be sending the data from a view to a template and generating that HTML line by line based on the state of the game.

I hope that helps. I will add that this is an unorthadox use of Flask but it can be done.

To write 2 Player Tic Tac Toe Python program you only need basic knowledge of python functions and list. In this program we have used 4 major functions required to make 2 Player tic tac toe using…

#

You'll have to send a POST request back with each submit. There is a submit type. Look into forms and POST requests in html

solar hatch
#

@native tide I already made a tic tac toe with minimax algorithm

solar hatch
#

what is easy to input x and o buttons or table

#

@native tide @grizzled harness

rustic pebble
#

@solar hatch you need to make each cell of the board a button

#

and then take actions using js

solar hatch
#

js what about python@rustic pebble

rustic pebble
#

You cant use python client-sided

native tide
#

You can do it... But it will involve each button sending a post request.

rustic pebble
#

Still don't

native tide
#

Yeah, imo...

#

I usually dont agree with Kiwi about when to sue Javascript

#

But here they are right

rustic pebble
#

You will also need to implement a way to determine which button is which

#

I usually dont agree with Kiwi about when to sue Javascript
@native tide ❀️

native tide
#

If you really are set on doing in Python just to do it

rustic pebble
#

And then load the server x9 for each player

native tide
#

Know that it involves sending post requests to the server and then doing the figuring out of what the state of the game is

rustic pebble
#

right

native tide
#

And then sending that info to a template

#

and laying out the board with the changes

rustic pebble
#

and refresh the page

#

somehow

#

with js

native tide
#

You can refresh by redirecting in flask

#

But yeah

#

JS is better suited for something like tic tac toe.

rustic pebble
#

oh right

solar hatch
#

cool

rustic pebble
#

@solar hatch if you need help ping me here

solar hatch
#

i need help

#

@rustic pebble

rustic pebble
#

Sure

solar hatch
#

<form action="#" method="post">

<div style="position:fixed; bottom:70%; left:42%">
    <button>{{hello}}</button>
    <button>#</button>
    <button>#</button>
</div>

<div style="position:fixed; bottom:60%; left:42%">
    <button>#</button>
    <button>#</button>
    <button>#</button>
</div>

<div style="position:fixed; bottom:50%; left:42%">
    <button>#</button>
    <button>#</button>
    <button>#</button>
</div>

</form>

rustic pebble
#

!code

lavish prismBOT
#

Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.

To do this, use the following method:

```python
print('Hello world!')
```

Note:
β€’ These are backticks, not quotes. Backticks can usually be found on the tilde key.
β€’ You can also use py as the language instead of python
β€’ The language must be on the first line next to the backticks with no space between them

This will result in the following:

print('Hello world!')
solar hatch
#

so how i do i input

#

@rustic pebble

rustic pebble
#

You need trigger actions

#

with buttons

#

Button can have an attribute called on-click and an attribute called id

#

on-click should call a js function which saves the user input

solar hatch
#

i don't know js

#

how i do it in python

rustic pebble
#

Do you have a server set-up?

solar hatch
#

??

#

yes

#

local host

rustic pebble
#

Flask server right?

solar hatch
#

yea

native tide
#

Consider making all those buttons checkboxes

#

And one submit.

rustic pebble
#

@native tide You can take it from here

native tide
#

Or radio

rustic pebble
#

this is long asf

#

What you need to do i sent a specific request for each key

native tide
#

To be honest...You're going to have to spend some time learning HTML forms before you can do this. Im not going to walk you through doing this. But I can tell you that before you can do this you need to learn HTML forms and POST requests.

rustic pebble
#

then diverse each key into different ifs

native tide
rustic pebble
solar hatch
#

ok...i get it when i need help i will ask

native tide
#

wooow

rustic pebble
#

πŸ˜„

solar hatch
#

πŸ˜†

native tide
#

I was able to jump into web apps from python because I have strong background of CSS and HTML.

#

If you really want to excel at doing web apps, you should take the time to do that.

#

its not as hard as a programming lang

turbid glen
#

is it best practise to use only one <h1> inside one html file?

#

heard from the website

solar hatch
#

hehe

native tide
#

Im not sure how much that is a rule or not, but it sounds like it makes sense. The idea of the h1 is to be the main title.

#

So I would say that yeah.

turbid glen
#

i heard using too much h1 ruined your "reputation"??

rustic pebble
#

I was able to jump to websites cause I decided it

turbid glen
#

ok

#

or what SEO thing

wet ibex
#

what concept does discord web uses?
i know ajax and ws is a thing but how does it load a new "page" with a new url in the address bar but not trigger the refreshing?

rustic pebble
#

I stayed in learning html,css,js

#

For like a week

native tide
#

I'm pretty sure it doesnt load new pages.

rustic pebble
#

@wet ibex

#

Discord web and discord app are the same

#

They are based on technologies like electron

turbid glen
#

the indent in html is kinda confusing compare to python

wet ibex
#

i think i kinda get it

rustic pebble
#

It is native app with refreshing elements

wet ibex
#

but i wonder how to implement the same amount of interactivity without traditional page reloading pithink

rustic pebble
#

Learn electron/react

#

either of those can do that

wet ibex
#

not possible with pure html/css/js?

rustic pebble
#

I dont think so

native tide
#

Look up single page application.

rustic pebble
#

And js is pure before ES6

wet ibex
#

oh thanks

#

i didn't know the terminology

rustic pebble
#

ES6 introduced like 1000 new things

rigid laurel
#

Single page applications can do roughly as much as traditional desktop apps - they just can't interact with the underlying PC as well. They are generally pure HTML/CSS/JS on the client side though

rustic pebble
#

Why not use frameworks?

wet ibex
#

nah im just new to using them

rigid laurel
#

Well, React is pure js in the same way the Flask/Django are pure Python

wet ibex
#

any opinions on using which frameworks together with django?

#

im new to angular/react/vue

rigid laurel
#

If you want SPAs, then I'm not sure Django is the way to go

wet ibex
#

huh

rustic pebble
#

React + Flask is good

rigid laurel
#

in general, React or Vue seem the nicest

wet ibex
#

i just want to make my dashboard not reload rip

rustic pebble
#

Vue is simple and straightforward, React is the real deal

native tide
#

I think most people who rely on server side rendering tend to not rely as heavily on JS. They sprinkle it in and tend just do everything they need JS for in vanilla.

Theyre all fads that are going to be dead in less than three years lol

rigid laurel
#

That shouldn't be too difficult. You just make a REST API backend, and use React/Vue on the frontend

#

Nah, React is probably gonna stick around relatively long term

rustic pebble
#

Rest API and Vue

#

Is the easiest

rigid laurel
#

we're at the point where most other frameworks are following some amount of Reacts ideas

rustic pebble
#

But if you want really good and efficient apps

native tide
#

Well i dont know anything about the js frameworks other than that they fall out of favor as quickly as they rise

rustic pebble
#

GraphQL + AIOhttp is good

wet ibex
#

interesting how no one talks about angular

rigid laurel
#

and its becoming the de facto solution at a lot of places

native tide
#

but you might be right

rigid laurel
#

That has been true with a fair few of them - and it could be true for react - but I think React will probably stick around

#

Angular is the other major framework, but they made a lot of mistakes that React aren't

rustic pebble
#

Charlie, have you used graphQL?

rigid laurel
#

namely massively changing things

#

I've used it a tiny bit, and it seems pretty pointless

#

its just a new way of interacting with RestAPIs

#

But its not currently difficult to interact with Rest APIs

rustic pebble
#

Not really, it is different API structure all together

#

ill brb

rigid laurel
#

The most common use of GraphQL is to collate Rest endpionts

native tide
#

I plan to get back to React when I have an idea thats good for REact. What Im working on now is a document based application that just is better the way im doing it with server rendering and definitely there will be vanilla JS somewhere. But its a website for fiction. shrug. It doesnt need to be an SPA.

#

But when I get that idea Ill do it.

solar hatch
#

how do i see what button i clicked

#

@rustic pebble

#

@native tide

native tide
#

HTML forms typically have 1 button.

#
 <form action="/action_page.php" method="get" id="form1">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname">
</form>

<button type="submit" form="form1" value="Submit">Submit</button> 
#

Thats an example.

rustic pebble
#

This is so damn easy

#

with js

#

haha

solar hatch
#

is js is easy to learn

#

@rustic pebble

native tide
#

What you're trying to do is doable, but its unorthodox and is going to be hard for you. You're trying to learn Flask, Post requests, html forms, all this stuff... which a project that makes all of that stuff more complicated than it needs to be.

#

You could do this project

rustic pebble
#
function tictactoe(action){
  if (action = 'youraction identifier'){
  }
}
#

then you just makes 9 ifs

native tide
#

But you need to learn HTML, http methods and responses, etc

rustic pebble
#

I wont walk you through

native tide
#

Like...

rustic pebble
#

andyou can just do for each button
<button onclick='tictactoe(clickidentifier);'></button>

native tide
#

Ive never understood the type of person who throws themselves into project that is above the things they know.

rustic pebble
#

That is exactly how I learn @native tide

native tide
#

For example, when I started learning Django, I made a blog site I didnt even intend to use.

rustic pebble
#

Haha

native tide
#

Because thats the stereotypical Django app.

solar hatch
#

so any other project ???

native tide
#

If I had gone into Django trying to use it to make tic tac toe lol

solar hatch
#

easy

native tide
#

I would have never got anywhere because I wouldnt have understood HTTP stuff and talking to the server

vivid cosmos
#

andyou can just do for each button
<button onclick='tictactoe(clickidentifier);'></button>
@rustic pebble I think it is better do add an eventListener

solar hatch
#

is a portfolio web is easy to make

#

????

native tide
#

@rustic pebble A lot of people do. I dont get it myself

rustic pebble
#

@vivid cosmos that is the easiest way, but how will you explain eventListener to someone who doesn't know the basics of js

#

onclick is self-defining

native tide
#

Yes, a webb portfolio is much easier. Personally I just follow tutorials doing other peoples projects until my own ideas start to pop out.

rustic pebble
#

@rustic pebble A lot of people do. I dont get it myself
@native tide I just do it, I find an idea and try to find the manners to implement it

solar hatch
#

yea...i will make a port folio app for myself

native tide
#

Well, if that works for you, thats great...

#

But if you're going to be that person, you cant show up in chat being like, "How do i..."

rustic pebble
#

Have I ever said that?

#

Haha

native tide
#

No.

#

You havent.

rustic pebble
#

I do deep research

solar hatch
#

πŸ˜„

native tide
#

But thats what im saying, if you dont know what you're doing

#

You have to teach yourself basic boring things first.

rustic pebble
#

And then I just ask with what I have

native tide
#

If that works for you then it clearly does.

rustic pebble
#

If you understand one language in a level which you can make pretty much anything that comes to your mind

#

Then every other language automatically becomes 10 times easier

#

It is way different knowing exactly what you want to do and just having a problem with the means

#

for example

native tide
#

That's true, but... when what you need to learn is basic HTTP protocol;

#

You have to start with that.

rustic pebble
#

If you want to push an item in a list on python you do listname.append(itemname) on js you do listname.push(itemname)

#

Same thing different manners

#

HTTP should be pretty simple tolearn

native tide
#

That's true. It is like that and you eventually do become able to do it.

rustic pebble
#

Given that you already know how to use the internet

#

haha

native tide
#

You would be surprised.

#

The average person doesnt realize the communication that goes on between a client and server

#

with headers and responses

rustic pebble
#

I might sound haughty but I somehow never had to read the basics like how does http work, how does js control elements

native tide
#

Im just saying that... you can learn to make a post request thats a thousand times simpler than having 9 different possible ones you could make to play a game.

#

And then once you understood you would be like

rustic pebble
#

I somehow knew it by myself

native tide
#

ah, I need 9 of those possible requests

#

But until then

#

it confusing

rustic pebble
#

That is true

#

But tbh we are here on web-development to help people like that. I love it when someone who doesn't know much comes here and they leave with a happy face

solar hatch
#

do any of you have a portfolio web

#

that i can see

rustic pebble
#

Because that is how I sometimes felt on stackoverflow

#

But they kill newbies there

#

@solar hatch Not really, @shadow hornet has a good one let me see if I can find it

solar hatch
#

πŸ‘

green echo
#

How do I enable https on Flask with SocketIO?

rustic pebble
#

@green echo You are talking about enabling it in a development environment right?

green echo
#

I don't think i do

#

i want it to work on a port forwarded Ip

rustic pebble
#

Oh, then you need an SSL certificate

green echo
#

How do i get one though

#

And what do I do with the certificate

rustic pebble
#

You can get from here

#

You need to add it to your webapp

#

I take it you are using nginx?

green echo
#

Dude

#

I have no idea what im using

rustic pebble
#

How are you hosting the server?

green echo
#

Using my own router

rustic pebble
#

Are you just doing python app.py?

#

to launch it

green echo
#

yeah

rustic pebble
#

That is a development environment

#

And very unsafe

green echo
#

Yeah, i know

#

I know it is super unsafe

#

and stuff

rustic pebble
#

There are bots running 24/7 and pinging random ips at random routes, executing exploit scripts, if one happens to hit your own ip and port, if one tiny hole exists in your system you are ruined

green echo
#

I just want to show my site to my friends which I know would do nothing to harm my pc

#

oh

#

OH

#

ffs

rustic pebble
#

Yea that is what I thought when I found out

green echo
#

I hate the internet

rustic pebble
#

You are gonna need to run it off somewhere else, there are hosts that you can rent servers for 2.5euros per month

green echo
#

ugh

rustic pebble
#

rip

rustic pebble
#

Lets see how fast I am going to finish it

#

I will make it dynamic so it adds the projects from my github

sly canyon
rigid laurel
#

Not without a link to the source code

sly canyon
#

forms.py

class ContactForm(FlaskForm):
    building_name = HiddenField('Nome do Empreendimento')
    name = StringField('Nome', [DataRequired(), Length(min=3, max=100, message="O nome informado tem que ter entre 3 e 100 letras.")])
    email = EmailField('E-mail', [DataRequired(), Email(message="Email invΓ‘lido")])
    phone = StringField('Celular/Whatsapp', [DataRequired(), Length(min=8, max=15, message="O telefone informado tem que ter entre 8 e 15 numerais.")])
    submit = SubmitField('Quero saber mais!')

    class Meta:
        locales = ['pt_BR']
#

routes.py

#...
@app.route('/manoeltavares', methods=['GET', 'POST'], host='maxiimoveis.herokuapp.com')
def manoel_tavares():
#...
    #  Form Handling
    form = ContactForm(building_name=building_name)
    if form.validate_on_submit():
        contact_handler(form, building_name)
        return thank_you(building_name=building_name, folder_name=folder_name)
#

@rigid laurel

#

Oh, I see, another bug because of the host parameter, damn, can get rid of that because if I do not place it, it will look for my staticfiles on www.maxiimoveis.com.br/static

#

Any ideas?

rigid laurel
#

I'm not entirely sure myself - but with the source code no one would be able to help

native tide
#

Best solution to monitor traffic on ur web app (unique visits etc..) using flask

rustic pebble
#

Question: Is there a way I can have styles under an if?
Like I want to add something like that
````if element_id == 'project_wrapper'`:
#style```

native tide
#

i had something like different color of headers based on if statement

#

i did it in jinja idk if that helps u

rustic pebble
#

Nah I dont want to make it that dynamic

quaint gazelle
#

Very ClichΓ© question. I’m trying to make a social media like Twitter/Instagram and I want to use python/Django for some backend stuff. I don’t know anything about backend. Does anyone have any advice on where I should start ? I do know about frameworks and things like AWS but I don’t know how to use any of them.
If possible can anyone go into detail on what Instagram would specifically use Django for

bleak bobcat
#

My advice would be to follow the official django tutorial and docs, it's complete enough to give you ideas of how to do what you want to do

quaint gazelle
#

Ok I see

#

Thanks bro

rustic pebble
#

How can I serve images from my flask backend to the frontend?

#

Ideally I want to add them here, with js of course

#

Basically instead of setAttribute I want it to display an image

#

Oh nvm I found it, I will convert them to base64, send them over with http request, and then just add them as src for an html img

#

using the built-in bs4 decoder

sly canyon
#

@rustic pebble I parse them in my route and then use Jinja to render it in a for loop.

rustic pebble
#

I want them to be dynamic

#

so only when a user clicks somewheree

#

an image gets loaded

sly canyon
#

Probably u want to use async requests then

rustic pebble
#

I am using async requests xD

sly canyon
#

Cool then, u've everything figured out

rustic pebble
#

this is my request for like one section

#
async function get_project_data(){
    let url = '/data';
    const response = await fetch(url, {
        method: 'GET',
        mode : 'cors',
        cache : 'no-cache',
        credentials: 'same-origin',
        headers: {
            'Content-Type':'application/json'
        },
        redirect: 'follow',
        referrerPolicy: 'no-referrer'
    });
    let data = await response.json();
    return data['Data']
}
rustic pebble
#

I am having a problem

#

So I am loading the top left image

#

Statically through jinja

#

And the rest I am decoding through base64

#

the left one works

#

the others don't

#

Any ideas?

rustic pebble
#

@native tide finally I used jinja

         {% for item in data %}
            <div class="box">
                <div class="imgBx">
                    <img src="{{ data[item]['img']}}" width="100px" height="109px">
                </div>
                <div class="content">
                    <h2>{{ item }}</h2>
                    <p>{{ data[item]['description'] }}</p>
                    <a href="{{ data[item]['url'] }}">Read More</a>
                </div>
            </div>
        {% endfor %}
#

haha

#

I couldnt do it without it

sly canyon
#

http://campanhas.maxiimoveis.com.br/laguna

When I submit the form accessing it through my alias_host it first redirects to app_domain and I have to submit it again in order it to proceed.

Any ideas why I have to submit the form twice?

__init__.py

#...
app = Flask(__name__, host_matching=True, static_host='maxiimoveis.herokuapp.com')
#...

routes.py

#...
app_host = 'maxiimoveis.herokuapp.com'
alias_host = 'campanhas.maxiimoveis.com.br'
#...
@app.route('/laguna', methods=['GET','POST'], host=app_host)
def laguna():
    #...
    form = ContactForm(building_name=building_name)
    if form.validate_on_submit():
        contact_handler(form)
        return thank_you(building_name=building_name, folder_name=folder_name)
#...

contact.html

#...
<form method="POST" action="{{url_for(request.endpoint, _external=True)}}">
#...

P.S: I'm using FLASK-WTF

rustic pebble
#

@sly canyon I faced that problem some months ago, I never found out how to fix it so I used js to submit the form

sly canyon
#

@rustic pebble Can u paste your POST script 4 me?

rustic pebble
#

I think it has to do with the flask routing

#

I unfortunately can't but I can build it for you

#

Could you send me your html form?

#

It is not that hard

#

@sly canyon

sly canyon
#

contact.html

{% from "forms/_formhelpers.html" import render_field %}
<form method="POST" action="{{url_for(request.endpoint, _external=True)}}">
    {{ form.hidden_tag() }}
    <!-- Name -->
    {{ render_field(form.name) }}
    <!-- Email -->
    {{ render_field(form.email) }}
    <!-- Phone -->
    {{ render_field(form.phone) }}
    {{ form.submit }}
</form>

_formhelpers.html

{% macro render_field(field) %}
    <div class="{{ field.name }}-wrapper">
    {{ field.label }} {{ field(**kwargs)|safe }}
    </div>
  {% if field.errors %}
    <ul class=errors>
    {% for error in field.errors %}
      <li>{{ error }}</li>
    {% endfor %}
    </ul>
  {% endif %}
  </dd>
{% endmacro %}
rustic pebble
#

ok you are going to need to add some ids to the inputs

sly canyon
#

If you want the form code rendered

rustic pebble
#

give me the form rendered

sly canyon
#

U can see it on the page

rustic pebble
#

sec

sly canyon
#

@rustic pebble I think I found a opssible solution

rustic pebble
#

I take it its this?

#
<div class="contact-form" id="contact-form">
        <div class="form-header">
          <p>Apenas uma unidade. Garanta jΓ‘!</p>
        </div>
        <div class="form-body">
          <div class="text">
            <p>
              O bem-estar de viver em uma das Γ‘reas mais privilegiadas da Zona Sul do Recife te espera.
            </p>
            <span class="bold">Preencha o formulΓ‘rio e aguarde nosso contato.</span>
          </div>
          <div class="contact-form-wrapper">
            

<form method="POST" action="http://maxiimoveis.herokuapp.com/laguna">
    <input id="building_name" name="building_name" type="hidden" value="Laguna">
<input id="csrf_token" name="csrf_token" type="hidden" value="IjFkYTFhZjExNjkwNzdjOWEzNzdlN2JlN2YzYmNlMDRkYjllZDJmYmQi.XnLFig.nD0YV_e9jey41caYP9Iq0UrRYqk">
    <!-- Name -->
    
    <div class="name-wrapper">
    <label for="name">Nome</label> <input id="name" name="name" required="" type="text" value="">
    </div>
  
  

    <!-- Email -->
    
    <div class="email-wrapper">
    <label for="email">E-mail</label> <input id="email" name="email" required="" type="email" value="">
    </div>
  
  

    <!-- Phone -->
    
    <div class="phone-wrapper">
    <label for="phone">Celular/Whatsapp</label> <input id="phone" name="phone" required="" type="text" value="">
    </div>
  
  

    <input id="submit" name="submit" type="submit" value="Quero saber mais!">
</form>
          </div>
        </div>
      </div>
sly canyon
rustic pebble
#

If it works for you

#

You don't have cors enabled?

sly canyon
#

I don't

#

I've never heard of it

rustic pebble
#

Oh

#

Then we have totally different problems

#

Haha

#

By default some http requests from paths that aren't the host

#

are denied

sly canyon
#

If I enable it, do I still have to do the post request through javascript?

rustic pebble
#

CORS enables that

#

It should fix itself possibly

#

Try it and we will see

sly canyon
#

I hope so, will read the docs

rustic pebble
#

You dont need much

#

You just do:

from flask_cors import CORS
CORS(app)
#

@sly canyon

sly canyon
#

just doing that didn't worked out

#

:/

rustic pebble
#

Hmm

#

Ok if you want we can try out the JS way

sly canyon
#

I'm still reading the docs, doesn't seem like those two lines are enough in my case

#

I've tried the @cross_origin() decorator and I'm getting

#

NameError: name 'cross_origin' is not defined

#

Meaning that my routes.py doesn't know anything about CORS

rustic pebble
#

doing CORS(app) is like applying CORS globally

#

so everything else you do is just a sub-case

#

@agile solstice You have posted it 3 times in total and one more here, total 4. Wait for someone to help you.

sly canyon
#

@rustic pebble
Indeed, I'm unable to achieve it even though I've activated CORS :/

#

Maybe that has to do with CSRF

#

Think I'll have to go with javascript

rustic pebble
#

I am not sure flask has activated csrf

#

by its own

sly canyon
#

But I'm using FLASK-WTF

rustic pebble
#

Give me a sec cause I am making my portfolio page

sly canyon
#

Sure

rustic pebble
#

and I am in a crucial css point

#

Ok @sly canyon
I guess what I sent earlier is the actual code for the contact form right?

#

ok let me concatenate it a bit

#
<form method="POST" action="http://maxiimoveis.herokuapp.com/laguna">
    <input id="building_name" name="building_name" type="hidden" value="Laguna">
    <input id="csrf_token" name="csrf_token" type="hidden" value="IjFkYTFhZjExNjkwNzdjOWEzNzdlN2JlN2YzYmNlMDRkYjllZDJmYmQi.XnLFig.nD0YV_e9jey41caYP9Iq0UrRYqk">
    <div class="name-wrapper">
      <label for="name">Nome</label> <input id="name" name="name" required="" type="text" value="">
    </div>
    <div class="email-wrapper">
      <label for="email">E-mail</label> <input id="email" name="email" required="" type="email" value="">
    </div>
    <div class="phone-wrapper">
      <label for="phone">Celular/Whatsapp</label> <input id="phone" name="phone" required="" type="text" value="">
    </div>
    <input id="submit" name="submit" type="submit" value="Quero saber mais!">
</form> 
#

so

#

What you sent is the flask request form

#

I will make a script which on submit sends a json with all the data you need

#

Btw the data you need is:

#
building name
csrf_token
name
email
phone
#

Correct?

sly canyon
#

I don't need the csrf_token actually

rustic pebble
#

Sure

#

Ok let me build this

sly canyon
#

I've done it before, but I forgot how to do it, long time without touching code :P

rustic pebble
#
async function send_contact_form(){
  let url='/laguna';
  let build_name = document.getElementById('building_name').value;
  let name = document.getElementById('name').value;
  let email = document.getElementById('name').value;
  let phone = document.getElementById('phone').value;
  let response_data = {'building_name':build_name, 'name':name, 'email':email, 'phone':phone}
  const response = await fetch(url,{
      method: 'POST',
      mode: 'cors',
      cache: 'no-cache',
      credentials: 'same-origin',
      headers: {
        'Content-Type': 'application/json'
      },
      redirect: 'follow',
      referrerPolicy: 'no=referrer',
      body: JSON.stringify(response_data)
      });
  return await response.json():}

Change the submit button to this:

    <input id="submit" name="submit" type="submit" value="Quero saber mais!" onclick='send_contact_form();'>

To access t he data on the backend you would do normally what you did with form but using the following

@app.route('/laguna', methods=['POST'])
def get_contact():
  data = request.json
  build_name = data['building_name']
  name = data['name']
  email = data['email']
  phone = data['phone']
#

@sly canyon

#

This won't check if the fields are empty or not

sly canyon
#

@rustic pebble Thanks, will try

rustic pebble
#

This works 99.99%

cobalt oyster
#

I know username of user and Post model with share foreign key with contrib.auth.User model.

#

But don't how it will effect the databases

weary arrow
cobalt oyster
#

@weary arrow thank you. But I haven't used flask I use Django and in Django the migrations takes care of database. So I am having trouble understanding how I can give foreign key relationship only on model level.

turbid glen
#

why the video i put on my website with iframe said "video unavailable"

rustic pebble
#

!ask

lavish prismBOT
#

Asking good questions will yield a much higher chance of a quick response:

β€’ Don't ask to ask your question, just go ahead and tell us your problem.
β€’ Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
β€’ Try to solve the problem on your own first, we're not going to write code for you.
β€’ Show us the code you've tried and any errors or unexpected results it's giving.
β€’ Be patient while we're helping you.

You can find a much more detailed explanation on our website.

turbid glen
#

<iframe width="560" height="315" src="https://www.youtube.com/embed/nUtgOwCh2uY" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> and <iframe width="560" height="315" src="https://www.youtube.com/embed/ct8In_FAvZE" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

#

copied the embbed code directly from youtube, first code works fine after playing the video

#

second one instant go 'video unavailable' after clicking play

limber laurel
#

I have flash messages in my app but for some reason when ever they are displayed, they are displayed with a distance from a top, any ideas on wjat cpuld be causing something like this?

rustic pebble
#

@turbid glen Not to sound offensive, but have you considered the possibility that the video is actually Unavailable

solar hatch
#

how do i put <p>dsgesdgrhg<p> in left bottom conner

#

with css

#

πŸ’©

rustic pebble
#

I make a div

#

with class namefooter

#

and add this

#
.footer {
    padding-left: 2rem;
    padding-right: 2rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
turbid glen
#

Im sure i copied the code correctly from the video. I googled a bit and if the user locked the video, it will appear as in the picture. But its not in my case so

rustic pebble
#

Actually I usually have it like that

#

So my css lookslike that

#

@solar hatch

.footer-sep {
    margin-left: 2rem;
    margin-right: 2rem;
    margin-bottom: 0;
    margin-top: 1rem;
    border: 1px solid #3f3f3f;
}

.footer {
    padding-left: 2rem;
    padding-right: 2rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
#

Hmm

#

@turbid glen There are some times where YouTube bugs out

#

When you get this it probably means it has been disabled for viewing outside youtube

limber laurel
#

If I have a bootstrap template, can it interfere with a css file

#

?

rustic pebble
#

Yea

solar hatch
#

HOW DO i put section h1 in the middle

#

@rustic pebble

rustic pebble
#

It depends on your css layout, but usually you could do either of those