#web-development

2 messages · Page 56 of 1

native tide
#

So, with a complicated package structure, it makes it not worth it. inline style is fine 😛

#

for this at least.

cold anchor
#

What kind of use cases @lofty matrix ?

lofty matrix
#

I make and host different projects for different clients. They are all generally based around the same code base, but with client specific needs implemented on each. Each client has a subdomain of my domain like client1.example.com. This points to an AWS load balancer, where the hostname is used to route traffic to the corresponding target group. Each project has one or more EC2 instances in a target group. It's working, but I have some concerns with load balancers not having the ability to reference an infinite number of target groups, some clients want to use their own domain, which requires a certificate to be added to the load balancer, and EC2 load balancers have a limit of 20 certificates. Also there's the issue of being able to patch, do rolling deployments, etc across all of these different but similar projects in the same infrastructure in a manageable way

tired root
#

At some point I'd look into Colo instead of cloud

#

A cluster can work a lot more efficient than a lot of cloud servers tied together

#

Also, instead of reverse proxy, you can use IP forwarding, effectively not having to worry about the certificate limit

#

BUt then each instance is under more load

#

Is this Python wsgi servers or php, fastcgi?

lofty matrix
#

wsgi

#

Django, specifically

tired root
#

Are you using haProxy or nginx as reverse proxy?

#

or apache?

lofty matrix
#

well the load balancer is proxying traffic to the EC2 instances, then each instance runs nginx to proxy to the application

tired root
#

So a mix of Layer 4 and Layer 7 balancing

#

The first load balancer is Layer 4, it ip forwards, the one behind is layer 7 as it fetches the website for the client

cold anchor
#

each client has a different version of the same application?

lofty matrix
#

not the same application, which makes it confusing. They share libraries I've written that handle a lot of the common functionality between projects

cold anchor
#

I'm confused on why you're using the same domain/LB at all if they're different apps

tired root
#

@cold anchor It is very common, the client can still put another domain on it as cname or A/quadA record

cold anchor
#

I understand that part

#

that's a typical whitelabel app

tired root
#

At my last job, we had something similar, a bunch of webshops running off the same code

#

But we used a Linux cluster with roundabout 20 servers

#

IN a Colocation setup

#

FUnny enough, I work now in that very datacenter they have colo in

#

😄

#

That happens when you refuse a raise

#

but 😛

#

sorry

lofty matrix
#

One reason is cost; it's cheaper to have 20 clients on 1 load balancer than to have 1 client per load balancer. Each client individually doesn't have much traffic. There's also a gateway instance in the VPC that handles some of the configuration management/deployment esque tasks

tired root
#

It's good enough to have one load balancer to serve many clients

#

if it can handle the load

#

But something you've never said: Where is your bottleneck?

#

I can give you general advice, but I am curious where your issue is right now

cold anchor
#

looks like 100

lofty matrix
#

It's not really a performance bottleneck. I want to be able to continue taking on client projects without worrying that at some point, I will hit a limit of how many taget groups/certificates/domains I can have, and I will have to re-think everything. It's also that I would like to manage all of them in the same way

tired root
#

I don't know how much you make, but at some point look into having root servers, but it increases the administrative workload

#

pros and cons

#

and further down the road colocation in a data center nearby

#

WHich requires an investment of a lot of money

cold anchor
#

alternatively if you can turn the differences in client implementations into just something you or they can configure, you don't need to use new servers for each or worry about load balancer limits

lofty matrix
#

What do you mean by root server, scorcher? DNS?

tired root
#

@lofty matrix Dedicated root, it means you rent the whole hardware and the server hardware is exclusive to you

#

You only get an OS supplied by the DC it is in

#

Colocation means you put your own hardware into a rented rack

lofty matrix
#

rdbaker do you mean similar to a product like gitlab, where each enterprise client has their own configuration of roles and things like that, but the product is just "gitlab"? I've thought about that, but I don't think I could make the functionality generic enough for that

#

scorcher, each client uses one or two of some of the cheapest EC2 instances, so it's like $20/month to host, and the clients absorb that hosting cost. I think in this case dedicated hardware would just add complexity

tired root
#

It's something to consider and you need to make that call. A whole dedicated root server costs about 40€/month plus traffic and an IP, but it may be worth it

#

but again, I can only give pointers

#

If cloud is still enough, then stick with it

onyx crane
#

Since nobody responded yet, ill just drop it here again for relevance :'D sorry

