#web-development
2 messages ยท Page 220 of 1
Hello everyone ๐ noob here,
im trying to use the submit button from wtforms with flask
to redirect the user to different pages of the website instead of using hyperlinks,
but whenever i have more than one form in the page only the first one on my if statement is ran.
from flask import Flask, render_template, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import SubmitField
app = Flask(__name__)
app.config['SECRET_KEY'] = '47b0cf0839ce0f8d8c632b7b'
class IndexPageButton(FlaskForm):
submit = SubmitField(name="index_submit_button", label="Go to index page")
class AnotherPageButton(FlaskForm):
submit = SubmitField(name="another_page_submit_button", label="Go to another page")
class ThirdPageButton(FlaskForm):
submit = SubmitField(name="third_page_submit_button", label="Go to third page")
def redirect_to_appropriate_page(page_route_string):
index_page_btn = IndexPageButton()
another_page_btn = AnotherPageButton()
third_page_btn = ThirdPageButton()
if third_page_btn.validate_on_submit():
print("clicked on third page")
return redirect(url_for("third_page"))
elif another_page_btn.validate_on_submit():
print("clicked on another page")
return redirect(url_for("another_page"))
elif index_page_btn.validate_on_submit():
print("clicked on index page")
return redirect(url_for("index_page"))
return render_template(page_route_string, index_page_btn=index_page_btn, another_page_btn=another_page_btn, third_page_btn=third_page_btn)
@app.route("/", methods=["GET", "POST"])
@app.route("/index", methods=["GET", "POST"])
def index_page():
return redirect_to_appropriate_page("index.html")
@app.route("/another_page", methods=["GET", "POST"])
def another_page():
return redirect_to_appropriate_page("another_page.html")
@app.route("/third_page", methods=["GET", "POST"])
def third_page():
return redirect_to_appropriate_page("third_page.html")
this is how all three pages lookwhich is correct
but when i click on any of the input buttons they all redirect the index page
someone know how do I add custom scss file to my flask project? for bootstrap
I have only guess how to do it in a custom way
put your scss files into one folder
runer scss compiler to perecompile it into regular css into another folder
specify flask to run with compiled css files
according to this page, this one is supported python sass compiler
pip install libsass
good docs to use it
is there just another way I can customize bootstrap variables without doing that, I want to add dark mode/light mode to my website..
Iโd be really interested in this. Iโm a Python Developer. Basically spend my time with Django.
If you just want an a tag to look like a button, you could use CSS.
https://stackoverflow.com/a/2906586 - refer to the CSS section of this response
i m having issue with the select tag
i am building a web app
<option disabled selected>Select Language</option>
<option value="ar">Arabic</option>
<option value="bn">Bengali</option>
<option value="zh-CN">Chinese</option>
<option value="nl">Danish</option>
<option value="en">English</option>
<option value="fi">Finnish</option>
<option value="fr">French</option>
<option value="de">German</option>
<option value="hi">Hindi</option>
<option value="it">Italian</option>
<option value="ja">Japanese</option>
<option value="ko">Korean</option>
<option value="pa">Punjabi</option>
<option value="ru">Russian</option>
</select>```
this is my code
What's the issue?
the issue is even though i select English it is returning nl which is for danish
sometimes it works correctly sometimes not
can you share your route/handler?
i will
@app.route('/', methods=['GET', 'POST'])
def root():
if request.method == 'POST':
trans_lang = request.form['lang_selected']
lang_to_translate = request.form['translate_to']
text = request.form['text_to_translate']
translator_obj = translator.Translator()
translated_text = translator_obj.get_translation(trans_lang, lang_to_translate, text)
print(trans_lang,lang_to_translate)
return render_template('translation.html', translation_lang=trans_lang, translate_to=lang_to_translate, translated_text=translated_text, text=text)```
any React expert can explain context providers to me a little
Hmm that all looks fine. What about the form?
Please respong fast if u can
<input type="text" id="entry" name="text_to_translate" placeholder="Type Here" required></input>
<select name="lang_selected" required>
<option disabled selected>Select Language</option>
<option value="ar">Arabic</option>
<option value="bn">Bengali</option>
<option value="zh-CN">Chinese</option>
<option value="nl">Danish</option>
<option value="en">English</option>
<option value="fi">Finnish</option>
<option value="fr">French</option>
<option value="de">German</option>
<option value="hi">Hindi</option>
<option value="it">Italian</option>
<option value="ja">Japanese</option>
<option value="ko">Korean</option>
<option value="pa">Punjabi</option>
<option value="ru">Russian</option>
</select>
<select name="translate_to" required>
<option disabled selected>Select Language</option>
<option value="ar">Arabic</option>
<option value="bn">Bengali</option>
<option value="zh-CN">Chinese</option>
<option value="nl">Danish</option>
<option value="en">English</option>
<option value="fi">Finnish</option>
<option value="fr">French</option>
<option value="de">German</option>
<option value="hi">Hindi</option>
<option value="it">Italian</option>
<option value="ja">Japanese</option>
<option value="ko">Korean</option>
<option value="pa">Punjabi</option>
<option value="ru">Russian</option>
</select>
<button type="submit">Translate</button>
</form>```
@outer apex this is it
who know how to fix?
IDK whenever something goes wrong with a docker build I just run docker system prune -f maybe try that.
but not
if you have any important data stored in images or volumes that's not backed up
on a different computer
guys, is there a way to store a formated date into a database using default=func.now()?
date_created = db.Column(db.DateTime(timezone=True), default=func.now())
I have such attribute in my class. I don't like how the date is stored. It looks like this:
Is there a way to store the date formated/truncated to only DD/MM/YYYY? I was checking some documentations (i.e. https://docs.sqlalchemy.org/en/14/core/functions.html) but could not find anything on that and I can't believe there is nothing that can be implemented to amend this. Does anyone know the solution to this?
I'd recommend storing it the way it is and formatting it on retrieval
Anyone who likes Python based web development with Flask or django want to check out my site I just finished working on to a point where its showable
Im new to web dev and trying to run flask on my IDE with this code
app = create_app()
if __name__ == '__main__':
app.run(host='localhost', port=5000,debug=True)
but am getting this error with no local host popping up.
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with watchdog (windowsapi)```
what error do you get when you access http://localhost:5000/ ?
sure
I get Not Found
When I removed debug = True, the site http://127.0.0.1:5000/ pops up
So your site works without debug, but not with debug?
Yeah idk why though
can anyone suggest where to learn Django rest framework, any youtube playlists/channels?
Hey @clever whale!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Hey @clever whale!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
i just realized this is the wrong channel, my bad lol
is there anyway i can do Internationalization without language prefix in django?
Hello! I'm here to ask for some important question..
I've created a flask web-app and want to upload data trough a POST request. The upload takes a while so I want to maje the upload a background process. Is it possible to return after that upload success data to the already loaded page?
I was thinking about a ajax GET in loop to get data, but It's ratelimited
Learn to code with our quick and easy to follow videos! Python, Django, Tkinter, Kivy, Node, Ruby on Rails, Ruby, HTML and CSS, Javascript, SQL, Ubuntu and More!
Check out my website Codemy.com for more videos!
guy's who know Docker and can hekp me with Nginx?
Anyone good with django?
yep
What kind of help you need? Don't ask to ask
i'm using brython and i'd like to change the class of an element on event like so
@bind(document.select(".row_not_selected"), "click")
def table_clicked(event):
event.target.parentElement.className = "row_selected"
@bind(document.select(".row_selected"), "click")
def table_clicked(event):
event.target.parentElement.className = "row_not_selected"
but the bindings apparently don't get updated, any idea how i can force to update the binding?
Perhaps there are no elements with such class when @bind is executed
so i have to rebind those on event, i guess?
I'm not sure, i usually use js frameworks ๐
okay, that works
it's a bit unwieldy
def table_clicked_select(event):
event.target.parentElement.className = "row_selected"
for x in document.select(".row_not_selected"): x.bind("click", table_clicked_select)
for x in document.select(".row_selected"): x.bind("click", table_clicked_unselect)
def table_clicked_unselect(event):
event.target.parentElement.className = "row_not_selected"
for x in document.select(".row_not_selected"): x.bind("click", table_clicked_select)
for x in document.select(".row_selected"): x.bind("click", table_clicked_unselect)
for x in document.select(".row_not_selected"): x.bind("click", table_clicked_select)
for x in document.select(".row_selected"): x.bind("click", table_clicked_unselect)
but works
simplifies
def table_clicked_select(event):
event.target.parentElement.className = "row_selected"
document[event.target.parentElement.id].bind("click", table_clicked_unselect)
def table_clicked_unselect(event):
event.target.parentElement.className = "row_not_selected"
document[event.target.parentElement.id].bind("click", table_clicked_select)
for x in document.select(".row_not_selected"): x.bind("click", table_clicked_select)
that looks nicer
<Flex maxH="100vh" alignContent="center" flexFlow="column wrap">
{comments.map((comment) => {
return (
<Box bg="#F3F3F3" maxW="350px" margin="2" borderRadius="md">
<Text fontSize="14" fontWeight="500" color="black" height="100%" padding="5">{comment.comment}</Text>
</Box>
);
})}
</Flex>
Any clue why wrap doesn't work
having issues with select tag returning incoreet value anybody help plz
hello everyone ๐ noob here,
im trying to learn flask
my route takes in a parameter in the url
@app.route("/confirm_deletion/<jrnl_entry_object>", methods=["GET", "POST"])
def confirm_deletion_page(jrnl_entry_object):
#some functionality here
but when i use call this function in jinja i get error
<form action="{{ url_for('confirm_deletion_page') }}">...</form>
the error is
werkzeug.routing.BuildError: Could not build url for endpoint 'confirm_deletion_page'. Did you forget to specify values ['jrnl_entry_object']?
what's funny is when i do pass in an argument it will say it only takes one positional argument
<form action="{{ url_for('confirm_deletion_page', 'some_arbitrary_string') }}">...</form>
error message:
TypeError: url_for() takes 1 positional argument but 2 were given
it works fine if i dont use url_for() though:
<form action="/confirm_deletion/{{ 'some_arbitrary_string' }}">...</form>
but i'd really like to use url_for()
any thoughts?
What is the best way to "scrape" data from say, a <p> of an external website using Flask?
use beautifulsoup
So I would find the URL I want to scrape from, the data I want to scrape, and use Beautiful Soup to return it to me, then display that data to the user, correct?
yeah lemme show u an example
ight thanks
codes not easiset to understand but ill try explain
while True:
urlstr=''.join(random.choice(lowercase+uppercase+digits) for i in range(random.randint(5,15)))
for schema in schemes:
for end in domain_ends:
num=random.randint(0,len(all_keywords)-1)
keyword=all_keywords[num]
if " " in keyword:
keyword=keyword.replace(" ","")
urls_to_try=
[f"{schema}{urlstr}{end}",f"{schema}{keyword}{urlstr}{end}",f"{schema}{urlstr}{keyword}{end}"]
for URL in urls_to_try:
try:
page=requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
results = soup.find("body")
os.chdir("keywords")
```
for file in glob.glob("*.txt"):
keywords = open(file, "r")
os.chdir("../")
for htmltype in htmltypes:
elements = results.find_all(htmltype)
for element in elements:
for keyword in keywords:
if keyword != "\n":
keyword_count += 1
if keyword in element.text:
if file==("amazon.txt"):
found_amazon_keywords.append(keyword)
else:
if file==("microsoft.txt"):
found_microsoft_keywords.append(keyword)
else:
if file==("mcafee.txt"):
found_mcafee_keywords.append(keyword)```
Alright
soup = BeautifulSoup(page.content, "html.parser")
results = soup.find("body")```
that part uses the html parser to find the body of the page
htmltypes=["div","span","a","h","p"]```
i then used a for loop on this list to find all the elements i need
I've never used Beautiful Soup before, is this something I can pick up quickly?
alright
for htmltype in htmltypes:
elements = results.find_all(htmltype)```
the find_all basically find all divs of a certain type
so basic example would be py page=requests.get(URL) soup = BeautifulSoup(page.content, "html.parser") results = soup.find("body") elements = results.find_all("div")
that would return all div elements
Could you help me write a BS request?
what are you trying to do with it
Scrape this:
<h2>Usual Pediatric Dose for Acute Promyelocytic Leukemia</h2>
<p><b>1 year and older</b>:<br />
45 mg/m2/day administered as 2 evenly divided doses until complete remission<br />
<br />
Duration of therapy: Discontinue therapy 30 days after complete remission or after 90 days of therapy, whichever comes first.<br />
<br />
<b>Comments</b>:<br />
-There are limited clinical data on the pediatric use of this drug.<br />
-Out of 15 pediatric patients (1 to 16 years) treated with this drug the incidence of complete remission was 67%.<br />
-Dose reduction may be considered for pediatric patients experiencing serious and/or intolerable toxicity; however, the safety and efficacy of doses less than 45 mg/m2/day have not been evaluated in the pediatric population.<br />
from https://www.drugs.com/dosage/tretinoin.html
and then return those elements to the user
Detailed Tretinoin dosage information for adults and children. Includes dosages for Acute Promyelocytic Leukemia; plus renal, liver and dialysis adjustments.
which elements in particuar <p>?
Now that I look at it, it doesn't have a <p>
just that data right there
def LogCMD(file_name, data):
with open(json_file) as json_datas:
for line in json_datas:
data = json.loads(line)
def check_index(index, json_file):
with open(json_file) as json_data:
data = json.load(json_data)
for i in data:
if i == index:
return True
return False
app = Flask('')
@app.route('/')
def home():
return "hi"
my_secret = os.environ['SecretCode']
@app.route('/AddBuyer')
def AddBuyer():
arg1 = request.args.get("SectretKey")
code = request.args.get("Code")
if arg1 == my_secret:
db[code] = "UNUSED"
return "asdf"
my_secret = os.environ['BuyerPurchase']
@app.route('/BuyerPass')
def Purchased():
arg1 = request.args.get("SectretKey")
code = request.args.get("DiscordId")
has = request.args.get("Has")
if arg1 == my_secret:
info = {"Hash": has}
key = uuid.uuid4()
print(check_index("7AA2984F-6AE3-4609-8619-6709C729B1FF", "hashes/hashes.json"))
LogCMD("hashes/hashes.json", info)
return "asdf"
gheres the full flask code, its still erroring
File "/home/runner/BaconHubNewBot/venv/lib/python3.8/site-packages/flask/app.py", line 1502, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "/home/runner/BaconHubNewBot/keep_alive.py", line 57, in Purchased
LogCMD("hashes/hashes.json", info)
File "/home/runner/BaconHubNewBot/keep_alive.py", line 11, in LogCMD
with open(json_file) as json_datas:
NameError: name 'json_file' is not defined
im pretty time restricted so this is all i have py import requests from bs4 import BeautifulSoup url="https://www.drugs.com/dosage/tretinoin.html" page=requests.get(url) soup = BeautifulSoup(page.content, "html.parser") results = soup.find("body") elementslst=["h2","p"] for element in elementslst: element = results.find_all(element) print(element) html=open("html.html","a") html.write(str(element))
Hey @native tide!
It looks like you tried to attach file type(s) that we do not allow (.html). 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.
There's multiple <a> and <h2> though
its not perfect but if u add some filters you can ignore the parts u dont need
How would I do that?
if statements
What conditions?
if word not in element:
pass
else:
print(element)```
something like that
Alright, thanks!
word obviously being a keyword u want
yea
if u have multiple then use a for loop to check them all
Ok, thanks!
you could also just use py results = soup.find("body") and replace body with the element u want
results = soup.find("h2")```
def LogCMD(file_name, data):
with open(json_file) as json_datas:
for line in json_datas:
data = json.loads(line)
def check_index(index, json_file):
with open(json_file) as json_data:
data = json.load(json_data)
for i in data:
if i == index:
return True
return False
app = Flask('')
@app.route('/')
def home():
return "hi"
my_secret = os.environ['SecretCode']
@app.route('/AddBuyer')
def AddBuyer():
arg1 = request.args.get("SectretKey")
code = request.args.get("Code")
if arg1 == my_secret:
db[code] = "UNUSED"
return "asdf"
my_secret = os.environ['BuyerPurchase']
@app.route('/BuyerPass')
def Purchased():
arg1 = request.args.get("SectretKey")
code = request.args.get("DiscordId")
has = request.args.get("Has")
if arg1 == my_secret:
info = {"Hash": has}
key = uuid.uuid4()
print(check_index("7AA2984F-6AE3-4609-8619-6709C729B1FF", "hashes/hashes.json"))
LogCMD("hashes/hashes.json", info)
return "asdf"
gheres the full flask code, its still erroring
File "/home/runner/BaconHubNewBot/venv/lib/python3.8/site-packages/flask/app.py", line 1502, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "/home/runner/BaconHubNewBot/keep_alive.py", line 57, in Purchased
LogCMD("hashes/hashes.json", info)
File "/home/runner/BaconHubNewBot/keep_alive.py", line 11, in LogCMD
with open(json_file) as json_datas:
NameError: name 'json_file' is not defined
def LogCMD(file_name, data):
with open(json_file) as json_datas:
for line in json_datas:
data = json.loads(line)
look at the arguments this function takes
json_file is not part of them
so you can't reference that variable inside the actual function
this is not for python but html and css, is there any possible way in html and css to scale down an image cause im trying to make it so it looks like a logp
Current size of the image is 2048x2048
Ping if u can help
you can use <img src=... width=x height=y>
Hello everyone! My name is Helen! ๐ I'm cohosting a hackathon this month & my team and I are currently looking for someone to host a 40 min. intro to HTML/CSS workshop. This would be a great volunteer opportunity for any aspiring web developers.
My team and I would like for this workshop to ideally be held on Saturday, March 26th @ 11 am (PST). If this time is inconvenient for you, we can also try to work around your schedule. Please DM if you're interested. ๐
Does your DB have a table named "user"?
No it's empty.
having problem with google trans lib
def translate():
if request.method == 'POST':
trans_lang = request.form.get('lang_selected')
lang_to_translate = request.form.get('translate_to')
text = request.form.get('text_to_translate')
translator = Translator()
translated_text = translator.translate(text=text, dest=trans_lang)
print(translated_text.text)
return render_template('translation.html', translation_lang=trans_lang, translate_to=lang_to_translate,
translated_text=translated_text.text, text=text)```
any help
Im using Django Money in my Django Model, AUD currency. It outputs the valued with a prefix A$100,000. How do you remove the prefixes?
Im also having trouble with .aggregate(sum()) cause its not a typical decimal or int field.
Can anyone shed some light?
You can't select from a non-existent table.
How do i fix this?
You'll need to add the table and its metadata. I don't know the SQL commands off hand to do so. You might need to look those up.
What?
How?
Django question in #help-potato
how do I make the navbar more spread out and make the font larger
paste the css
A guide for how to ask good questions in our community.
hey guys, I have a flask social media / web app with a postgresql db attached & hosted through heroku. the app has a feed page where you can view all posts, but I want to make it so it only loads 3-5 randomly selected posts every day / 24hr period. what's the best way to set that sort of time delay with how my app is hosted?
Anyone know why this occurs?
i've had good luck with flask-qrcode:
https://marcoagner.github.io/Flask-QRcode/
are your environmental variables set correctly? in your .env you should have
FLASK_APP=myapp.py
FLASK_ENV=development
or set them using the CLI with export / set commands
hello there! Im new on python, how can I run python script on html?
python can't run in the browser (unless you compile to WASM)
I donโt have an .env currently but I ran set FLASK_ENV= development in windows command line
did you use command prompt or a bash shell? any sort of error come up when you entered it? & most importantly, did you enter it in the correct directory? im pretty sure you have to be in an active virtual env to execute them (not 100% sure though)
I tried both in command prompt and bash shell. My IDE is spyder, not sure if thatโs effecting it
have you read this thread? i dont use spyder so i'm not familiar, but something in here might help?
https://stackoverflow.com/questions/60210038/using-system-environment-variables-in-spyder
I donโt think I did it in the right directory Iโll try that
^ that might be dated actually, idk
``
<!DOCTYPE html>
<html lang="en">
<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">
<title>My Socials</title>
</head>
<body>
<h1>Here are three of my Socials</h1>
<ul>
<li><a href="https://discord.com/"></a>Discord</li>
<li><a href="https://www.youtube.com/"></a>Youtube</li>
<li><a href="https://www.planetminecraft.com"></a>Planet Minecraft</li>
</u>
</body>
</html>
``
Can anyone please help me,with why there links are not working??
put the </a> AFTER Discord,m Youtube and planet minecraft
@frozen ice
<li><a href="https://discord.com/">Discord</a></li>
Ill dm it to u
Thank you so much
yw
<main role="main" class="container">
<div class="row">
<div class="col-md-12">
{% with messages = get_flashed_messages(with_categories=true)%}
{% if messages %}
{% for catagory, message in messages %}
{% if catagory == 'error' %}
<div class="alert alert-danger alert-dismissible fade show" role="alert">
{{ message }}
<button type="button" class="close" data-dismiss="alert">
<span aria-hidden="true">×</span>
</button>
</div>
{% elif catagory == 'success' %}
<div class="alert alert-success alert-dismissible fade show" role="alert">
{{ message }}
<button type="button" class="close" data-dismiss="alert">
<span aria-hidden="true">×</span>
</button>
</div>
{% endif %}
{% endfor %}
{% endif %}
{% endwith %}
</div>
</div>
</main>
how can I make the alerts dismiss after x amount of time (im using bootstrap)
how do I spread out the text in my navbar
@import url('https://fonts.googleapis.com/css2?family=Oswald&display=swap');
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
body {
font-family: 'Oswald', sans-serif;
color: #333;
line-height: 1.6;
}
ul {
list-style-type: none;
word-spacing: 1000px;
display: flex;
justify-content: space-between;
}
a {
text-decoration: none;
color: #333;
}
p {
margin: 10px 0;
}
.navbar {
background-color: #6b1010;
color: white;
height: 80%;
word-spacing: 1000px;
}
.navbar ul {
display: flex;
word-spacing: 1000px;
}
.navbar a {
color: white;
font-size: 5em;
display: flex;
align-items: center;
justify-content: center;
text-decoration: none;
padding: 0 1rem;
height: 100%;
word-spacing: 1000px;
}
.navbar .flex {
justify-content: space-between;
word-spacing: 1000px;
}
.container {
max-width: 4000px;
margin: 0 auto;
overflow: auto;
padding: 0 40px;
word-spacing: 1000px;
}
.flex {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
word-spacing: 1000px;
}
'''
me?
nope...its just my question
oh
What django library do I need to be able to {% load index %} in a template?
if you want all templates to extend a base file, you need to do {% extends file_name.html %}
i dont want from django to translate specific paragraph is there any tag i can use for it?
You can use ```dislplay:flex;
justify-content: space-around
django translate stuff that i don't want to translate how i can disable that
always when i translate from en to ar django change this number from $129.80 to $129,80 how i can disable that?
I realized that I needed to build a custom filter. All is well ๐
when making an api based website is the frontend portion typically made separately and just talks to the api or is it made in the same package as the backend api? (basically is it all 1 file or 2 separate files)
I use 2
The project I'm working on rn has a front end that connects to an api but I store the API code in a separate area
ok, i had a feeling it was something like that but wasnt 100% sure
Personally I just like to keep different parts of code separate as it makes it easier to edit one or the other
my program works like pthon flask app is the front end, which communicate to python api, and api communicate to database
all 3 seperate host
that way hacker have more layer to go through
Not strictly
print(b'payload_json=%7b%22r_id%22%3a%22123123231213%22%2c%22s_id%22%3a%22435543345543534%22%7d'.decode())
@still palm
its not json response
hmm
give me a minute i'll be right back ok
@still palm
from urllib.parse import unquote
print(unquote(b'payload_json=%7b%22r_id%22%3a%22123123231213%22%2c%22s_id%22%3a%22435543345543534%22%7d'.decode(encoding="utf-8")))
!e
!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!*
!e
from urllib.parse import unquote
print(unquote(b'payload_json=%7b%22r_id%22%3a%22123123231213%22%2c%22s_id%22%3a%22435543345543534%22%7d'.decode(encoding="utf-8")))
@eternal kestrel :white_check_mark: Your eval job has completed with return code 0.
payload_json={"r_id":"123123231213","s_id":"435543345543534"}
it is url encoded
so now we decode it
np
!e
json.loads(unquote(b'payload_json=%7b%22r_id%22%3a%22123123231213%22%2c%22s_id%22%3a%22435543345543534%22%7d'.decode(encoding="utf-8")).strip("payload_json="))
@eternal kestrel :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'json' is not defined
Is it feasible to create a site with just python or would some knowledge of HTML and JS be required?
FLASK question: I have website is popping out and I want to click around it. I have a market tab that I click but it won't allow me to switch pages. It just keeps showing my 1 home page. Why could this be? I have different html files and @chrome fractal that lead to them. Both are in templates folder (Spelled exactly templates).
When I click on market tab I get a "Homepage#" symbol.
My website is running locally atm on my PC.
And actually I fixed it. Turn out I put rennder with two n's.
smh
Hello! I have built a little app to control a heat lamp for my lizard. I also built a small web app using fastAPI that shows the json data of the status of the lamps and the temperature. I am using sql alchemy as my ORM for the Postgres database.
I would like to add some HTML to make it pretty to see for the wife. What is the recommended library to slap on top of my set up? Should I just hand roll some html or whatโs the pythonic way?
You if all do not mind replying so that I get a notification I would appreciate it ๐
i dont know the most about it yet so take this with a grain of salt. but i think using a bootstrap for visuals and then hand rolling a bit of html/js yourself to communicate with your api would be the best for your case
anyone here know how to make smart contracts? dm me pls
Jinja is a good templating engine and relatively simple to set up too. It's built(?) and maintained by the same group that builds/maintains Flask, and Jinja is baked into Flask. There's docs within FastAPI to set it up too.
https://fastapi.tiangolo.com/advanced/templates/
Awesome, thanks!
I'm not sure if this is the right category, but I'm in the process of changing career paths and am hopefully going to be starting some python classes soon. I had an idea for a web-based portfolio, but I'm not sure how practical it would be to implement. I was thinking I could run a server-based python shell and then have almost like a computer file browser type "GUI" so even people who are unfamiliar with python would be able to interact with the interactive games or whatever, and those who know how to read python would also be able to read the source code of the file that is running.
Is that something that would be possible, or is that just way too complicated?
I've tried looking for some sort of python interpreter for a website, but all I've really found is people who I guess have written their own and deployed them. Not ones where I'd be able to incorporate it into my own website
I am planning to start learning web development. Need some guidance on how to start
This a really easy question probably, but I am still kinda new to html/css. I got 3 boxes here, but I want them all next to each other if you getme.
!paste
try to put them in a list:
<ul>
<li></li>
<li></li>
<li></li>
</ul>
How do I do that in my case, I'll send my updated code in 1s
!paste
@covert yew https://paste.pythondiscord.com/potorikojo
<ul>
<li>first item</li>
<li>second item</li>
<li>third item</li>
</ul>```
Yeah but how do I apply this here?
I just wait 3 divs next to each other
Not really lists
Shouldn't it be something in the css just to get the divs next to each other?
after that you write in the css to display them how you want
Yeah that's the whole point
I don't know how to do that
.square {
border-radius: 25px;
background: #23272A;
padding: 20px;
width: 500px;
height: 400px;
margin-left: 100px;
vertical-align:top
}
.square2 {
border-radius: 25px;
background: #23272A;
padding: 20px;
width: 500px;
height: 400px;
display: inline-block;
vertical-align: top;
}
.square3 {
border-radius: 25px;
background: #23272A;
padding: 20px;
width: 500px;
height: 400px;
display: inline-block;
vertical-align:top
}
I got this now
Now there are the dots from the list as well
pretty sure you could just use display grid and align them next to each other
@covert yew can you remove/change the Discord invite link in your code snippets before pasting. You're triggering our filters.
So how what do I do in my css then?
@native tide
my bad sorry
good now?
hello i am new to python and have completed the back end work for my code however i have no idea how to approach the front end side of things can anyone help?
yes holdup
ya
!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.
you can also check on roadmap.sh
is there a reason to use ModelSerializers (django rest framework) for InputSerializers
If u a going to save deserialized data in db, and u wish to avoid code repetition, then yes
i dont think reading a list of fields is pleasing for debugging purposes
also for maintenance either**
Just press right click at model class written in serialiser, to be teleported to original model.
This point is invalid
fair, im reading a stylesheet and it advises against modelserializers
but it can be used if it works
naturally, ill just do modelserializers then
also ill need to find a way to make a hyperlink to another URL from a service
but thats something i think i found a solution to
https://paste.pythondiscord.com/imiduforon someone help trying to split image into 100 vertical sections and save each section as separate image but image saved at end is same image as inputted
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="{{ url_for('views.home') }}">
<img src="{{ url_for('static', filename='images/logo.png') }}" width="60" class="d-inline-block">
Testing
</a>
<button
class="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#navbar"
>
<img src="{{ url_for('static', filename='images/icons/menu-burger.png') }}" width="15">
</button>
<div class="collapse navbar-collapse" id="navbar">
<div class="navbar-nav">
{% if user.is_authenticated %}
<a class="nav-item nav-link" id="home" href="{{ url_for('views.home') }}">Home</a>
<a class="nav-item nav-link" id="user" href="{{ url_for('views.dashboard', username=user.username) }}">
<img src="{{ url_for('static', filename='images/icons/user.png') }}" width="15">
</a>
<a class="nav-item nav-link" id="user" href="{{ url_for('auth.logout') }}">
<img src="{{ url_for('static', filename='images/icons/sign-out.png') }}" width="15">
</a>
{% if user.permissions == 1 %}
<a class="nav-item nav-link" id="admin" href="{{ url_for('admin.admin') }}">Admin</a>
{% endif %}
{% else %}
<a class="nav-item nav-link" id="login" href="{{ url_for('auth.login') }}">Login</a>
<a class="nav-item nav-link" id="signUp" href="{{ url_for('auth.sign_up') }}">Sign Up</a>
{% endif %}
</div>
</div>
</nav>
how can I make the user, logout icon go to the right side of the nav bar
Using Bootstrap?
What framework are you using?
yes
None actually Demi it's just raw code at the moment
You'll need some kind of web framework to get setup. You can do one of two things:
- Pick a templating framework like Django or Jinja to use simple backend Python and html/css/js on the front-end all built-in to one framework.
or - Use any Python framework, Django, Flask, or FastAPI recommended, to create an API. Then create the website with a front-end framework (React, Angular, Vue, etc.) to make calls to the API for the needed data.
#2 is more advanced but is also the more standard way of creating web apps these days.
basically how would you authenticate that the user that made an order is logged in the website?
so random "hacker" couldnt spam the api
guys is there any free hosting other than heroku,replit,pythonanywhere to host my discord bot and website?
you won't get a free host that is reliabke
you can host discord bot on vultr which is a VPS. it is extremely cheap
host website on heroku
ping me when replying
You could always buy a old laptop and run it on that.
yeah but i dont want fbi to search my house for a nuclear bomb
django i can't get my tests detected, even if the app is detected, and the test file is named tests.py, and the class using TestCase, and the test function itself begins with "test" in its name
using django 4.0
DigitalOcean is cheap and good quality.
It's worth the $6/mo
def login(request):
form = forms.LoginForm()
if request.method == 'POST':
form = forms.LoginForm(request.POST)
if form.is_valid():
user = authenticate(username=form['username'], password=form['p'])
if user is not None: # user != null
login(request, user)
else:
return "Username or Password Are Incorrect"
return render(request, 'Account/login.html', {'form' : form})
Why it gives me this error in the screenshot and it is a login not a register?
What are you fetching from the forms JSON / Dict? and how are you checking the returned object for the correct password? Right now it looks like its just fetching the username in the password portion of the form.
password=form['username']
fixed it, but it gives the same error
password=form['password']
have you tried printing what it returns to see if its getting what you expect?
ik know its a bit of an obvious question. But i have to ask ๐คฃ can't tell you how many times i've found my answers that way lmao
what variable exactly
username and password
print(form['p']) and print(form['username'])
even the returned "user" from authentication.
print(user)
print(form['username'])
print(form['password'])
printed nothing.
after submitting ofcourse
However putting the code block outside form.is_valid()
gives me this error
Each thought it was WTFormsField has a data attribute with the value submitted. So you probably want form['username'].data
Also if you're using WTForms, you can access the fields via attributes instead of the dict-like syntax you have. For instance if you created a username attribute for a field, you can do thought it was WTFormsform.username; saves you a few characters ๐
also you should use cleaned_data https://docs.djangoproject.com/en/4.0/ref/forms/api/#accessing-clean-data
tried this
def login(request):
form = forms.LoginForm()
if request.method == 'POST':
form = forms.LoginForm(request.POST)
if form.is_valid():
user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'])
print(user)
print(form.cleaned_data['username'])
if user is not None: # user != null
login(request, user)
else:
return "Username or Password Are Incorrect"
return render(request, 'Account/login.html', {'form' : form})
nothing worked
it still gives me the same error
what does your template look like?
I guess seeing your LoginForm class would also help
is there a name for this type of json-esque structure? just editing the upstream application configs instead to use a json converter{key=value} i'm trying to find a way to json.loads it but it's obviously not json
dictionary/hashtable/hashmap
well i'm trying to get it into a dictionary, but right now it's a string that i'm trying to do somethiing like json.loads with
if i must reemovee brackets and split by comma, then equals, so be it--but if there's a standard way of doing it that's better
parsing can get quite complicated
can you share code with minimal example for what you're trying to achieve?
You can use numpy/pandas, or yes, you'll have to get very specific with manual text manipulation how you want it.
sorry, i'm not understanding--there is a numpy and/or pandas function for taking sorta-json-like shapes with arbitrary missing quotes or separators, and coercing those strings into json a la json.loads?
I'm not entirely sure. I know that they can be used for text manipulation but I never did so.
I generally stick to building my own functions to do it.
there is a numpy and/or pandas function for taking sorta-json-like shapes with arbitrary missing quotes or separators, and coercing those strings into json a la json.loads?
I'm pretty sure, there's not
!warn @torn roost This is not a place to advertise your YouTube channel about JavaScript
:x: The user doesn't appear to be on the server.
๐ฟ
Anyone know how I would go about doing this?
I want to add a hamburger menu to the left side of my nav bar, away from the navigation links
what's the difference about post and put?
can you give an example in apis
Hi! Just recently started learning Django, and a lot of emphasis seems to be on the fact that itโs a back end tool
Is it best to use Django in conjunction with a front end system? Doesnโt Django handle that kind of stuff?
With templates and whatnot
i mean django itself cannot do any front end stuff, other than getting data in and out of the front end
youll need to know some basic frontend if you want to make an actual website with it
Hmm ok thanks 
Django gives only really limited frontend support
It gives only templating language
Real Frontend Frameworks unleash full power of javascript
To make interactive website/app without rerendering
Ahhh I see
Because I thought templates were like front end designs
But I get what you mean, thanks!
More than half of frontend features are tied to JavaScript
Django gives u ability to use only vanilla js, which is really awkward for that
It is possible to add JQuery(vanilla js on steroids)
Or even static linked vue.js frontend framework into Django templates
But it is all half measure perversions
By vanilla js you mean like standard CSS and HTML formatting right?
Orโฆ I donโt know Iโm still new ๐
https://youtu.be/cuHDQhDhvPE
This would be the best video to explain
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...
this shows making interactive simple application without page rerender
(Btw, in my opinion there is choice only between React / Angular / Vue.js )
all other frameworks aren't deserving to be used ;b
Thanks so much!
they show how to do the same in vanilla js too there
Iโll keep it that in mind ๐
purely because React/Angular/Vue.js trio are occupying 98% of the market
their ecosystem is rich and having solutions for all common problems
stable to be used
That would be a good start to grasp CSS basics
https://mastery.games/flexboxzombies/ + https://cssgridgarden.com/ will explain the rest of tools in game format
Hi can I use a python lib as an API for users to communicate with my app ?
here is my full code:
https://codesandbox.io/s/wandering-grass-7e3qlx
- How to always have the logo_img in the middle of the header? + What is the best way to do that?
- How to use an image as the background of the header
Can anyone help me plsss?
Choose a framework and learn how to use it.
Start with FastAPI if you don't have a preference. The main alternatives are Flask and Django.
guys, is there a way to handle two different forms (in a html template) inside one and the same endpoint?
I have one where I'm listing my flashcard sets. Also, on the same template I have two modals with two different forms - one to create a set and one to change its name.
I'm having problems figuring out how to approach this properly. My endpoint is only contructed for listing my sets, but since I'm using two different modals, I can't create another endpoint just for editing the name.
@views.route("/sets", methods=['GET', 'POST'])
@login_required
def sets():
user = User.query.filter_by(id=current_user.id).first()
seth = user.sets
if request.method == 'POST':
set_name = request.form.get('setname')
if not set_name:
flash("Can't be empty", category="error")
else:
new_set = Set(name=set_name, user=current_user)
db.session.add(new_set)
db.session.commit()
flash("Set added!", category="success")
return redirect(url_for("views.sets"))
return render_template("sets.html", seth=seth)
{% for set in seth %}
<div class="setlist">
<div style="display: flex">
<div><a href="/flashcards/{{set.id}}">{{set.name}}</a></div>
<div style="position:absolute; right:300px">Created on {{set.date_created.strftime('%d-%m-%Y')}}</div>
<div style="position:absolute; right:250px">
<div class="dropdown">
<a href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fa-solid fa-pen"></i>
</a>
<div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
<!-- <a class="dropdown-item" href="/change-set-name/{{set.id}}">Change name</a> -->
<!-- <button type="button" class="dropdown-item" data-toggle="modal" data-target="#updateModal">Change name</button> -->
<a class="dropdown-item" href="/delete-set/{{set.id}}">Delete</a>
</div>
</div>
</div>
</div>
<div style="height: 1px; width:100%; margin-top: 10px; background-color:#B6A2A2"></div>
</div>
{% endfor %}
this is where I'm inputting the name of the set
<!-- Update modal -->
<div class="modal fade" id="updateModal" tabindex="-1" role="dialog" aria-labelledby="updateModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" style="font-family: Play;" id="updateModalLabel">Change set name</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="POST">
<div class="modal-body">
<div style="display: flex; justify-content: space-evenly;">
<input type="text" class="inmodalinput" name="updatesetname" id="updatesetname" placeholder="Change set name">
</div>
</div>
<div style="text-align: center">
<button type="submit" class="add_new_button">Save new name</button>
</div>
</form>
</div>
</div>
</div>
and this is the modal for updating the name
it shows up properly, but does not work, because I don't know how to hand out said set's ID to the endpoint
You confused me somewhere.
Btw yes, it is possible to use same endpoint multiple times
There are GET, POST, PUT, DELETE and etc methods
Usually get used to view
Post to create
Put, update or patch (not remembering which one) to update
Delete for delete
the problem is that I'm using one endpoint with two different forms and the second form is outside of the loop where I'm listing my flashcards (because it is in modal)
and since it is outside of this loop, I have no access to any given flashcard's id, which then I'm unable to give back to the endpoint
it would help if I could access said flashcard's ID in this modal, but then I would have to loop it in this modal, which I guess doesn't work
then the problem is, that my endpoint 'sets' does not accept any variables
so I don't know how could I amend this, because just for listing the sets, no variable is needed
well, it actually is, but I retrieve it by using "current_user.id"
but for modifying any set, this variable is then needed
this is my first project that I'm doing on my own, with no direct help of any tutorials, that's why my logic is skewed ๐
I think I've built too much on it and now don't want to go back, hence looking for solutions to that problem
there is no UPDATE request. PUT replaces the target resource while PATCH only makes a partial update on a resource.
๐
function like(postId) {
const likeCount = document.getElementById(`likes-count-${postId}`);
const likeButton = document.getElementById(`like-button-${postId}`);
console.log(likeCount.value);
}
<li class="list-group-item">
{% if user.id in post.likes|map(attribute="author")|list %}
<img
src="{{ url_for('static', filename='images/icons/heart_b.png') }}"
width="15"
id="like-button-{{post.id}}"
onclick="like({{post.id}})">
{% else %}
<img
src="{{ url_for('static', filename='images/icons/heart.png') }}"
width="15"
width="15"
id="like-button-{{post.id}}"
onclick="like({{post.id}})">
{% endif %}
<span id="likes-count-{{post.id}}">{{ post.likes|length }}</span>
</li>
when I press the button it shows on the console undefined
thanks
Anybody know why my font awesome icon imports into my html file looking like this?
It's supposed to be a hamburger menu
<i class="fa-solid fa-bars"></i>
Yeh so I put in 2 other ones and both showed up perfectly
What version of fontawesome?
I have the free version
number version
What browser?
I'm using Google Chrome
Wait I got it to work
That was weird
If you're curious to know how I fixed it check out this link
But you had fa-solid
I'm not sure why it worked, I just put "fa" in front of fa-solid and the icon showed up
you are required to have "fa" class on all font awesome icons
it is base class for icons
question, how do I troubleshoot my 403 forbidden error when accessing the static folder from docker
what OS? what is framework/server is delivering the page?
im running a dockerized flask on ubuntu
its via uwsgi
drwxrwxrwx 2 root root 4096 Mar 15 13:10
changing my entry point to flask run instead of wsgi seemed to fix the issue. Could this be something with wsgi and docker?
anybody know why when I try to run a fastAPI project with uvicorn it would not detect that I have bcrypt installed?
does anyone have a better solution to this
if User.objects.filter(email=email).exists():
raise ValidationError('Email already registered')
elif User.objects.filter(username=username).exists():
raise ValidationError('Username already registered')
what is the easiest way to host a server ?
I'm trying to create an clear all button for a to-do list but the button isn't working. I suspect the issue is in the JS code. My list looks like:
<li class="list">
<input type="button" class="done" onclick="markDone(this.parentNode)" value="✓"/>
<input type="button" class="remove" onclick="remove(this.parentNode)" value="✕"/>
<input type="button" class="imp" value="!" onclick="important(this.parentNode)"/>
Make to-do list
</li>
</ul>```
followed by the button:
```<input type="button" id ="clear" value="Clear all tasks" onclick= "clear()"/>```
Then the JS:
```function clear() {
document.getElementById("tasks").innerHTML = "";
}```
readability is sometimes preferred over an elongated if statement
hi, which book can u recomended to improve python?
youtube
Whats the easiest way to transfer all your commands to slash
hi
Hey
is there a webdev deployment channel somewhere?
that's here
deployment might be in #tools-and-devops but we can help here
Ah deployment
grr
No clue sorry
I might ask in another server potentially
Reverse proxy isn't working and I don't know why - it's as straight forward as I can make it
It was working for a hot minute and then not
hi
you need to get that food list in a database?
im trying to link a webhook with my Nolt page. when i try to link the webhook via Nolt it returns error 400. any ideas as to the cause?
(I've put in both the Endpoint URL and Verify Token on the Nolt side)
anyone know why my fontawesome icon won't show up when I open a live server?
<div class="menu">
<a href="#"><i class="fa fa-solid fa-bars"></i></a>
</div>
do you have the link to the fontawesome stylesheet?
@slate narwhal <link rel="stylesheet" href="https://cdnjs.cloudfare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"> I used this in my index.html with no success, so Im hoping for a similar solution as mine dont show up either.
Hey all anyone know of a good status page that can ping servers and websites and return green for good yellow for warning etc ?
Ideally using Flask
I will suggest using Django
it makes what you wish out of the box with its Django Admin feature
But in reality, in reality
you are reinventing the wheel
You are actually needing prometheus to use
it will be trully simple solution for monitoring out of the box
it can do more than returning just green and yellow for pinging
it will also allow you easily configuring alerts for my more things
django is really great
someone know how can I bootstrap alerts dismiss after x amount of time
I use selenium and i want when open the second window i will get data if data is more than 1 it will close second window and it will open the window and get data again
can i use oauth to login/logout people in django, or is it not intended for that
OAuth is for authentication
its for 3rd party authentication
so, to login, it will be useful, but not sure about logging out..
If you want social auth, login with Google etc, check out django-allauth
no it isn't
its an upgraded phpmyadmin that people try to hack into a user dashboard
@unique shore tell me i'm lying? ๐
it's fairly secure. not sure how it would be insecure; plus it's customize able and you can easily hide the admin url from potential attackers
i'm saying its overall usefulness to your project outside of being a dev tool
@wooden ruin I did not mean hack from a security perspective
[Hiring][Remote][Anywhere]
We are planning to make big e-commerce platform so we need expert python(Django) developer.
Because of the large project scale, if you want to join, You have to pass a small test.
IF you are interested, please DM.
Hi Folks. I'm learning django, and just noticed a lot of people use the following pattern:
try:
some_model = SomeModel.objects.get(...)
except SomeModel.DoesNotExist:
# some_model is None
I want to know, is this a Pythonic way of writing code? (I come from Rails and I prefer the exists get/first pattern, but if this is the Pythonic way, then I can get used to it)
it is python enough, but I would recommend alternative solution to consider first
some_model = SomeModel.objects.get(...)
if some_model is None:
# Handle not found situation
applying some_model somewhere
it has a bit better taste i think
My personal taste goes that way too. Thanks Darkwind!
u a welcome. Take a special notice that the normal flow of the code continues without identations
we handle only extraordinary flow with identation. We specifically reverse if situations to avoid going identation deeper
which keeps happy path on the left
...it is actually Golang enforced rule as far as I discovered
and it makes some sense.
ops.
It could use some further explanation though
i wanted to show someone my website as i do need more tips on how to make it better
Or it could be a plot, to advertise the project by asking the tips
just kidding.
lol
there is time for simplicity, and there is time to go full scale war
at least CSS transitions/animations could be used to make it more flashy
recommending this book
as a full scale war, I would recommend to use frontend framework, like Vue.js (or React)
Vue.js has specifically more room for animations
and setup SCSS for that, it will make writing the CSS easier (SCSS comes with frontend frameworks setup instruments like Vue Cli 5)
you can setup SCSS on your own too though. it does not require to have frontend framework
with frontend framework you will have ability to animate in any way you wish you every step
CSS/SCSS will make transitions/animations all around with more lightweightness though
and less effort
so learn CSS/SCSS features first
example of little transition. It is just pure CSS
https://shapevpn.com/ check the Vultr button, hover your mouse over it
ShapeVPN provides WEB GUI to install Wireguard as a self-hosted VPN to Ubuntu 20.04 server.
How do you make animations on css, sorry im new
@mixin hovering-scale() {
transition: transform 0.5s ease-out;
&:hover {
transform: scale(1.03);
}
}
the transitional animation on hover which I did at the web site, are just those code lines
oh hover to scale the object)
read the book I provided
it covers the topics pretty well
Okay
this book?
@feral widget this book
I was accepted into a web dev bootcamp (Launchcode). I currently work in data analytics and data science but have been interested in web dev. This program is free and I would only be doing this "for fun" meaning I am not looking to change careers, but mainly want to learn new things. Worth my time?
@timid parcel I have never seen much try's for checking if data is there
and I've seen alot of django
also why django over rails? Usually don't get much cross play in django
new job
that will do it
many people say they are similar but I think they are very different
I've seen some big django projects that was 20 files, I've seen small rails projects that were 3,000 files
I have worked with Laravel, Rails and Django. And Django is way different from Rails/Laravel.
agreed
Or we could say that every framework from the late 2000 is the same, since they all use some kind of mvc architecture with a lot of other patterns 
I have found for whatever reason simlar projects end up bigger in rails
more files for sure
the ORM used to be quite different , today more similar
But the file count is just a trade-off. In rails you have 30 files with 80 lines each one, in django you end up with 1 model file with 2000 lines. (or whatever other mix up from the amount of apps you create)
what is the proper way to use CSS when using react in a django project with webpack and babel? im getting npm errors like ```Missing semicolon. (1:4)
1 | body {
| ^
2 | background: gray;
3 | }``` when importing import '../styles/sidebar.css'; in my react script.
i installed and added this to my webpack config { test: /\.css$/i, use: ["style-loader", "css-loader"], }, i dont even know if its possible but do i import my css into the normal base html page?
it appears that it just works by putting it in the html page that react is targeting, but is that the 'proper' way of doing it?
that or should i just be putting my css in the react file itself....? so many different ways ๐ฆ
this is relatively flask related but i have an image uploader for sharex built in flask and was wondering how i could allow mp4's to be uploaded?
i can actually upload mp4s through sharex but it gives me an internal error
thats all my code
Guys I need help with docker and flask where should I go?
Flask would be here. Docker prolly in #tools-and-devops
@unique shore Thanks I'll check it out I mainly need help with setting up docker with flask and psql, though I think I found most of the solutions I need just by searching in the search bar.
is it worth it to learn django when i already know flask?
sure, but you should probably find a niche stack and roll with it
hey guys, can someone help me with PyCharm Integration in open edx devstack? I'm following this documentation https://github.com/mitocw/edx-platform/wiki/Setting-up-PyCharm-for-edX-development but when I try to find python interpreter /edx/app/edxapp/venvs/edxapp/bin/python I can't find it in my IDE
is it possible to send 3 file inputs in one form or atleast all in one request?
I am using django rest framework to make an api, and I have a generate token stuff https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication
- is it possible to refresh the token?
- if so how
Advice for an easy first project with HTML/CSS that isn't a portfolio? I'd like to make a portfolio after I have a couple projects to include in it.
im just so mad bruh ๐ IT DOESNT LINE UP IT MAKES ME FURIOUS
im not good enough at front end to make it line up tho ill have to live with it
smh
maybe imitating a website you know of?
i know when i was learning it i once imitated this one resturant website's front page
I think I know why
It's because you just set it to the middle
The whole line
I dont think its the right channel for that
how do I unzip a zip file uploaded via the django admin, and access the sub files in it?
can you help me with this? the documentation doesn't seem very clear
whats unclear?
check ZipFile.open and ZipFile.extractall
there are code samples
yes, got it
does anyone know why this payload is encoded? and how to decode? its surely not in base64
hii, any idea why the image are not loaded?
if I click on the src path, it takes me to the image, so the path is correct, but it won't rendered on the page
P.S. I m using django and these are uploaded files via admin panel (if this helps)
What's the Content-Type header?
you sure it's not just compressed?
What do the headers say?
are u using a server ? like vscode's live server ?
also check networks tab in your browser's dev tools
I think it has something to do with the storage you're using, if you're using compressed manifest them it won't work
yes, I m running through a server
i uploaded a zip file and then through ZipFile module I unzipped it and rendered the html file present in it with the screenshots..
not loaded
it works if I specify the path as
src = ../media/Delhivery Limited/out/screenshots/https___www.example.com.png
but src="out/screenshots/https___www.example.com.png" should also work as they are in the same folder, but it doesn't work
Read file
JSON load it into js object
Open file
Write the columns in the file, with using as delimiter , or ;
Done
the thing is
i have a list of dictionnaries
from a scraper
do i need to convert the list to json object first?
@inland oak heres the json
"name" :
"year" :
"rating" :
"genre" :
"description" :
}
Aight
from aiohttp import ClientSession, TCPConnector
from asyncio import get_event_loop
from ssl import create_default_context
from certifi import where
async def test():
ssl_context = create_default_context(cafile=where())
conn = TCPConnector(ssl=ssl_context)
async with ClientSession(connector=conn) as session:
async with session.get('https://python.org/') as response:
print(response.status)
file = await response.text()
print(file)
get_event_loop().run_until_complete(test())
why do i get this warning
- DeprecationWarning: There is no current event loop get_event_loop().run_until_complete(test())
you arenโt supposed to have a />
itโs just >
for img
They r commonly used ones
Not sure, acc to me its encoded/compressed
No, actually check the content type. What is its value?
Whats the headers in general
Should i tell tom? Its midnight here for me, i ll just xopy paste the curl command here ok?
Or i occupy a help channel
can anyone help me with an apache server im trying to setup?
I'm also monkeying around with servers, poorly, so shoot your shot
so im trying to setup a home page and i just downloaded a template and uploaded the folder to the root directory
Knight is a beautiful Bootstrap 4 template for product landing pages.
here is the demo
but the colors on the website i have won't show up only the html
this is how it shows up
do you know what css is?
ok
thats a paid service, not going to be the strongest start for you right now I think
css is paid?
that SO post isn't quite related but might help
i know nothing about python
ok ill look at it thx
no, that site is part of a paid service, might not be appropriate for a beginner. in any case you are needing to look up how to import your CSS into your HTML. good luck friendo.
i dont think it is paid
when i download and ran the html file on my computer it ran perfectly
all the files are free
when I scrolled down the first thing I saw was a pricing plan you know?
thats part of the demo
this is the download
anyway, the important bit is you're gonna end up needing something like this
<link rel="stylesheet" type="text/css" href="/public/css/style.css">
to incorporate the CSS. If you don't know CSS or HTML it might be good to try and find a tutorial on those topics? sorta depends on how comfortable you are with programming already, I guess I'm assuming you're new
go look up what an anchor element is
woof, sorry, I wish I had a resource off hand to suggest to you, wouldn't mind doing a dive on some web fundamentals myself
did it work?
oh whats that?
some thing that renders the css onto the browser
here is where i found about it
are you confident that the href is pointing to a real file?
Flask completely crashes the entire site when a certain browser goes to it. It then endlessly loads until I completely stop the application and start it again. Anyone know how to fix this?
i just fixed it incase you wanted to know what i did
so i was using a amazon linux instance in ec2 and for that you need to install lamp
im guessing its a version of apache
so instead i installed apache on ubuntu
now it works!
What browser?
Some mobile ones. I canโt pin down which ones
Do you have a traceback?
No thereโs no error or anything
In having an error with flask.
Im trying to connect a html file.
Python.
you need to call render_template from the flask package
Ok.
from flask import render_template
This?
from flask import Flask, render_template
app = Flask("app", __name__)
@app.route("/")
def hello_world():
return render_template("index.html")
Not working/
from flask import Flask, render_template
app = Flask("app")
@app.route("/")
def index():
return render_template("index.html")```
my bad, it should be Flask(__name__)
Ok.
and templates should go in the templates folder.
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")```
Looks good?
Yes. Did you put your html files in the templates folder?
Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if itโs a package itโs actually inside your package:
templates/index.html
๐
Is express compatible with Python?
express is javascript
Ik.
What are you trying to do?
Then why are you asking about javascript?
No, express code is not compatible with python
Alright.
It doesnt work.
Oh ok.
or you can set the env var FLASK_APP=main
Ok.
hi I am making an api
and I want the clients to be able to make an account in my api but hwo do I make that ?
I want to prevent stuff like spamming, automatin
hi
i need help
im getting not null constraint failed error
i
n django
anyone help pls
help, I don't know what went wrong
here is my configuration
I'm trying to follow this documentation https://github.com/mitocw/edx-platform/wiki/Setting-up-PyCharm-for-edX-development create a debug configuration for LMS server
please help
Hi! Pretty new to django so im probably missing many technical terms for the stuff i need.
Im making a todo list app and im using CreateView to add new tasks to the list with <a href="{%url 'task-create' %}">Add</a>
But this sends me to a new page to create the task, what do i use to create a task/edit it in the same page?
I am trying to center a carousel horizontally and also my next and previous buttons are not working can anyone help me with this
i probably asked the wrong question
what do i use to make a text input with an add button that adds an item to an already printed list?
xD
Lol dude
school homework
<a href="Aller en haut de la page" โ nawak
like ,this ?
and that's at the top of the page
so like
<h1 id="haut_de_page">
(au fait l'orthographe c'est pas trop รงa LOL)
Then
<a href="#haut_de_page">Aller en haut de la page</a>
โโโ and then it works straight
blam blam
lemme try
Same for your "go to bottom of page" โ I think you should do it with your signature
<p id="bas_de_page">Deniz</p>
why not h1 this time ?
then <a href="#bas_de_page">Aller en bas de la page</a>
it's not the H1 that matters
it's the fact that you're giving it an id
oh
Excellent ๐
if i have to put it as a website
i should do <a href="website link i have to put">
right ?
lol yes totally, but you should give a proper example
<a href="google.com"> โ generally no
<a href="https://google.com"> โ yup
I mean yes, but that sounds like an issue in the first place
Like, notepad, really? Not even notepad++? ๐
oh
nvm
it is notepad++
you got syntax highlighting
good good
yes, my bad
haha
lemme try with another website i have to create
thanks for your help sir
much needed and appreciated
Anyone ?
No worriez hahaha, that's what I'm currently here for
@hybrid pilot i have another question if ur available ofc
: D
how can make my texts blue
font blue
i successed writing the title in red but idk how to make font of the texts in blue
Hahahahaha
It shouldn't be much different
p {
color: blue;
}
Excellent ๐
Any suggestions for react server guys ?
Hi, is there any way to make a page, where on the same view has more than one app with django?
you mean you want to use a view on multiple apps ?
if you meant this ,there is a quot i've read before
no, 4 example, I have an app of a chat, and another for posts of a online store, and I want to have one side to the other one on the same page
or wait.... I didn't see what you wrote
oh!
ok i'm gonna repost it
"A django app doesn't really map to a page, rather, it maps to a function. Apps would be for things like a "polls" app or a "news" app. Each app should have one main model with maybe a couple supporting ones. Like a news app could have a model for articles, with supporting models like authors and media.
If you wanted to display multiple, you would need an integration app. One way to do this is to have a "project" app next to your polls and news apps. The project app is for your specific website- it is the logic that is specific to this application. It would have your main urls.py, your base templat(s), things like that. If you needed information from multiple apps in one page, you have to have a view that returns info from multiple apps. Say, for example, that you have a view that returns the info for a news article, and one that returns info for a poll. You could have a view in your project app that calls those two view functions and sticks the returned data into a different template that has spots for both of them.
In this specific example, you could also have your polls app set up so that its return info could be embedded- and then embed the info into a news article. In this case you wouldn't really have to link the apps together at all as part of your development, it could be done as needed on the content creation end."
So if I have a flask socketio app, that has different rooms
Whatโs the best way to deploy a scalable version of it?
I was thinking App Engine or Cloud Run
But thought I should ask others for advice first
Hey, guys !
hi guys i need a little help please
i have added image in carousal but in output its shows nothing
<div class="carousel-inner mt-3">
<img src="pic1.jpg" width=900 height=400 class="d-block w-100" alt="...">
</div>
Any server specially for flask ?
any element on top of this <img> and its <div>? check the relative image path first. make sure the image is in the same folder as that render/html file.
the images is in same folder
but when run that code with live server its showing the image
but i'm working on django
well, if it shown successfully in the browser. did you mean it doesn't show it the IDE/Editor preview?
Hello all, just wondering if anyone has gone through this course? Iโm interested in doing an API dev beginner course and this seemed like a good start.
Learn Python API development in one of the most comprehensive courses ever on the topic. You will build a full-fledged API in Python using FastAPI. You will learn the fundamentals of API design including routes, serialization/deserialization, schema validation, and models. You will also learn about SQL, testing with pytest, and how to build out ...
I see, your server current directory isn't set to the working directory where the render and image file in. the current working directory is /home/. in that project setting, change the working directory to where your file are
Okay got it
Briefly checked the video/course: It uses FastAPI (which is one of the best python frameworks for web development right now), covers sql basics, sqlalchemy, testing, authentication, docker, github actions
it looks very solid
Awesome. Iโm going to start it tomorrow first thing
hey guys
my css file is not working with my html file
help
welp
this is my first time using css liek this
so i have no clue wut is wrong
both are in same folder btw
Hi is this a good place to ask an unspecific django question..?
I just wanna know why the generated settings file is missing the USE_L10N setting in django 4.0. I have used multiple 3.x versions, and they all had that setting.
You need to include the css file using the link element.
You're welcome.
@plush bloom I saw your message about background image - you should use url
https://developer.mozilla.org/en-US/docs/Web/CSS/url
<link rel="stylesheet" href="(filename).css"/>
put this in the head
thanks both of you
np
i am only 14 but i love python django
๐
the best web dev platform
bruh i only know django
check out FastAPI
i built a website for my school with it
okay i will
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
sorry
oh, thank you very much <3
pip install django
` import pandas as pd
import folium
import glob
from ipywidgets import interact, interactive, fixed, interact_manual, Layout
import ipywidgets as widgets
from IPython.display import display
import datetime as dt
all_files = glob.glob("*.csv")
li = []
#function to make a color code for distance
def color_producer(total_distance):
if 4100 < total_distance < 4300:
return 'green'
else:
return 'red'
map = folium.Map(zoom_start=14, control_scale=True,tiles='Stamen Terrain')
def change_parameters(start ,end ):
for filename in all_files:
date1 = filename.split('_')[1] #split filename to name and date
date1 = date1.replace('.csv','')
date2 = dt.datetime.strptime(date1, "%Y-%m-%d")
if start <= date2 <= end: #compare the file if it falls within the range
df = pd.read_csv(filename, index_col=None, header=0)
li.append(df) #append to the list
car_location = pd.concat(li, axis=0, ignore_index=True)
total_distance = pd.concat(li, axis=0, ignore_index=True)
car_location = car_location[["Latitude", "Longitude"]]
total_distance = total_distance[['total_distance']]
total_distance = (total_distance).iloc[-1] #To read last value in "total_distance" column
total_distance = int(total_distance)
folium.PolyLine(car_location, color=color_producer(total_distance), weight=3.0, opacity=1).add_to(map)
li=[]
map
start_date = widgets.DatePicker(
description='Start Date',
disabled=False
)
end_date = widgets.DatePicker(
description='End Date',
disabled=False
)
widgets.HBox([start_date, end_date])
out = widgets.interactive_output(
change_parameters,
{'start': start_date,
'end': end_date
}
)
ui = widgets.HBox(
[widgets.VBox(
[widgets.Label(), start_date, end_date])
],
layout=Layout(display='flex', flex_flow='row wrap', justify_content='space-between')
)
display(ui, out) `
Can anyone help me with this
I am able to take input but canโt generate plot
Guys guys., how do I build a url for an endpoint within the app and not a template, for example
return {
"Original_url": _u[0]['original_url'],
"Short_url": url_for(_u[0]['short_url']),
}
This is currently inside a file as utils.py and I import the class from utils to my app.py and I wanna build the url for short_url which is just a bunch of random characters
(flask)
i love 
What foilum is used for
I need help setting a background as fixed. I need my main background to stay in the front while the second background is fixed but behind all other things.
<!DOCTYPE html>
<html>
<head>
<title>Website Name</title>
<style>
body {
flex-direction: row;
background-color: lightgray;
background-image: url("https://cdn.wallpapersafari.com/33/64/GOTJrK.jpg"), url("https://th.bing.com/th/id/R.918f3ac1a08bacf7d20e2dee91f01200?rik=ndQ9LzejBLRGZw&riu=http%3a%2f%2fgetwallpapers.com%2fwallpaper%2ffull%2f9%2f3%2ff%2f1192687-desktop-wallpaper-space-theme-1920x1200-720p.jpg&ehk=KhsqY%2bMiBIYek%2bEZWqcWuyvzja3W7xtyWJEzm1HPGCs%3d&risl=&pid=ImgRaw&r=0");
background-repeat: no-repeat;
background-size: 100%, 100%;
position: absolute,fixed;
}
</style>``` The images and everything are just placeholders off google and will be changed in the final product
The forest picture is the front background
There is a space themed one behind it but I cant seem to get it to become fixed so that when you scroll down it follows your screen
To plot geo data on maps
transparency?
wdym?
No I mean I want it so that the space theme (that is currently behind the forest picture) to show when you scroll down
"fixed" to your screen
Dang
yeah but where do I place it?
in the <body>
Hold on let me try it
I knpw
HTML
<div class="hi">
CSS
.hi{
color:red;
}
But the problem is that when I set it at "fixed" it overlaps everything else
my navbar is under it now
position: sticky?
as sticky when I scroll down it doesnt follow my screen
am I using sticky wrong?
not sure
with position fixed you can adjust it by using bottom, right, width etc u know that right?
so maybe z-index
is the key
z-index: 1 is infront but if we use z-index: 2 that comes infront
I tried z-index
a
but the navbar wouldnt move infront
Im thinking ill put a masked version of the front image and set it as z-index 1 then put the space theme as z-index 0
but I dont think the navbar will show
you can try
I have to go Ill figure it out later XD
u got this
Thanks
I got it!!! XD
Anyone know why my sidebar menu isn't taking up 100% of the top and bottom space in my website?
Here's what it looks like right now
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home_view(request, *args, **kwargs):
print(args, kwargs)
print(request.user)
return render(request, 'home.html', {})
def contact_views(request, *args, **kwargs):
print(args, kwargs)
print(request.user)
return render(request, 'contact.html', {})
def about_views(request, *args, **kwargs):
print(args, kwargs)
print(request.user)
return render(request, 'about.html', {})
def social_view(request, *args, **kwargs):
print(args, kwargs)
print(request.user)
return render(request, 'social.html', {})
what is the *args and **kwargs?
hii, I m trying to add zoom buttons for d3 svg map
https://stackoverflow.com/questions/25333309/d3-js-how-to-add-zoom-button-with-the-default-wheelmouse-zoom-behavior
following this
but i m getting error on .call(zoom), pls help me with this..