#web-development

2 messages · Page 142 of 1

vestal hound
#

nope

#

the database will be separate

#

unless you use an in-memory database

#

or local storage

#

which you should not do

#

why not

eternal blade
vestal hound
#

in that case, then yes, bad idea

last patio
#

If you’re scared of losing your data because of the platform, I wouldn’t risk using the platform

vestal hound
#

but you really should avoid sqlite for anything other than really small projects or testing

eternal blade
vestal hound
vestal hound
#

every IaaS/SaaS platform

#

does this.

#

servers are fungible.

eternal blade
vestal hound
#

you can’t write to the local filesystem on AWS either

#

if your fear is that you will lose data like that

#

then I would say you are approaching the problem from the wrong direction.

#

your database should not run where your app does.

eternal blade
#

There are only about 5 users if I migrate to postgress and they'll probably register again but it will be a new experience for me trying to migrate to a new db without breaking stuff

vestal hound
#

you can run a data migration

#

is not difficult with a bit of preparation

#

and you have little data

eternal blade
vestal hound
#

-> fewer edge cases

vestal hound
eternal blade
#

So should I also have static/media files separately?

#

I've never deployed anything before, I'm new to that

eternal blade
vestal hound
#

they’re static

#

i.e. don’t change

#

if by media you mean user uploaded stuff

#

then yes separate

#

okay maybe to give you some context

#

the reason you should separate app and data is

#

that makes your app stateless

#

you can run as many copies of your app as you want

#

if one goes down, just restart it

#

you lose nothing unrecoverable

#

imagine if you want to serve 10 different copies

#

and each has its own database on its local filesystem

#

how are you going to sync each of them?

#

imagine you connect to one but your user data is somewhere else

#

where will all that logic to switch you to a different server go?

#

if your apps are stateless

#

the user will never be exposed to this kind of detail

eternal blade
#

Sorry, give me a moment to catch up

#

So, if I have a media separately how can connect to it?

eternal blade
noble bolt
#

Hello everybody
I need help with Django-Restframework
I've been searching on google but I couldn't find something useful, could anyone help?

tribal pewter
#

what is it

lethal tulip
ocean dirge
#

im doing a login but i get an error

#
@app.route("/login")
def login():
    code = request.args.get("code")
    red = request.args.get('red')
    if code is None:
        if session.get("token"):
            user = Oauth.get_user_json(session.get('token'))
            return f"already logged in as {user.get('username')}#{user.get('discriminator')}"
        return redirect(f"{Oauth.discord_login_url}")

    else:
        try:
            at = Oauth.get_access_token(code=code)
        except:
            return "Invalid Code"
        print("Session")
        session["token"] = at
        if red is not None:
            redy = red.replace("$", "/")
            print("Accessed - ", redy)
            return redirect(url_for(red))
        else:
            return "Successfully logged in"

@app.route("/<guildid>/announcements")
def announcements_page(guildid):
    print(guildid)
    if session.get("token"):
        return "Valid Session"
    else:
        return redirect(url_for(f"/login?red=${guildid}$announcements"))
#

login

#

and error is

lethal tulip
#

@ocean dirge The url you are calling is then redirecting to the login url right? Have you tried calling the login url directly?

ocean dirge
#

if i pass a value into the discord login url will it come back again?

#

i need to pass the redirect url around a good bit

ocean dirge
#

i got it fixed

#

is this good code?

@app.route("/login")
def login():
    code = request.args.get("code")
    red = session.get("redirect")

    if code is None:

        if session.get("token"):
            user = Oauth.get_user_json(session.get('token'))
            return f"already logged in as {user.get('username')}#{user.get('discriminator')}"
        return redirect(f"{Oauth.discord_login_url}&")

    else:

        try:
            at = Oauth.get_access_token(code=code)
        except:
            return "Invalid Code"
        print(at)

        session["token"] = at
        if red is not None:

            return redirect(f"http://127.0.0.1:5000/{red}")
        else:
            return "Successfully logged in"
cloud path
#

guys, it always returns 1, in a form with flask

#

gender = SelectField('Sesso', validators=[DataRequired(message="Inserisci il sesso del tuo personaggio."), ], choices=[('M','Maschio'),('F','Femmina')])

#

def generategender(self, gender):
if gender == 'M':
return 0
else:
return 1

#

does anybody know how come?

frank pawn
#

idk why my website taking too time to load ?(using django)

#

after uploding videos website work one time.BUT when i reload it,it only load. why this is happening?

misty gate
#

Hey, everyone! i'm an intern in a college lab for air quality and they are starting to implement a webapp that runs a executable program (in rust if I'm not wrong) in the server (like, the user uploads the necessary files to the web page, the webpage redirects it to the server where it will run the program and give back the results). But the thing is that the user needs to keep that page open all the time. Is there a way that we could program it to do it like: the user uploads and submits the files and leave the page, then once the program finishes the server sends the result to the users email?

summer dirge
#

the best way to do this is to have the process running independently of the web request, with something like subprocess. then you could either send to an email (would have to code that too, maybe a small python script that calls the program, gets results and dispatches a email) or actually write results to a database together with the username/id. if you do it based on user id the user could just reopen the page to check the results at a later time.

misty gate
summer dirge
#

not sure, i would start by googling something like "long running processes in django"

lethal tulip
#

@misty gate have you tried Huey or Celery? It can be used to run asyncronus tasks. You can write your django views as required and then write a function for asyncronus task.

#

They have examples there so it won't be hard.

misty gate
lethal tulip
#

Celery might be overboard, but huey is definetly light weight, useful and simple.

tender goblet
#

Hi, I have a question. Someone know how I can send a file to user since Flask?

#

They give me parameters and I have to give them a file

lethal tulip
#

@tender goblet serving file in frontend or sending email?

misty gate
tender goblet
#

They give me parameters through a form data

#

And I send them a file on the backend

misty gate
#

awesome, could you give some more info about the project?
frameworks you are using, which language is the backend written on

tender goblet
#

I am working with Flask, what I have to do is receive some parameters through form-data. With those parameters that they give me I have to create a .kml file and return it

#

But I don't know how return the file

little bridge
#

I wanna set up a kahoot bot but the game pin wount type on the website

toxic flame
#

hi guys so i ran into this error

#

I know its not related to python but it's react and i need some help ;-;

#

Site works fine, i just dont like this error ;-;

cedar lodge
#

Hey Thanks for replying to my msg. I am passing a list for modifiers, I get an error shouting at me that
MODIFIER IS EXPECTED TO BE A dict but got a str

#

Hey guys this problem is the reason i am unable to sleep, If any one have something to help, I would really appreciate that. 😦
#web-development message

past cipher
#

Can someone explain how I can send Jinja variable to a Javascript function in an external filesheet, whilst using base templates?

#

<button onclick="logUsername('{{user.username}}')>Click Me</button>

This sends {{user.username}} to the javascript function, and not the Jinja value

#

It only happens with my child template, which inherits from a base template

native tide
#

(PHP, MySQL) Is there anything that im doing wrong? (im getting syntax error)

#

So I'm going to use this

https://getbootstrap.com/docs/4.0/components/modal/#scrolling-long-content

But I'd like to see a way to either have a black overlay over the background or blur the background when it pops up. Preferably blur. Does anyone know a way to do that?

terse dust
#

Can anyone help me with web parsing?

formal axle
#

how would I make a menu for a phone in one media quarry not display for another media quarry for the desktop/tablet

#

in css

#

never mind figured it out

strong rapids
#

I have a question - I want to ask if it can be programmed that when I enter a web address on the discord, such as www.example.com, a predetermined embed will appear.

cyan pawn
heady iris
#

so im trying to learn flask as of now and i was hopping if someone could help me understand how i can use teh main python file (such as idk app.py) how i can use it and what i can insert there

#

ping me if someone can help

cloud path
#

class CreateCharacterForm(FlaskForm):
telephone = SelectField('Telefono', validators=[DataRequired(message="choose whether your character will have a phone"), ], choices=[('1','yes'),('0','no')])
def generatenumber(self):
if self.telephone == 1:
while True:
rn = random.randint(100000, 999999)
char_same_num = Char.query.filter_by(telephone=rn).first()
if char_same_num is None:
break
return rn
else:
return None

#

guys it always gives NULL, why?

outer apex
#

@cloud path You should be comparing self.telephone.data. Also I think the value will be coerced into a string (I might be wrong here!) so check the type of the data so you're comparing the same types (1 != '1')

#

@heady iris what are you specifically interested in knowing about the main python file for Flask?

cloud path
#

yeaa thanks

#

i also put int(self.telephone.data)

outer apex
#

I think you can pass in a function (in this case int) as a coerce keyword argument for the SelectField. That way you don't have to do the manual int casting and catching of errors. So you'd have SelectField(...., ..., ..., coerce=int)

#

Also according to the docs, if there's no specific reason for DataRequired, use InputRequired as the required validator.

north aspen
#

I'm not quite sure how to debug when using Flask and Dash/Plotly. For instance I have the following callback:

@app.callback(
    Output('right-lower', 'children'),
    [Input('station-dd', 'value'),
     Input('all-graph', 'selectedData')],
    [State('right-lower', 'children')])
def display_selected_data(dd_selection, graph_selection, children):
    ...
    c = children
    ...
    if children is None:
        figure = None
    else:
        figure = None

So I'm trying to get the figure from the children and I have breakpoints at the ellipses but when i trigger the callback the breakpoints dont break and I cant see the variables so I dont know how to extract what i need.

floral fulcrum
#

Is there any way to view html code generated after Javascript has run and added content?

#

I'm trying to port wikimedia pages to github docs/wiki and wondering if there is any easy solution anyone is aware of.

gleaming mulch
#

@floral fulcrum I believe the request-html library can capture text rendered by JavaScript to a variable that can be output/parsed/manipulated as you see fit...

heady iris
last patio
#
@receiver(signal=signals.post_save, sender=Event)
def create_event(sender, instance, created, **kwargs):
    if created:
        for fighter in Fighter.objects.filter(retired=False):
            instance.registered.add(fighter)```
I'm trying to add to add Fighter object to Event object's registered ManyToMany once its created
but when i check, they havent been added
Any ideas?
gleaming mulch
#

So I'm having trouble with sqlite3 while learning django... Every time I run py manage.py dbshell I get "CommandError: you appear not to have the 'sqlite3' program installed or on your path." I both have sqlite3 installed and added to my user variables and system variables! Since it wasn't working with the sqlite3 directory in path I even went as far as adding the actual .exe file paths to my env variables... At this point I'm completely lost, any help would be GREATLY appreciated!

outer apex
#

@heady iris Typically that file will contain the code to tie everything together into a Flask app. It might contain things like the database connector, routes, and additional middleware you want to include in your app. When you call flask run, the package will read this file and run your application.

#

Have you tried spinning up a hello world with Flask?

heady iris
#

yes i have

outer apex
#

👍

heady iris
#

@outer apex but how can ik if i need to put something in teh app.py when creating soemthing?

outer apex
#

It depends on how you want to structure your app. Let's say you have a simple app with two routes, index and about. If there's no complicated procedures for these routes, makes sense to have two functions in the main file. But let's say you had a few set of routes, you probably don't want to put all the functions into the main file. Instead you'd pull these sets of routes into their own packages and then in your main file, import these packages. Flask already has a pattern called blueprints that does this.

#

It's a bit difficult to answer that question without much context since the context really defines how you would choose to structure and organise the files, right

heady iris
#

i woudl need to make a route for it

#

i woudl also have an html file lets name it signin.html

#

there i woudl display everything so that i can input my username and pass

#

the reason i ask this question is to understand how will i be able to check if the user had entered somthing specific so taht he/she will be redirected to another page

#

and also where will i check that

#

so thats why i asked what i can use teh main pyhton file

wicked elbow
#

well basically you do this

@app.route()
def login():
  if user=user and password=password:
    return NextPage
  return LoginPage
``` in the simplest terms
#

i dont know flask, so dont ask me specifics. just the same concept for every language

heady iris
#

and just above it ill clarify what each is

#

hmm ok

#

thx

ocean dirge
#

im requesting a guild count from my ipc for my discord bot but get his error

heady iris
ocean dirge
#
ipc_client = ipc.Client(secret_key="HELLO")

@app.route("/<guildid>/settings")
async def announcements_page(guildid):
    user = await discord.fetch_user()
    if user:
        session["redirect"] = None
        guild_count = await ipc_client.request(f"get_guild_count")
        return f"Valid Session, accessing for {user.name}#{user.discriminator}, bot is in {guild_count} guilds"
    else:
        session["redirect"] = f"{guildid}/settings"
        return redirect(url_for("login"))

website side

#
async def run():
    description = "Mattress, the backbone of any server"

    credientals = CREDIENTALS
    db = await asyncpg.create_pool(**credientals)
    await INIT(f"Successfully connected to {credientals['database']} database")

    await db.execute("CREATE TABLE IF NOT EXISTS guilds(guildid BIGINT PRIMARY KEY, prefix TEXT)")
    await db.execute("CREATE TABLE IF NOT EXISTS users(userid BIGINT PRIMARY KEY, announcements BOOLEAN)")
    await db.execute("CREATE TABLE IF NOT EXISTS members(userid BIGINT REFERENCES users(userid), guildid BIGINT REFERENCES guilds(guildid), announcements BOOLEAN, PRIMARY KEY(userid, guildid))")

    async def get_prefix(client, message):
        if message.guild.id not in prefixes:
            pr = await db.fetchrow("SELECT prefix FROM prefixes WHERE guildid = $1", message.guild.id)
            print(f"[PREFIX] - cached prefix '{pr[0]}'")
            prefixes[message.guild.id] = pr[0]
            return pr[0]
        else:
            return prefixes[message.guild.id]

    client = Client(description=description, db=db, intents=intents, prefix=get_prefix)

    @client.ipc.route()
    async def get_guild_count(data):
        return len(client.guilds)
#
    try:
        await client.ipc.start()
    except Exception as e:
        print(e)
        pass

    await client.start(TOKEN)


class Client(commands.Bot):
    def __init__(self, **kwargs):
        super().__init__(
            description=kwargs.pop("description"),
            intents=kwargs.pop("intents"),
            command_prefix=kwargs.pop("prefix"),
            case_insensitive=True
        )
        self.ipc = ipc.Server(self, secret_key="HELLO")

    async def on_ready(self):
        await INIT(f"{self.user} is online")


    async def on_ipc_ready(self):
        await INIT("IPC is Online")

    async def on_ipc_error(self, endpoint, error):
        await ERR(f"{endpoint} raised {error}")

loop = asyncio.get_event_loop()
loop.run_until_complete(run())
heady iris
#

idk what teh context is but when i get soemthing liek that i usualy check the last line cuz thats where teh problem is

ocean dirge
#

i have all relevant code here

wicked elbow
#

is localhost:20000 a valid location?

ocean dirge
#

i never refer to localhost:20000 anywhere

#

flask site is on 127.0.0.1:5000

#

is there a config for port?

#

should i change ipc port to 5002

wicked elbow
#

thats what your error is. meaning something is pointing to that location. find what is pointing there and youll solve your problem. i have no idea, dont know flask. and dont know discord.py. also no idea on connections between the 2. but thats your error.

ocean dirge
#

its apparently an error with the get_guild_count line

wicked elbow
#

your connections have to match. thats true for anything. for instance a db server runs on a specific port, or redis runs on a specific port. if the port isnt active, then itll refuse the connection.

ocean dirge
#

so everything has to run on :5000?

#

now im getting invalid response status

wicked elbow
#

not not necessarily. redis for example is port 6379, postgres is port 5432. if i havent started the servers, the ports will refuse a connection. make sure everything is running and running on the correct ports

native tide
#

So I'm going to use this

https://getbootstrap.com/docs/4.0/components/modal/#scrolling-long-content

But I'd like to see a way to either have a black overlay over the background or blur the background when it pops up. Preferably blur. Does anyone know a way to do that?

wicked elbow
#

cant really blur that i know of, maybe make and image thats partially transparent. like every so many pixels to use as a background that way its hard to tell whats behind it

native tide
#

its not really the actual background color I'm looking to change, but to createa a layer/blur over everything behind the popup

gleaming mulch
#

@floral fulcrum I forgot to mention selenium too... If the JavaScript that renders the html that you're trying to capture requires any interactions with the page in order to render then you'll want to look into selenium because it can automate page interactions to get the JavaScript you're looking for to render...

wicked elbow
#

because thats exactly how you do it

native tide
#

yea

#

tho I would prefer a blur, a partially transparent color would have to do too ig

wicked elbow
#

theres is no blur, but you cant make it be less transparent so its harder to see

native tide
#

well, there is css body { filter: blur(2px); } for what I know, but idk how to do that only when the popup is active and not blur the popup itself

#

Ended up with a reversed effect bonk

wicked elbow
#

should be able to do it with something like:

<div style="height: 100%; width: 100%; background: rgba(255,255,255, .3), position: relative">
  <div style="position: absolute; left: 50%; top:50%; transform: translateX(-50%) translateY(-50%); background-color: #FFFFFF">
    Whatever here
  </div>
</div>

use the blur in the first div if you want it there

#

may have to do it seperately, or like this

<div style="position: relative; height: 100%; width: 100%;">
  <div style="height: 100%; width: 100%; background: rgba(255,255,255, .3), position: relative">
    blur here
  </div>
  <div style="position: absolute; left: 50%; top:50%; transform: translateX(-50%) translateY(-50%);  background-color: #FFFFFF">
    Whatever here
  </div>
</div>
#

have a feeling its like opacity. and youll have to do the bottom method to achieve it

last patio
#

its a many to many

#

dont need save for it

hollow scaffold
#