Django:

  1. When i use the .save method of my ModelForm, i think the .save method of my reference Model gets called.
    I already overwrote the save Method of my Model which worked perfectly. Now i want to make the ModelForm call a "first_create" method that is an extended version of my overwritten .save method of my Model. This does not work though. (https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/#the-save-method) i couldnt find anything about this here.
  2. Is there a way to pass a javascript variable back with my form without displaying a formfield ? Like a hidden field i can populate with javascript, depending on on site conditions that then gets submitted with the rest of the form ?
cold anchor
lofty matrix
#

rdbaker, so you're just running one application (accross multiple server/instances), and clients have separate logins and api tokens and billing and such, correct?

cold anchor
#

yeah exactly

#

then the app they interact with is just static JS hosted by a CDN and the configuration is fetched based on the domain and we point *.ourdomain.com to the CDN

lofty matrix
#

Yea, unfortunately I can't generalize my use cases like that

cold anchor
#

dang, then yeah, the last time I had to do something similar we ended up creating new "stacks" per customer and would build the expense of it into their bill, lucky for us though, customers were high-touch and paid a lot

onyx crane
#

cough

Since nobody responded yet, ill just drop it here again for relevance :'D sorry

Django:

  1. When i use the .save method of my ModelForm, i think the .save method of my reference Model gets called.
    I already overwrote the save Method of my Model which worked perfectly. Now i want to make the ModelForm call a "first_create" method that is an extended version of my overwritten .save method of my Model. This does not work though. (https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/#the-save-method) i couldnt find anything about this here.
  2. Is there a way to pass a javascript variable back with my form without displaying a formfield ? Like a hidden field i can populate with javascript, depending on on site conditions that then gets submitted with the rest of the form ?
    @onyx crane
tranquil robin
#

is there something wrong with my flask route?

@app.route("/bookmarks/<int:id>/delete", methods=["DELETE"])
def delete_bookmark(id):

I keep getting 404, all of my other routes are working fine except for this one.
Let me know if I should provide any other info

queen bough
#

@tranquil robin No error?

tranquil robin
#
127.0.0.1 - - [30/Apr/2020 20:41:28] "DELETE /bookmarks/1/delete HTTP/1.1" 404 -
queen bough
#

So there is no error? That might mean your function code is incorrect.

tranquil robin
#

its not seeing my route at all, thats the problem

cold anchor
#

does the flask routes command show your route correctly?

tranquil robin
#

god, guess I need to take a break, it was an extra tab indentation -,-

queen bough
#

Where?

tranquil robin
#

i have been trying to fix it for 1 hour -,-

#

in the line of code before the route -,-

native tide
#

I tried to have it programmatically generated. so I didnt even have to write the conditions more than once and could easily change the values of the bottons and icons. But ehh... Seems like jinja2 doesnt know how to render jinja2 given to it to render after it is done rendering the first time.

#

You live and learn

#

Its probably one of those situations wheere you try to not repeat yourself and avoid hardcoding to the extent that you waste time on something you will never change or want to change.

#

(...maybe)

tiny siren
#

how do i setup a ddos protection loading page

#

that tells the user to wait 5 seconds

#

you know.

native tide
#

I'm pretty sure its more effective to monitor server logs and set up automated ip bans.

#

Not that i know how to qualify what deserves that...

#

Unless you're just trying to make people look at ads. 😛 But that isnt to protect against DoS

native tide
#

can some one help me i cant disable flask's anoying logger
ex. 127.0.0.1 - - [2020-04-30 22:32:30] "GET / HTTP/1.1" 200 2255 0.015633

the code i tried:

website_app = Flask(__name__, static_folder=path.abspath('./libs/templates/static'))
log = getLogger("werkzeug")
log.disabled = True
website_app.logger.disabled = True
#

nvm i have fixed it

#

changed

http_server = WSGIServer(("0.0.0.0", SETTINGS["PORT"]), website_app, backlog=False)```
to
```python
http_server = WSGIServer(("0.0.0.0", SETTINGS["PORT"]), website_app, backlog=False, log=None)```
cold anchor
#

you could also remove the logging handler:
website_app.logger.removeHandler(website_app.logger.handlers[0])

native tide
#

thanks

#

do you guys now how can i catch KeyboardInterrupt

Traceback (most recent call last):
  File "C:\Users\coolguy\AppData\Local\Programs\Python\Python37\lib\site-packages\gevent\_ffi\loop.py", line 
234, in python_check_callback
    def python_check_callback(self, watcher_ptr): # pylint:disable=unused-argument
KeyboardInterrupt
2020-04-30T19:41:35Z
#

i have tried

try:
  http_server.serve_forever()
except KeyboardInterrupt:
  print("")
  error("closing!")
  _exit(0)
#

its working actually but when closing it just prints that

cold anchor
#

do you want to catch a keyboard interrupt or an OS level kill signal?

native tide
#

keyboard interrupt

rare oar
#

hey all, I got a pretty stupid query that is giving me a lot of lengthy response times, especially when on heroku.

#

I'm wondering if anyone have tips to optimize?

#

that has the generated query, the view, and the models

tiny siren
zealous siren
#

Write it off to database

tiny siren
#

How lol

feral minnow
#

@tiny siren What are you using for this app, flask/django?

native tide
#

any of u huys know how to use pyngrok in termux

#

ngrok works fine but pyngrok raises The ngrok process errored on start error

tiny siren
#

@feral minnow django

feral minnow
#

@tiny siren I don't have experience with django but you can have a look here https://docs.djangoproject.com/en/3.0/ref/databases/ you can search to see what the easiest one to start I think its sqlite because I use it in flask, I didn't dive to deep with databases but sqlite is fine and simple for now, anyway if you're a beginner with web development I would recommed flask because people says that flask will teach you how things works , but django will save you more time and I think its easier than django.

sharp plaza
#

I am interested in making a website using Python. But the one thing that I am not sure to use is Django or Flask. I am more of a beginner as I have only been learning Python for about 5-6 months. If anyone has some suggestions or advice for me, please tag me.

feral minnow
#

@sharp plaza Flask is better to start than django, its easier im saying that from my experience with flask and what I read about them, so Flask is more straight forward and will make it easier to understand how things work, Django has more built-in functions so it will save you some more time , So go on start with flask and after spending sometime with it you can move to Django

sharp plaza
#

Ok, thank you very much! 🙂

feral minnow
#

Welecome 😀 , and if you don't know where to start here's a tutorial https://www.youtube.com/watch?v=mqhxxeeTbu0&list=PLzMcBGfZo4-n4vJJybUVV3Un_NFS5EOgX, I started with it his explainstion is pretty good

Welcome to the first flask tutorial! This series will show you how to create websites with python using the micro framework flask. Flask is designed for quick development of simple web applications and is much easier to learn and use than django. If you are less experienced wi...

▶ Play video
sharp plaza
#

Amazing! Tech with Tim! I was just going on his channel to look for Flask tutorials! 😄

feral minnow
#

Good luck man 😄

long forge
#

Just finished that series - it's pretty good but he sucks at naming things

#

Also what are everyone's thoughts on Django vs flask?

cerulean vapor
#

Flask is simple and a nice place to start for beginners

#

Django is complex, but completist - it covers most everything in some form

#

That said, Flask has a lot of add-ons that allow its functionality to be expanded

#

@long forge

long forge
#

I see. How does a plug in equipped Flask compare to Django in terms of security?

#

Assuming you run security plug ins

shy holly
shy holly
#

some how i need to override django-import-export library so I can skip the new "records"

native tide
#

hey, I have a flask project that worked quite well but the virtualenvironment was full of libraries that werent necessary anymore. so I deleted all dependencies and only installed those again, that are necessary for the project

#

Now I redeployed it again and everything works in production and uses less ram. But on my local machine i cannot open it for testing

#

this is what i get in the cmd:

#
127.0.0.1 - - [01/May/2020 12:14:21] "GET / HTTP/1.1" 302 -
127.0.0.1 - - [01/May/2020 12:14:21] code 400, message Bad request version ('Ð\x96U\x8a\x02ÛÀ\x15µ¿\x04Vö]\x8b\x8bü«÷Ôc³k\xadOÜ{C\x16¶0\x9a\x00"**\x13\x01\x13\x02\x13\x03À+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x00')
127.0.0.1 - - [01/May/2020 12:14:21] "  üŽ‡ï¼Êå•]Nð«sÍíXŒ`‘€cêZÀµK ЖUŠÛÀµ¿Vö]‹‹ü«÷Ôc³k­OÜ{C¶0š "**À+À/À,À0̨̩ÀÀ œ  / 5 " HTTPStatus.BAD_REQUEST -```
#

i guess something is wrong with the SSL but how can I fix it so that I can also run it on my machine without SSL?

#

Do I need some local environment variable that bypasses the HTTPS?

candid basalt
#

I don't see any ssl there.

#

It runs on http, so if there is no reverse proxy or something on top of it - there is no ssl to worry about.

#

Do you have nginx or something on top of it?

native tide
#

well I do have ssl in production. and there everything works. but locally I can not run the app anymore.

#

I use flask-talisman with this code:

#
    'default-src': [
        "*",
        "'unsafe-inline'"
    ]
}

talisman = Talisman(app, content_security_policy=csp)```
candid basalt
#

What do you perform requests with?

native tide
#

now i can make it work if I comment out the talisman line.

#

what do you mean with requests? If I use http or https?

candid basalt
#

Oh. Talisman:

Forces all connects to https, unless running with debug enabled.

#

So set it to debug mode for local dev and you should be fine.

native tide
#

ah, okay! that makes sense

#

I'll try it

#

many thanks!

candid basalt
#

Welcome.

native tide
#

works effing great

#

thank you DiRaven

candid basalt
#

You are very welcome.

pliant falcon
#

by xpath

#

I have a PHP script that works for simple xpaths

#

for example on Amazon I use this xpath for the price: ``` //span[@id='priceblock_ourprice']

#

and it's works..

#

but the battle net is different.. //span[contains(text(),'59.99')]

#

:/ aand it doesn't works.. any idea?

solar hatch
#

Which is more easier flask or node js

glossy musk
#

Using Flask and

@app.route("/login", methods=["POST", "GET"])
def login():
    if request.method == "POST":
     user = request.form["nm"]
     return redirect(url_for("user", usr=user))
    else:
    return render_template("login.html")```
zealous siren
#

Line 20

#

Or more likely Line 19

#

Oh, you are mixing tab and spaces, don’t do that

haughty turtle
#

Django is no joke haha

#

like relearning a new language 🙂

#

Anyone here switched from a framework such as Laravel to Django and found any benefits?

cold socket
#

Does anyone know if I can use Flask to render a game from pygame onto the web?

solar hatch
#

@cold socket you can use JavaScript

#

And it pretty easy

hallow moat
#

Does anyone know if I can use Flask to render a game from pygame onto the web?
@cold socket you can't do that

tiny siren
#

How come when i press this button locally it works and when i upload it, it doesn't?

hallow moat
#

pygame & web applications are whole different things

sonic flicker
#

Can anybody help me with this issue

tiny siren
#

So my question just got buried.

#

Great

versed sigil
#

lol u mad @tiny siren

#

youre going to have to do some troubleshooting on your end

#

open chrome/ff dev console

#

track down whats going on

tiny siren
#

yeah i get errors in the console, but i don't know if it's related

#

@versed sigil

oblique delta
#

can I ask a WAMP question here?

versed sigil
#

@tiny siren you can try posting the errors, but without any code or errors not much can be done

#

WinAmp was my favo mp3 pllayer

oblique delta
#

nvm, found my answer

frosty mauve
#

.Can anyone here help me with formsets on django?

#

['ManagementForm data is missing or has been tampered with']
Getting this error...been trying to troubleshoot but no luck yet

shy holly
frosty mauve
#

I think there is a builtin onchange() function that might be worth looking into

cerulean pelican
#

Hello, i'm trying to save a file which is uploaded using FileField (Flask), heres my code video_form.video_file.data.save('uploads/' + filename) But it says AttributeError: 'str' object has no attribute 'save'

#

Any help I could receive?

feral minnow
#

@cerulean pelican Are u sure .data is required here ?

cerulean pelican
#

yes .data is required because otherwise this will be in the traceback instead

#

AttributeError: 'FileField' object has no attribute 'save'

feral minnow
#

Im reading the doc but im not seeing anything about data

cerulean pelican
#

tho its 7 years old

feral minnow
#

you want to save the file to somewhere in the clients device ?

#

or you want to give them the option to choose?

cerulean pelican
#

no no i want to save it on my server

#

its a flask application

feral minnow
#

so something like recive a file from the client or download it directly from another site

cerulean pelican
#

mate its a website, they upload the file and it will do a post request and my server gets the file in the request and downloads it and stores it on my end

feral minnow
#

just use .save try it I don't think you need .data

cerulean pelican
#

I did and this was the response

#

AttributeError: 'FileField' object has no attribute 'save'

lament moss
#

im trying to open lots of tabs on chrome as i need the random string at the end of the website any way i can do it out of chrome

feral minnow
#

@lament moss What you mean with random?

#

You can get the url string without opening the taps, but if you want to do both you can or you meant a random string in the website content?

frosty mauve
#

Anyone here good with formsets?

grizzled crescent
#

Hello, does someone know a website that store covid datas ?

solar hatch
#

Api

#

??

#

@grizzled crescent

grizzled crescent
#

API or website @solar hatch

solar hatch
#

@grizzled crescent

obsidian parrot
#

does anyone know if data from admin.py gets sent or is just representing data from the db because im trying to query it and for some reason i cant use .filter() or any of that, the only thing that works is .all()
django btw

candid gull
#

I have this Resource:

class RatingsResource(Resource):
    def get(self):
        try:
            ids = request.get_json()['articleIds']
        except Exception:
            ids = None

        rating = Rating.objects(article_id__in=ids)
       
        return rating.to_json(), 200

The JSON returned is being escaped:

"[{\"_id\": {\"$oid\": \"5eab76b49121a126eed50eef\"}, \"user_id\": \"854c9a9b-4a4a-410f-867c-9985c17878d8\", \"article_id\": 1, \"created_at\": {\"$date\": 1588280739226}}, {\"_id\": {\"$oid\": \"5eab7c279121a126eed50ef0\"}, \"user_id\": \"854c9a9b-4a4a-410f-867c-9985c17878d8\", \"article_id\": 1, \"created_at\": {\"$date\": 1588280739226}}, {\"_id\": {\"$oid\": \"5eab8a709121a126eed50ef1\"}, \"user_id\": \"854c9a9b-4a4a-410f-867c-9985c17878d8\", \"article_id\": 2, \"created_at\": {\"$date\": 1588280739226}}, {\"_id\": {\"$oid\": \"5eab8b389121a126eed50ef2\"}, \"user_id\": \"854c9a9b-4a4a-410f-867c-9985c17878d8\", \"article_id\": 2, \"created_at\": {\"$date\": 1588280739226}}, {\"_id\": {\"$oid\": \"5eac4fbd9121a126eed50ef3\"}, \"user_id\": \"854c9a9b-4a4a-410f-867c-9985c17878d8\", \"article_id\": 1, \"created_at\": {\"$date\": 1588280739226}}, {\"_id\": {\"$oid\": \"5eac7e08d5f3c28020d0755d\"}, \"user_id\": \"854c9a9b-4a4a-410f-867c-9985c17878d8\", \"article_id\": 3, \"created_at\": {\"$date\": 1588354045805}}]"

Anyone know why?

#

This fixes it: json.loads(rating.to_json()) - but does not seem good

native tide
#

hey

#

can i use flask forms for any form?

#

or just login and registration form?

wild thunder
#

hey guys, just made it
Link: https://github.com/ngeorgj/fast-flask

it's an far cousin of django for flask projects,
it create an editable structure with the boring part
hope it's useful to you guys,

please rate it if you can

outer apex
#

@native tide Can help with your wtforms question if you still had some!

native tide
#

yes pls @outer apex !!

#

ok so i want to do a form that uses selectField

#

so like dropdown

outer apex
#

yup

native tide
#

ok so

#
class TestForm(FlaskForm):
    unit = SelectField('Unit Type', [DataRequired()], choices = [('python','CITS1401'),('dsa','CITS2200'),('ai','CITS3001')])
    testtype = StringField('Type', validators=[DataRequired()])
#

i've got this

#

i just dont know

#

how to access this in jinja2

#
{% block content %}
    <form class="login" action="" method="post">
        <h2>Choose your test</h2>
        <h4>Select from the below options</h4>
        
        <div class="field">
          {{ form.unit.label }}
          <span class="form-error">{{ error }}</span>
        </div>
      ```
tired root
#

Either do the whole form in WTForms or all in HTML

#

don't mix

native tide
#

what you mean?

outer apex
#

Oh, just {{form.unit}}

native tide
#

oof

#

legend!

#

@tired root what you mean?\

outer apex
#

Well, label is handy too, since you'd want to label it

#

We've seen people writing wtforms on the Python side and not harnessing its power in the template. I think @tired root was referring to an instance like that.

native tide
#

oh ok

#

appreciate the help!

#

btw

#

for QuerySelectField

#

what import does that fall under?

tired root
#

<form class="login" action="" method="post">
I hope you are adding some path to the action here

native tide
#

sorry ignore that

#

stole it from the login form

stuck current
#

Hi people, I was asp.net programmer at 2000. I used mostly vb.net. I did a long brake for programming.
So nowadays i want to return to web development for my personal website. I want to learn & use Python.
But i have some questions before starting & i couldn't find any answer for these on the internet.
So here are the questions:

1- Is it possible web development with Python "without installing frameworks"? (for example Django, Flask or whatever)
I want to install only Nginx and Python. Is it possible?

2- In PHP coding in HTML possible, but is it possible in Python?
For example is there a syntax like this in Python?
<html>
<title>Hello World</title>
<body>
<?php echo "Hello World!"; ?>
</body>
</html>
3- If these are possible where can i find tutorials? When i tried to find tutorial all of them was Django or any other frameworks.

Note: Sorry for my bad English. I know it's not well and i sorry for that : )

polar nova
#

1-no 2-yes 3-corey schafer

stuck current
#

thanks a lot : )@polar nova

native tide
#

I have a problem with Jinja and Flask-wtf: Is it possible to use a variable inside a variable?

                    {{ form.keyword(class_="single-input-primary", value="{{pre_keyword}}") }}

                        {% else %}
                    {{ form.keyword(class_="single-input-primary") }}
                        {% endif %}```
#

In this case I check if the variable pre_keyword is passed to the template. if it exists the input field should be prepopulated with it -> value = {{ pre_keyword }}

#

Unfortunately it literally renders "{{pre_keyword}}" in the template since the whole input is a variable

#

how can i prefill the form with a variable?

tender crater
#

Was wondering about logging best practices for a Flask application that ideally should be deployed on GCP. I'd like to gather some opinions on:

  • Logging directly to Stackdriver
  • Write/find a handler to log to a MySQL db
  • Log to a file written inside the container
nimble epoch
#

I have a question about flask

#

What is _get_current_object()?

zealous siren
#

Stackdriver or DB, containers should have nothing in them that isn't instantly disposable

tender crater
#

@zealous siren Forgot for a moment about that golden rule.

#

I'm leaning towards dropping a text file in a storage bucket vs. Stackdriver

zealous siren
#

that's fine too

#

it's less useful then stackdriver but probably less costly as well

native tide
#

hi how do you make a redirection in django

sharp plaza
#

I was just wondering if it is possible to make an online game using Flask? When I say online game, I mean games like surviv.io, agar.io, krunker.io, etc.

zealous siren
#

Cifer, not really

#

You can write backend but you need JS for browser part

#

And you need Websocket support so hopefully Flask supports that

knotty seal
#

I am new to flask and I'm trying to pass form data from one route to another... Here's what I have: ```py
@app.route("/index", methods = ["GET", "POST"])
def index():
coffeeForm=CoffeeForm()
if coffeeForm.validate_on_submit():
return redirect(url_for("order"), coffeeForm)
return render_template("index.html", form=coffeeForm)

@app.route("/order", methods=["GET", "POST"])
def order(coffeeData):
return render_template("order.html", form=coffeeData)

#

The order.html will just display the order in a table.

#

Would it be better for me to create a list containing the data from coffeeForm and pass that, rather than trying to passing the actual form?

feral minnow
#

@knotty seal if you want to get data from another function you gotta use "sessions"

#

so something like this session["coffe"] = coffeeForm.theformyouwanttogetdatafrom.data

#

then you will go to order

#

coffe = session["coffe"]

#

and if you want to use a list you can also

knotty seal
#

So do I need to pass the data to the view function

def order(coffeeData):
  return render_template("order.html", form=coffeeData)
#

Or is the form global?

feral minnow
#

you put the form in index.html right?

knotty seal
#

That's right

feral minnow
#
def index():
  coffeeForm=CoffeeForm()
  if coffeeForm.validate_on_submit():
    session["coffe"] = coffeeForm.theformyouwanttogetdatafrom.data
    return redirect(url_for("order"))
  return render_template("index.html", form=coffeeForm)


@app.route("/order", methods=["GET", "POST"])
def order():
  user_coffe = session["coffe"]
  return render_template("order.html", form=coffeeData)

knotty seal
#

I have actrually changed the index view function now to create a list...

@app.route("/index", methods = ["GET", "POST"])
def index():
  coffeeForm=CoffeeForm()
  if coffeeForm.validate_on_submit():
    coffeeData = [coffeeForm.drink_type.data, 
                  coffeeForm.milk_type.data, 
                  coffeeForm.sugar.data, 
                  coffeeForm.extras.data,
                  coffeeForm.email.data, 
                  coffeeForm.username.data,
                  coffeeForm.payment.data]
    return redirect(url_for("order"))
  return render_template("index.html", form=coffeeForm)```
feral minnow
#

yup you can create a session and store a list inside it two, so session is like a "variable" that you can get its data from every function.

#
                  coffeeForm.milk_type.data, 
                  coffeeForm.sugar.data, 
                  coffeeForm.extras.data,
                  coffeeForm.email.data, 
                  coffeeForm.username.data,
                  coffeeForm.payment.data]```
knotty seal
#

Do I need to install Flask-Session for this?

feral minnow
#

from flask import session

knotty seal
#

Hmm. Okay

feral minnow
#

I didn't install it but maybe you have too idk

#

I think it was downloaded automacily when I installed flask

knotty seal
#

This will be interesting. I'm just testing it

feral minnow
#

yup its useful

knotty seal
#

@feral minnow I love you and would like to have your babies.

#

😛

#

Also, thanks - I got it working.

feral minnow
#

wtf

knotty seal
#

My sense of humour.

#

I’m just appreciative. And yes, I’m male.

feral minnow
#

Ah np... Welcome (:

native tide
cerulean pelican
#

Hello, I'm wondering of how I could get this piece of code but inside a FlaskForm? ```
{% for genre in genres %}
<option value="{{ genre.name }}">{{ genre.name }}</option>
{% endfor %}

#

thats inside my html file which contains my jinja2 syntax

#

this is my form

#
class VideoForm(FlaskForm):
    """New Genre Form."""
    title = StringField('Title', validators=[validators.Length(min=3, max=75)])
    # genre = SelectField('Genre', [DataRequired()],
    #                    choices=[Genre.query.all()])
    description = StringField('Description', validators=[validators.Length(min=10, max=250)])
    video_file = FileField('File')
    submit = SubmitField('Upload')
tiny siren
#

If i send somebody my html code would they be able to fix it for me? I've been trying for a day

#

( The problem is that when i upload the file to host, the dropdown context button stops working, and idk why )

hallow moat
#

@tiny siren Just send it here

candid gull
#

I'm relatively new to Flask. I have integration tests. In node apps I have written, I can prepend NODE_ENV=test onto the test command. In python with unittest, can I do this?

#

Currently I am using flask.config.from_object

tiny siren
#

The button doesn't work

outer apex
#

@cerulean pelican What are you trying to achieve? Are you trying to render the choices for genre as dropdowns?

native tide
#

I am using Django 3.0.5 with a PostgreSQL database. I want to rename the field called first_name to fname. I believe I have to use the AlterField() operation, but I am not sure how to do so. Anyone have any experience with this?

class Contact(models.Model):
    first_name = models.CharField(max_length=50)

https://docs.djangoproject.com/en/3.0/ref/migration-operations/#alterfield

outer apex
candid gull
#

@outer apex I have done this.

class Config(object):
    DUBUG = False
    TESTING = False

    MONGODB_SETTINGS = {
        'host': 'mongodb://root:example@rating-service-db:27017/rating?authSource=admin'
    }


class ProductionConfig(Config):
    pass


class DevelopmentConfig(Config):
    DEBUG = True


class TestingConfig(Config):
    TESTING = True

    MONGODB_SETTINGS = {
        'host': 'mongodb://root:example@rating-service-db:27017/rating-test?authSource=admin'
    }

However, how do I tell my tests to use the testing config? I currently have this:

if app.config['ENV'] == 'production':
    app.config.from_object('core.config.ProductionConfig')
elif app.config['ENV'] == 'development':
    app.config.from_object('core.config.DevelopmentConfig')
else:
    app.config.from_object('core.config.TestingConfig')

Can I change the env in the base test?

outer apex
native tide
#

that's exactly what i am using

#

anyway, i think i found the answer

#

gonna try now and will report back

outer apex
#

@candid gull How are you instantiating your test client?

#

@native tide Good luck. Back up if data is important!!

native tide
#

through makemigrations and migrate

#

this is just a personal test project

candid gull
#

@outer apex I am using Docker - So I am running the tests inside of Docker. This is the issue - I am setting FLASK_ENV to dev - and I dont want to keep restarting the container when testing. In node, I can just prepend NODE_ENV onto npm run test as an example... Can I do this in Flask/Python?

#

Am I making sense?

outer apex
#

@candid gull That makes sense. I think you could set app.config directly, like app.config['ENV'] = 'testing', before you run the tests

candid gull
#

@outer apex So I did this:

    def setUp(self):
        app.config['FLASK_ENV'] = 'test'

Does not work though...

outer apex
#

@candid gull Looping back a little, what are you hoping to happen after updating ENV? What are your expected results?

#

How is app defined and are you importing it from the module it is defined in?

candid gull
#

@outer apex I want to change the database connection

#

My app:

app = Flask(__name__)
api = Api(app)

if app.config['ENV'] == 'production':
    app.config.from_object('core.config.ProductionConfig')
elif app.config['ENV'] == 'development':
    app.config.from_object('core.config.DevelopmentConfig')
else:
    app.config.from_object('core.config.TestingConfig')

init_connection(app)
init_routes(api)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
outer apex
#

I see. You're using the instantiated app to run your tests. So setting the ENV here won't update the remaining config variables.

#

You could update the database connection directly.. app.config['MONGODB_SETTINGS']. Not "clean" but get's the job done..

candid gull
#

ah ok

#

How would I restructure the application to override the env?

outer apex
#

If you just want to change specific config, changing it directly works. Like this database connection scenario.

#

You could also adopt the factory pattern. Put all this instantiation process into a function, and wherever you need that app, call that function

#

app_factory

def create_app():
    app = Flask(__name__)
    ...
    return app

main

from app_factory import create_app
app = create_app()

test

from app_factory import create_app
app = create_app()
#

Note how you can create different app instances, and pass in args to this function to make it use different config object if you wish.

viral sphinx
#

Hey guys, so I have a flask web application , I want to do some route testings

#

Any recommended libraries ?

#

I’m new to unit testings

zealous siren
#

Are you testing rest methods or what?

#

there is unittest

viral sphinx
#

Yes

zealous siren
#

I use Powershell Pester but I'm familiar with it

viral sphinx
#

I want to throw some requests parameters to the routes and test for 200 statuses

#

unittest would be best?

#

I’ve been trying to go on YouTube but there is no good explanations

zealous siren
#

unittest has ton of documentation, not sure if it's best for web testing

#

you will have to build requests to rest endpoints

#

which is why I use Powershell

#

that's built in for me

#

good rest testing should throw a simple sanity check at it

viral sphinx
#

Thanks bro

#

Appreciate it

zealous siren
#
def get_json_data(uri: str) -> dict:
    """Returns JSON Data in dict format"""
    try:
        response = urllib.request.urlopen(uri,timeout=60)
        urldata = response.read().decode("utf-8","ignore")
        jsondata = json.loads(urldata)
        return jsondata
    except:
        return None``` Quick and dirty hit URI and get rest method back, if it fails, return None
#

needs import json import urllib.request

#

as someone who is at a company that builds REST API for a living, my recommend I picked up from them was making a ping function on your rest API that touchs some of our other functions for quick sanity check

#

if any of them return false, barf HTTP Exception 503, makes monitoring really easy

native tide
#

@molten kite Try asking your electron.js question here

molten kite
#

thank you @native tide

#

anyone here works with Electron.js?

native tide
#

Go ahead and ask your full question

#

!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.

native tide
#

@outer apex ```python
from django.db import migrations, models

class Migration(migrations.Migration):

dependencies = [
    ('contacts', '0001_initial'),
]

operations = [
    migrations.RenameField(
        model_name='contact',
        old_name='first_name',
        new_name='fname',
    ),
]
that is my custom migrations file that i had to create
molten kite
#

So im starting with Electron.js and I dont actually know if its the css which is kinda empty or I have to configure it but any ouput from the html + css doesn't extend fully in the screen.

native tide
#

it's gotta have something to do with the html and/or css

#

why do you think it should extend fully in the screen in the first place?

molten kite
#

the content is extended, I tried with padding and other css variables but still doesnt extend to the full screen.

native tide
#

i know nothing about electron.js 😦 you'd be better off asking in the webdev discord

#

i think reddit has one /r/webdev

#

but it's definitely the html/css for sure

#

as javascript is just for interaction

#

although maybe it's something you do in electron.js that alters the html/css

native root
#

It's definitely something to do with your css

#

IIRC by default electrons <html> and <body> elements cover the entire horizontal space, but maybe not vertical

molten kite
#

thank you!

molten kite
#

IIRC by default electrons <html> and <body> elements cover the entire horizontal space, but maybe not vertical
@native root I feel dumb it was in front off my eyes all the time. lmao thanks anyways

velvet sluice
#

In django, is the norm to use class based views or function based views?

marsh canyon
#

any works, but I prefer class based views as there are some pre-built ones which can be quite useful

#

like listview, detailview, etc

velvet sluice
#

I see. So I assume there is no standard, just depends on what the company (or should I say engineering team) prefers?

marsh canyon
#

kinda but class based views are cleaner as well

#

as each section is split into methods

#

like 1 method for get requests, and another method of post request, etc

#

more info here

velvet sluice
#

oof I can see how it's much better than if request.method == 'GET' and etc.

#

Awesome, thank you! @marsh canyon

marsh canyon
#

yep

#

have a good day

velvet sluice
#

🙂

supple loom
supple loom
#

okay so the problem is i am entering data in my db manually but it's not updating

tired root
#

are you committing?

#

@supple loom

supple loom
#

it gives error when i apply

#

it's not giving any error now ..i just restarted

cerulean pelican
#

Hello, I'm wondering of how I could get this piece of code but inside a FlaskForm? ```
{% for genre in genres %}
<option value="{{ genre.name }}">{{ genre.name }}</option>
{% endfor %}


thats inside my html file which contains my jinja2 syntax

This is my form

class VideoForm(FlaskForm):
"""New Genre Form."""
title = StringField('Title', validators=[validators.Length(min=3, max=75)])
# genre = SelectField('Genre', [DataRequired()],
# choices=[Genre.query.all()])
description = StringField('Description', validators=[validators.Length(min=10, max=250)])
video_file = FileField('File')
submit = SubmitField('Upload')


I'm trying to render the choices for genre as dropdowns.
feral minnow
#

form.genre.choices = [ (genre,genre) for genre in genres ]

#

and genre should be before adding choices something like this genre= SelectField("Genre", choices=[], validators=[DataRequired()])

#

@cerulean pelican

#

so for the first one form.genre.choices you will put this at the function where you want to add choices and form here stand for whatever variable you give it the value of the class Videoform()

cerulean pelican
#

So what would my jinja 2 syntax look like? @feral minnow

feral minnow
#

if you mean the html file

cerulean pelican
#

yea

feral minnow
#

you will put this {{ form.hidden_tag() }} {{ form.genre }} in the template that you want the selectfield to be shown to the user

cerulean pelican
#

what is form.hidden_tag?

feral minnow
#

its something for the csrf_token like secuirty I don't know much about it I just put it in my forms

#

I think it will generate a hidden csrf_token

cerulean pelican
#

ahh okay

#

lemme try it out 1 second

#

its empty

#

this is my code

#

video_form = VideoForm() video_form.genre.choices = [(genre, genre) for genre in Genre.query.all()]

#
class VideoForm(FlaskForm):
    """New Genre Form."""
    title = StringField('Title', validators=[validators.Length(min=3, max=75)])
    genre = SelectField('Genre', [DataRequired()],
                        choices=[])
#

and it also doesnt look anything like my other dropdown

feral minnow
#

wait what Genre stand for?

#

Genre.query.all()

cerulean pelican
#

Genre is a model

#
class Genre(db.Model):
    __tablename__ = "genres"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)

    def __repr__(self):
        return '<Genre %r>' % self.name
