#web-development
2 messages · Page 38 of 1
Is there a way? Yes. Is there a reasonably easy way? No
So could you share with me an example of a fix
{{ url_for('buy') }}${fit.name}
You cannot mix jinja and javascript templating without making connections back to your server
What you should do is have url_for return a prefix that would apply to all the stocks, and then simply append to it with javascript
I don’t understand how to do that
I get what you’re saying that the jinja and ja script won’t work together
But I don’t get how to do what you are proposing
You can't pass data from javascript to jinja, but you can pass data from jinja to javascript
Since, at least to me, it appears your urls are like this: http://mysite.com/stock/things/11111
You could request from jinja a url that is not 100% complete, but you could add data on to in your jjavascript code
So, if you do url_for('buy') with no parameters (and that works on your script side), you could expect output of http://mysite.com/stock/things/, and then you could immediately have javascript drop in the ID/name, to make the original url again
Ooh I see
That’s smart
I’ll try and do that when I get home
I’ll let you know how it goes 🙂
How would I take the last word(JavaScript) as a parameter in the app.py file though
<a href="{{ url_for('buy') }}${fit.name}">
You don't. You remove stock_id from your 'buy' url
And how would I do that?
Well...I don't know enough about flask, I'm more django oriented, but there must be somewhere you defined a route named 'buy' and also defined that route needs a 'stock_id' parameter ?
Yep
But I thought to pass a parameter using url_for
You had to give the function url
Followed by a , and then something like stock_id=VALUE
In jinja yea, but we've already established you can't pass your js variable back to jinja
I don't understand where you're stuck actually because after Bast's explanation you said "I see" ?
So if i do they code snippet that will do the url for (let’s just say) localhost/buy/stock_id value
That’s what I thought
Is that a wrong assumption?
Ok, show me your routes/urls then
Why is it another person answering x)
And do you already have a route with only "/buy/" somewhere ?
(if not, create one, it doesn't need to do anything and can even return an empty resonse, or a 404, or whatever you want, you only need it to so you can generate a http://www.domain.com/buy/ url using url_for)
Anyone here have experience with google SEO?
If I make a json rest endpoint that does not need to return anything upon success, should I still return an empty dict, or is it fine if it's blank
Anyone recommend a good django video or reading tutorial for beginners?
people
please
before i destruct all my home office
i'm like 3 days
trying to END THE FUCKING SCROOLING
in this shit
@distant bobcat Corey is good
Thanks
HOW TO stop scrolling
close discord
no man, in html + css
ohh
my page does be static
always the fucking scroll bars
i tried 100%, 100vw
i'm really pissed
anybody can give me a tip?
i have a div (called #full) this contains the whole page
THIS SHIT IS ALWAYS getting scrollbars
there is any way i can make it stop w
?
shit, i hate this
are you trying to hide the scroll bars? or just get rid of them altogether
@wild thunder
get rid of them
for life
i'm really pissed
this fucked my afternoon
i'm fully stressed
yes
but not in the entire page
just in inside elements
i made some styles that makes that shit not visible
it just scrolls
but i dont want my "fullscreen" to scroll
elements can scroll
not header nor footer
just body elements
like, is everything scrolling on its own? or am i just massively misunderstanding...
imagine you are on a page
ok
it's static right?
my page was supposed to be static too
the full page
like "width 100% and height 100%"
fullscreen - no scrolling
i can do this one time
when i start modeling inside elements
this shit began to appear again
my page start to have horizontal scrools
are you using inline styling or a separate stylesheet
Start with the outermost element and reintroduce the others one by one
when you get your scrollbars, that's a sign which element is the issue
yes, i got that, but i'm using % for all my inside elements
it should not behave that way, right w
?
i re-read my code at least 20 times
this shit is ok
Be careful of margins and paddings if you don't have border-box on your elements
(Also default browser's margins)
@bleak bobcat beat me to it
did you do this?
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
That shouldn't matter
Doesn't matter
can you https://ngrok.com/ your code ?
ngrok secure introspectable tunnels to localhost webhook development tool and debugging tool
@frosty nymph i'll add that "box-sizing"
well, i think it's getting somewhere now
it worked
cool
So it was a padding on one of your elements
i had made this interface already, it was ok
then i'm using flask
idk why, but some stuff got out of align
Has nothing to do with flask, we're only talking html & css here
and when i tried to fix, got worse
i'm re-doing
the page
and got this problem
i almost throw my tv at the wall
3 hours for a shitty problem
damn scrolling, i hate this
sorry for all this hate
i really lost my temper
thanks for helping guys
this channel rocks
It's fine, people who don't understand how css works usually hate css :p
yes
i'm 4 months programming
started with python
for django
but it needs html and css
then i went to it
i made a homepage + login scren + user interface
Are you using any css framework ?
now, left django, started flask
@bleak bobcat no, which kind of frameworks are out there?
idk it has frameworks lol
The most famous and used one is https://getbootstrap.com/
and sorry my mispelling/word order, english is not my native language
I heart Bootstrap
can you list the 3 main reasons bootstrap is useful? i'm new to all of this
It saves you from having to reinvent the wheel when creating many common interfaces
I'm working on a personal wiki app that uses BS templates
it's a massive timesvaer
Basically you could build a whole, nice looking website, without writing a single line of css
IT gives you lots of classes to style/layout your elements
You can modify the results later with your own custom CSS, as you get experienced
but you can just drop it in as-is and go
THis is what the UI looks right now
BS4 saved me tons of trouble
(that page is for a book I'm working on; the wiki is mainly to let me organize my writing projects)
@wild thunder don't get the wrong version. the first time i tried bootstrap, i almost broke my computer. it made me write about 30 <div> tags with separate id attributes and i wanted to scream. apparently theres other spoof versions of bootstrap?
man you give all this roundabout to be working on a book at the same time
you are my hero now
There's also https://foundation.zurb.com/ https://materializecss.com/ and https://bulma.io/ which are pretty nice (only use one though, there's no point combining those)
@echo dawn i'm fully stressed, i guess i'll continue tomorrow
@wild thunder I was using another wiki app but it wasn't very good, so I decided to write my own
guys, let's make it simple, if i pass what i want to make, can you tell me whats best choice?
i don't want to be a front-end specialist, i preffer back end stuff
if i can make my interfaces cool enough i'm happy
@cerulean vapor definetely you are my hero
BS4 is easy enough to get going with - they have tons of examples you can just boost as-is for many common applications
GTG, BBL
can I jump into django with very little html experience?
@wild thunder I know a ton of back-end developers who don't know much about html & css but still manage to build ok looking website just because they took the time to learn how to use bootstrap
i read the word "bootstrap" many times while studying css
but never looked for
all this problem started when i tried to "centralize" my text vertically
it was aligned to top (default) but my text did not align
I have a small web app I wanna make. Typically a C# dev but I’m wanting to use python. What frameworks should I be looking into it? I’ve seen flask and Django mentioned. Is flask only server side api? Meaning no front end component?
I guess you'd call it server side ...
I mean you can use it to serve js
I don't know what frameworks do include a front-end component
Everything I’ve read says Django supports front end
It’s a full stack framework apparently
I don’t need much of a front end. Just a few text boxes. Super simple
ok so i am making a app that will take a spotify playlist and do some stuff with it(already made this python script), but i want to combine this script with a nodejs server. What is the best way I could do that?(I already tried python shell and i spent like 3 hours trying to get it to work then i gave up) Thank you for the responses
@last bobcat you can make full-on websites with both django and flask
They both have templating engine integrated
hey i know how to make django blog but i want to implement google maps in to find nearby shelter for night if possible pls tell me how to proceed ahead?
is this normal? chrome renders colors very differently
on chrome
on ff
like miles away different
rgb(24,24,255)
should look like on the ff
No, that is not normal
also that rgba() call is wrong, rgba requires four values: r, g, b, and alpha (which goes from 0-1 unlike alll the others)
I have a flask app (a discussion forum) that is dockerized and hosted on digital ocean. Users can upload avatars and stuff that currently get placed in the 'static' folder in the app. The problem is, since it's a docker image, if I update the app on my local machine and want to replace the old docker image with a new one, that static folder is overwritten. What's the best way to solve this? Store user uploads outside of the docker image? Download the contents of the folder to my local machine before re-imaging?
you might take look at amazon s3 bucket or dropbox
and you can save your avatars there
there are apis for accessing both dropbox and amazon s3 instances
that's a good idea
Does docker volumes could also be something to consider here ? (I do not know, i ask to see if i understand it)
I think that would work as well, yes
yes it could
hi
i want to add a functionality
when i click a certain button an area of my webpage translates to the language i want
i've tried it with JS
here
var briefAbout = getElementById('brief-about');
function translate_to_english(){
return briefAbout.innerHTML = `This website was created by me(Kenny Hoft).
I am a middle school student who creates website just for fun.
So it's my Hobby. But this website was created to put my summary on it from the books i read for school.
And i created it so i can hone my web development skills.
I also put the names of the people of my group here so they can write their summaries too.
This website was possible because my teacher allowed it that i made a website to put my summary on it for her to read, so thanks to her.
Enjoy reading!`;
}
function translate_to_dutch(){
briefAbout.innerHTML = `Deze website is gemaakt door mij (Kenny Hoft).
Ik ben een middelbare scholier die een website maakt voor de lol.
Dus het is mijn hobby. Maar deze website is gemaakt om mijn samenvatting erop te zetten uit de boeken die ik voor school heb gelezen.
En ik heb het gemaakt zodat ik mijn vaardigheden voor webontwikkeling kan verbeteren.
Ik heb hier ook de namen van de mensen van mijn groep geplaatst, zodat zij ook hun samenvattingen kunnen schrijven.
Deze website was mogelijk omdat mijn leraar het toestond dat ik een website maakte om mijn samenvatting erop te zetten zodat ze het kon lezen, dus ik bedank haar.
Veel plezier met lezen!`;
}
</script>```
i added an onclick event
<button onclick="translate_to_english()">English</button>
<button onclick="translate_to_dutch()">Dutch</button>
</div>```
i don't know what i am doing wrong here
i am a beginner at JavaScript so yeah
need some help here
I have a question
how would I get all the links that a website has
Example:
etc..
nvm think I've figured it out
@native tide make sure your Javscript file is imported at the very end of body, see: https://www.w3schools.com/js/tryit.asp?filename=tryjs_whereto_external
@jovial portal Sitemaps / Custom scrapers.
@dense hound it still doesn't work
@native tide you have to link your js file in your html
But it doesn't matter if i do it internal right?
i put the script tag in the same file where the page template is @vagrant adder
Put it in static folder so you can link it properly
Then link it in html via script tag and url_for in src attribute
I can help you when i get home
I'm trying to remove borders from my input boxes with CSS. I've applied the border: none;, everything gets removed but this top part
What the hell do I do
box-shadow: none;?
I'm guessing its a framework that added the shadow - thats why I find using bootstrap or similar very frustrating
It's a project that got literally tossed to me and I have to do the frontend for it
how would i implement a webserver in python the dynamically adds data to the webpage without having to reload the whole page? i am getting the data from a client via sockets. can someone link me a project where i can learn it from? any ideas?
You would need JavaScript to do that
Kind of on the same topic, i'm trying to accomplish something similar. With refreshing the page automaticly with new records from a DB. And I found this example: https://stackoverflow.com/a/46719768
but I'm using a Mysql DB, how would I do the same with those records I pull then?
i already can update the entire html document with javascript every x second by inserting window.location.reload(true); into the html but i liked to reload when my python scripts decides to reload
@rigid laurel
Ok saki
First of all, thats quite a bad way of updating the page. Second of all, in that case you could poll a python endpoint until the endpoint tells you the page has updated, then reload the whole page
so you'd need to make a small python api in something like Flask
@native tide oof i'm not home anymore
I'm using the glitch webserver (glitch.com) and for some reason this is returning an error
Is this because of python 2? Anyone know how to update it?
that's python3 code, and you're using python2 to run it
see if you can run it with python3
that's what I don't get
I don't see anywhere where it says python2
actually, the source demo I copied this from says it's python 3 lol
it uses gunicorn whatever that means
why would it say "python2" if it's python3?
How are you running it?
"gunicorn" is a decent web server written in python
look inside it.
with python server.py
there's your problem.
🤔
your system's "python" is almost certainly python2
that's odd, though, that they did that; since the code clearly requires python3, I'd have expected start.sh to say python3
was the start.sh written by the same person who wrote the rest of the stuff?
there ya go
The code is mine
so fix it
oh hey
its working now
but its still not printing to the console
even im using file=sys.stderr
I dont see a log file
it could be anywhere
I'm looking in the files right here
assets is just a bunch of random pictures
oh wait
for some reason you have to visit the page for it to start logging
why is that?
probably "laziness" -- it doesn't have anything to say until you visit a page
is there a way to bypass this
you can "raise" the "logging level", that might help.
You'll get a few messages as soon as you start up, saying stuff like "Hi, gunicorn here; I'm running three threads and my process ID is 12345" and stuff
there's probably a gunicorn.conf somewhere that defines the logging level(s)
five files total?
that's not many files for a whole web server
I'd be surprised if gunicorn can even run without some sort of conf file
idk what im doing here lol
you're learning how to run a little web server
I'm trying to get the server.py file to write to a log.txt
logMsg = "On program load at " + formattedTime + ", " + setCommas(list(newAddition)) + " were online"
with open("log.txt", "a") as logFile:
logFile.write(logMsg + "\n")```
This isn't doing it
Please ping me
@iron sinew why do you say it's not doing it? What are you observing that differs from what you expected to observe?
The file has nothing in it
is that code that you pasted above complete?
'cuz I'm running that code, and it works for me
my guesses:
- you have two files named
log.txt, and you're looking in the wrong one - you have a bunch more code inside that
with, and the file isn't getting closed before you look in it
That's all that is in the with block
ok, what's the working directory of the python process?
ooh another guess:
- the
openor thewriteare failing with an exception, but for some reason, you don't see that exception
well you don't need to set it, but it'd be good to know what it is, so you can, for example, figure out where your log files go 🙂
perhaps print it out!
perhaps use an absolute file name instead of log.txt
os.getcwd yeah
your stdout and/or stderr are probaby going to other log files.
we talked about that earlier
sorry I don't know what app.run is
it runs the main() method
if you think some code isn't being executed, stick 5/0 in there -- if that does get executed, you're pretty likely to notice the divide-by-zero error
ok that should tell you something
another option, if you think the code is being executed, but it's too hard to find the files to which stdout is being redirected -- have your prints go to some file whose location you know. For example: ```py
logMsg = "On program load at " + ", " + " were online"
with open("log.txt", "a") as logFile:
with open("/tmp/another-log-file", "w") as damn_it:
logFile.write(logMsg + "\n")
print(f"Wrote that log message to {logFile}", file=damn_it)
you probably don't have write access to that directory
/tmp is better
no idea what you mean by "this server ... shouldn't support python, but it supports html".
yes, open as I wrote it will create the file if it doesn't exist (and will overwrite it if it does). Note that I removed one of the two / in the file name
do you have permission to create files there?
I know you had an empty log.txt there once, but I don't know how it got there
I'll take a look, but there's only maybe a 30% chance I'll be able to get it running
xd
OK I hit the 5/0 as soon as I pointed my browser at http://127.0.0.1:5000/
you say you didn't see that?
I thought it means projecturl:5000
cuz thats how I started it before
i didnt know it hosted it on my machine
oh did u copy the code onto ur machine
I don't know what you mean by "I thought it means ..."
yes, I copied the code onto my machine
I don't know how to use glitch
I'd need to access https://mc-player-logger.glitch.me:5000
so you're running this code on someone else's server (namely: the "glitch" people). It's possible that that server does crazy stuff, like throw away anything you write to a file; I don't know
I don't think that's likely, but it's possible
ill ask the support ppl
well you could shove all that output into the response
what it returns?
yeah
pretty sure you don't want your / route to loop forever
that means the person hitting your server will have to wait literally forever for the page to load
web servers need to return responses quickly
It wasn't designed to be accessable
I'm literally only using flask because it doesn't support python, but it does support html, and you can run flask on the html basis?
idk how the whole thing works
also I don't see you generating a response anywhere
OK I gotta admit: "I'm literally only using flask because it doesn't support python, but it does support html, and you can run flask on the html basis?" makes exactly zero sense
flask is for writing webservers, and only for writing web servers.
If you don't want to write a web server, don't use flask. Simple.
Do you want to write a web server? I literally can't tell.
so this is something that runs all the time, and does ... something?
Yeah
What is it supposed to do?
Log players on a minecraft server
Like, if it were to suddenly stop working, who would notice, and how would they notice?
it looks like it's collecting a little bit of data about Minecraft, and then ... not doing anything with it
I want it to store it in the file
what does "Log" mean here?
ok, so you want it to write stuff into a file. Who will read this file? When? How?
ok, so hosting it on glitch might make sense. Using flask, however, doesn't
unless you already know how to write a web server (or are happy to learn)
this is something I would probably do with an EC2 instance, but that's just me
(or linode or whatever)
EC2?
EC2, yes.
do you not know what that is? It's basically "rent a Linux computer in the cloud"
I have no way to pay for any of that tho
I don't have a credit card
Do they have a free tier or something?
they do; I don't know how many zorkmids you get for free, though
I'd have said "mojo" but that doesn't come in discrete units 🙂
anyway you certainly can make a web app to do this. But you should check that files on glitch work the way you'd expect; as I said, it's possible they're doing something odd
Anyone here familiar with cloudflare and GCS?
@native tide bugbounty
google it
and what's the purpose of posting that here?
i can't post my website online
and what does "Hacking Twitter for $$" has to do with that. Why did he post that
idk the question. Ask
ok
how can i set the html code i have online so that people can see the website
if they know the url
@marble pulsar
use any free webhost and just rename the html file to index.html and upload to webhost
you can even use github for that
look up https://pages.github.com/
Websites for you and your projects, hosted directly from your GitHub repository. Just edit, push, and your changes are live.
or you can use other hosts
it's your_username.github.io
ok
will that be as i want to the code?
ok thank you
will github set it online for me?
all you need to do is push your code to your repo and it'll be up in a few minutes
that's not how it works
how to do it then?
you have to use your github username
so in your case, Dart2004.github.io
ok thank you
yes except you don't have an index.html
it is on .github/workflows
isn't that working?
@shadow hornet
not working i tried no website
you'll have to wait a few minutes as i said earlier
ok
it doesn't come up instantly
can you look at it then too?
ah i think the repo name has to be all lowercase
not 100% on that though
nvm it doesn't
just wait a few minutes
ok thank you
i just realized
you have that repository private
that's not going to work, unless you upgrade to pro
@native tide
to public?
yeah
wdym?
a new folder to the repository
ah make a folderlike you normally would, commit, and push?
alright
i will tell you per ping ok?
sure i'll respond if i'm around
ok thank you
👍
Anyone here good with front end ?>
I also need to calculate the prices from the django back end. Of the selected quests
Does anyone have a clue why this won't work?
.navbar-right .button-prijava:focus, .navbar-right .button-prijava:hover {
color: #ad1e1e;
background-color: transparent;
}
I know I'm targeting the right class since if I try changing the font, it changes. I want to make it when you hover over the text the colour changes to red. I have the exact same class, just on the different side of the navbar and it works
Um what. If I press the button the colour changes to red?
@native tide try set .button:active
@native tide
button {
background-color: #ad1e1e;
}
button:focus,button:visited,button:active {
background-color: red;
}
Well then look at your element's styles in the console
Can you https://ngrok.com/ it ?
ngrok secure introspectable tunnels to localhost webhook development tool and debugging tool
hey guys, when using django and it's next redirecting it just wont take second queryparamters.
for example my url http://localhost:8000/login?next=o/authorize/?response_type=code&client_id=blahblahbla and this trimmed down cliend_id part. Can anyone know how to solve this?
ok thank you
guys, can i learn flask from here, or are there other functional tutorials for beginner? https://flask.palletsprojects.com/en/1.0.x/
How to make adhaar verification page using django?
Yes @cloud path, docs are a great place to seek specifical info
But if you want full-on tutorial, check out corey schafer on yt
ok thanks!
Hey guys, I have architecture related question
I would like to ask you about following scenario: I have bunch of Scrapy scrappers which after scraping also processes data and eventually saves it to database.
The second logical component is simple django application for displaying data.
The problem I see is that scrappers uses models from django which doesnt follow separation of concerns in my opinion.
The other pain with current solution is those crawling things are executed on webserver - I know it should be using Celery tasks.
But if I would separate scrapy logic from django then I could run it serverless and pay even less?
I know that drawback would be to set up the same model for scrapy and each change in it would require to adjust code in second component.
What do you think about that, how would you solve it? Is it ok for you to have scrappers inside django application?
you can make an api
so when scrapers do the job, they don't interact with the database through models
they can make a post request to the api and api deals with the models and database
Yeah, this is some idea but with hundreds of such requests I could make self harakiri to it 😅
i think it could be the only way
You are most likely running forms.py in a different environment. Close the terminal and restart with the correct environment.
If you are using Visual Studio, just delete the venv and start afresh with a new one,
and use the requirements.txt to make installation faster
mm i'm using it in this
it's the same of the windows shell
but if i write py -3 -m venv venv it tells me this
i've runned it as administrator
!warn 665314772593541180 don't crosspost your question
:incoming_envelope: :ok_hand: applied warning to @ocean onyx.
what is the warning about
@ocean onyx the reason is in the warning command and in your dms. you posted a link to a channel you asked a question in order to get more attention on your question, we don't allow that
i am new so, i don't know how to ask but i am sorry.
that's why it's a warning. just take note of it in future
ok
Hi i'm trying to use Insomia a REST client to GET a gzip file and have it display as plain test or JSON so it should be
At the moment this is all i'm getting
I've set the header as Accept-Encoding with values as gzip and deflate
But it's still showing the weird encryption
Any ideas? 😄
Deflate is supposed to do it automatically but not sure it works outside of a browser
Can we see your project structure?
Try import app.routes
Try creating init file in ucp
this error..
probably the new version does it automatically? because until yesterday I was following a tutorial that puts everything in a one file like this
but then I changed, because it was a tutorial by voice on youtube, and in english I didn't understand much
i've insert the import in ucp.py
here there is no problem
probably, in the others I have to remove them, even if it is strange, since the tutorial shows it as I did
Anyone able to help me use the ssl-context option throught flask?
im using a program that utilizes flask-script and I can seem to figure out how to add the --ssl-context='adhoc' to the run portion
from flask_script import Manager
from app import create_app, db
manager = Manager(create_app)
@manager.command
def createdb(drop_first=False):
"""Creates the database."""
if drop_first:
db.drop_all()
db.create_all()
if __name__ == '__main__':
manager.run()
using flex
my elements are in wrong order
i put one with 15% width and other with 85%
the 15% one should be first (left) and the other at right
why it's in wrong order?
how can i fix it?
see
that green element should be at left
What's the html look like?
<div id="header">
<div id="logo"></div>
<div id="menus"></div>
</div>
header
logo @ left , menus @ right
i guess the problem is my css
#header {
height: 80px;
width: 100%;
background-color: rgb(255, 255, 255);
box-shadow: 0px 0px 10px grey;
display: flex;
flex-direction: row;
}
#logo {
background-color: grey;
width: 85%;
height: 100%;
background-image: url("logo.png");
}
#menus {
background-color: rgba(5, 37, 6, 0.705);
width: 15%;
height: 100%;
}
oh, wait
i guess i found it
sorry, nevermind
guys
Can you explain more
Hey there,
I am currently working on CS50W project1 where I am supposed to create a website using (Python, FLask, SQLAlchemy) but I am not allowed to use ORM (so all SQL queries should be performed using SQL commands "using .execute(" SQL COMMAND HERE ")" )
so i am trying to make classes that will have methods that perform the commands i need
in the search method I am getting a None result and I dont understand why.
see code below
from libreria import db
class User():
def __init__(self, username, password):
self.username = username
self.password = password
self.id = id
def create(self):
username = self.username
password = self.password
db.session.execute("INSERT INTO users (username, password) VALUES (:username, :password)", {"username": self.username, "password": self.password})
db.session.commit()
def search(self):
temp = db.session.execute("SELECT username,password FROM users WHERE username = :username", {"username":self.username, "password":self.password}).fetchone()
db.session.commit()
print(temp)
tempuser = User("username1","password1")
print(tempuser.search())
the result is of the print is:
('username1', 'password1')
None
why is there None there?
So this is the function thing
So see, there is a print function in the search function
But the function isn't returning anything, there is no return statement
So when you do print(user.search()), print() within gets triggered and return value of the function gets printed
Yes, return temp
and i do not need to use db.session.commit() when executing a SELECT query right?
Quick tip: remove print statement in function when going to production
yeah already did, was just to know what the contents where, thanks 😄
not being allowed to use ORM was such a pain 😛
been at it for 2 days now
but its finally working 😄 😄
🤘
For some reason my ```css
@media screen and (max-width: 768px){
.header{
display: flex;
justify-content: flex-end;
width: 100%;
}
.container{
position: fixed;
width: 25%;
background-color: blue;
}
}
is being overridden by
```css
.container{
display:flex;
list-style: none;
width: 75%;
height: 100%;
justify-content: space-around;
align-items: center;
}
.header{
width: 75%;
display: flex;
justify-content: flex-end;
}
when the screen is below the given width. But only some parts. The background does set itself to blue, but the width does not apply
i'm writing aiohttp app behind nginx, I want to be able to generate temporary urls to files, but don't want aiohttp to send them, nginx should do this.
How could I do it? Here's the algo:
- user: requests file
real_file.txtfrom HTML page - frontend: sends request to server to generate temp access token
- aiohttp backend: generates and returns temp access token
1234 - user: makes request to
/real_file.txt?access_token=1234url - aiohttp backend: validates
access_tokenand returns302redirect toX/real_file.txtif valid - nginx: catches
302and returns file fromX/real_file.txt
I found this SO answer about catching 302 redirect internally: https://stackoverflow.com/questions/20254456/intercepting-backend-301-302-redirects-proxy-pass-and-rewriting-to-another-loc
I'm not sure what X url from this algo should be, could it be just
location /random_path {
root /media;
}``` ?
In this case this path can be bruteforced and I would need to change `X` in both backend and nginx
Is this an optimal solution overall?
im learning django now, man its so good
so powerful, and admin panel built in for you
yes
i don't know how are you having 2 websites running on same vps, but yes databases usually allow for more connections
mm ok ok well, and can each use a different type of database manager? for example, the one Mysql and the other sqlite, for the same database?
well, mysql and sqlite are 2 different databases, not dbms-es
your database can be sqlite and mysql
it's the orm/library that allows for db interacting that can be different
hey there,
I am currently trying to use flask-login with a custom user class to login my users.
but I am getting an error.
this is the user class and login decorator part
from libreria import db, login_manager
from flask_login import UserMixin
@login_manager.user_loader
def load_user(user_id):
return User.searchwo(id=user_id)
class User(UserMixin):
def __init__(self, username, password=None, id=None):
self.username = username
self.password = password
self.id = id
def create(self):
db.session.execute("INSERT INTO users (username, password) VALUES (:username, :password)", {"username": self.username, "password": self.password})
db.session.commit()
def search(self):
response = db.session.execute("SELECT id,username,password FROM users WHERE username = :username", {"username":self.username}).fetchone()
if response != None:
self.id = response[0]
self.password = response[2]
return response
@staticmethod
def searchwo(id=None, username=None):
if id is not None:
response = db.session.execute("SELECT id,username,password FROM users WHERE id = :id", {"id":id}).fetchone()
elif username is not None:
response = db.session.execute("SELECT id,username,password FROM users WHERE username = :username", {"username":username}).fetchone()
return response
when I try to login on my website I get the following error
sqlalchemy.exc.DataError: (psycopg2.errors.InvalidTextRepresentation) invalid input syntax for integer: "None"
LINE 1: SELECT id,username,password FROM users WHERE id = 'None'
^
[SQL: SELECT id,username,password FROM users WHERE id = %(id)s]
[parameters: {'id': 'None'}]
(Background on this error at: http://sqlalche.me/e/9h9h)
any ideas?
so there is probably something wrong with the user_id being set to None, but I don't really understand the when and where the load_user() is being called so I dont know if the id is defined at the time and place
Are you sure it's set to None and not 'None' (string) ?
yeah
i changed it from id to username, and now the website works
but i dont understand why, and I dont understand when this "user_loader" is being called
because in my login route i set the ID of the user, that i get from the DB
Does requests automatically set the cookie header when using requests.Session()
hey guys just a lil question with flask
in the paramters of app.route(), is it possible to add a second paramter after that /<name>
of course
wait really
yes
how
can you paste your code from the screenshot?
`@app.route("/<name>")
def home(name):
return render_template("index.html", content = name, title = "Hello")
if name == "main":
app.run()
`
@app.route("/<name>/<surname>")
def home(name, surname):
return render_template("index.html", full_name=(name, surname), title="Hello")
if __name__ == "__main__":
app.run()
this should work
i think i just broke it
@app.route("/home") @app.route("/<name>/<lastname>") def home(name, lastname): return render_template("index.html", full_name(name, lastname), title = "Hello")
am I allowed to put 2 of @native vessel.route
saki can you pls help
you can add more route pointers if they have same arguments
you can't do
@app.route("/")
@app.route("/name/<name>")
but you can do
@app.route("/<name>")
@app.route("/name/<name>")
what you are trying to acomplish is simply not possible
you mean 404 error?
it changed to this
👋
@inner stump there is a space after the % in {% endblock% } dont know if that will cause an error or not though
omg it worked
I don't wanna complain but this thing is a bit extra
but thank you bro
hey guys
is it possible to add more than one function under a single @app.route
can someone please clarify for me
@inner stump https://stackoverflow.com/questions/52811041/how-can-i-use-the-same-route-for-multiple-functions-in-flask
thankk you man
idk if this is the right spot for this, but im trying to send a POST request to a certain website, and the response is either 403 or 406. ive been messing with the headers for about an hour and I have no idea what to do. any pointers anybody?
do you know what those responses mean? I don't, without looking them up
403 is forbidden, 406 is non acceptable
I get 406 more
I read it has to do with the “Accept” header, which ive played with over and over, no progress
ive done a lot with these types of projects, and ive never seen 406 this much. the site doesnt require proxies or anything either.
well I can't tell without knowing a lot about the web site, unfortunately. They're free to return any response they want for any reason they want.
what would you suggest i do to become more knowledgeable about the site then?
maybe im missing something about it, seemed pretty simple going into it
this is a good example/method as well:
@app.route('/users/', defaults={'page': 1})
@app.route('/users/page/<int:page>')
def show_users(page):
pass
@inner stump
@lean birch I can't suggest anything you wouldn't think of on your own -- read their API docs, if they have any; use the "developer tools" in your browser to see what a successful request looks like ...
Does anyone have experience with redis queue?
don't ask in a zillion channels
they block dev tools on a successful submission
maybe you need to spoof the User-Agent header
i.e., lie to them and say you're using Chrome instead of requests
ive been using a chrome User-Agent
Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36 to be exact
requests would show python-requests or something with no header user agent selected, and no site likes to accept anything from that
well, some sites reject that
stupid sites
but also, when i sign up through chrome with that User-Agent, it succeeds
im so lost LMAO
use the browser's developer tools to examine the requests, so that you can duplicate them
@inner stump its really bad practise to do two functions on one route
@vagrant adder why is it a bad practice to have two functions on one route?
Because the code will get dirty very quickly
dirty as in complex?
Yes
oki great,
Another quick question, is there a way using (python, flask and html - no JS or anything else) to get the following:
click a button, send me to a route, and after a couple of seconds, send me to another route
so (I am in home.html, i click logout, i go to logout.html, the after lets say 5 seconds, I go to login.html)
aha, well too bad I guess 😄 , the user will have to just logout without any eye candy 😛
You aren't allowed to do any js?
nah, I don't know any JS, its the next chapter in the course
so I am expecting that applying it will take time as I know nothing about it
if its easy and you could guide me, then great. If not then no user eye candy 🤣
I know some basics like creating stuff onclick, redirecting and shit
I can show you what i knoe
what I want is something very simple, it goes like this
I am on any of my routes (main, books, reviews...etc) and the user clicks "Logout"
I then want to go to (Logout.html) which has a fancy goodbye message, the he gets redirected to (/login) again
he stays in logout.html for like 3 to 5 seconds
I am not home rn, i can show you a when i get
sure nps, will hopefully get the rest of the site ready by then 😄
@native root thank you so much
@login_required
def signup(rid):
voyage = models.request_voyage(rid)
ships = models.request_ships(rid)
retrieve=[]
for ship in ships:
retrieve.append(ship.id)
seats = models.request_seats(retrieve)
user=current_user.id
rank = models.request_rank(user)
rating = models.request_rating(user)
return render_template("signup.html", voyage=voyage, ships=ships,
user=user, rank=rank, rating=rating, seats=seats)```
when visiting: http://127.0.0.1:5000/signup/1
returns :
werkzeug.routing.BuildError: Could not build url for endpoint 'signup'. Did you forget to specify values ['rid']?```
using flask. python3.6x
full traceback: https://gist.github.com/epoxe/200df61bcaa367a02294ca481c34bf23
any ideas?
Hey guys, I am considerably new to python but not bad though, I want to know what are the requirements before I get into Django .. HTLM as first and the track to go as fullstack.. thing what is next ? PHP or CSS?
no idea what you're asking
surely you don't need to know PHP if you know python and django.
HTML and CSS would be useful
@quasi ridge what about js?
quite useful
so you know: PHP is an alternative to python and django. (And it's a really terrible one, too; I wouldn't work for a company that proudly uses PHP)
Thanks
guys how can one make PWA on django ?? i learnt about service workers and web manifest but since django is MVC framework, how can one structure the projects so that it can be used as PWA. ??
no idea what PWA is, sorry
Progressive Web App
well, now I know what the letters stand for; but I don't know what those words mean. You probably want someone else to help you
You can do it with something like django-progressive-web-app - like this one https://github.com/svvitale/django-progressive-web-app
Basically you will need a serviceworker.js
And then you can inject it
I found a medium post that's very informative about it as well, you can read about it here - https://medium.com/beginners-guide-to-mobile-web-development/convert-django-website-to-a-progressive-web-app-3536bc4f2862
just ask m8, if someone knows and can help they will answer you
I'm making REST HTTP json API, I have a /nicknames/check endpoint used to check if nickname is used or not, what status codes should it return?
Possible cases are:
- nickname aready taken -
200? - nickname is not taken -
404? - nickname has invalid format -
400?
OK cool @tranquil robin , I've got this code which works for filtering the Total_Scheduled values I want:
for (var i = 0; i < source.get_length(); i++){
if (source.data['Total_Scheduled'][i] >= SchedSlider.value[0]
&&
source.data['Total_Scheduled'][i] <= SchedSlider.value[1]
){
indices.push(true);
} else {indices.push(false);}}return indices;
''')```
But the thing is that I want to expand this to also include filtering for another variable, but of a category (not a number)
Hello. I just started out with Django a few days ago and I'm struggling with implementing the login page properly. I'm using the default LoginView (from django.contrib.auth import views as auth_views). How can I customize this view so that it will accept a 'title' variable for the page?This page is an extension of a base.html page, where I've added the proper conditions to accept a title passed in the view. Thank you!
I found this JS code from a stackoverflow response, which worked well by itself, but I don't know how to adapt and integrate it into the code above. Pycharm doesn't show what might be wrong as it's all in quotes... :
let selected = checkbox_group.active.map(i=>checkbox_group.labels[i]);
let indices = [];
let column = source.data.species;
for(let i=0; i<column.length; i++){
if(selected.includes(column[i])){
indices.push(i);
}
}
return indices;
""",```
@maiden bay don't return statuses, return message in a body
Could someone please help me figure out how I can merge these codes together? I could paste what I've drafted but it's a complete nonsensical mess lol
That way users can differentiate if request went badly or name is taken
is this how REST supposed to work though?
Yes it is
Status codes are to desribe request as a way to send/retrieve data from an api and request body is a message that is from/to server
I would need to invent my own error codes then and include in response to let frontend display localized error message
I don't understand what you just said
frontend can't show user raw error message from json response, it would need to translate it first
what do you mean can't show user raw error message from json response
yes you can
request.body
in flask
anyone can help me with this?
this is the init
this is the code that gives the errors
with quart, is it possible to run it alongside discordpy?
ur welcome
hey.. ive decided to learn Flask and am following Corey Schafer.. any good text sites or resources ? like amazon books ?
best place for an intermediate pythonner
id say watch all the tutorials and then start working on projects.
Start with simple projects like a todo app, dictonary, etc and then do some complex ones (like twitter clone website, etc).
As you increase the complexity of the projects, you will start learning new stuff, like finding things on the docs, so (my opinion) is to do more projects and learn as you go along
its a good idea.. i need to get the basics of flask first tho
prob cant watch all the tuts
soo many
😉
but thanks
with quart and it's websockets, how can I change the session values from a totally unrelated async function
I am trying to make the user send a random generated code to a discord bot and have it set the session values when that matches
@native tide if you dont wanna watch all the tuts but want to get the hang of basics, then freecodecamp on youtube has some flask tutorials too! some of them are under 1 hour
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
@marsh canyon NICE! thanks
i did also find this: https://www.udemy.com/course/the-build-a-saas-app-with-flask-course/?LSNPUBID=jU79Zysihs4&ranEAID=jU79Zysihs4&ranMID=39197&ranSiteID=jU79Zysihs4-kx6mBsk1Jvyp3He3qD7CHQ
cool cool 🙂
but your is more affordable
lol
heh.. tho the saas app course also has some vids on docker
which i also need to learn
my company uses docker in a major way
and im totally blank on that
oki
i like how flask apparently has ready made extensions ?
thats awesome
like if i need a map for stuff, its there for the taking ?
not very experienced with flask, cant comment on that 😅
oh
ok
omg
@native tide just a note I figured out while watching Corey Schafer, his whole Flask series is based on the book "Flask Web Development by Miguel Grinberg"
Miguel Grinberg also has a website with tutorials called Mega tutorial or so
AHA... son of a gun.. i almost bought grinbergs book..
i actually bought the udemy flask course.. seemed so smooth
its very nice
GL 🙂
@native tide i have a cheatsheet that i use for reminder
@vagrant adder thank you very much.. i am not flask smart enough yet to see its full potential but thank you
If you get into some troubles feel free to jump in here
oh you bet.. thank you..
🤘
im prob gonna start with greenberg and then do the kinda scary udemy flask/docker tut
lots of stuff im unfamiliar with
I started from corey's tutorial series
He goes over a lot of flask's features in that
And i found myself going to that tutorial more times than not
the udemy course is based on building an actual money making app but mentions modules i have never heard of, like celery, redis and gunicorn
Gunicorn is webserver
ah
its like background workers ?
ah
a lot of the stuff used if not all of it, is based on using docker.. bc its allready set up
And most of the times scheduled tasks are some kind of database interaction which be done with cron
Yes, dockered setups often use redis but i recommend starting before docker
So you can actually get to know your os
yeah im gonna start with corey
👍
stick with that for a while
prob gonna take months to get to a decent level
thanks
🙂
👍
hello .. uwsgi .. how do i get all the workers to share the same mysql connection pool?
yes
and each workers has a connection pool to the database
and each wokrer has only one connection per pool
other than having a single connection act as a proxy, i don't see it being possible either
My problem:
I'm trying to add a Submission to an Idea. An Idea can have many submissions, a Submission can have only one Idea. I want to validate my form (which is working, with no valid) by checking if the author of the new submission has already created one against an Idea.
# forms.py
class NewIdeaSubmissionForm(forms.ModelForm):
class Meta:
model = Submission
# this is prob a bad idea...
exclude = ('idea',)
def __init__(self, *args, **kwargs):
self.idea = kwargs.pop('idea', None)
super(NewIdeaSubmissionForm, self).__init__(*args, **kwargs)
def clean_idea(self):
idea = self.cleaned_data.get('idea')
author = self.cleaned_data.get('author')
print(idea)
existing = Submission.objects.filter(
idea=idea,
author=author
).exists()
if existing:
raise forms.ValidationError(u"Subsystem already existing")
return idea
# models.py
class Idea(models.Model):
title = models.CharField(max_length=60)
description = models.TextField()
created_at = models.DateField(auto_now = True)
slug = models.SlugField(null=True, blank=True)
author = models.ForeignKey(User, editable=False, null=True, blank=True, on_delete=models.CASCADE, )
def __str__(self):
return f"{self.pk} - {self.title}"
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save(*args, **kwargs)
def get_absolute_url(self):
return reverse('idea-detail', args=[self.pk])
class Submission(models.Model):
unique_together = ('idea', 'author')
idea = models.ForeignKey(Idea, on_delete=models.CASCADE)
url_to = models.CharField(max_length=250)
author = models.ForeignKey(User, editable=False, null=True, blank=True, on_delete=models.CASCADE)
def __str__(self):
return f"{self.idea}"
# views.py
class SubmissionCreate(CreateView):
template_name = 'ideas/submission_form.html'
form_class = NewIdeaSubmissionForm
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.author = self.request.user
idea = Idea.objects.get(slug=self.kwargs.get('slug'))
self.object.idea = idea
self.object.save()
return HttpResponseRedirect(
reverse_lazy('idea-detail',args=[self.object.idea.slug]))
Hi guys, I need some help with django and graphQL
Basically I'm given shopify link with access token, I need to build api to get get my products with graphql
i just want to know if you have the pay if you build a website which includes payment methods
i want to know if i have to pay for the hosting server
i want to build a webstore for someone
Payment processing is usually best done through Paypal's or Stripe's API, so you just access those like normal APId
I'm not really sure what your question actually is though
Bokeh is about DataScience
My gamer name is Beerykenny .lol
@rigid laurel i want to create a website
A webstore
Something like Amazon but not that that advanced
I want to put products on it so people can buy them via online
But how?
The same way you'd create a normal website. You'd then interface with PayPal to handle payment
Through a rest api
what is a rest api
you make http requests to them and they return json information
You'd just use your Django/Python to talk to the Paypal API
e.g using requests to send a request to Paypal's servers
Oh - actually, it might need some JS. I haven't touched paypal in a long time
can you maybe
point me in the right direction
where to start
tutorial or something
https://www.youtube.com/watch?v=qKS87S0Imsk
https://overiq.com/django-paypal-integration-with-django-paypal/
https://django-paypal.readthedocs.io/en/stable/
I can't say how good/bad those are. But they seem like they should let you get started.
@native tide edx harvard cs50w has one of its projects (i think the third one) about creating a pizza webstore
u can check the lectures and content needed for that
I've a flask app and I want a button to start/stop a python script that runs indefinitely without refreshing the page. is the best way to go about this ajax and having the start button launch a process and the stop kill it?
Setup an endpoint that starts off your process, and an endpoint that kills your process. Its probably best to make them return json. If starting/stopping the script requires information, then you can take that as a url param, or change the endpoint to be a post and take it as a json paramater
any examples? Not sure where to start with that. I was thinking starting a subprocess in a function and then killing it in another one, and tying those to buttons with some javascript
@app.route('/start-script')
def start_script():
# Some code here that starts your script.
# I don't know how this works, but its the same as in a normal function
return jsonify({"status": "script started"})
then from the js side, you'd set the button that starts the script to make a request as part of the onclick
hmm and I could probably set a variable somewhere in the script that checks whether or not it should be running. and in stop_script just modify it
no need for subprocess then
the issue is: please paste text, not images
1 moment
from app.models import User, Post
@app.shell_context_processor
def make_shell_context():
return {'db': db, 'User': User, 'Post': Post}```
I suspect the issue is: after you ran flask shell, you forgot to import your code
you probably need to type import my_stuff, and then you can type my_stuff.db and it might work
or maybe you need to type from app import db
the function should be to avoid having to import things into the shell, or so the tutorial says this
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iv-database this tutorial at the last paragraph
oic
The only thing I can think of is: you somehow put your make_shell_context in the wrong file
mm now i check better, this mistake is strange, i will do in the old way if i can't solve it
thank you for the support anyway!
Solved! I accidentally called the name of a dictionary entity with the same name as the tutorial, and not with what I gave it, lol
indeed db command still does not work, oh well lol
<body>
<nav></nav>
<div></div>
</body>
Is there a way I can let the div take an automatic height size that is equal to the remaining screen size not used by the navbar?
@tranquil robin I think the only way to do that is with JS
get the height of the navbar, subtract the screen size, set the div to that height, and trigger all that in an onresize event for the window
I don't think there's any pure CSS solution
got it
give the navbar for example 10vh height and the 90vh to the div 🙂
but for some reason the pc is bugging out, I cant click the navbar buttons -,-
If you use fixed heights for each it would work, just not if you want dynamic resizing
like, if you hard-assigned 10vh and 90vh, that's fine, but if you wanted to change based on the contents of each, that's another story
nah its just a search page with a navbar and searchbar div