Hey guys, little desperate to figure this out for a Client. Their web host doesn't have Python Apps or App management enabled in cPanel and don't offer SSH. Though they claim to offer python. Is there a way for me to run an app (Django) utilizing PERL or something else?

tulip relic
#

do they have "normal" cgi support?

#

I can't remember how "normal" cgi works, but you might be able to set the interpreter to python

#

regardless this seems like a security vuln if you're forced to put everything under doc root

hollow scaffold
#

I tried testing a file in public_html/cgi-bin and got a 500

tulip relic
#

yea idk how well this would work

hollow scaffold
#

I'm about to tell them to find a better host or move over to me

tulip relic
#

django expects wsgi i think, it supposedly also works with asgi but idk what that is

#

that means you have the connections run as different threads served from the same interpreter i think

#

normal cgi spawns a new interpreter each time

#

barely anyone uses normal cgi anymore, it's mostly fastcgi, wsgi, or some other thing where the request is forwarded to a backend service

hollow scaffold
#

Even that's getting a bit over my head at this point lol

tulip relic
#

yea it's pretty hard to do in a sane manner

hollow scaffold
#

I should just be able to pull the repo, and run it through Python App (cloud linux) or through the application manager (neither of which they have)

#

with a venv

tulip relic
#

are they migrating the app or is it fresh?

hollow scaffold
#

it's fresh

tulip relic
#

also, make sure you aren't using django's integrated server, it's not production ready. I've found uwsgi is simple enough to setup, but there are many ways to securely connect django to the client

hollow scaffold
#

Yeah, it's still in development, so I'll set that up when it's ready

tulip relic
#

ah

hollow scaffold
#

I just wanted to get it tested on the existing server for my sanity

#

but at this point it's safe to say that he's gonna have to move

tulip relic
#

cpanel is designed to run php and maybe perl stuff

#

it's pretty antiquated

hollow scaffold
#

Yeah, but in recent years, it's no problem to get basic python support, even with a little setup

tulip relic
#

are you sure there's even a python 3 interpreter on there?

hollow scaffold
#

Lol NOPE

#

can't even get into SSH to test it

#

for all I know it's probably only 2.7

#

all the client got from the host was Python support is already enabled on all of our servers. If you're having trouble using Python, please provide us with steps that can be taken to replicate the problem.

#

when I asked them to request the cpanel applications to be enabled

tulip relic
#

I feel like if you're running a django app you should probably shell out the additional like $4/month to get a proper VPS

hollow scaffold
#

probably

tulip relic
#

this is probably running shared between like 10 different users

hollow scaffold
#

exactly

#

I'll tell them to move or run under me

tulip relic
#

anyway, I had a question about django I thought I might try to ask here

hollow scaffold
#

Thanks for the help, if I know anything I'll stick around

tulip relic
#

np

#

I've historically used flask + jinja + some db driver for my projects, but I've been looking at trying django for my next project, altho idk if it's the right fit

#

actually I think I've figured it out after trying to explain it lol

#

django would prolly be best for this

#

it seemed kind of overwhelming at first compared to the minimalism of flask

sly trail
#

how do i get a client's ip when hosting a django site off of repl.it

#

every attempt ive made has led to a wrong ip

tulip relic
#

it may be sent through a proxy

sly trail
#

yeah

#

the ips they give are google cloud ips

tulip relic
#

there might be an X-Forwarded-For header I think

sly trail
#

tried that

tulip relic
#

hmm

hollow scaffold
#

@tulip relic I haven't used Flask, what are you trying to accomplish?

#

@sly trail are you trying to get the IP from the request, or your provider?

sly trail
#

from the client

#

the person who accesses the site

hollow scaffold
#

ah that's easy

#

during the view... let me pull up one of my projects

tulip relic
sly trail
tulip relic
#

altho django makes it easy to manage the db

hollow scaffold
#
#my_app.view

def MyView(request):
  ...foobar
  ip = request.META.get('REMOTE_ADDR')
  ...foobar
tulip relic
#

@hollow scaffold the problem is Stocker's server never observes the client directly

sly trail
#

AttributeError: 'Request' object has no attribute 'META'

hollow scaffold
#

ohhh didn't catch that

#

derp

sly trail
#

and i already tried remote_addr

#

:(

tulip relic
#

there's no way to tell without making the client specifically mention it in the request somehow

sly trail
#

rip

tulip relic
#

also, there are some cases where the client doesn't have its own public IP

hollow scaffold
#

almost seams like you would need another server just to act as the proxy and make the requests from your actual site

sly trail
#

172.18.0.1

#

this is the ip remote_addr gives

hollow scaffold
#

and get the IP's there

tulip relic
#

thats not google cloud p sire

#

thats a private ip

sly trail
#

the ips keep changing lol

#

depending on how i choose to get them

#

remot_addr gives a private ip i believe

#

json api gives one, x-forwarded-for gives another one, etc

quiet ridge
#

This is the landing page of my fully working website ignore the song and video quality bcoz I forget to stop and customise them

sly trail
#

im trying to do something to check for alts (discord py)

quiet ridge
hollow scaffold
#

@tulip relic yeah, I wonder if there is a library that might handle the downloads for you that you can implement into your project

sly trail
tulip relic
#

there is

#

but downloads can take 20 mins and the app may crash in that time

quiet ridge
#

Thanks @sly trail

tulip relic
#

it'd leave a file on disk and may or may not leave invalid metadata

#

i think i found a way tho

sly trail
#

np

hollow scaffold
#

@tulip relic lol okay

#

@quiet ridge looks good

sly trail
#

ye

quiet ridge
#

Thanks dude but it's only the landing I have made the full website

#

And after sometime I will upload whole website

sly trail
quiet ridge
sly trail
#

@tulip relic btw so basically i cant get the client's ip if im hosting the flask page off of replit right?

tulip relic
#

p much

sly trail
#

alr

#

my goal is to create something like altdentifier in a way where it detects alts, but idk how to do that securely

tulip relic
#

oh, you wouldn't do that by IP

#

VPNs exist

#

look at OpenID @sly trail

sly trail
#

okay

tulip relic
#

its what powers the login with google, login with facebook, etc

sly trail
#

ic

sly trail
#

also what would OpenID be used for

tulip relic
#

it's possible for multiple legitimate users to share the same IP and for a single user to have multiple IPs. It's way more useful, if you're trying to use it for alt detection to use OpenID

#

OpenID basically makes it so a user can identify using third party accounts

#

it's harder to create multiple google accounts than it is to get more than one IP

sly trail
#

oh okay

swift wren
#

hey guys, was trying to deploy to heroku and it was successful but then i ran into this problem

Traceback (most recent call last):
  File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 204, in _get_response
    response = response.render()
  File "/app/.heroku/python/lib/python3.7/site-packages/django/template/response.py", line 105, in render
    self.content = self.rendered_content
  File "/app/.heroku/python/lib/python3.7/site-packages/django/template/response.py", line 81, in rendered_content
    template = self.resolve_template(self.template_name)
  File "/app/.heroku/python/lib/python3.7/site-packages/django/template/response.py", line 63, in resolve_template
    return select_template(template, using=self.using)
  File "/app/.heroku/python/lib/python3.7/site-packages/django/template/loader.py", line 47, in select_template
    raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)

Exception Type: TemplateDoesNotExist at /login/
Exception Value: todo/userCreation/login.html

this is the view that is causing the error