feral minnow
#

ohh

#

do you have anything in databases?

cerulean pelican
#

Yes

feral minnow
#

but you want to get the id or the name?

cerulean pelican
#

name

#

wait

#

ik the reason

#

for why its not working

cyan flicker
#

what website would you recommend to use to make my own website?

#

godaddy is a no no

cerulean pelican
#

Namecheap

#

@feral minnow fixed it but it still doesnt look like my other dropdown

feral minnow
#

oh can I see you code

cerulean pelican
feral minnow
#

for the html and form

cerulean pelican
#

sure

#
                    <div class="form-group">
                      <p class="help-text">
                        Video Genre
                      </p>
                      {{ form.genre(class_="custom-select", name_="video-genre") }}
                      <select class="custom-select" name="video-genre">
                        <option value="0" disabled selected>Select Genre</option>
                        <option value="Test">Test</option>
                      </select>
                    </div>
#
class VideoForm(FlaskForm):
    """New Genre Form."""
    title = StringField('Title', validators=[validators.Length(min=3, max=75)])
    genre = SelectField('Genre', [DataRequired()],
                        choices=[])
    description = StringField('Description', validators=[validators.Length(min=10, max=250)])
    video_file = FileField('File')
    submit = SubmitField('Upload')
feral minnow
#

so now its adding the values but you want it to edit the style i believe?

