#web-development
2 messages ยท Page 204 of 1
dispay: flex;
justify-content: center;
aligh-items: center;
universal centerer
does someone know about postgres here?
I know extremely limited postgres..., but their discord is pretty cool/active imo.
css-tricks has a great flowchart for flexbox, and other layout stuff like grid etc.
https://css-tricks.com/snippets/css/a-guide-to-flexbox/
(aside from the postgres discord, the #databases channel here is also a good source of info. Quite a few ppl use it, but the specific channels can be a bit slow compared to general)
hey everyone, hope you all are fine I am having some trouble with Elastic Search and Django, so when i make some change in data stored in models the respective change is not reflected in the elastic search query until I manually update the concerned model by self assinging any of the field of that model through python manage.py shell, is there any better way to reflect those chenges?
Hey
In my Django project i have a admin page where i can manage all users:
How can i display a formated string, and not UserObject(x) in the "title"?
go to respective model and add an str method for the same
in your case u have to overwrite the Users model's str method
Can someone help me with this error? I've checked my python39/scripts file, it successfully installed django-admin.exe there, but why I can't use it thru cmd?
add the path as mentioned in error
Can you elaborate more?
you can see a path mentioned in the warning
C:\Users......something
add that entire directory to ur path
i think it is done through enviroment variables in windows
but if u want to avoid adding path maybe u can try using a virtual environment
like this?
noo
just check
on google
how to add a directory to path
on windows
u have add that complete directory starting from C:Users.......Scripts to ur path
Yes, I've searched on Stack this is what I found https://stackoverflow.com/questions/9546324/adding-a-directory-to-the-path-environment-variable-in-windows, right?
yes this thing
but when I tried to run the command window they suggest, nothing happens
hmm but they said run the command in cmd
Ohh it works rn, but only in current active session. Then I read that you can make it permanent using setx, but a user gave warning about using setx like I show from the pic I gave, what does it mean?
dont use this
just try to set the path through the gui or with admin privleges and u will be good to go
if u are not comfortable with setting paths
what gui?
u should try using virtual environmant
i dont rememebr just search environment variable in your control panel
This? by adding the python scripts path to this?
yessss
thiss
there are two of these
add the one in which u see ur python path added
omg it works bro, jsdfjsadfbasjdfa
TforThankyousomuchhhhh
no problem
@app.route("/addviolation", methods=['post'])
def addviolation():
id = request.values.get('id')
data = request.get_json()
print(data)
y = json.loads(str(id))
reason = request.values.get('reason')
x = json.loads(str(reason))
print(y)
print(x)
return str(200)```
its supposed to receive JSON from a Roblox game, but it gives me this error.
`json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)`
print(str(id))
before data
maybe its empty
or maybe reason variable is empty
print both before json.loads
its None
both of them?
yeah
so it will through this
i guess if its None it should through some error related to None type
i might be ""
i mean what u sent to loads?
what is the value of str(id)
and what is the value of str(reason)
when u send it
thats remnant of a previous experiment
so if u send str(none) or "" to json.loads
u will keep getting that error
just make sure before u pass value to json.loads - it has something other than none and empty string
yea
so u'll keep getting that error
just put that in an if else statement
to use json.loads only when those value are not none
hi how can i send a file to my flask webserver using requests ?
and than the webserver will download it
This thing?
almost
i dont want to do it from gui
like in html
i need to write an app that sends the files to a webserver
That's what that is
Yeah flask supports that
Could you show me the full path?
C:\Users\oriko\PycharmProjects\python-p\raspi-zero\img.png
!rule 9
Also ES6 isn't current, it's very old
I mean what you wrote for src.
Can you show me the code snippet?
look:
code:
@app.route('/get/<path>')
def get(path=None):
if path == None:
return "{'msg':'please enter a path'}"
else:
for file in [val for sublist in [[os.path.join(i[0], j) for j in i[2]] for i in os.walk('./')] for val in sublist]:
if path == file[2:]:
if str(path).endswith((".png", ".jpg", ".jpeg", ".webp", "svg", ".ico", ".apng", ".avif")):
path = os.path.abspath(path)
return render_template('img.html', img=path)
else:
return render_template('content.html', text=open(path, "r+").read())
return "{'msg':'please enter a valid path'}"
html:
<!DOCTYPE html>
<html>
<head>
<title>{{ img }}</title>
</head>
<body>
<img src="{{ img }}" alt="img">
</body>
</html>
Have you ever tried like this?
wdym ?
yes
Show me screenshot
thats the worst screenshot i have ever seen
tuff
does someone know about postgres here? can someone help me?
post your query, if someone knows, they'll help
your question must be in databases channel though i guess
i have a jsonb column name document in Postgres however
when i query select * from database it returns like this one
id : 1, document : {"data": 1}
how to return like t his one
id: 1, "data": 1
removing the document:{}
Thanks
please help
i am making a personal website and it has some issues
on my pc it looks like this
but on my ipad it looks like this
how can i fix this?
starting with reset technique should be good
:incoming_envelope: :ok_hand: applied mute to @inland oak until <t:1638858808:f> (9 minutes and 58 seconds) (reason: newlines rule: sent 132 newlines in 10s).
!unmute 370435997974134785
:incoming_envelope: :ok_hand: pardoned infraction mute for @inland oak.
!paste
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.pythondiscord.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.
use our pasting service for long blocks of text
well, I'll drop copy here then
this is one out of two ways to reset CSS between different browsers
@hushed vortex apply it somewhere globally in the root of your project
for example in vue.js I have it applied...
App.vue
<template>
<router-view />
</template>
<style lang="scss">
@import "@/assets/style/_reset";
</style>
right at the almost most global scope, in the beginning of my style code
if u aren't using vue.js...
just use css importing and have it in header
@hushed vortex importing looks like this in regular HTML5 code
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="stylesheet" href="css/reset.css">
</head>
<body>
</body>
</html>
provided example above for regular html
plus use those meta tags too
anyone knows what pusher is ?
I need help about channels
the viewport one helps for better mobile compatibility too
@inland oak this is the file i use for the layout on all my pages
<!-- this file is for template inheritance-->
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<style>
body {background-color: #171717;}
</style>
<meta name="apple-mobile-web-app-capable" content="yes">
<div class="container">
{% block content %}{% endblock %}
</div>
</body>
</html>```
well, add the stuff to head of it
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="stylesheet" href="reset.css">
with adding the reset.css file with mentioned stuff to your project root
did you add to <head> ?
did u make sure that reset.css is imported correctly
<!-- this file is for template inheritance-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="stylesheet" href="css/reset.css">
</head>
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<style>
body {background-color: #171717;}
</style>
<meta name="apple-mobile-web-app-capable" content="yes">
<div class="container">
{% block content %}{% endblock %}
</div>
</body>
</html>```
did you create folder css and having put reset.css to it...
just verify in your browser, if the styles were applied
if not, fix it
use Chrome dev tools to check applued styles
and console to see if there was importing error
could you kindly link me the reset.css
@hushed vortex
I would highly recommend to read Head First CSS 2nd edition book
and CSS the missing manual 4th edition
ok
both django and flask currently use multi-threading
each request is processed in a new thread
Hey,
I need some help with django. I am very new to this and I just want to link the database to the form tag in html, so I can input the data and save in the model.
is there anyone who can spare 5 mins?
how much python should i know before learning flask?
hi all
I am defining the slack_events_adapter in main, so of course the decorators are not resolvable,
any advise anyone
I am a self tough programmer ๐ so be nice ๐
app = Flask(__name__)
# Create an event listener for "reaction_added" events and print the emoji name
@slack_events_adapter.on("reaction_added")
def reaction_added(event_data):
print("rection_added")
@slack_events_adapter.on("message")
def reaction_added(event_data):
print("message")
def main():
""" Main function
Returns:
None
"""
arguments = args()
my_logger = logger(arguments.debug)
my_logger.info('Starting slack_bot')
variables = get_vars(arguments, my_logger)
slack_events_adapter = SlackEventAdapter(variables[0], "/slack/events", app)
app.run(host=arguments.flask_host, port=arguments.flask_port, debug=arguments.flask_debug)
i basically am making a quiz type application using django the problem im facing is i made a next button
so 1 question paper contains 20 question
each question has a img file question
4 options a,b,c,d
n one answer (radio button)
(same as google forms but question in img format)
the problem is for the next question feature i implemented js , it's working fine but the question is how can i render/fetch my objects of db to js
the first object is loading from the html loop (rendering from the db) so how can i load more from db
how can i retrive post from db to js ?
how can i make a search code for this xpath
Why not define your event handlers in the def main(): block?
hey, graingert, i need some help in django database, can you help?
it will only take like 5 mins, im very new to django and stuff
Ask your question in the channel, don't ask to ask
actually i need someone to see my screen and guide, im a little unsure on how to ask the question
in short i am having trouble in linking my database to the form input in html
with selenium
cause I dont think I know how to do it ๐ฆ
Idk if this is the right place to ask since its not really web development but
Im trying to get into webscraping using beautifulSoup and requests. So I've gotten the htmlcode for a website and this is a small part of it:
<span class="p-3">3</span>
I try this:
soup = BeautifulSoup(html_text, "lxml")
price = soup.find_all("span", class_="p-3")
print(price)
However it returns None, anyone got a clue?
Select them then cut and paste them into the def main():
what does your flask code look like?
and why are you involving js here? it's a type="file" input element
it should just work without js
and you see request.files ?
Hey , I want to create a countdown timer and the number of minutes should come from a Django model object.Which model field fits for this purpose ?
im trying to use puppeteer to scrap the crypto data from coin market cap but i found that only the first few data can be scrapped. Does anyone know how to scrap more with puppeteer?
ok problem fix, the keyword is "lazy loading"
Hey guys! Is there any way to plot a normal distribution graph in Flask?
Everytime I plot one, a window pops up instead of returning it into the browser
matplotlib?
Matplotlib is not compatible with Flask I suppose
what are you using to plot then
It just plots a graph for me, but displays it in an alternative popped up window
Right now I am indeed using Matplotlib, but that's why the error occurs
yea. so save the figure as a picture format then serve it with flask
Ah, I see
So everytime I use different variable values, it will just generate new images for me?
yes,
jinja
<div class="content-body">
<!-- row -->
{% include 'pages/index.html' %}
</div>
i want to replace index.html with variable
like i will pass the {"page": "index.html"}
while rendering
<?php
$connection = mysqli_connect("local","username","password","api") or die("MySQL failed to connect ensure creds are correct... " . mysqli_error($connection));
$id = $_GET['id'];
$sql = "SELECT * FROM users WHERE id="; //here I want to parse the value of the GET HTTP Variable **id** ?id=1337 into the statement (I know if I don't escape it then I will end up with an SQL Injection vuln but that's what my end goal is not sure if mysqli_query() function will prevent that but if it is I will find an alternative way of parsing the query.
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$f = array();
while($row =mysqli_fetch_assoc($result))
{
$f[] = $row;
}
echo json_encode($f);
mysqli_close($connection);
?>
Thanks! ๐
id=the_users_value < goal
you probably want to use new PDO instead of mysqli
and also this is the python discord - not php
What's the difference? Haven't used new PDO
#web-development ๐ค doesn't say #flask-development
real easy to use placeholders and the whole server is python themed so yeah we tackle web here but in context of python
you can ask but don't always expect answers since it's likely that this server is more python devs than php devs
at end of day, php IS off topic for the server
Of course, I expect that but can't find any PHP Servers.
It's a python server so it's mostly python frameworks we chat about.
there's also the OT channels
Once again it's called webdevelopment which is a wide variety of web not saying it means its for PHP etc but I mean specifically mentioning it here because the channel name and secondly because its not to do with Python so entering it in a Python help will be just out of order.
but yes, look up doing sql with PDO and also look at how to use placeholders for safe sql
I don't want safe.
Here
everything in this server, except OT, is FIRST python themed, THEN broken down into other python-related topics
$sql = "SELECT * FROM users WHERE id="; //here I want to parse the value of the GET HTTP Variable **id** ?id=1337 into the statement (I know if I don't escape it then I will end up with an SQL Injection vuln but that's what my end goal is not sure if mysqli_query() function will prevent that but if it is I will find an alternative way of parsing the query.
okay so what do you want? just inject your variable in that sql statement and boom, you have a vuln
SQL Injection. It's a development for something I am doing but it's been a pain because I am also going to add this into a Rest API later on in the project.
literally just put $id in your string or concatenate it on .. either way, it creates a sql injection vuln
and you're doing a bad thing on purpose yes?
basically
/api.php?id=1
the sql is configured to use the where query to identify the id column value
if they parse 'OR 1=1 -- -' a true statement it'll drop the everything I need
What?
lol, don't get pissy homie
If its for a bad purpose i'd be attacking the application not adding intentional vulnerable code.
We're not usually in the business of helping people purposefully write BAD code
I am not, you're getting the wrong concept/
This guy. ๐คฆ๐ผโโ๏ธ
Is this a hidden camera show? LOL
Of course which is why I am asking you to simply help me parse the value of the Param into the query so it'll be
select * from users where id=the_users_input
url
website.com/api.php?id='OR 1=1 -- -' < true statement will drop DB
I already have mysqli_query() function in place which will prevent that by appending back slashes
no
PDO supports parameterized queries
$dbh = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare("SELECT username FROM users WHERE id=:user_id", array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':user_id' => $id))->fetchAll();
I am testing others how to test for SQL Injection in BBP's or when they're doing a web app pentest.
If you want UNSAFE code, I said just literally put $id in your SQL statement
That's why I need it to be unsafe
Will that work because I am trying to add a variable into a string?
I'm sorry. You're an instructor?
difference between what and what?
If you don't know the difference between a web app pentester and a web app developer then I suggest you don't help because you're getting confused here.
I am not teaching them to write PHP Code.
fuck if I know
You're very bad at explaining.
You have no idea how to ask for help, dude.
Congregating and all winging at me for asking a question?
** $sql = "SELECT * FROM users WHERE id="; //here I want to parse the value of the GET HTTP Variable id ?id=1337 into the statement (I know if I don't escape it then I will end up with an SQL Injection vuln but that's what my end goal is not sure if mysqli_query() function will prevent that but if it is I will find an alternative way of parsing the query. **
very simply question
Just read
put the variable in the string wtf
Then figure it out yourself if it's so simple.
yeah, super simple, good luck
I'm sure you're a real successful pentester
Correct
๐
Difference between zero-day hunters and Pentesters.
We don't usually have access to the backend ๐
I still don't think you know the actual definitions lol
We test stuff blindly
we're in web dev channel, you posted backend php, and asked how to make it unsafe
I mean if you think I am dumb at what I do with pentesting you can add me and we can hop in a private call and discuss some stuff?
sooooorrrry I don't know your life history haha
No
I asked you something completely different my intention is to make it insecure
but
If you read the code mysqli_query() is parsing the $sql statement variable which will block any SQLI
So by parsing the ID Param isn't making it vuln
<< >> <_<
At this point, it doesn't matter what you think you asked or didn't ask, or whatever, no one is going to want to help you with that attitude.
I mean he was giving me attitude first lol
nah, the whole conversation can be read
I'm reading the conversation and can perceive who was doing what for myself, but ok.
Sure different perceptions here.
Sure that's your perception, you keep that.
Mmmm, blocked cleared that up real quick. Have fun y'all.
Thanks
I asked a question ina web dev channel and I got get told that this isn't really for PHP
It's okay tho, I can figure it out. I am sure it's easy
Fyi his solution doesn't work. I tried it earlier it causes a SQLI error when parsed into the DB
Goodnight ๐
That's because there's more than one web framework in Python. This channel is generally intended for Python web-dev help, not PHP.
You'd be much better off asking for help in a dedicated PHP server, rather than in a python server such as this.
!guilds should have some PHP servers
Communities
The communities page on our website contains a number of communities we have partnered with as well as a curated list of other communities relating to programming and technology.
(Under the "curated list")
I appreciate that. I also agree but I couldn't find any servers for that. I appreciate the way you have dealt with things. Thanks (:
r2toretto โ Today at 3:37 PM
Hey guys I had a problem with 100 Days of Code Day 61 Flask and WTForms, about the validation, the docs I think they are horrible or they think we know everything about it, got to love the irony about the docs, anyways, I found this videos that can help anyone that had or will do the 100 Days of Code in Python bookmark this video to help you. This is like a rare pokemon that has only been seen by God himself.
https://www.youtube.com/watch?v=GbJPqu0ff9A&ab_channel=Codemy.com
In this video we'll start to use Web Forms for our Flask project with WTF (What the Forms!).
Web forms with WTF are incredibly easy to use and come with all sorts of features that we need like form validation, CSRF token creation, and even reCAPTCHA.
You can always build out web forms by hand, but using a 3rd party system like WTF just mak...
hi! having a problem
here's the website link (i know its not up to a standard) https://00012252.github.io/NewWebCW0/
the menu pop up wont show and i cant figure out why
should look like this
but this is what i get
Does it ever show or just somtimes?
Looks like your background color isn't getting rendered.
never now
will check now
Link to the relevant component or part of the code, I'm not going to be able to search the entire repo for it.
hi guy's, does anyone know if heroku is working ?
and where is the code where the css style is applied?
its the one, the sidebar isnt showing
show the html snippet of where you apply the css style
Didn't dive into the repo, but just took a quick look in the web console and it looks like the .sidebar has right: -40em. If I set it to 0 instead, it shows up
I wouldn't be surprised if the AWS issues currently going on are affecting Heroku
ok but is it working or not?
๐
check their status page?
y
huh?
it says problems in US and EU services
well there you go
this also makes it stay in place - I would assume the transition isn't happening with state change
when in doubt, find the status page
okay
Is the sidebar separate from the element that the X is attached to?
Ah, yeah it has that value before I try opening the menu too.
Anyone any idea how this formula would be written in an IDE?
Hey @tight ocean!
It looks like you tried to attach file type(s) that we do not allow (). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
Anyone?
I need it in a variable
Could you just write it out and follow PEMDAS to put it in a variable?
I don't know how to write this formula out tbh xD
Or else I could've already put it in a var
So like (((e^(z-u)^2) / (2x^2)) / etc...
Just make sure your equation follows pemdas and you should be able to write that out.
Mb, this one has to be written out
I will try
What does file.save(...)? do?
Don't you need to await it?
What is the repr of file?
Hello does anyone know the best pattern/app structure for flask where you have a single app file and blueprints within a APIs folder? I have python-dotenv to load local config but I am having to repeatedly call the load_dotenv("local.env") in each blueprint file for it to work correctly. There has to be a more efficient setup where you load config once and that is accessible across blueprints
I store config on the app then read it from flask.current_app
Yeah like print(f"{file=}")
Happen to have an example I can view?
Try using fetch instead of xhr?
Are infinite series in Python possible?
((reclaim_rate)^(0) * 0.5^1)+((reclaim_rate)^(1) * 0.5^2)+((reclaim_rate)^(2) * 0.5^3)+((reclaim_rate)^(3) * 0.5^4) and so on to infinity
Why would the python backend change anything?
Hey, so my html looks good on my main screen, but when i move the window to a smaller screen or reduce the size, the size of the content doesnt change
how do i make my html responsive?
Bootstrap specific class called container or css property called media. Search it.
please help
im using flask, html, css and python
on my pc my website looks like this
but on a smaller screen it look like this
hwo can i fix this?
idk, sometimes its fun to make your own css
which code do you need?
just more painful
wherever you're keeping the css
Mostly time is costly so pain isn't the best
what is bootstrap?
what is .htlm ending
a more efficient css library
makes your life easier
oh leeave that
you can look it up
....
..
if not you can import it from a link
i think they mean the file not css in general
I understand
yea
yeah that's got bootstrap
Bootstrap!
this is a css/html problem, not python
but yes, you could more efficiently use bootstrap
Bootstrap responsive website search and you have immediately 10 links
although it looks like they are using it
anyway
this is specifically flask but...
i've been trying to upload a file to a directory and continually get 400 bad request errors.
@app.route('/upload/', methods = ['POST','GET'])
def upload():
if request.method == 'POST':
pack = request.files['package']
pack.save(os.path.join(uploads_dir, secure_filename(pack.filename)))
return 'file uploaded successfully'
this is the upload code...
and below is the html form i'm using:
<form action="https://example.com/upload/" method = "post">
<input type="file" id="package" name="package"><br>
<input type="submit">
</form>
(example.com) is just to protect the web address, I didn't screw that up
Bootstrap is CSS framework
A pack of boilerplated solutions
The lazy arse solution to use CSS without learning it yet fully
so i have this website and a website i am creating and i need to add python code to a button so when the button is clicked it will execute the python code
how can i make my pc an https server using python and flask?
u can achieve it for example by usage of
using Submit Button from html input form. It can invoke POST requests for any specified url.
make some endpoint url at your python server, and specify this url at the button
Alternatively... if all u need to invoke python code without any input data, u can just use <a> tag, it will make GET request to any specified url
Sure, frontend frameworks are used to change web site without refreshes
it depends on answers...
do u wish your server being accessed only by local users, without public usage?
if yes, it can be achieved with different levels of difficulty, depending on your current OS
if u wish it exposed to the world, than u need (public / white / static (synonyms)) IP address for your PC
efficient?
can you help me do it?
@inland oak you there?
i want to make a website that can run open-cv projects made in python on a pc and or phone
nah. ask questions to everyone, don't single me out.
read the guide if necessary, how to ask questions right
u need to specify prevent default behavior, it is surely possible
folks,
The goddamn iphone changes the letter A and H to black. And only these 2 letters. Anyone know what the hell is the problem? Works fine on android.
in this video there is mention how to do that for vanilla JS, i copied the right second for that
https://youtu.be/cuHDQhDhvPE?t=207
I built a simple app with 10 different JavaScript frameworks... Learn the pros and cons of each JS framework before building your next app https://github.com/fireship-io/10-javascript-frameworks
#javascript #webdev #top10
๐ Resources
Full Courses https://fireship.io/courses/
Performance Benchmarks https://github.com/krausest/js-framework-benc...
form.onsubmit = (event) => {
event.preventDefault();
addTodo(input.value);
}
ev.preventDefault(); as codeline to your code
const input = document.querySelector("[name='todo']");
https://github.com/fireship-io/10-javascript-frameworks/blob/main/vanilla-app/index.html
for input field todo
for its value (text)
Has anyone come across any fastAPI boilerplate, like say authentication/db minimal front end?
Is python used for web dev?
django and flask yes
and fastapi ;b
Thanks
Would python be slower as a backend than if you used java
but is speed in a backend something you should take in to consideration when you are choosing backend
So make it an async function
Show your code?
The server returned 404
Don't template your <script> code
Put your js in a .js file and load it with static files
Don't template JS use a static file
<script
src="{{ url_for(...) }}"
type="module"
data-guild-id="{{ guild_id}}"
data-upload-url="{{ url_for('upload') }}">
</script>
Then you get the data with:
const { guildId, uploadUrl } = document.currentScript.dataset;
โ๏ธ
The .js file at the top
Also add export {}; to the bottom to show it's a module
You don't need templates at all
Just server_id: guildId
Yes the last line of the js file
Show your code and full traceback
Ah woops it doesn't work with modules
<script
src="{{ url_for(.../static/main.js) }}"
type="module"
id="my-metadata"
data-guild-id="{{ guild_id }}"
data-upload-url="{{ url_for('upload') }}">
</script>โ
const { guildId, uploadUrl } = document.getElementById("my-metadata").dataset
@charred sphinx I forgot you have to use an id instead
Ah don't use onclick
Use addEventListener
Give the form an id then select the button
$( "#form-id-here" ).on( "click", ".save" submit_form);
Ok select the button in a different way
You can use $(".save").click(submit_form);
It's addEventListener not onclick
Just after you define the submit_form function in your .js file
That's the server returning a 400 look at your server's logs
And look at the http response in the network tab
See where it says response
On the top right
Show the full output
You cut the important part
You probably want to run your server in debug mode to see the traceback
But it's because you're accessing a key on your form that you didn't send
Ok well stick a try: except Exception as e: breakpoint(); raise around your upload handler
Yeah
The whole thing
You missed a line at the top
Yeah try that
Hey @charred sphinx!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
โข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
โข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
!eval [code]
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*
Show it so I can see it
With my eyes
Type !e to run the expression e which prints the value in e
It's like a repl
But you put ! first to let it know it's not a debugger command
Into the debugger I assume it's running in your terminal
uhh
try logging it instead? @charred sphinx
import logging
logging = logging.getLogger(__name__)
...
except Exception as e:
logger.exception("the bad")
Hello there, anyone having few moments of time to help me a bit?
@charred sphinx do you get any output? Remember to raise also
Sure no need for a semicolon you can use a newline
Yeah so there's no key called "file" in your .files object
You need to send a form with a file in the file field of the post data
Yeah
You're sending it as json
Get rid of the content-type header
Yeah I think so
Don't use .then, use await
Yes
Yes
Whenever you see v.then(func) you can use func(await v)
anyone could help me with a dumb flask error if possible? I swear it won't take too long
Don't ask to ask
Don't ask to ask
https://paste.pythondiscord.com/kelerotitu.py
I have a thread and I want to set global variable which I named distanceVar,temperatureVar, but when I try to use them in my render it gives me a nameError, I have been stuck there for 2h now
?
So you see v.then(func) in your code? The pattern I'm asking you to look for could have any expression v on the left and any function func on the right
e => e.json() is a function
And fetch(...) is an expression
You have fetch(...).then(e => e.json())
So can you see how it fits the v.then(func) pattern?
Hello, can someone tell me how do I put my website public?
Show the full traceback
It's best to only put sys.exit(main()) after your if __name__ == "__main__": block
what webserver u using
The error really seems to be in my render_template
I dont know what a webserver is, im new to coding
Windows 11
Yeah so you didn't define those values globally. But also you need to watch out because this won't work with gunicorn or any normal way of deploying your wsgi app
ah
I tried not to set them globally but same result, also this is just for a localhost final work
Is this just the OS of your personal computer? Do you have a cloud computing or other isp account?
get a vps or dedi or shared or change ur own os to linux and do apt install apache2 or nginx
also not related but windows 11 sucks
Ok so number one is to use the idiomatic form of __name__/__main__
Ok thanks
not sure what does that mean
It won't fix your problem but might make it clearer how to fix it
https://paste.pythondiscord.com/huxovoxuce.swift
not complete
but now I can't access dht and capteur in my platine() method anymore
what can I do
@haughty isle https://paste.pythondiscord.com/ijuqizikul.py
I think I did it good hopefully
I return the var in the main so I can grab them in my method
does that make sense?
idk what I am doing and I need to get this done lmao
Have another read of the https://docs.python.org/3/library/__main__.html#idiomatic-usage your code doesn't use sys.exit at all
?
And I don't see return 0 anywhere in your code
I have been working for 10h straight and idk what I am doing anymore honestly. Our teacher gave us a very limited lesson on flask and never teached us thread or anything and I just can't do it. I need to sleep lol
What's the exercise that you need to do? Does it specifically mention threading?
You can send anything you want in a FormData object
You can append new fields
Did it work?
Did you try that?
Why did you do that?
It was fine when you did new FormData(form);
Yes, you said it needed a key and a value
Did you try that?
@charred sphinx I'm interested in your reasons for choosing to remove the form from the FormData constructor call
which server id?
why did you remove the form from the new FormData(form); ?
right but that's just an example of how to make an empty FormData()
you want a FormData() with the data from your form and some additional data
ok does it work?
where's "serverID" in your JS code?
ok but why are you looking in request.files for serverID?
that's for files
I'm not totally sure why request.form doesn't contain files but there we go
oh wait you're using quart
what?
looks like it's working to me?
show your code
don't use a bare except:
just catch the exceptions you expect to see
just catch the exceptions you expect
also don't call chdir
just save to the path you want to save to
right you don't need to chdir fort that
what makes you think that?
just:
UPLOAD_PATH = pathlib.Path("/path/to/static/upload")
async def upload():
...
path = UPLOAD_PATH / werkzeug.secure_filename(guild_id) / "thumbnail.png"
await quart.run_sync(path.parent.mkdir)(parents=True, exist_ok=True)
await file.save(path)
Are you able to update without refreshing without having some JS on the front-end?
Or maybe I'm just assuming and you do actually have JS to handle the front-end.
oh I see
I updated the code @charred sphinx
or maybe
UPLOAD_PATH = pathlib.Path("/path/to/static/upload")
async def upload():
...
guild_dir = UPLOAD_PATH / werkzeug.secure_filename(guild_id)
await quart.run_sync(guild_dir.mkdir)(parents=True, exist_ok=True)
await file.save(guild_dir / "thumbnail.png")
Catching just Exception is almost as bad as just Except. It is number one worst thing to do in python, because it makes debugging a hell. It makes ignored even syntax errors
Late answer but I really needed sleep. So I need a thread because I need to constantly check if the capteur.distance is within a range for 40 cm
But he showed us the bare minimum for flask so its all learning
import algo.config as config
import asyncio
import websockets as ws
ws_client = WebsocketClient(api_key=config.api_key, secret_key=config.secret_key)
async def main():
asyncio.create_task(
ws_client.connect()
)
await ws_client.subscribe(
events=["!ticker@arr"],
)
loop = asyncio.get_event_loop()
loop.create_task(main())
loop.run_forever()
loop.close()```
I can get it to output in a console but I cant get it store in a variable
/list
its using this module
Can anyone help me? I get TypeError: Invalid status argument error
guys i'm making a login page but I need to verify if the fields are empty and if the fields are empty the border of the input should turn red. But it's not working... Here's the code
no one knows what your code looks like or what you are trying to do thats giving you this error
from flask import Flask, render_template, request
from flask.helpers import url_for
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Agg')
import scipy.stats as stats
import numpy as np
import math
import pandas as pd
import plotly.express as px
app = Flask(__name__)
# Home page
@app.route("/")
def home():
return render_template('index.html')
@app.route("/", methods=['POST'])
def my_form_post():
mu = 0
n = 5
burn_chance = request.form['burn_chance']
burn_chance = int(burn_chance)
burn_chance = (burn_chance / 100)
reclaim_rate = (1 - burn_chance)
for n in range(n):
p = ((reclaim_rate)**(n-1) * 0.5**n)
u = p * n
o = math.sqrt(u * (1-p) * p)
n += 1
x = np.linspace(mu - 3*o, mu + 3*o, 100)
plt.plot(x, stats.norm.pdf(x, mu, o))
plt.savefig('static/images/plot.png')
return render_template('index.html', url='static/images/plot.png'), reclaim_rate
if __name__ == "__main__":
app.run(debug = True)```
tell me details about where this error is occuring
It doesn't tell me
but you know what you are doing thats causing this error
It has to do with request.form['burn_chance']
when I leave out burn_chance = int(burn_chance), it says uncompatible operand type str int
what is reclaim_rate?
i thinks this line
return render_template('index.html', url='static/images/plot.png'), reclaim_rate
might be where your error is
why are you putting reclaim_rate there?
when you do something like return x , y for a flask module, y should a valid http status code
whatever you're putting there is not valid
The error occurs when I change upper lines though
This is a list of Hypertext Transfer Protocol (HTTP) response status codes. Status codes are issued by a server in response to a client's request made to the server. It includes codes from IETF Request for Comments (RFCs), other specifications, and some additional codes used in some common applications of the HTTP. The first digit of the status ...
yeah, but im reffering to the error you sent here
im telling you what that is reffering to
How could I then return the page and input values?
where is the input value supposed to go?
There are gonna be added 2 more, so that would be problematic
well?
what?
you want a function to return a value, and use that value within that function, am i understanding you correctly?
does that make sense to you?
hmm
cool i guess
ty
what do you mean by this?
Like when the user inserts the wrong email, the login button should disappear
butttt
there's one more important thing
could you help me in this
^^
show the full route code perhaps
k, so you have emailEmptyField but you're not passing this variable to your form
or html page rather
so login_template is where you want to use this variable right?
you're using it there, but it's basically not being defined
you need to do this
return render_template(login_template, emailEmptyField = emailEmptyField)
that should work properly
yessir! It works! Thank you! I'm currently a newbie in web dev xD
anyone here knows how to scrape dynamic websites using selenium ?
Okay so I'm doing a new portfolio design, mixing it up. I have this as of now. Kind of a rough draft. I would love some feedback on it!
https://gfycat.com/happyselfreliantboto
Hey guys can anyone help me cause my image is not appearing in my html file in chrome and Microsoft edge but it appears when i open live server in vs code in microsoft edge ,it is confusing and here is my codes and webpages screenshot and then share the code to me thank you ๐
Absolutely phenomenal design for above the fold. Love the dark/light theme switch changing the environment.
Does the theme follow what you have set in Chrome or is it a page-specific setting?
it follows the system wide theme.
I think it would be awesome if as you go down, you're descending through layers of the Earth, or better yet, some kind of dungeon or adventure-style level for each section
that would be nice!
I'm going to do that, make it look like there are things buried more and more as you scroll
Would love to see updates. Do you do the art?
Not here. at least not the main parallax art. Those are through freepik premium. Though each layer is a different base eps file that I then edit in ps and illustrator to match my design, remove backgrounds, change colors and things like that. But then stuff like my logo and my photo I did.
css usually goes in your static folder
are you using Flask?
yes
Flask uses the static folder as the default root for files
yes or change the default path
ty
<head>
<title>Flask Shop</title>
<link rel="stylesheet" href="/static/style.css">
</head>
Basically something along those lines.
^
And you might need to collectstatic - I don't know if flask requires that like Django does.
@app.route("/", methods=("GET", "POST"), strict_slashes=False)
def index():
if current_user.is_authenticated:
return render_template("index.html", title="Home")
else:
return redirect(url_for('login'))
@app.route("/login/", methods=("GET", "POST"), strict_slashes=False)
def login():
form = login_form()
if form.validate_on_submit():
try:
user = User.query.filter_by(email=form.email.data).first()
if check_password_hash(user.pwd, form.pwd.data):
login_user(user)
return redirect(url_for('index'))
else:
flash("Invalid Username or password!", "danger")
except Exception as e:
flash(e, "danger")
return render_template("login.html",
form=form,
text="Login",
title="Login",
btn_action="Login"
)
trying to figure out why when I go the login page via redirect the css folder path lookup changes to
"GET /login/static/custom.css HTTP/1.1" 404 -
instead of
"GET /static/css/custom.css HTTP/1.1" 200 -
uhh don't think I have one of those lol
ah
Flask, then. Not sure.
my guess would be something where you have a / where it shouldn't be
so it doesn't create a relative path
so maybe login/ instead of /login/?
hi, nice to meet with y'll. i got stuck with a flask problem and wondering if anyone can help.
this works, changed @app.route("/login/" to @app.route("/login
ah great
Cept i don't fully get it lol
Having the extra slash changes whether the route is relative or absolute I believe
Hey guys can anyone help me cause my image is not appearing in my html file in chrome and Microsoft edge but it appears when i open live server in vs code in microsoft edge ,it is confusing and here is my codes and webpages screenshot and then share the code to me thank you
PLs help me
ok so when I set strict_slashes=False for the route it should allow you to access the route without the slash, and it does as it loads the login.html file, but the css is missing because the word login is now put before the href path href="static/css/custom.css" becoming /login/static/css/custom.css. So im not really understanding how the href works
Maybe itโs stuck in a div pushing it down
Has anyone encountered an issue where django suddenly generates a number of sleeping database threads and the web app stops responding? It can go on for days or weeks with no issue or each day could have problems. Restarting Apache clears out the db connections, but they usually just stack up immediately when Apache starts. Seems to line up with the potential peak time, but resources donโt seem to be an issue. Any ideas on what to look for?
how can i fix that?
Iโd have to look at the html, but essentially what Iโm suggesting is to review your html to see where the button element is located and whatโs around it. Maybe itโs contained within a tag that keeps it locked down
In my experience, itโs always another divโฆ. Damn divsโฆ
So that divโฆ is it within another div?
Didn't you just have this issue? You usually need an ajax or other JS call to the backend so that it re-renders without refreshing.
you can use chrome dev layers to find out probably
layers tab, its under settings, more tools, layers
On your site did you just layer divs over one another with separate images that have transparent BGs? Besides the parallax stuff.
for what part? Off the top of my head the only part like that is main parallax
oh I also kind of did that for the work section, those are divs with text, then on hover the div and text go transparent
but the tech section is a grid with perspective and RotateY, on hover it uses scale
i removed the div but iget the same result
Ah yeah, the trees and the rest are full viewport size, positioned absolutely. order from front to back is trees, mountain, text, moon, stars, colored div. the images are set as cover.
you can right click those document tags and expand them to get more info
@thorny rover
What if you put the buttons within a div with class row?
Not sure. Not strong with styling. Itโs always a PITA for me lol
lol
How do i use multiprocessing in Django?
the thing i'm making a quiz app using django , so i have 20 quizes (img format) i wanna render all the quizes 1 by 1
(via POST req)
so the issue is when i hit next it submits n saves the data to db + renders the result page
n when i remove the next button (which was in form tag) so it doesn't show any error it opens the next quiz question but it doesn't send post request so how can i then make result
my one friend told me that write a condition it should save when all 20 questions r done
- to have django processing requests in multiprocessing? automatically enabled when deploying with normal web servers like gunicorn
- to have just multiprocessing for some particular thing? same as in any other python.

margin just makes certain amount of space around the object content, it is just bigger invisible border
top, left is for relative/absolute/fixed positional movements
for example we can freely move with top, left, bottom, right outside of the object borders
which was perfect to shift appeared menu outside of the parent object
like this dropdown meny
plus with top, left, bottom, right, we can position child object at ANY corner of the object
don't use bare except, remember to use pathlib and not os.path and always do blocking path calls with quart.run_sync
also use functions for all your duplicate code
@haughty isle can i get help sir
..
and fix the driectory traversal vulnerability
what do you expect secure_filename(f"thumbnail.png") to do?
show your code with the suggestions I made applied?
this stuff
I fixed it for you when I gave you code for if yesterday
โ๏ธ
You need to call
guild_dir = UPLOAD_PATH / secure_filename(guild_id)
Then you can use guild_dir / "thumbnail.png" etc
hey coders, I just needed help!
Currently, I am learning to build websites with Django. And I have finished one, now I wanna deploy it but I will be needed an Amazon AWS account. because I need to use RDS to push my static files. But I am under 18 now, I do not have any credit cards, also I have already tried with my parent's credit cards but that didn't work as their bank didn't support any international transfer.
So can anyone help to create or get an amazon AWS account? please? I would be really grateful
N.B: "I know that I can also deploy the website on pythonanywhere for free, but this is some kind of a professional website"
Show your full code and Traceback
Where is your pathlib import?
Show the code
The whole file, because I can't see pathlib anywhere here
I still don't see pathlib anywhere...
You're supposed to use pathlib.Path
Then you don't need os.path anymore
Nope
Don't use f" for paths
Use guild_dir = UPLOAD_FOLDER / secure_filename(guild_id)
Also you don't need to check it exists because you just wrote the file
@charred sphinx you may need Ajax
So things load on a static page for your emojiโs
Hello,
Somebody knows the Django Rest Framework and Django channel to ask questions? Thanks ๐๐ฟ
django are on #django in libera.chat and a https://gitter.im/django/django
hi i get FileNotFoundError: [Errno 2] No such file or directory: '/output.png' when i try to send_file through flask but i did os.listdir('.') and it lists the file tho
does the files should be in a folder like templates?
For static files I think you want S3 buckets instead of RDS. In any case, the other major cloud platforms have equivalents to both, maybe try those?
I'm thinking the / before the filename might be the issue?
i moved it to a folder and it worked ๐ thanks!
yeah i should try, can you suggest a particular cloud platform?
If cost is not an issue, Azure (Microsoft) is the obvious alternative to AWS, followed by GCP (Google).
how ca n i align a button to the bottom left in a button?
im only able to move it left
Dang that's good
text-align: center
maybe?
that will make it in the center
my bad i automatically thought you wanted it centered, sorry
try line-height
copy code as text. screenshots are bad. I am lazy to rewrite your code from screenshot in order to give working example
anyway, I am usually using flexboxes as universal gun
display: flex;
justify-content: flex-start;
align-items: flex-end;
this will move things to bottom-left
i just need the text to move to bottom-left
this will move anything to bottom left
as alternative solution ๐ค
u can write code like
.button {
position: relative;
}
.text_in_button {
position: absolute;
bottom: 10px;
left: 10px
}
it will move stuff to bottom left too, less elegant solution though
as it is not promising to hold content inside of the object in comparison to flexbox solution
wait a second, there is vertical-align property
lets try to use this one
xD, this will require using old school stuff
super bloated code in result
.button {
}
table, td {
height: 100%;
width: 100%;
vertical-align: bottom;
color:#fff;
}
<div class="button">
<table>
<tr><td>Some random text</td></tr>
</table>
</div>
we can align with usage of tables
because vertical-align property can be applied at least to its cells
much dumber solution than using flexboxes or absolute-relative positioning๐ค perhaps vertical alignment can be applied to smth else
oh well, we have fourth method left
the last, the most overkill way to have item at bottom left...
.button {
display: grid;
grid-template: 15% / 95%;
justify-content: end;
align-content: end;
}
comparing all methods, obviously flexboxes win
Hey, I'm trying to add a footer to my page, but it keeps sticking to the bottom of the screen rather than sticking to the bottom of the page itself
I use bootstrap v5.1
<footer class="fixed-bottom text-center text-white" style="background-color: rgba(39, 41, 46, 0.95);">
<!-- Copyright -->
<div class="text-center p-3">
ยฉ 2021 Copyright:
<a class="text-light" href="https://mygames.idevision.net/">MyGames.iDevision.net</a>
</div>
<!-- Copyright -->
</footer>```
use flexbox
you can push it down with it
your class is probably applying position: fixed
flex and flex grow property i believe
so basically, whatever is in the middle needs to grow to fill the remaining space
I tried the flex classes used in this example, but unfortunately that didnt change anything for me
the navbar is fixed here, that's not the method im suggesting
wait, nvm
let me send a codepen
guys where should i put this code to generate a Json view in my terminal ? (in a django project) import json datas = [{'title':'a cool title','artist':'john doe','year':2020},{'title':'a second music'}] print(json.dumps(datas, indent=4))
thanks
something like that
you can probably use body as your container here
but whatever comes before your footer needs to be contained in a parent div or something for this to work
or you can just add the flex grow property to the element before the footer
whatever works for you
Thanks! That works wonderful. I've spread it across the body {} and main {} and now its finally at the bottom of the page 
nice
Do you also happen to know how fastapi works?
Because that's what I use for my page and I somehow cant get it to use css files. It will only use css if I put it inside the html file 
hmm. what do you mean?
I have to put all css classes in the <style> in the html file
because it for some reason wont get it from a .css file
oh, so it's not serving the css file?
yea
app.mount(
"/static",
StaticFiles(directory="/home/dutchy/gamesite/static"),
name="static",
)```
<link rel="stylesheet" href="{{ url_for('static', path='/css/main.css') }}" type="text/css">```
this doesent work either
yea im mainly a flask guy, not sure about fastapi
but i tried something and it might work
<button type="submit"; class="living_room_button"><h1 style="position: absolute; top: -10; left: 60; text-decoration: none; font-size: 16px; color:white;">Living Room</h1></button>```
is this static directory in the same folder as your python file?
i mean is the structure like this
why not use a relative path?
seems like you specified the entire folder from your home folder
yea, idk. I've tried a couple things but none seemed to work
just static doesnt work?
doesnt seem like it
yeah idk
please help
<button type="submit"; class="living_room_button"><p style="position: absolute; top: 11; left: 25; text-decoration: none; font-size: 16px; color:white;">Living Room</p></button>
it just stays there
no matter how much i change the top and the left
you need to specify a unit for your top and left
anyone know why when i movee my img
my
thermostat_up_button, thermostat_down_button and thermo_tempalso move?
why you using positioning for this layout? why not use flexbox or grid?
Somebody that might be able to help me with selenium?
im not familiar with that yet
a hypothetical situation
mhmm
say you wanted to add a new component
you realize that you're gonna have to reposition everything right?
yessssssss
so save yourself the work and learn flexbox or grid. not that hard to grasp
see that icon top left where your image should be
that means the path you gave for the image is likely wrong
use url_for(static, filename)
if you're using flask
if not look up how to do it in your framework
whats better for a responsive website?
both work
Looks like you download what I call a fake transparent png
now export to jpg and then screenshot it on your phone
just made my first website!
and uploaded it to the internet
never felt a rush like this before lol
I used a free web hosting service and those are shite and messed things up but free is free
please help i want to reference a python function in my html file
html file:
what are you using? (flask, etc) also provide text not screenshots if possible
<title>Hello from Flask</title>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello, World!</h1>
{% endif %}```
from https://flask.palletsprojects.com/en/2.0.x/quickstart/#rendering-templates
You want to live update the page when the light state changes?
yea
flask
try adding spaces between test like {{ test }}
i think its because its in ""
no, i doing it without quotes will show the flask in html
any errors in the console?
nope
huh, super weird