path('login/', auth_views.LoginView.as_view(template_name='todo/userCreation/login.html'), name='login'),```
tulip relic
#

if you turn your router off for a minute and turn it back in it is likely you'll get a completely different IP

sly trail
#

oh damn

swift wren
#

that doesnt seem true

tulip relic
# sly trail

it looks like altdentifier makes you use a discord account with a linked e.g. steam account that matches what you login to altdentifier with

sly trail
#

i think you connect that to altdentifier

#

lemme check rq

swift wren
#

unless you have your ip set to dynamic it wont change everytime

tulip relic
#

residential ISPs don't offer static by default

sly trail
#

yeah

swift wren
#

servers should have static ips

sly trail
#

you connect those accounts to altdentifier after logging into it with discord

tulip relic
#

yea his server does, but he was concerned about the client

sly trail
#

yeah'

tulip relic
#

generally, IPs shouldn't be used at anything higher than the network level, because that is really their only intended purpose

sly trail
#

what do you mean?

tulip relic
#

it's kind of like keeping track of someone via their home address
people move, and they can have roommates

#

it stays the same for a while but it doesn't have to

sly trail
#

ah

tulip relic
#

it's better to come up with another way to keep track of that person, like a name (altho people can change their name in the real world, I can't think of a better example)

swift wren
#

yo does anyone have some insight into my issu

tulip relic
#

lemme see

#

looks like your templates aren't in the right folder

#

or they are rename d

swift wren
#

im beyond that bruv

#

thats not the issue

tulip relic
#

oh i c

sly trail
#

@tulip relic ty for the help

tulip relic
#

np

sly trail
#

oh btw

tulip relic
#

wait are you sure that file exists where you think it does

sly trail
#

even tho using their ip isnt always reliable, i think altdentifier does that as well when gcaptcha is the only option

tulip relic
#

templates/todo/userCreation/login.html

tulip relic
#

maybe

sly trail
#

yeah

tulip relic
#

it's really easy to get a new IP (I can do it in about 6 seconds), so you cant rely on that alone

#

i think discord's bans are ip based in some cases

surreal horizon
#

I am trying to web scrape https://finance.yahoo.com/trending-tickers with urllib and bs4, but this page is completely rendered my javascript, so when I try to open the page with urlopen and print the page content, I get a bunch of Javascript in my console. Does anyone know a workaround this so that I can get the HTML content of the page after the Javascript has been rendered? thanks!

sly trail
#

or at least im pretty sure they're supposed to be

tulip relic
#

yea maybe selenium

sly trail
#

kinda slow but idk what else

tulip relic
#

there's not an easy way to do it bc pretty sure they sell an api for it

sly trail
#

makes sense

surreal horizon
sly trail
#

ye

#

1s

surreal horizon
#

ok thanksman

tulip relic
#

i gtg, i might be able to help tomorrow though

sly trail
tulip relic
#

o/

surreal horizon
sly trail
#

you can look at both, and no problem

surreal horizon
#

ok thanks

#

lovely

sly trail
#

this will probably help more than those

#

you can play around with the sleep values to find the lowest sleep value you can do

surreal horizon
#

ok man thanks

#

hopefully this shall help

sly trail
#

np

swift wren
sly trail
#

ok

urban stone
#

I am trying to create a login API in django where User can login using email and password can anyone help me out please i am completely new to API

versed python
wicked elbow
#

lets hear what you think of the redesign? theres so many lines of code to make something so seemingly simple look like that. random meme pulled from reddit/random filler text. no offense intended

versed python
#

looks pretty good

#

i'd prefer if the 34 days ago had a little more contrast

urban stone
#

how can i also check that user which is logged in is an admin or not

neat briar
opaque rivet
versed python
opaque rivet
#

@versed python yeah that's what I mean

rustic pebble
#

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

true oriole
#

im getting an error on importing flask that is:

#

ImportError: cannot import name 'Flask' from partially initialized module 'flask' (most likely due to a circular import)

#

any help is appreciated

urban stone
leaden widget
#

is there anyone that can help me with some javascript, because i am using Ducument.getelementbyid but it is not working for me?

coarse bridge
#

how to create a new page using Django and configure the HTML and CSS files in the website while running the website or server?
Like the wiki fandom

native tide
#

can someone explain this

versed python
#

when you try to access a restricted page, django usually redirects to the login page. The first is the path for this redirect page.
The second one is basically a reference to path where the login page (it is not related redirect url in any way), and it is often equal to the redirect url

upbeat berry
#

hey,
I'm starting to work on a web app, and I want to use a js framework(like react or vue) along with python as backend - how can i easily do it? is there ant python framework that can help me build a dynamic web app?

tough oak
#

Flask or django which one is better?

toxic flame
wicked elbow
toxic flame
toxic flame
#

For authentication, I suggest JWT, alot of people dislikes it by its need for refreshing but I personally read the entire documentation and I was able to change the expiry date.

versed python
toxic flame
#

I'm 2 lazy to learn another auth library

#

I've been using express and experimenting with other backend libraries ( strapi, express, nuxt )

wicked elbow
#

use django-rest-knox. it stores the tokens encrypted. jwt is plain text so anyone with access to the db can log in as that user. also jwt is one per user, and knox is 1 per device

#

knox is basically the same as jwt i believe in terms of use

versed python
#

jwt is useful because it has a small expiry time. If you increase to a large time, all benefits of jwt are gone. at that point you might as well use auth token method which is much easier to integrate

versed python
toxic flame
#

nope hahaha

#

socket-io with express

#

Since strapi is just a plain old headless fms

#

Cms

#

strapi very useful for quick n easy fast apis

wicked elbow
#

man drop downs with frameworks are so much easier to make then doing it in plain old JS. i remember building multi-tier drop down menus using onMouseOver/onMouseOut in JS 13 years ago and it was a nightmare. but boy was it a masterpiece when it was done

silk portal
#
from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():

    return "Hi, dit is mijn eerste website!<h1>Hi<h1>"

if __name__ == "__main__ ":

    app.run()``` it doesn't say anything
#

does someone know whats wrong?

#

and yes i did download flask

quiet ridge
plain carbon
silk portal
#

Yup

#

i didn't saw the space

plain carbon
#

ahh, easy to miss

silk portal
#

Yup

plain carbon
#

Anyone here experienced with Flask SQLAlchemy? Having a bit of trouble wrapping my head around Many-to-Many relationships 😒

native tide
#

in react i have an <h1></h1> and everywhere i go in routing it's still giving me the same tag why?

versed python
native tide
#

what do you mean?

#

it's in my app.js

quiet ridge
plain carbon
#

@quiet ridge I managed to sort it, somehow. I don't really understand how the code is working since I've pieced bits together that I've found online but I'm trying to figure it out. Thank you though!

#

can you elaborate?

#

@void wagon

void wagon
#

nevermind

#

i solved it

plain carbon
#

okay

void wagon
#

thank u for your response

true ivy
#