cerulean pelican
#

yes

#

I want it to look like this one

feral minnow
#

oh give me a sec let me see my code

cerulean pelican
#

aight 🙂

feral minnow
#
                    <form method="post" name="ch"   action="#choose-start" style="margin: 0 auto;">
                        {{form.hidden_tag()}}
                        {{ form.startChapter(class="custom-select") }}         
                    <div class="input-group-append">
                               <button class="btn btn-outline-secondary" type="sumbit">Start Chapter</button>
                      </div>
                      </form>
                </div>
#

so in my code I put it in a form which is inside a div

#

and added the bootstrap classes that I want

#

are you using bootstrap btw or you just styling it yourself?

cerulean pelican
#

Bootstrap

#

How would I assign a name variable to my genre field?

#

e.g name="video-genre"

feral minnow
#

you mean the value

cerulean pelican
#

ye

#

because I tried this

#

{{ form.genre(class_="custom-select", name_="video-genre") }}

#

but it doesnt recognize the name_="video-genre"

feral minnow
#

ohhh

cerulean pelican
#

but this select

#

has it

#

<select class="custom-select" name="video-genre">

feral minnow
#

you wanna get what user choose?

cerulean pelican
#

the name="video-genre" is a styling part i believe

#

fixed it

#

nvm

#

Thanks for all your help (:

feral minnow
#

Welcome,glad to help 😄

cerulean pelican
#

But I still have a problem with one of my models

#

I have this inside my Video model

#

genre = db.Column('Genre', backref='video_genre', lazy=True)

#

and it gives me this error

#

TypeError: Additional arguments should be named <dialectname>_<argument>, got 'backref'

#
class Genre(db.Model):
    __tablename__ = "genres"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)

    def __repr__(self):
        return '<Genre %r>' % self.name
#

Genre model

feral minnow
#

one sec

#

try adding def __init__: self.name

#

in your class

cerulean pelican
#

to which model?

#

or class

feral minnow
#

databases class

cerulean pelican
#

Huh?

feral minnow
#
    __tablename__ = "genres"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    def __init__:
        self.name = name
    def __repr__(self):
        return '<Genre %r>' % self.name```
cerulean pelican
#

oh in there okay

feral minnow
#

you have to give it a value which is name

cerulean pelican
#

still get the same error

#

TypeError: Additional arguments should be named <dialectname>_<argument>, got 'backref'

#
class Genre(db.Model):
    def __init__(self):
        video_genre = self.name

    __tablename__ = "genres"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)

    def __repr__(self):
        return '<Genre %r>' % self.name
feral minnow
#

put it under the Colums and I forget to tell you that you need to add def __init__(self,name)

cerulean pelican
#
class Genre(db.Model):
    __tablename__ = "genres"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)

    def __init__(self, name):
        name = self.name

    def __repr__(self):
        return '<Genre %r>' % self.name
feral minnow
#

its must be self.name = name so you will set the self.name to the value name

cerulean pelican
#

still same error

#

TypeError: Additional arguments should be named <dialectname>_<argument>, got 'backref'

feral minnow
#

From where the error is coming?

cerulean pelican
#

genre = db.Column('Genre', backref='video_genre', lazy=True)

feral minnow
#

You have to classes for databases?

cerulean pelican
#

what do you mean

feral minnow
#

I mean im not seeing ```genre = db.Column('Genre', backref='video_genre', lazy=True)

cerulean pelican
#

that genre = db.column

#

is on the video

#

model

#
class Video(db.Model):
    __tablename__ = 'videos'

    # Values which are important
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), unique=False, nullable=False)
    description = db.Column(db.String(250), unique=False, nullable=True)
    views = db.Column(db.Integer, default=0, nullable=True)
    genre = db.Column('Genre', backref='video_genre', lazy=True)
#
class Genre(db.Model):
    __tablename__ = "genres"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '<Genre %r>' % self.name
#

sorry if it was a bit confusing

feral minnow
#

im not too good with databases so what backref does here?

cerulean pelican
#

not completely sure, I copied it from a example

feral minnow
#

oh

#

So I don't wanna say something I don't know and break your code but try to delete if it didn't work try ask people at #databases

solar hatch
#

Has anybody use heroku before

#

Or now

sudden crest
#

yes i'm sure almost everyone here has

solar hatch
#

How does free hosting works

#

@sudden crest

#

Is it limited or unlimited

sudden crest
#

what

solar hatch
#

Heroku free hosting

sudden crest
solar hatch
#

What is Dyno

sudden crest
#

i would highly recommend at least reading the pricing page of a host you plan to use

solar hatch
#

Oh

sudden crest
#

why is installing and using uwsgi with python so goddamn painful

native tide
#

I have a problem with Jinja and Flask-wtf: Is it possible to use a variable inside a variable?
``` {% if pre_keyword %}
{{ form.keyword(class_="single-input-primary", value="{{pre_keyword}}") }}

                    {% else %}
                {{ form.keyword(class_="single-input-primary") }}
                    {% endif %}
In this case I check if the variable pre_keyword is passed to the template. if it exists the input field should be prepopulated with it -> value = {{ pre_keyword }}
Unfortunately it literally renders "{{pre_keyword}}" in the template since the whole input is a variable
how can i prefill the form with a variable?
#

This is my SearchForm:

    place = StringField('place', render_kw={"placeholder": "City / District / Address"}, validators=[DataRequired("Please enter a place.")])
    radius = IntegerField('radius', render_kw={"placeholder": "Radius in [m]"}, validators=[DataRequired("Please enter a number between 1 and 100000"), NumberRange(min=1, max=100000)])
    keyword = StringField('keyword', render_kw={"placeholder": "Keyword"}, validators=[DataRequired("Please enter a keyword.")])
    submit = SubmitField("Search")```
native tide
#

solved in help-iron

#

just needed value=pre_keyword instead of {{pre_keyword}}

native tide
#

@tired root

#

i am inheriting from base.html

#

and the main webpage is home.html

#

i added both to jsfiddle

tired root
#

works fine in chrome

#

firefox is also ok

native tide
#

try using it on a device toolbar

#

for example an iphone 6

#

when u press the menu it goes behind the picture

#

the poster

tired root
#

I am, I am resizing the result window

native tide
#

did it work?

tired root
#

oh the menu

native tide
#

the hamburger

tired root
#

Fixed it

#
nav ul{
  float: right;
  margin-right: 60px;
  z-index: 9999;
}```
#

with the z-index the menu will stay on top of things

native tide
#

it messed up the look on desktop

tired root
#

use a media query

#

and do that only for small screens

native tide
#

how do i do that? (sorry i am a newbie)

#

i only know the bootstrap stuff

#

i am new to css

#

ok

tired root
#

This will apply the z-index on screens not wider than 720px

native tide
#

Ok

#

do i leave the other nav ul?

tired root
#

yes

native tide
#
  float: right;
  margin-right: 60px;
}

@media only screen and (max-width: 720px) {
nav ul{
  float: right;
  margin-right: 60px;
  z-index: 9999;
}
}```
#

ok

tired root
#

Mhh, you can also use an extra selector

#

Probably cleaner

#
nav ul{
  float: right;
  margin-right: 60px;
}