Error

  File "./src/server/main.py", line 6, in <module>
    app = Flask(
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 601, in __init__
    self.add_url_rule(
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 98, in wrapper_func
    return f(self, *args, **kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 1275, in add_url_rule
    rule = self.url_rule_class(rule, methods=methods, **options)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/werkzeug/routing.py", line 666, in __init__
    raise ValueError("urls must start with a leading slash")
ValueError: urls must start with a leading slash

At first, I thought it was my @app.route(s) but all URL(s) there starts with a leading slash (/)
I don't understand why it throws the error

#

I'll get my code

#

main.py

from flask import Flask, request, render_template, send_from_directory
from os import path
from colorama import Fore, Style
from random import randint

app = Flask(
    __name__,
    template_folder='../public/pages',
    static_url_path='../public/cdn'
)

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

@app.route("/style/<path:path>")
def send_css(path):
    return send_from_directory('style', path)
    
@app.route('/monitor')
def monitor():
    return '{"status":{"code":200,"message":"OK"}}'

if __name__ == '__main__':
    print(f'{Fore.GREEN}[Python]{Style.RESET_ALL}: Running Webserver')
    app.run(
        debug=False,
        host='0.0.0.0',
        port=randint(2000, 9000)
    )
#

line 6 is the app variable ```py
app = Flask(..., ..., ...)

native tide
#

html:

<div class = "spinner"></div>```

css:

.spinner:before {
content: "";
box-sizing: border-box;
position: absolute;
top: 50%;
left: 50%;
width: 60px;
height: 60px;
margin-top: -30px;
margin-left: -30px;
border-radius: 50%;
border-top: 2px solid coral;
border-right: 2px solid transparent;
animation: spinner 0.7s linear infinite;
}

@keyframes spinner {
to {
transform: rotate(360deg);
}
}```

Currently this loading circle is locked in the center of my screen, is there any way to move it to the top right of the screen?

plain carbon
#

@native tide top: 50%; and left: 50%; is probably what is keeping it in the center

plain carbon
true ivy
#

That's wierd

plain carbon
#

Has the original Flask installation been messed with?

true ivy
#

colorama and random is just additional modules

plain carbon
#

Has the Flask package that is installed been messed with at all?

#

Flask itself

true ivy
#

no

#

i installed it, and use it normally

#

should i uninstall and reinstall it?

plain carbon
#

That's what I'd try. I'm by no means an expert, so maybe someone else can advise. But I see nothing wrong with your code, so I can't understand why it isn't working

true ivy
#

same. the error make's no sense

#

i even searched S.O. for answers

#

didnt find one

#

so I've uninstalled and reinstalled flask

#

same thing

plain carbon
#

I think you need the absolute path

true ivy
#

should i use sys.path.abspath?

native tide
#

anyone know of a good js discord?

true ivy
#

there's TCD
they support almost any languages

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @scarlet patio until 2021-03-20 17:02 (9 minutes and 59 seconds) (reason: chars rule: sent 3134 characters in 5s).

nocturne jetty
#

!unmute 487761079389257742

lavish prismBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @scarlet patio.

nocturne jetty
#

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

nocturne jetty
#

use that

scarlet patio
#

Oh. Id just type my question in separate messages

#

I have to „create a backend for RESTful API that should able to persist collections of GPS points (in JSON format), these collections are called traces” with example trace given:

[
{ "latitude": 32.9377784729004, "longitude": -117.230392456055 },
{ "latitude": 32.937801361084, "longitude": -117.230323791504 },
{ "latitude": 32.9378204345703, "longitude": -117.230278015137 }
]
#

As it is my first time doing something using Flask, i started from basics to expand it later.
Created database as stated:

    id = db.Column(db.Integer, primary_key=True)
    trace = db.Column(db.Integer, nullable=False)
    latitude = db.Column(db.Float, nullable=False)
    longitude = db.Column(db.Float, nullable=False)```
#

As I thought it would be a good idea to just insert data point by point and connect them into one trace with ‘trace’ number. It works fine for adding points one at time, but when it came to changing my code to let it take the whole trace (list of objects as stated above), I dont know how to do that. Is it possible to access objects from PUT request one by one and add them to separate rows? Or i should change my database structure to something different?

#
    def put(self, point_id):
        point_put_args.add_argument("trace")
        point_put_args.add_argument("latitude")
        point_put_args.add_argument("longitude")
        args = point_put_args.parse_args()

        point = PointModel(id=point_id, trace=1, latitude=args['latitude'], longitude=args['longitude'])
        db.session.add(point)
        db.session.commit()
        return point, 201

#

I just got lost, not sure if my database idea is even a good one

formal axle
#

anyone work with netlify I need some help

swift coral
#

Hwlllo, how to get rid of useragent stylesheet?

#

its putting margins and i cant fill the background

void summit
#

hello django users, anyone tried ModelForms with async views ? it seems not working since it needs to get data from database to render the form

#

I use sync_to_async helpers when dealing with DjangoORM calls, but this one is at the template level ..

#

maybe the render() function should be wrapper with sync_to_async 🤔 I'll give it a try

#

oh it works

#

here is the solution:

def _sync_render(*args, **kwargs):
    return render(*args, **kwargs)

async_render_wrapper = sync_to_async(_sync_render, thread_sensitive=True)
void summit
#

you will also need a wrapper for form validation

def _sync_validate_form(form_instance):
    return form_instance.is_valid()

async_validate_form = sync_to_async(_sync_validate_form, thread_sensitive=True)
#

as far as I see, django is not yet ready for async python 😐

manic frost
# swift coral its putting margins and i cant fill the background

You can use something like a "CSS reset", which is basically a stylesheet that resets all the styles set by default by the browser.
You can also do ```css

  • {
    padding: 0;
    margin: 0;
    }``` if you want to just set the default margin and padding to 0 on everything.
#

or you can just set margin: 0 on body and html

plain carbon
uncut spade
#

Hi, I have a little issur. When I want to upload for the first time a video on a user account, it uploads on his account, but when i want to upload on an other, it gets the main user's name and uploads on the first person that has uploaded. Is there a way to change the user when uploaded because i use a form field ? Thanks Here are my codes

#
from django.conf import settings
from .validation_taille import  validate_file_extension
from django.contrib.auth.models import User
# Create your models here.
class Videos(models.Model):
    user=models.ForeignKey(User,on_delete=models.CASCADE,default=1)
    caption=models.CharField(max_length=100)
    Video=models.FileField(upload_to='video/',validators=[validate_file_extension])
    def __str__(self):
        return self.caption
#
def Profile(request):
    all_Vid=Videos.objects.filter(user=request.user)
    print(all_Vid)
    if request.method=='POST':
        form=Video_Form(data=request.POST,files=request.FILES)
        if form.is_valid():
            form.save()
    else:
        form=Video_Form()
    return render(request,'Utilisateurs/Profile.html',{'form':form,'all':all_Vid})


def login(request):
    if request.method == 'POST':
        form = AuthenticationForm(data = request.POST)
        if form.is_valid():
            username = request.POST['username']
            password = request.POST['password']
            user = django_authenticate(username=username, password=password)
            if user is not None and user.is_active:
                django_login(request,user)
                return redirect('MonProfile')
            if user==None:
                messages.error(request,"Le nom d'utilisateur ou le mot de passe n'est pas bon")
    else:

        form = AuthenticationForm()
    return render(request,'Utilisateurs/Connexion.html',{'form':form})```
#
    class Meta:
        model=Videos
        fields=('caption','Video')```
winged moss
#

hello ive got a doubt

candid ridge
#

does anyone know how to fix: 'sqlite3.OperationalError: table "AboutMe_aboutme" already exists'

lavish pine
#

anyone know how to use fontawesome with html/css files only?

oblique carbon
#

because the table has already been made it cant be made again

candid ridge
#

i'm looking for a group of people who are new at django too and are welcome to learn together.

#

anyone?

tribal pewter
lavish pine
#

bruh

#

and how

tribal pewter
#

do you know any html?

hollow relic
#

hello, not really a python question but a javascript one. I wanted to make a chrome extension that filled some forms automatically. Could I go about installing selenium in the extension resources, or are there other ways to do it?

wicked elbow
# void summit as far as I see, django is not yet ready for async python 😐

It actually has little to do with Django. Anything non db related runs fine with async. But async db calls don't really do that much for you. Dbs have queue lines. That's just how they work. Even if Django was perfect with async it wouldn't actually do that much because a db isn't handling the async calls as async anyways

void summit
#

yeah but db calls are io so sure it will help

toxic flame
#

Just have a seperate url for response and install ajax on the site :3

#

ajax is really laggy though for some low end pc because it's sending alot of requests per min

#

there is also djangosocketio

#

i only heard of it but nevee used it

#

Had a look on its doc a few weeks ago

wicked elbow
#

You'd get more out of Django async if you used Django as an api rather then using it for views. Don't really need async from what I can tell unless your using non help requests anyways

wicked elbow
#

yea, databases arent async. thats why you have to wrap db calls in database_sync_to_async wrapper.

#

they run in queue. not simultaneously

native tide
#

hey, having a little issue with my background....

#

this is what the background should look like

#

but once I added another part for text, which was too big to fit in the screen so it had to become scrollable, this happened

#

I'm using this css .cover-bg { background-size: 100%, 100%; background-position: center, right top; background-repeat: no-repeat, no-repeat; background-color: rgba(44, 48, 56, 1); }

<body class="cover-bg" style="background-image: linear-gradient(to top, rgba(44, 48, 56, 1) 20%, rgba(44, 48, 56, 0)), url('https://images.igdb.com/igdb/image/upload/t_screenshot_huge/sc8ecz.jpg');">```
#

how can I make it be like in the first ss again?

fringe wyvern
#

Can someone send me an up-to-date web development course please?

rustic pebble
#

Hi, I need a second opinion in this:

I have the following schema:

type Subscription{
  "Get all the posts from all following users of the user in context, if `UserID` is provided then only the posts from that specific user are passed, Range should be in this format: `0-10` `10-20` `20-30`"
  getPosts(Range: String!, UserID: String): Post!
}

type Post{
  ID: String!
  Author: User
  Title: String!
  Published: String!
  Visibility: String!
  Disabled: Boolean!
  Content: Content!
  Reactions: [Reaction!]
  Comments: [Comment!]
}

type Comment{
  ID: String!
  Author: User
  Content: Content!
  Disabled: Boolean!
  Comments: [Comment!]
  Reactions: [Reaction!]
}

So what happens here is that the client can subscribe to the getPosts event and basically retrieve the posts as they are loaded so there is no big server side buffer to hold more than 1 post at a time.

A post has a field called Comments which returns a list of Comment, comment has many fields and SubComments which are a list of Comment.

Should I retrieve all the comments and subcomments with each post or should I make another subscription for comments to be sent for each post when needed.
The latter is more work obviously so I am looking for a second opinion in this

proper hinge
#

You need to have some sort of limit on comments retrieved. For really large threads, it wouldn't be a good idea to retrieve all comments at once. You could limit it to a few sent with the initial thread request and then request more comments separately later in chunks.

rustic pebble
#

Yea the limit is 10 comments maximum

#

That's preset

proper hinge
#

In total or per level?

rustic pebble
#

I am not using Python, I am using GoLang to resolve the subscription, the data is gathered through a gRPC stream from the posts microservice

rustic pebble
proper hinge
#

If it's only 10 then I think it's okay to get them together with the post, as long as you're not returning 10 for each level of nesting cause that could quickly add up. You wouldn't want to have threads on their own without comments would you?

rustic pebble
#

When you say threads you mean nested comments?

#

100 comments doesn't seem that bad of a number, its a fairly fast query to the db

proper hinge
#

I meant posts, sorry.

rustic pebble
#

Ah okay

proper hinge
#

Well 100 is fine but if you don't have a hard limit then it could get infinitely large, or until the content length limit is reached or something.

rustic pebble
#

Well again, the first 10 posts will be retrieved

#

You are able to range

#

so there is a 0-10 first 10 posts, 10-20 20-30 XX-XX

proper hinge
#

So, basically pagination?

rustic pebble
#

Yes

#

But the thing is that they aren't first buffered and then sent together

#

Each post gets sent as soon as it gets found

#

So the memory footprint of a process like that is equal to loading one post from the db

proper hinge
#

But what about comments, are they paginated? I was concerned with infinite nesting of comments, not with many posts being returned.

rustic pebble
#

Oh there aren't infinitely nested comments

#

There are only 2 levels of comments

proper hinge
#

Ah okay

rustic pebble
#

The primary comment which sits under the post

#

And the comment of the primary comment

#

I am just trying to think rationally what would be best for scaling

#

What I can do is for each post that is found fire a new process instead of waiting for it to complete

#

So that as soon as it a post gets found it iterates to the next while still processing the previous one

#

The problem with that is that if a post has no comments there will be no loop and no structuring so it will finish faster and they get sent to the client directly so the order will be messed up

#

Because if a newer post takes more time to process than an older post the older post will get sent first

proper hinge
#

Yeah I see what you mean

rustic pebble
#

I can implement a wait group but that would basically buffer the posts waiting in the memory which I dont want

proper hinge
#

And you don't want the client to have to fix the order

rustic pebble
#

Because that will also make the client buffer the posts

#

And it will look bad UX wise

#

Imagine having posts randomly appearing in ur feed

#

in random places

proper hinge
#

Well you have to display the post anyway so just display it right away and if you get an earlier post find the right spot and insert it. But you're right, it is worse ux. No buffering needed though

rustic pebble
#

I will figure it out at last, thanks for discussing this with me

#

I haven't been able to wrap my head around it for a bit

proper hinge
#

I think for comments it's okay to send them with the post since you'll be requesting them anyway. Though there isn't much flexibility if the client doesnt want to show them all at once. Like, it probably won't show all 100 if it gets that many, but it will be forced to have them and therefore store them locally somewhere.

rustic pebble
proper hinge
#

I mean it may want some and not all

rustic pebble
#

oh you are right

#

I should make the comment subscription anyways then

#

I didnt think of that

proper hinge
#

And later request to load the rest if the user clicks show more

rustic pebble
#

Shit thanks haha

proper hinge
#

Like how Reddit works

rustic pebble
#

i forgot that could be a case

rustic pebble
proper hinge
#

Like I said at the start it may be fine to send a very small amount and have a means to request more in chunks but yeah you could make it fully subscribable

rustic pebble
#

Thanks a lot

proper hinge
#

You're welcome

scarlet patio
#

Can someone please help me? project in flask```point_fields = {
'id': fields.Integer,
'trace': fields.Integer,
'latitude': fields.Float,
'longitude': fields.Float
}

@app.route('/', methods=['POST'])
@marshal_with(point_fields)
def Add():
point=list()
req_data=request.get_json()
count = len(req_data)
for i in range (count):
point.append(PointModel(id=i+1, trace=1, latitude=req_data[i]["latitude"], longitude=req_data[i]["longitude"]))
return point[0]how to make fields so I can return the whole point list like that:[{...],{...}, ... ,{...}]```

rustic pebble
#

@scarlet patio you are returning only the first element of the list, you need to change return point[0] to return point

scarlet patio
#

the point is, It wont work this way as im returning marshalled version of point. only one point

#

i probably should make another dic that would act as list of point_fields

#

not sure how it should look

rustic pebble
#

Why are you returning them marshalled?

scarlet patio
#

need an output to be in json as follow: [ {...}, {...}, ...., {...}]

#

like a list of objects

rustic pebble
#

Yea if you just do: return {"data": point}

#

it will return it in that format

#

Or just point in that matter

#

They get marshalled internally

#

Another thing you can do is: return json.dumps(point) this will render the list as a json object, then once you receive it you can parse it as json in the frontend

#

But returning a list is a valid json object

scarlet patio
#

tried return {"data": point}, but the output is only one empty point_fields

rustic pebble
#

Remove the@marshal_with(point_fields)

#

Let me just fix it up for u

#

give me a second

#
@app.route('/', methods=['POST'])
def Add():
    point=list()
    req_data=request.get_json()
    count = len(req_data)
    for i in range (count):
        pointObject = PointModel(id=i+1, trace=1, latitude=req_data[i]["latitude"], longitude=req_data[i]["longitude"])
        point.append({"id": pointObject.id, "trace": pointObject.trace, "latitude": pointObject.latitude, "longitude": pointObject.longitude})
    return {"data": point}
#

Try this ^

#

@scarlet patio

scarlet patio
#

gives an error :/

rustic pebble
#

oh mb

#

Try now @scarlet patio

scarlet patio
#

yes, works 🙂 thank you so much

rustic pebble
#

np

native tide
#

what is below the below the navbar called?

quick cargo
#

The main body?

#

Doesn't really have a direct nam3

native tide
#

below the navbar

#

does it have a name?

past cipher
#

I have a route with @ in the url. If I visit the route normal, then it works. However, when I send a redirect to that route, it replaces @ with %40. How can I resolve this ?

wicked elbow
#

dumb question?

<div id="container" onClick={()=>doSomething()}>
  <div id="child" onClick={()=>doSomethingElse()}></div>
</div>
``` when you click on child, does container get called?
#

in case anyone wondered, the answer is to also do event.stopPropagation(); in the callback

opaque rivet
wicked elbow
toxic flame
#

Me either, thanks for the information

plain carbon
#

Hello, what is the ideal way of doing a like/unlike post system? at the moment I have it set up to go to 0.0.0.0/like/postid but is it better to use forms instead?

#

with Flask*

nimble epoch
#

you want not to show the id?

#

or you mean you use forms instead of a simple button?

plain carbon
#

For example

nimble epoch
#

i dont use flask

#

im just giving my idea about like and dislike system

toxic flame
#

I believe he wants to have a live feature where he can send likes and stuff.

plain carbon
#

Here, Miguel uses an empty form to post to the server to follow/unfollow users, whereas the way I'm liking/unliking posts is by going to a URL, (0.0.0.0:5000/like/postid

#

I'm just wondering if there are any benefits over going with Miguel's way of doing this type of thing

toxic flame
#

The way on doing it is onclick post the data as a parameter, and have the server take it in as a parameter

toxic flame
nimble epoch
#

isnt it better with buttons?

toxic flame
#

You have buttons, but how will you handle the request?

#

What will happen when you click the button?

nimble epoch
#

i mean a link tag

toxic flame
#

You either: redirect to a certain link then return

Or

Post the data to the server

nimble epoch
#

using a tag i mean

opaque rivet
plain carbon
#

Okay thank you people 🙂

plain carbon
opaque rivet
past cipher
warm cape
#

Hi. Can someone recommend a good video tutorial of Django?

opaque rivet
royal tendon
#

Hi all — anybody able to advise on how best to implement maps?

I have a flask web app for customer management and bookings, and I would like to plot customer addresses on a map. It will be all address that have a booking on a given date.

I’ve only just started researching how to get it done, so any guidance from experience would be appreciated. Thanks

opaque rivet
past cipher
# opaque rivet use `.unescape()` to stop revert escaped HTML.

do you mean like:
return redirect(url_for('donate.donate', username=user.username)).unescape()

because that doesn't seem to work, and I don't see what it does. Is it not possible to unescape the whole route? because I have several redirects to this page

opaque rivet
past cipher
#

Thanks anyway, I will look into it more

royal tendon
opaque rivet
#

or check pypi for some flask-related map packages

#

there's also Leaflet, if you don't want google maps.

fair agate
#

Pertaining to Django:

I'm trying to work out why I'm hitting an error, I recall it was working yesterday and I don't think anything actually changed -

error:

Using the URLconf defined in barHubCore.urls, Django tried these URL patterns, in this order:

admin/
[name='homepage']
single/<slug:slug> [name='single']
^media/(?P<path>.*)$
The current path, single/first-post/, didn't match any of these.

slug = 'first-post'

code from views:

def single(request, slug):
    data = Post.objects.get(slug=slug)
    return render(request, "single.html", {"post":data})

also code from urls:

    path('single/<slug:slug>', views.single, name="single"),   
marsh canyon
#

it should be path('single/<slug:str>'

#

you are taking slug as a string

#

@fair agate

fair agate
#

still the same error returned

#
Using the URLconf defined in barHubCore.urls, Django tried these URL patterns, in this order:

admin/
[name='homepage']
single/<slug:str> [name='single']
^media/(?P<path>.*)$
The current path, single/second-post/, didn't match any of these.
#

all of the other endpoints/functions seem working, and I recall it worked yesterday and I don't think I changed anything so it is bizarre

marsh canyon
#

its actually <str:slug>

#

mb

#

@fair agate

fair agate
#

I tried that too and it didn't work either 😦

#
Using the URLconf defined in barHubCore.urls, Django tried these URL patterns, in this order:

admin/
[name='homepage']
single/<str:slug> [name='single']
^media/(?P<path>.*)$
The current path, single/second-post/, didn't match any of these.
sour cairn
#

How can i make a custom domain when i have my own domain name. To be more specific -
i have one domain say - abc.com then how can i make something like - test.abc.com? Asking this for a friend, thank you for your answer

toxic flame
#

I use cloudflare to manage my domains and its pretty simple to do with cloudflare

fair agate
#

I resolved it by adding a / following the slug:slug

#

seems working now

haughty turtle
#

Your looking to serve subdomains

sour cairn
#

Cheers bud

opaque rivet
native tide
#

how to make an image full screen?

austere acorn
#

guyss

#

so i am trying to do something with js

#

but i am facing issue

#

so i am trying to detect a resize event for an element, after it's resize i want to give it a margin depending on its size

#

but when i give it the margin, the resize event is called again, and the final value will be messed up

opaque rivet
weary bough
native tide
#

it works

#

thanks

gentle stag
#

In Brython, I'm have a syntax error at the end of this line, but I don't seem to have the same issue in vanilla Python, and syntax checking sites don't seem to see one either. Any ideas what's going wrong?
note = browser.html.DIV(browser.html.SPAN(text,id=textId) for text,textId in {"Note Text 1":"noteText",":"Letter 1":"letter1","Letter 2":"letter2","Letter 3":"letter3","Note Text 2":"noteText"}.items(),id="noteDiv")

toxic flame
weary bough
#

packages can work, but is there any problem with my code?

toxic flame
#

Not sure didn't check

#

The library checks if the smtp of the provided email address is valid

weary bough
#

you cannot guarantee that an email is correct until you send the mail or Helo

toxic flame
#

ok then how will the email that send know it works? That's right, by checking if the smtp ip is real for that address

weary bough
#

the email is a text file. Once the other end receives it, it sends back a response telling which email addresses it could find and which not. The other end parses the text file

#

the web server implements HTTP, the mail server IMAP, POP3, SMTP

lucid jetty
#

hello

#

is anyone online ?

#

i just need to ask one thing

#

is it dangerous to install Django and Flask on the same machine ?

real hare
#

No, of course not

frozen wren
west bolt
#

Hi there. I'm finding that CherryPy seems to be reading static files as some encoding other than UTF8 because unicode chars in files are showing in the browser as garbled nonsense. Does anyone know if this can be fixed with a config setting or something? Thanks.

dawn dome
#

How do you render a template INSIDE of another template in Flask?

Passing a rendered template as a value into another doesn't seem to work

Like, I'm looking for:

render_template("main.html")

And from main.html,

<body>
  {{ navigator }}
  {{ content_from_specific_page }}
</body>
quick cargo
#

you probably want jinja's macros

#

or using template inheritance with extends

dawn dome
#

that second one might work. lemme try it

dawn dome
#

Thanks!!

quick cargo
swift igloo
#

Hi, im not sure if this is the right place to ask but here i go anyway. I want to control some relays with my Raspi over a web-interface. The problem is that i dont know what i am even looking for to find tutorials online so if guys have any idea Ty

west bolt
oblique carbon
#

What do you guys recommend learning first Flask or Django

fair kettle
#

is there someone who has used allauth python for google authentication in their django app?

green sequoia
#

Django is becoming more popular i've noticed

#

I also think it's a more contemporary in its design philosophy (sort of similar to popular js stacks- mern, mean etc)

#

in other news- does anyone know a good hosting service for django sites (similar to netlify or docusarus but for django)

#

would very much apprecaite it

#

(just tried digitalocean but they immediately locked my acccount (????))

wicked elbow
green sequoia
#

awesome, i'll look into costs w/ aws- ty

wicked elbow
green sequoia
#

oh- rereading what u wrote it doesnt sound like complete jargon. hopefully it'll make more sense to me as i proceed through aws

#

so as this point i go- platform: linux, blueprint.... django (?)

wicked elbow
#

first month is free if youve never used it and 3.50/month after

green sequoia
#

ight dope, $40ish a year w/ domain like 45

#

affordable enuf 😎

wicked elbow
#

can get a domain normally for 8-20$ a year. unless your looking for something super specific. but until you get a domain, just use the static ip your given

#

and you can run the dev server in the instance as well just an fyi, just have to open port 8000 in the firewall, and start the dev server on the local ip address

green sequoia
#

yeah i searched through for the domain over go daddy earlier, it's for a family website & lucky it's not a popular name

#

🤔

#

appreciate the support ! going to keep clikcing thro the aws

wicked elbow
#

personally i think its the best option, just not completely free

green sequoia
#

also good excuse to start becoming familiar with AWS 😎

wicked elbow
green sequoia
#

i've already built everything locally on my laptop

#

how would I push it onto the instance

wicked elbow
#

you also dont need to use their database. from a linux instance, just install it yourself

#

or for a small website just use sqlite3

green sequoia
#

🤔 could i ftp transfer files

#

or perhaps... ssh

#

oh 🤔

wicked elbow
green sequoia
#

OHHH

wicked elbow
#

and if use a dev server, you have to use screen to keep the dev server running

green sequoia
#

🤔

#

probably could throw it up to a git repo & pull it ?

#

wow i feel my braincells rubbing together

#

tyvm 😎

wicked elbow
green sequoia
#

i;ve just never used (or head of) a s2 container

wicked elbow
green sequoia
#

to google 😎

wicked elbow
#

although its way way out of date now

#

and im running django/rest framework/react from inside it

green sequoia
#

😎 sort of following, can kind of do same thing w/ just ubuntu os (instead of django, little difference so far)

#

go it running off the instance ip- 4:30 am, think ima come back to it tomorro

wicked elbow
#

who builds their nav bars

<nav>
  <ul>
    <li>Nav 1</li>
    <li>Nav 2</li>
  </ul>
</nav>
VS
<div>
  <div>Nav 1</div>
  <div>Nav 2</div>
</div>
``` and why should you use the top version?
proper hinge
#

The former uses semantic elements, namely the nav. Not sure if using an unordered list really matters.

#

Semantic elements have better readability for both us and machines

#

So it could enable a browser to provide better accessibility features

#

For example, the reader view on Firefox

#

Using an unordered list probably helps that too now that I think about it

silver pollen
#

My Flask app is using an external API with one user only, and today I'm using Lock() on a bool variable "in_use" to serialize access to the API if many requests try to use it at once.. This works for multiple thread but not multiple processes.. Any idea how I could share that variable in multiple processes?

acoustic narwhal
#

Anyone has worked on django here?

silver pollen
#

what do you mean why?

vestal hound
#

each process has its own memory space

silver pollen
#

because only one request at a time can use the external API user

vestal hound
#

locks are for synchronising access across threads

vestal hound
#

that’s what I’m asking

#

I don’t understand the motivations behind that design

silver pollen
#

because we only paid for one API user

silver pollen
#

it's a CAD integration to an ERP system

vestal hound
#

wait

#

what lock are you using

silver pollen
#

i actually don't really know if it's a problem yet. maybe i can run just one process

vestal hound
#

I’m assuming

#

when you say multiple processes

#

each is running an instance of your server?

#

i.e. the processes are not spawned by Python

silver pollen
#

running the app on mod_wsgi in apache on a windows server

vestal hound
#

okay

#

well

#

then each process has its own lock

silver pollen
#

but i read somewhere now that maybe mod_wsgi on windows doesn't support multiple processes so it could work anyway. feels bad though to not be able to move it to linux or something just because of code design

vestal hound
#

to synchronise access

#

there’s defo a better way

#

but I haven’t really had to deal with this so I don’t know what it is offhand

silver pollen
#

hmm, true i kind of forgot about sqlite. i was thinking i could use my database but sqlite is probably waay faster. could use it to cache some requests too i guess

#

i'll look into it, thanks

native tide
#

How do i include performance data on the api in terms of request/ second

#

On flask

cloud path
#

guys how can I put the "cognome" besides "nome"? there are no <br> between the two ones

inland copper
# cloud path

above the nome do a <div class="row"> <nome> <cognome> </div>

#

if it doesn't work u shld try a container

#

if it does work let me know lemon_happy

cloud path
#

thanks imma try!

inland copper
#

okay let me know if it works

opaque rivet
#

@cloud path use flexbox. You'll be able to get a grid-like layout with rows/columns in pure css.

inland copper
#

i just gave you a quick and ready to use solution

#

using flex will make it look better

#

but it is a lot of code

cloud path
#

oh ok i'll try to learn flexbox

#

the first ones solutions don't work

inland copper
#

are u using {{ form.as_p }}

#

then it won't

cloud path
#

yeah

inland copper
#

oh sorry

#

then it won't

opaque rivet
#

@cloud path
https://css-tricks.com/snippets/css/a-guide-to-flexbox/#background

It's really simple, if you use bootstrap you can also leverage flexbox. It's a must!

Our comprehensive guide to CSS flexbox layout. This complete guide explains everything about flexbox, focusing on all the different possible properties for the parent element (the flex container) and the child elements (the flex items). It also includes history, demos, patterns, and a browser support chart.

cloud path
wicked elbow
#

is there to much going on now?

pulsar hull
#

could someone help me with flexbox?

inland copper
wicked elbow
inland copper
#

so u like frontend dev

#

HE

wicked elbow
green sequoia
#

hey fellas some pretty basic questions w/ django

#

deployed my project via aws recently

#

but having a hard time routing to the assets (images, css, etc)

#

what is the ideal way to organise that within django ?

#

(it all runs fine when I deploy it locally)

wicked elbow
green sequoia
#

yeah

wicked elbow
#

django is put into production mode when you put debug=false and no longer serves static, youll have to install apache or nginx/gunicorn to serve your static

green sequoia
#

😎

wicked elbow
#

a lot of people use apache to run django, and use nginx to serve static

#

and yes, you run both servers at the same time

green sequoia
#

ty for guidance

#

luckily there's heaps of yt videos on this 👍

wicked elbow
native tide
#

do you guys have a fix for this problem when the image is not loading?

#

profile.html

#

maybe I missed typed something?

manic frost
#

@native tide Can you type http://(your hostname)/media/profile_pics/solo_leveling.png in the browser?

#

and is DEBUG on?

native tide
native tide
#

😆 I am new here

manic frost
native tide
manic frost
#

no

#

Can you show the URL you're using when looking at your website?

native tide
cosmic harbor
#

right click on the image, copy image address, and paste here....your site is working fine but your avatar image is missing, probably the image does not exists or you point to the wrong path

green sequoia
#

is this the corey schafer tutorial ? 😏

#

went through it compulsively the other week- it's great, i think the problem is as described, maybe not directing the src to the image

green sequoia
#

also, i'd reccomend this resource for anyone trying to deploy django using aws: https://www.youtube.com/watch?v=ZpR1W-NWnp4

Learn how to deploy a Django website on Nginx with uWSGI as a web server gate interface. In this complete tutorial, we will use Ubuntu 20.04 and the latest version of Django and uWSGI. Nginx will communicate requests to the WSGI via a UNIX socket. Additionally, we will create a system service to launch the website at boot (and keep the service r...

▶ Play video
west bolt
#

Hi there. I'm finding that CherryPy seems to be reading static files from filesystem as some encoding other than UTF8 because unicode chars in HTML/JS files are showing in the browser as garbled nonsense. Does anyone know if this can be fixed with a config setting or something? Thanks.

hallow ferry
#

Hi All,

#

I have a static website (really old) that displays every employees names/title/extension, (up to 100). Is there a way to modernize it?

#

Or does anyone know a good way to update it?

strong rapids
#

I have a question - can discord bot create a server? Thank you for your reply.

neat phoenix
strong rapids
#

ok!

#

Thank you

strong rapids
neat phoenix
#

No

strong rapids
#

oh no

neat phoenix
#

That's just common sense. Think about how many millions of bogus servers would be created every day if you could automate it.

strong rapids
#

That's true

buoyant shuttle
#

hey guys is there like a shorter syntax to a child component props equal to the current states

#

like a component inside another component, in react,

uncut spade
#

HI guys, I m trying to do a ManyToMany Model field which contains a list of added users, but I want it to be empty on default. The problem is : it gets all the Users per default in my model. any suggestions ?

#

users = models.ManyToManyField(User,blank=True)

cloud path
#

hey guys, my flask web app was working fine on a server of a friend of mine, then he moved the database to another server and i changed the datas but it gives now this error, and isn't working

#

Warning: (3719, "'utf8' is currently an alias for the character set UTF8MB3, but will be an alias for UTF8MB4 in a future release. Please consider using UTF8MB4 in order to be unambiguous.")
result = self._query(query)

nimble epoch
#

this is the way to do what you want to

uncut spade
#

doesn't work :/

#

I want the field users to be blank

nimble epoch
#

i dont get what page you are on now but if you registering new...(thing) hen thats true

#

in here it says who you wanna create it for you can leave it or choose someone

#

if it didnt work add it like users = models.ManyToManyField(User, blank=True, default=None)

#

and now you can just leave it

nimble epoch
crimson peak
#

Hey, I am using flask

#

I wanted to know the best way to accept payments on my site....

#

pls help

#

PLS HELPPPP

quiet ridge
opaque rivet
formal axle
#

anyone know why when i try to dp FlASK_BLOG=hello.py in the terminal it shows an error

#

even though i did exactly what the docs say

#

its so i can run the application but its saying| Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.

  • Debug mode: off
    Usage: flask run [OPTIONS]
crimson peak
#

Hey, I am using flask
I wanted to know the best way to accept payments on my site....
pls help

opaque rivet
# uncut spade doesn't work :/

it is empty by default. the admin form just allows you to select many users to apply to your row within the database. If you do not assign any users to that row, it is empty.

#

you can test this by using the django interactive shell python manage.py shell and checking the users field of a row.

uncut spade
#

@nicky si how could I do an empty list in which i can add many users ?

opaque rivet
#

you already have that... as I have explained

opaque rivet
crimson peak
opaque rivet
#

payment processor = the company which processes your request, PayPal, Stripe, etc.
You integrate their payment processing by following their documentation, or the other option stated.

crimson peak
native tide
opaque rivet
#

it shouldn't be too hard, but I guess you could look for a stripe wrapper on pypi for flask which could simplify things

#

anyways, if anyone atm is learning React, I just wanted to say you should 100% learn typescript to go with it, it makes things so much more reliable.

opaque rivet
buoyant shuttle
#

if i have lots of javascript running in the background the browser would become slow?

opaque rivet
#

generally, yep. if you have thread-blocking functions in your JS script, async could help make things "faster"

buoyant shuttle
#

ah

#

so ill have to use async

#

cause i belive one of my functions, are thread blocking. looping over an array of objects

#

700 objects. i see

toxic raptor
#

has anyone deployed a flask web application on heroku?
stuck in an error here

nimble epoch
#

maybe i can help

native tide
#

With this py file = open("templates/index_graph.html","w") file_to_add = open("templates/g_test.html", "r") file.write(file_to_add.read()) file.close() it rewrites content of index_graph.html with g_test.html. How to add it not rewrite whole file?

opaque rivet
#

a = append

#

w = write (writes over any existing content)

native tide
#

oh thanks!

#

i need to add values to html trought render_template, and add that html to another html with that values. how?

opaque rivet
#

@native tide jinja2 template inheritance

pulsar pulsar
#

Anyone tried working on a live streaming mobile application? Can you share how you designed your infrastructure

swift wren
#

hey guys, in flask, is using blueprint the same as going to django and creating a app?

gaunt tulip
#

It's not identical, but a lot of the patterns and purpose are the same.

young ferry
#

Hi everyone
just getting started with django, reading the documentation, installing it
as far as I understood installation involves the process of just creating template files with default settings etc.
I wonder if it is possible to create a django project from zero without installing it from terminal

#

i thought it would help to better understand the structure of the project

compact flicker
#

@young ferry
Technically, it is...
but you don't wanna do that...

serene prawn
#

What frameworks you guys can recommend for frontend? 🤔

young ferry
#

Emm.... Django? py_guido

serene prawn
#

React/Vue/Angular

compact flicker
# serene prawn React/Vue/Angular

React(btw out of these only Angular is a framework rest are libs)
also, It depends.

I was asking the same question once...
at that time a friend of mine who uses Vue recommend React because of its community support and available resources...

You can't go wrong with any one of these...

serene prawn
#

Isn't vue considered a framework though? 🤔

quick cargo
#

Yes in reality

compact flicker
#

That's one discussion of its own...
but i think so...

quick cargo
#

They're not really libs as they're considerably more opinionated in how they're setup etc but vue is more flexible in that regard

swift wren
#

i dont get why people use statebased frontends

quick cargo
#

Overall I'd say go with Vue just nicer to work with

swift wren
#

i mean its fine if you have static webpages, and its also good if you know json as your very first langauge, but if you have a python background, learning js is so hard

serene prawn
#

I don't really like vuex compared to angular services

swift wren
#

bro react and redux over any other framework

serene prawn
swift wren
#

yes it is bruh what you on about, do you honestly think you can teach redux to someone who has a python background

quick cargo
#

Js isnt really hard, react babies you so nuch its pretty easy todo stuff

swift wren
#

in the same time its takes to teach somone who knows js

serene prawn
#

Redux isn't hard but it's tedious to write all these actions and reducers compared to angular

quick cargo
#

pithink your point doesn't really make any sense

serene prawn
#

or say mobx which i don't really like

swift wren
#

redux is such a different approach to frontend that ive ever seen, it was such a curve ball when i first started to learn it

quick cargo
#

If you want a real doffrent approach just use Wasm for everything 🤣

swift wren
#

damn that was funny bro

wicked elbow
#

redux is easy, put simply its a global state manager. pull this data store the data in a specific spot. now every item that subscribes to that data has access to it.

quick cargo
#

Tbf I've written entire frontends in wasm, suprising amount of fun and nice to use a language other than JS at times 🤣

serene prawn
#

I just don't really see a point in using mobx when observables in angular are so much easier

swift wren
#

i would say that a frontend framework is somthing you need to learn not somthing you want to learn if you realise how easy the rest are, but bing honest, after all the dogshit boilerplate, redux and react are pretty fun to code for, but that learning curve was jsut way too much for one attempt

serene prawn
#

I had problems with react since it give you too much freedom and needs 3rd party libraries

#

So it's hard to choose 😉

quick cargo
#

ichi_shrug alot of people prefer frontend to backend especially in large systems