@media only screen and (max-width: 720px) {
.on-top{
  z-index: 9999;
}
}```
#

then add on-top as class to the <ul> element

native tide
#

ok

#

still :/

tired root
#

Do you have <meta name="viewport" content="width=device-width, initial-scale=1.0"> in the header?

native tide
#
      <input type="checkbox" id="check">
      <label for="check" class="checkbtn">
        <i class="fas fa-bars"></i>
      </label>
      <label class="logo">Flixnet</label>
      <ul class="on-top">
<li><a class="active" href="#">Home</a></li>
<li><a href="#">Projects</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
<li><a href="#">YouTube & Discord</a></li>
</ul>
</nav>```
#

yes i do have it

tired root
#

It's fine in my preview

#

with the changes added

native tide
#

i will try to restart the django server

#

still

#

maybe because my laptop screen?

tired root
#

wait you already have a media query which breaks at 858px

#

add the on-top class to that and remove the new one

native tide
#

how?

tired root
#

just add it to the media query you already have

#

I mean, you wrote it, you must understand it

native tide
#

it was a snippet

#

and i was modifying it

tired root
#

then please learn some basic css first

native tide
#

i do not understand what should i do

#

sorry

tired root
#
@media (max-width: 858px){
  
  .on-top{
    z-index: 9999;
  }```
native tide
#

Okay

tired root
#

Seriously, learn css from scratch

native tide
#

Okay 😂

#

ok it now works thanks!

grizzled crescent
#

Hello, i M developping a website with django and I want to use JavaScript to make forms without refresh. I M beginner with js. Can you advise me to do this task ?

native tide
#

also that white space

native tide
#

@native tide using boostrap ?

cold socket
#

Hey guys

#

What is the best Flask application/file structure?

native tide
#

@native tide its OK I fixed it, also yes I was using bootstrap

native tide
#
return redirect('contacts:login')

the above code works fine, but if i remove contacts:, and leave only login in there, it stops working. why?
here is my route:

path('login/', views.loginPage, name='login'),
#

p.s. contacts is the name of my app

onyx crane
#

Django
How can i change the 'selected' choices of a ChoiceField in a ModelForm through JS?
I added the "selected" class to the parenting list element, which is all a natural selection does. Still it does not get displayed in the field and does not get used when i submitt the form.
Also. Could i not visibly render a choicefield but still have it "there" ?

hollow root
#

@onyx crane for your first issue, i don't exactly understand the question. for the second question you can use hidden form fields

Django
I have a mapping for a API and my DB that looks like this

# my db field: the api field
DEVICE_STORE = {
    'device_stores_id':'id',
    'name':'name',
    'description':'description',
    'record_status':'recordStatus',
}

My model for this looks like follows

class DeviceStores(models.Model):
    device_stores_id = models.CharField(max_length=255)
    name = models.CharField(max_length=255)
    description = models.CharField(max_length=255)
    record_status = models.CharField(max_length=255)

i do a get or create when i get the object like this at the moment

obj, created = models.DeviceStores.objects.get_or_create(
                device_stores_id=item['id'],
                name=item['name'],
                description=item['description'],
                record_status=item['recordStatus'],
            )

Is there a way i can do some sort of mapping or transform the API response to map to the correct item from the mapping contsants i created above.

polar nova
#

@native tide set display: flex

#

make your container's display flex

#

or use bootstrap and add d-flex to classes div

#

or use grid system bro

proud dome
#

Guys I am quite new to wordpress php and the likes and I have a question:

When I create a child theme folder in WP, do I have to copy all files from the parent folder or are they created automatically? I.e. my folder contains style.css functions.php and some other folders but not footer.php, I then changed the footer in WP editor and expected it to create a new folder in my child theme root directory, but it did not. It also did not overwrite the parent footer.php --- where is the data stored then?

solar hatch
#

What is the difference of writing flask rest api for a Todo and doing it the normal way

#

Are there any disadvantages

#

I know this is a stupid question

ember kayak
#

YES

cloud path
#

guys

ember kayak
#

ya

cloud path
#

is there a tutorial to upload images through flask into a server?

ember kayak
#

idk

#

wait

#

u are using flask

cloud path
#

yeah

#

i'm developing a prototype of a social media

ember kayak
#

i just started like 5 min ago

cloud path
#

ah alright

ember kayak
#

thats cool

cloud path
#

yeah

ember kayak
#

i had a diffrent website

#

but that was in html

cloud path
#

html is the front-end

ember kayak
#

i am beter in python so i did it in python

cloud path
#

for the front-end you use flask for back-end

#

you have to use both

cloud path
#

oh thanks i'll try to do it following this tutorial

ember kayak
#

lmao

#

wait

#

how do i make a button

#

that takes me to discord

cloud path
#

oh you can do <a href="https://discordapp.com/"> type something here </a>

#

that will be a text but you can turn it into a button by bootstrap

ember kayak
#

ok

#

so
import bootstrap

cloud path
#

the aesthetic like a button, you can import bootstrap by putting this into the head

#

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

#

and this at the bottom before closing the body

#
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>```
ember kayak
#

UH ok

cloud path
#

then

#

besides href at "a" tag you can put the class parameter

#

like that class="btn btn-primary"

#

there are all the buttons that you can use

#

through bootstrap

ember kayak
#

ok

#

from flask import Flask, redirect, url_for

app = Flask(__name__)

@app.route("/")
def home():
    return "Hello! this is the main page <h1>HELLO<h1>"

@app.route("/<name>")
def user(name):
    return f"Hello {name}!"

@app.route("/admin")
def admin():
    return redirect(url_for("user", name="Admin!"))

if __name__ == "__main__":
    app.run()

#

lmao this is all i have

cloud path
#

it's okay you will get improved, i'm also very noob lol

ember kayak
#

lmao

#

File "website.py", line 20
return f"<button type="button" class="btn btn-link">Link</button>"
^
SyntaxError: invalid syntax

#
@app.route("/Test")
def test():
    return f"<button type="button" class="btn btn-link">Link</button>"

cloud path
#

mmm i advise you to create a "templates" folder

#

and create a html page into it

ember kayak
#

ok

#

how

cloud path
#

create a template folder into the folder of your app in which you are programming

#

then create something like "index.html"

#

into it put all the html code

#

then into the route test

#

add at the bottom return render_template('index.html')

ember kayak
#

ok how do i call the file

#

oh

cloud path
#

you can call the file how you want

#

from flask import Flask, redirect, url_for

#

here add also render_template so

#

from flask import Flask, redirect, url_for, render_template

ember kayak
#

add this to the main page or the index

cloud path
#

this to the main page into the back end

#

you just have to add render_template besides the other things

ember kayak
#

like this

cloud path
#

create a folder in that folder

ember kayak
#

oh

cloud path
#

name it "templates"

ember kayak
#

ok

cloud path
#

then put index.html into it

ember kayak
#

ok

#

and for the index.html i put
<button type="button" class="btn btn-link">Link</button>
in it

cloud path
#

yeah but you have to put the html code as well so

ember kayak
#

wdym

cloud path
#

<doctype HTML>
<html>
<head>
</head>
<body>
</body>
</html>

#

and put that button between the body tags

#

btw from which tutorial you're learning flask?

ember kayak
#

uh tec with tim

#

and others

#
<doctype HTML>
<html>
<head>
</head>
<body>
<button type="button" class="btn btn-link">Link</button>
</body>
</html>

like this

cloud path
#

yeah it's fine now you can do

ember kayak
#

ok

cloud path
#

return render_template('index.html')

#

at the bottom of the route test

ember kayak
#

ok

#
from flask import Flask, redirect, url_for

app = Flask(__name__)

@app.route("/")
def home():
    return "Hello! this is the main page <h1>HELLO<h1>"

@app.route("/<name>")
def user(name):
    return f"Hello {name}!"

@app.route("/admin")
def admin():
    return redirect(url_for("user", name="Admin!"))

@app.route("/test")
def test():
    return render_template('index.html')

if __name__ == "__main__":
    app.run()

cloud path
#

yes it's good

ember kayak
#

Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

cloud path
#

it is in localhost i cannot see it

ember kayak
#

ik

#

i am showing u i am at the page

cloud path
#

mm is there a debug?

#

by the way you have to add

#

render_template besides url_for

#

where you have from flask import etc

ember kayak
#

hmm

cloud path
#

you have to put another comma and type there render_template

ember kayak
#

uh ok

cloud path
#

i mean here

ember kayak
#

ok

#

i do

cloud path
#

try to run now

ember kayak
#

kk

#

same error

#

wait

#

do i need to , render

cloud path
#

mm

#

no you need to

ember kayak
#

ok

cloud path
#

"from flask import Flask, redirect, url_for, render_template" instead of "from flask import Flask, redirect, url_for"

ember kayak
#

from flask import Flask, redirect, url_for, render

cloud path
#

render_template

#

not just render

ember kayak
#

YES

#

how do i postion on the page

cloud path
#

mmm position what?

ember kayak
#

the button

cloud path
#

where is it?

ember kayak
#

top left

cloud path
#

try to <center> before it and </center> after it

ember kayak
#
<doctype HTML>
<html>
<head>
</head>
<body>
<center>
<button type="button" class="btn btn-link">Link</button>
</center>
</body>
</html>
cloud path
#

yeah

ember kayak
#

ok

#

i am sorry but how do i make it mid center
it is no top center

cloud path
#

mm i don't know the right tag but try to put three or four <br> after <center> tag

ember kayak
#

uh ok

#
<doctype HTML>
<html>
<head>
</head>
<body>
<center>
<br>
<button type="button" class="btn btn-link">Link</button>
</br>
</center>
</body>
</html>
#

like that

cloud path
#

there's no need to close the br tag

#

you can do just <br>

#

put like three of them

ember kayak
#

ok

#
<doctype HTML>
<html>
<head>
</head>
<body>
<center>
<br><br><br>
<button type="button" class="btn btn-link">Link</button>
</center>
</body>
</html>
cloud path
#

yeah it's good

ember kayak
#

ok

#

ok so if i want to move it down a bit i put more <br>

cloud path
#

yeah technically

ember kayak
#

ok

#

thanks so much for ur help

cloud path
#

no problem!

ember kayak
#

well what does ur website look like

cloud path
#

i'm using a free-use template

#

i'm just coding the backend

ember kayak
#

oh

#

ok

cloud path
#

it is a bit long but not so much xp

ember kayak
#

ok

#

wait

#

i just forgot what i was going to say

#

would django be easyer

cloud path
#

mm i think django is more complex than flask

#

i heard that

molten kite
#

it is, flask is more flexible at most times and doesnt follow like a pipeline on how to do it I believe

zealous siren
#

flask is more lightweight which can mean simpler

#

or it can make life very hard because you are manually doing things that Django could do for you

tender crater
#

Agree with @zealous siren, Flask forces you to learn to build things that are built-in in Django

zealous siren
#

DJango is best for building bigger website where you don't want to write a ton of HTML, Flask is better for smaller ones or where you will be embedding, FastAPI for where you simply building REST APIs for SPAs

#

that's generic recommendation, obviously every use case varies

feral minnow
#

Guys how I can upload a zipfile

#

using flask

#

I tried send_from_directory and send_file

#

but they are not working

#
def upload():#Send files
    print("hi")
    path=session["file_path"]
    dirPath=os.path.dirname(path)#Get the path for the dir


    baseName=os.path.basename(path)#The file name
    return send_from_directory (os.path.abspath(os.path.dirname(path)),f"{path}.zip", attachment_filename=f"{path}.zip", as_attachment=True)```
ember kayak
#

uh people how do i make a button clickable

tender crater
#

@ember kayak what do you mean?

ember kayak
#

like i can click it

#
<doctype HTML>
<html>
<head>
</head>
<body>
<center>
<br><br><br><br><br><br><br>
<button type="button" class="btn btn-link">Discord</button>
</center>
</body>
</html>
#

where do i put the link

tender crater
#

I would personally go for something like

<a href="http://www.discord.com/"><button>Discord</button></a>
ember kayak
#

ok

#

how do i clolor the button

feral minnow
#

you mean the button?

ember kayak
#

yes

tender crater
ember kayak
#

ok

#

in html not css

feral minnow
#

you can style it inline

ember kayak
#

?

feral minnow
ember kayak
#

like with #1efi34

feral minnow
#

yes

#

you can put it there i believe

ember kayak
#

ok

knotty seal
#

Another flask question :)
Is there a way to access the label from a SelectField to output?

#

e.g. I have the SelectField py milk_type = SelectField("Milk", choices = [("fullCream", "Full Cream"), ("hilo", "Hi-Lo"), ("skim", "Skim"), ("almond", "Almond"), ("soy", "Soy"), ("none", "None")])

#

After the user has selected their milk type, I want to output to a table in another view function.

#

At present, it's displaying the value, rather than the label

feral minnow
#

you mean you want to get data to another function?

knotty seal
#

I can do that

#
@app.route("/order", methods=["GET", "POST"])
def order():
  myData = session["coffeeData"]
  print(myData)
  return render_template("order.html", data=myData)
feral minnow
#

you want to get what user choose and display it as a label?

knotty seal
#

So - myData is the input that the user has made. I am sending it to order.html which is just a table at present.

#

Output is as follows:

#

So rather than having flatWhite and fullCream being output, I want "Flat White" and "Full Cream"

#

Which are the labels from the different SelectFields

#

At present I am saving the inputs as a list. Would it be better as a dictionary?

feral minnow
#

It depends at what your trying to do

#

but if it will make the code more cleaner this would be nice

#

But dict really help it saved me 60 line of code or more

knotty seal
#

lol. That would have annoyed me... 60 lines of code.

#

Okay. So at present I am saving the user input as: py session["coffeeData"] = [coffeeForm.drink_type.data, coffeeForm.milk_type.data, coffeeForm.sugar.data, coffeeForm.extras.data, coffeeForm.email.data, coffeeForm.username.data, coffeeForm.payment.data]

feral minnow
#

If you want to make a dict you can add a key for every value e.g {"drink_type":drink_type.data}

knotty seal
#

True, but I just realised that won't help. Am I allowed to say [coffeeForm.drink_type.label] instead of [coffeeForm.drink_type.data] ?

feral minnow
#

I don't know actually

#

but try to google it

knotty seal
#

I just tested. You can, but it didn't work the way I wanted

#

milk_type = SelectField("Milk", choices = [("fullCream", "Full Cream"), ("hilo", "Hi-Lo"), ("skim", "Skim"), ("almond", "Almond"), ("soy", "Soy"), ("none", "None")])

#

The label is "Milk"

feral minnow
#

If you want to put what user choose as label you can do this return render_template("coffe",label=coffeForm.drink_type.data)
html:

knotty seal
#

@feral minnow - I have figured it out. It was more simple than I expected

#

drink_type = SelectField("Drink", choices=[("Flat White", "Flat White"), ("Cappucino", "Cappucino"), ("Black", "Black"), ("Mocha", "Mocha"), ("Hot Chocolate", "Hot Chocolate")])

feral minnow
#

Cool,you just changed the names?

knotty seal
#

Yeah

feral minnow
#

nice

knotty seal
#

Now to make it a little bit pretty and add pricing 😛

#

I am wondering if it would be better to just use bootstrap

feral minnow
#

For design yes

#

I use in my website without it my website will look like websites in 1999

#

but if you're a very good designer this is another thing

knotty seal
#

I'm horrible at design. I may be good one day.

#

Do you use FontAwesome ?

feral minnow
#

nope, is it a framework like bootstrap?

#

oh i just searched for it, its something used with bootstrap

knotty seal
#

Yeah. Icons and stuff

supple loom
#

which commad do we run after git add . ?

feral minnow
#

im not sure but maybe git commit

supple loom
#

okay

feral minnow
#

Uploading zipfiles is workinggg

supple loom
#

what do i wanna put in my .gitignore file if i want to ignore a directory inside my project directory?

tired root
#

folder/**

supple loom
#

okay ..thanks

onyx crane
#
$(".learn_talent").on('click', function(event){
                    
                    if ($("option:contains('" + this.name + "')").is(":selected")){
                        $("option:contains('" + this.name + "')").removeAttr('selected');
                        $(this).parent().parent().attr('class', 'card hoverable blue-grey darken-1');
                        alert("?2");
                    }
                    else if (!$("option:contains('" + this.name + "')").is(":selected")){
                        $("option:contains('" + this.name + "')").attr("selected", true);
                        $(this).parent().parent().attr('class', 'card hoverable blue-grey darken-3');
                        alert("?1");
                    }  
                });

Just quickly need a second pair of eyes to spot the obvious ...
I want to select and unselect an option. This works fine once(select, unselect, select) but then im stuck in the else if for some reason and i can't figure out why

queen bough
#

@onyx crane Not sure, but how can you check if !...is(":selected") if you remove the attribute?

onyx crane
#

previously i had the attribute set to false, but that ended in the exact same behaviour

viral sphinx
#

Anybody familiar with Wordpress?

#

I’m trying to host only a database on their and connect it to my website that is on another server(Heroku)

onyx crane
#
$(".learn_talent").on('click', function(event){

                    if ($("option:contains('" + this.name + "')").is(":selected")){
                        //$("option:contains('" + this.name + "')").removeAttr('selected');
                        $("option:contains('" + this.name + "')").attr("selected", false);
                        $(this).parent().parent().attr('class', 'card hoverable blue-grey darken-1');
                    }
                    else if (!$("option:contains('" + this.name + "')").is(":selected")){
                        $("option:contains('" + this.name + "')").attr("selected", true);
                        $(this).parent().parent().attr('class', 'card hoverable blue-grey darken-3'); 
                    }  
                });
viral sphinx
#

Is that possible?

queen bough
#

@onyx crane Why not if/else? Is there a third/multiple case(s)?

onyx crane
#

@queen bough if/else had the same issue. I was wondering if i just missed a case with else and used a second conditional.

#
<option value="1" selected="selected">Bogen-Talent</option>

This is where it's stuck

#

and normally by clicking the button again, it unselects again

#

i just cant see a reason why it would work once but not twice

queen bough
#

Can you post the full learn_talent element?

#

@onyx crane ^

onyx crane
#
<div class="card-action">
   <button class="waves-effect waves-light btn learn_talent" name={{talent.talent_name}}>Erlernen</button>
</div>

The other classes are just css styling classes from a framework

#

i iterate over model instances, create a card with a button, and every button on every card calls the method to modify its parenting card, and add the responding element to the selection of my <select> field

queen bough
#

Can you create a minimal demo with just the failing elements so that I can quickly test a few things? I think this is an issue with the selectors or (less likely) that the click event isn't being called as you assume.

#

@onyx crane ^

#

Pardon me if you've already seen it.

onyx crane
#

no actually i didnt :D

#

mb

#

Actually im not sure how to create a minimal demo for this reall quick, since there are so many dependent things involved in this view.
Would you want to hop into a stream and id show you what i got ?

#

(@queen bough , thanks already for the effort :) much appreciated)

queen bough
#

Stream?

#

Sure, I've only got ~10 mins though.

onyx crane
#

np

limber island
#

Would this Be a Good place to ask for help in regard to Processing a JSON array returned by an http request?

#

Basically I'm pigning an API endpoint and I can get what I need from a single array item, but I need the Data from every item in the array so I can biuld a tuple

#

I fugired out how to iterate the arry, but not how to make it construct a tuple

rustic pebble
#

Yo, does anybody know of any JS lib I can use to make a datepicker like that?

zealous siren
#

wisper, you could construct a list to start then cast into tuple

#

it's just matter of python x = tuple(list)

fair agate
#

is this the spot to ask about Django?

feral minnow
#

@fair agate yes its for web development go on and ask you question (:

fair agate
#

sweet! I'm getting a syntax error on this def str(self): I tried to implement and I'm not really sure why as everything looks fine in terms of syntax to me

#

i'll paste in

#
from django.db import models
from django.contrib.auth.models import User

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'
#

returning syntax error with def highlighted

#

oh shit

#

no closed ) on the previous line

#

my bad

ember kayak
#

ok

#

so i am useing flask

#

i am portforading my computer

#

but the link does not work

limber island
#

@zealous siren It was an issue with how janky the data structure was, I got it solved in a Help channel

feral minnow
#

guys I scrape a website to get a list of img but it put all img elements at one index how i can split them?

native tide
#

when to use justify-content ?

feral minnow
#

nvm,I created a for loop to itereate over the items then put them into another list

molten kite
#

just a random comment: why CSS is so annoying?

#

Some times I get frustrated. I rather download a template and modify it than go from zero

summer dirge
#

thats what id actually recommend, use a css framework like bootstrap, makes everything so much easier IMO

molten kite
#

I'm reading about tailwind css, have you heard about it?

summer dirge
#

nope, seems decent tho from a quick look

molten kite
#

it is, still getting to know it. can't have a final opinion rn

onyx crane
#
<form method='POST'> 
                {% csrf_token %}
                <div class="row">
                    
                    <tr>
                        <th>{{ form.pc_name.label_tag }}</th>
                            <td>
                            {{ form.pc_name.errors }}
                            {{ form.pc_name }}
                            </td>
</tr>```
Im rendering my ModelForm like this currently to get acces on how and where the different form elements are displayed. 
How can i go even further and adjust the classes of the input elements itself instead of just modifying the wrapper around `form.field` ?
elder wyvern
#

Hey so I made a simple program that takes api from Spotify to create a playlist. I’m trying to learn framework so I can turn it into my first simple web app. I really only need a home page that lets you authorize through Spotify, maybe a loading screen and then a success page for now. Is flask a better option than Django?

cerulean vapor
#

@elder wyvern Flask will be a whole lot less complex than Django for something that basic, yes

shy holly
#

ModuleNotFoundError: No module named 'import_export'Django
although I did install it
and added to settings
this's so weird

empty pivot
#

@shy holly you have to tell us more about the problem you are having

shy holly
#

@empty pivot what do u mean ?>.>
I tried to install django-import-export library .
and now I'm getting this error.

empty pivot
#

Okay how did you install it?

#

Did you do $ pip install django-import-export

native tide
#

It's better to master CSS than use a framework

#

it's kinda messy with bootstrap

#

and if you already know css and want to use a framework you have to learn bootstrap which is a whole nother CSS

shy holly
#

Did you do $ pip install django-import-export
@empty pivot YUP

empty pivot
#

Share your code here please otherwise it's hard to say what your issue is

molten kite
#

and if you already know css and want to use a framework you have to learn bootstrap which is a whole nother CSS
@native tide yeah, it's tedious

proud dome
#

noob question but

#

what would be the best way to allow for the shadow on the right panel

#

to go beyond the margin of the panel?

#

I cant seem to fix that

native tide
#

maybe postion absolute?

knotty seal
#

I am wondering how you could assign values to items in a SelectField in flask.i.e.

milk_type = SelectField("Milk", choices=[("None", "None"), ("Full Cream", "Full Cream"), ("Hi-Lo", "Hi-Lo"), ("Skim", "Skim"), ("Almond", "Almond"), ("Soy", "Soy")])
#

Let's say I wanted to assign a float to each of those items for the price

elder wyvern
#

@cerulean vapor thanks. At what point is django a better option than flask?

onyx crane
#

Django:
For some reason every button that i have inside my <form> tags is trying to submit the form :D The initial button has the type="submit" and value="Save". The others don't ..

haughty saffron
#

How can i make it so when someone goes to an ID (forgot what its called) it highlights the element? e.g if ive got a div element called "part-1" and you go to example.com#part-1, how would i make it change the background colour of the div?

versed sigil
#

set up en event listener

haughty saffron
#

ok

versed sigil
#

youd need to listen for something like mouse click on maybe theres an onEnter event

#

then youd call the function to change the color

#

using JS

tender crater
#

I am working with Jinja2 templates and I need to conditionally apply css attributes. So far I've managed to achieve that by applying condition to element creation:

{%- macro render_listing(listing) -%}
{% if listing["has_highlight"] %}
  <div class="job_listing" type="highlight">
  {% elif listing["has_custom_color"] %}
  <div class="job_listing" type="custom_color" style="background-color:    #00FF00">
  {% else %}
  <div class="job_listing">
{% endif %}
    <span class="job_title">
      {% if listing["has_logo"] %}
        <img src={{ listing["company_logo"] }} id="company_logo">
      {% else %}
        <i class="fas fa-briefcase"></i>
      {% endif %}
      <a href="{{ url_for('board.get_job', job_id=listing['id']) }}">
        {{ listing["title"] }}
      </a>
    </span>
</div>
{%- endmacro -%}

How do I apply conditions in the type attribute? I'd like to cut some stuff and avoid creating a new <div> each condition

cerulean pelican
#

Hello, i'm wondering for how I could possibly get the information of a user with jinja2 e.g i have comments which have the user_id of the user who wrote the comment though i dont know how to do a request and get the information of that user

feral minnow
#

@cerulean pelican if you can get the id

#

then you do ```user_filter = youclassname.query.filter_by(user_id = theuseridfromcomment).first()

#

then try doing user_filter.name

#

what i said is for sqlite

somber wedge
#

Hello

#

I was tasked with creating a CMS for our university website using python. I have built a API using flask before. Should I go along with Flask or pickup django?

#

I also had a question about which library should I use for using jwt with flask? authlib or python-jose?

tired root
#

Just go with what you know

#

makes no difference

zealous siren
#

Django is probably more "Out of the box" for CMS

tired root
#

There is nothing you cannot do with Flask

zealous siren
#

though learning curve obviously

tired root
#

I personally hate Django tbh, I find it clunky and convoluted

#

Flask is quick and simple

zealous siren
#

I didn't say that, but with Flask, you might be re inventing the wheel instead of just "buying" it

tired root
#

If I need more, I can add packages as I need them

somber wedge
#

I'd prefer to use flask cause I already got the hang of it

zealous siren
#

without knowing your skill level and like

#

it's possible that flask will get the job done quicker

#

or it might be faster to learn Django despite slow build up time

#

I'd prefer to use flask cause I already got the hang of it <-- can be dangerous mindset to get into, learning new things is important

somber wedge
#

I've intermediate knowledge of python. But I'm only a beginner for web dev. I find flask simple as it's a route+function=done.

zealous siren
#

sure but Django has tools to build the content of the webpage

#

are you just building backend or both?

somber wedge
#

The front-end will be decoupled

#

I just need to build a backend

zealous siren
#

so SPA JS frontend with REST API backend?

somber wedge
#

Yes what you said

zealous siren
#

Flask or FastAPI

#

Django is probably overkill

somber wedge
#

But I still need to have some form of auth

#

Which is secure

zealous siren
#

ok?

#

easily doable

#

we build JS SPA with auth all the time at work

somber wedge
#

So I wondered upon jwt, which seems better than just a username password model.

#

Which kind of auth should I use?

#

I'm kinda confused on that part.

jagged lark
#

JWT like in Java Web Tokens?

somber wedge
#

JS web tokens yes

zealous siren
#

we auth against AzureAD, which returns a token, you send that token to API which validates it and stores token into Azure Storage Table storage for lifetime of token

jagged lark
#

Web Tokens are just here to say "I have passed the authentication method, I am this person"

#

As username/password is an authentication method

#

They don't really serve the same purpose

#

JWTs are used behind the scene in most case

somber wedge
#

I see

#

If I want to do stateless auth, what should I look into?

zealous siren
#

to put in passport terms, you go get a passport from trusted provider (Authentication server) then you go elsewhere with your passport, you present your passport to third party (rest of application) to valid yourself, that third party calls up Trusted Provider and says "Hey, is this passport number valid?", gets yes/no and proceeds accordingly

#

stateless auth is what I described, browser stores the token, likely in a cookie

somber wedge
#

@zealous siren oh I just remember, I could use firebase auth?

jagged lark
#

Stateless auth would use JWTs

zealous siren
#

you will have to work with JS developer on whatever you want to do

jagged lark
#

Because you don't need to store anywhere which token correspond to what, you signed the token as valid

#

That's like an ID

#

You gave the people their ID card, and signed it, so when they give it back to you, you know that it is valid because it has your signature