#web-development
2 messages · Page 71 of 1
There are some things I do not understand like why don't they make seperate files for each part instead of refactoring
@coral raven Because not all pages are the same
And it aint
Worth it
To repeat the same thing
Like the title
Of the page
The header
Is almost always the same
So why write it over and over again
that only applies to templates right?
why don't they make separate files for models, views, routes etc and wait till the file becomes large enough to maintain
in Corey's guide he refactored the code 2 times
I mean when you import libraries or modules in python you are refactoring too,cause you are not writting those libraries from scratch
@coral raven Just to be mote organized
In django there are specific files to place specific parts, which is good but there is no freedom
Yeah thats the point of django
Its a framework
After all
Its not a library
Like flask
More or less
Also templates are kinda like views
And from what i saw in coreys code
He uses
A model
But the project is pretty small
So you dont really need
A bunch of models
And also the controllers are separated
But that seems to be a personal choice
Not a standard
Cause flask gives you more flexibility
On the way you separate your models views and controllers
I think you're confusing the enter/return key with the space/dot key
Hi everyone
Which aws service can be used to deploy django backend with android app?
you could use lightsail but be careful as they charge you for the storage space used in lightsail services but not for the lightsail service itself
(one of the many alternatives)
@fickle saffron go for amazon lightsale bcz it's free
coupled with elastic beanstalk
but be carefull you will be charged regardless of the plan you use (personal experience)
@bleak bobcat What do you mean
Hello. I'm new to security with flask. I have a restful api server. For a basic authentication, I want to give my customer an access token that I want to return a response only who has a valid access token.
I can just create a random key, deliver it to my customer and say "when doing a request, send me the access token in it" and check if the incoming requests includes a token and is valid.
I want to do this in the right way but I don't know which way is elegant and not amateurish. Thank you for your advices
Hello. I'm new to security with flask. I have a restful api server. For a basic authentication, I want to give my customer an access token that I want to return a response only who has a valid access token.
I can just create a random key, deliver it to my customer and say "when doing a request, send me the access token in it" and check if the incoming requests includes a token and is valid.
I want to do this in the right way but I don't know which way is elegant and not amateurish. Thank you for your advices
@minor horizon Take a look at json web tokens (JWT)
Looking for it, thanks
@tardy trellis I mean that you don't need to press return every 3 words
Hi, anyone that has experience with React and Python? I have an <input type='file'> that passes its data (type is JS's formData) via an http request to my Python app. And I can't read/parse it. It shows up empty.
What's the best way to pass a file from React/JS and read it in Python? Maybe I'm not using the right format, or most probably I'm not reading it correctly
@dawn elk what are you using for the backend?
python
@dawn elk a web framework?
+asyncio but nothing like django or so
@dawn elk how are you sending an http request to a python standard library?
Do you have a simple HTTP server setup in python?
From React I'm doing an http request using fetch.
On the Python side I am using WAMP and Crossbar
@dawn elk Okay, do you have the ReactJS proxy feature setup?
You need to setup a proxy redirection from React to the python server.
I believe the aiohttp_cors I'm using from aiohttp does this
In the same fetch request I'm sending other data (JSON). That data is read just fine.
So the problem I believe is with the formData I'm sending
const files = Array.from(e.target.files);
const formData = new FormData();
files.forEach((file, i) => {
formData.append(i, file);
});
setImages(formData)
};
This is on the React side the handler for onChange
And then I take the formData and pass it as an argument on the fetch POST request
OOh I just noticed:
variableX: variableX,
photo: images,
}),```
This is the body of the request and I am JSON-stringify-ing it
Maybe that messes things up
stringify-ing the file?
yeah I am also sending other data
so I 'forgot' that I am also sending a file
and I'm passing it alongside the other stringify-ied data, bad right?
So, inevitably I'll have to do 2 requests, correct?
One for the JSON data (stringyfied) and a separate one for the file
Yeah, I would look to sending it as binary data
Or can I send 2 types of data in 1 request?
you can send two types of data in 1
ok thx, I'll check that later
I want to add a delete button in flask, I am wondering is there a way I coyld use def delete(self): and send a delete requsst somehow when the button is pressed?
Or shpuld I use a post request redirecting to a delete page
anyone know how i can
create a pyplot plot
and dynamically display it
using jquery
in flask
I want to add a delete button in flask, I am wondering is there a way I coyld use def delete(self): and send a delete requsst somehow when the button is pressed?
@limber laurel You can make a delete request using AJAX, I don't think HTML forms support delete requests.
But it also can't hurt to just as you said use a post to a delete endpoint
Alright, will look into it, could be a good learning experience as I havent worked with that or even JavaScript yet
Thank you
I am following Tech with Tim's flask tutorial, and he is doing this
@app.route('/admin')
def admin():
return redirect(url_for("home"))```
But I found out that this works py @app.route('/admin') def admin(): return redirect('/')
@limber laurel see how I add delete functionality to Flask
What's the difference between the two and why would I use one over the other?
@chrome scaffold where do you want to direct the user?
those may possibly direct the user to two different locations
The home /
I am just asking about if there is a time in which I want to use one over the other
url_for seems more dynamic
One creates the endpoint based on function name and the other expects an endpoint
If you end up changing uo the routes as you scale your project
@limber laurel Is correct, url_for is more dynamic.
Oh so if I then change the route for the page I don't have to change it in more than 1 place
Unless you change function name.
👍
totally, JS isn't required to create a site with Django
hi im using an old book to learn some basics of django
and in one example we try to get a digit of the url using this code path('time/plus/(\d{1,2})/'
the book is a bit old so it looks like this url(r'^time/plus/(d{1,2})/$'
do i still need the caret or dollar sign and im assuming i dont need to say its a raw string
@native tide would appreciate if you added me
@modest scaffold is this for a class? If the book isn't required for something else, I'd honestly recommend the docs/tutorial. If you have to use the book, check the beginning for which version is used and them look up urls.py in the docs, hover the bottom right-hand corner, and change the docs to your version
The Django docs are so good you can pretty much get away without a book for a while, then pick up two scoops of Django for the latest version
Hi! Can you help me in Django?
So I'm creating a DetailView, but what if I'd like to use a username instead of pk?
Is it OK, if I just simply use <username> in my url
and pass these two attributes to my UserDetaulView class?
slug_url_kwarg = 'username'```
Can you use html templating in a github page?
@native tide k thanks
is sqlite3 your database backend?
Hoy, is there a library for using google forms? To simplify Form creation etc...
Doesn't sound likely mabye you can make it!
totally, JS isn't required to create a site with Django
@cold anchor Only HTML and CSS?
Hey guys what is docker, and is it useful for all applications???
even css isn't really required, but html is definitely required
you'll need css if you want it to look nice
in forms
u dont need html
tbh
u just do {{ form }}
and ur done
but
html is required
ur not writing it
but django is
idek why people dislike writing forms tbh
Like i dont find them that bad to write out manually and it makes it easier in places for stuff like css
sup guys, any1 available for questions?
!ask
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving.
• Be patient while we're helping you.
You can find a much more detailed explanation on our website.
i want to build a website for myself, but dont want to pay like 20$ a month to one of those sites like wix or whatever
if i build it myself, will it be cheaper in the end ?
oh yeah
massively cheaper in the long run
and short tbh
and you learn a new skill
do I only have to pay for the domain?
what are hosting prices like?
it also depends on how you want to spend your time, if you want to build a site that's a pretty www.mysite.com page, then yeah do it yourself
i saw domains for like 1$ a year ? lol
$12/yr usually
hosting can easily be < 5$ a month
it also depends on how you want to spend your time, if you want to build a site that's a pretty www.mysite.com page, then yeah do it yourself
@cold anchor check http://oliviamolinapragency.com/ for example, I like that design, not sure how difficult it is to learn to create smth like that myself tho tbh :/
I see
well i always bought my domains at godaddy, i think they were like 0.99$ for first year
very simple, I saw something like that for a site I wanted and just copied it
go daddy say theyre 0.99 for the first year
very simple, I saw something like that for a site I wanted and just copied it
@cold anchor you can just copy ? lol
yeah, right click > view page source
i wonder if i can just buy it for a year, cancel the subscription, and after i dont have it anymore, buy it again for 0.99 after the 12 months
lol I don't think so
apple lol
they keep a record of the domains you bought and won't offer it for the same price again
new acc :p
most domain sellers put a parking page on the domain for a while after it expires so they can hold it in case somebody wants to buy it and they can sell it at a higher rate
its not hard to pickup tho overall
https://crunchy-bot.live/home I did this after about a week of learning css lol
do i only have to learn css to be able to do that?
I did that entire site without writing any css lol
https://tailwindcss.com/ is the framework i used for that site
html isnt that bad to learn and you can pick it up quickly
idk what a framework even is
a css framework (I personally prefer Tailwind but things like bulma also exist) makes it so you dont need to write any css really
its all done with the class names
so rather than some massive css block to make a flex box the moves everything center
in the html's class
you can just do something like flex justify-center
may I ask what the total cost of that website of yours is /month ?
That site costs me maybe 2$ a month or lesss
nani
but the domain is free and its ran on the side of a bigger site
I feel like css is easy enough to not have to use a framework even
The actual cost of hosting on my servers is > 150$ a month
but thats because they're much bigger systems
i dont really know much about this tbh
all this hosting stuff and so on
but
can you tell me where i should start now?
heroku free tier
like, I know that things like ( domains , framework, hosting, css, html ) exist now, but dont really know what to do with that knowledge
Id say have a look at flask for the backend (if you need the site to be dynamic not static)
as for css look at some css frameworks it might make your life easier
and yeah as for host, heroku do a free tier but its not 24/7
very easy to set up, and cheap to scale to something worthwhile
how should I start now?
have you worked with a backend framework like flask before?
i literally just know a bit of python
@solar crag 😄
i was serious when writing that lol
then let me introduce you to the main man Corey!
In this Python Flask Tutorial, we will be learning how to get started using the Flask framework. We will install the necessary packages and get a basic Hello World Application running in our browser. Let's get started...
The code for this series can be found at:
https://githu...
He does an amazing series on using python to create a dynamic website and goes through everything like deployment etc...
thanks! i will start there
idek why people dislike writing forms tbh
I love making them but i cant really design anything good... i have css and html knowledge but the idea doesnt come
sign up for a bunch of products and see how they do forms
but now im a backend dev and i have a frontend dev so no need to..
look especially at their use of spacing, color (to highlight), font changes (between labels, helptext, titles, etc.) and animations
just a suggestion ¯_(ツ)_/¯
you're welcome! I also refer to this pretty often to help https://medium.com/refactoring-ui/7-practical-tips-for-cheating-at-design-40c736799886
I relate to that intro
how long did it take you to learn css and html?
How can i know if site is secure enough??
Oh and yes hoe can i create table in flask???
many to many relationship
can anyone explain url_for? ping if you know
@native tide i been writing a shit ton of flask so I could help
what does url_for do exactly?
anyone got any thoughts on celery vs rq vs flask_executor for job management?
what does url_for do exactly?
@native tide https://github.com/pallets/flask/blob/a12a34100ac0ab85c29f87117ac0b75100b52d3c/src/flask/helpers.py#L211
you can read it there
but the gist of it is that it takes the __name__ of your function, looks it up in a look-up table that gets created when you annotate with @app.route, and returns the URL for it
if you'd like to know more, track the app_ctx object through flask or read https://flask.palletsprojects.com/en/1.1.x/appcontext/
anyone got any thoughts on celery vs rq vs flask_executor for job management?
anyway though, i really am stuck at a crossroads
in rails I'd just be using whenever
U should do it with js @native tide
can't you just do?
<a href="github.com" class="github">See code? </a>
you can!
but @native tide if you do something like <a href="/path_on_my_site"> then you change the endpoint for /path_on_my_site, you'd want your links to update
and that's where url_for comes in
Well flaks is backend, if you want real time clock u should do it in js
ok thanks
Yeah, but its not that hard, basically typing in yt how to make clock in js eill drop you tutorial for that
@oblique jungle I researched them all a few years back and liked the community and flexibility of celery best
and I have a personal preference of using SQS as the message broker, but if you use redis you get a nice admin console
here's a list of the brokers and their features
does anyone here know about google sites for creating websites?
Hi i had a question. Where can I learn basic Web development
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Why are figures normally rendered as indented?
Test this sample with image.png in same folder:
<p>Normal paragraph</p>
<figure>
<img src="image.png" title="Captioned figure" />
<figcaption>Captioned figure</figcaption>
</figure>
Continuing from my question about how to receive/handle formData sent from a React/JS app into Python. I still can't figure out how to parse the data (it's a file).
I'm sending the data from React like so:
const formData = new FormData();
files.forEach((file, i) => {
formData.append(i, file);
});
setImages(files);
fetch(url, {
method: "POST",
mode: "cors",
cache: "no-cache",
body: images,```
On the Python side, I'm logging the payload to my console and the output looks like this:
<Request POST /url >
I can't find a way to parse/get the actual data.
Anyone?
<a href="github.com" class="github">See code? </a>
@celest lynx is this about my question?
no sorry
I'm not using Django or any other framework
Then without more information about your python code we can't do anything
Tell me what info you need
How do you handle the http requests ?
Here's the part that handles the request:
async def handle_method(cls, payload):
logger.info(payload) # logs <Request POST /url >
```
And I want to access the actual file somehow
What's your webserver ?
WAMP & Crossbar router
Don't know much about crossbar, look into https://crossbar.io/docs/File-Upload-Service/?highlight=upload
Hi All, just a quick question - does db.session.commit() | db.session.flush() |db.session.rollback() closes the session ?
or do we need to explicitly write db.session.close() to close the session ?
So I'm writing some inventory management but I've hit a bit of a roadblock.
I'm using Django and I have my shelving units defined, but the problem is that I have similar items that exist in multiple locations in varying quantities so I'm trying to figure out the best way to represent this.
Ideally something akin to
location = {
binA: 3,
binB: 2,
binC: 5
}
Hrm. I guess I can have the master item model, then physical item models that point to that master item model and a bin.
Thought I'd try the web gurus again.
Why are figures normally rendered as indented?
#web-development message
Browser default styling
Example for chrome :
figure {
display: block;
margin-block-start: 1em;
margin-block-end: 1em;
margin-inline-start: 40px;
margin-inline-end: 40px;
}
Where is that css?
Is it possible to define a figure css block that just ignores the default figure block and formats the code like it had never been defined?
Where is that css?
@open tinsel As I said, browser default styling. It's defined by your browser.
Just wondering how I find it.
for any browser
https://github.com/flywire/caption/issues/3#issuecomment-660056171
I have no idea and it doesn't matter. it's different for every browser, and even if you change it inside your browser it will not change inside the browser of other people
so it seems I need to define it if I'm not happy with it for others to use
yes
thanks
Just like you need to define the font-size of h1, h2 etc... if you're not happy with their default size
Same thing
I'm trying to do minimal but I can't live with indented figures - I'm using them for other things
Hello Everyone,
Can any one guide me regarding Django. I want to know the repositories to follow on github to understand the application structure of django and how its flow in larger code base
Is there a reason Miguel uses datetime.utcnow instead of datetime.now(timezone.utc)?
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iv-database
https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow
hi, anyone familiar with selenium web driver ?
File "/Users/user/Desktop/employee_env/lib/python3.7/site-packages/selenium/webdriver/common/service.py", line 76, in start
stdin=PIPE)
File "/Users/user/opt/anaconda3/lib/python3.7/subprocess.py", line 775, in __init__
restore_signals, start_new_session)
File "/Users/user/opt/anaconda3/lib/python3.7/subprocess.py", line 1522, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'chromedriver.exe': 'chromedriver.exe'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "supreme.py", line 35, in <module>
go = SupremeCheckOut(keys)
File "supreme.py", line 11, in __init__
self.driver = webdriver.Chrome("chromedriver.exe")
File "/Users/angelmoreta/Desktop/employee_env/lib/python3.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 73, in __init__
self.service.start()
File "/Users/angelmoreta/Desktop/employee_env/lib/python3.7/site-packages/selenium/webdriver/common/service.py", line 83, in start
os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'chromedriver.exe' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home```
i am getting this error, but thats weird because i have the chromedriver in the same directory, please help
It needs to be in path, not in the same directory. You could programmatically add the directory of the file to path with
from pathlib import Path
import sys
sys.path.append(Path(__file__).parent)```
i was able to get around this issue by installing a webdriver manager
thank you for gettin back to me, appreciate it
i can't seem to change something in visual code studio i'm trying to make a website
if you want to help ping me
what is that thing you want to change
Hi.
Is this the right place for a stackoverflow link related to a Django issue?
If it's long and advanced, maybe #❓|how-to-get-help is more appropriate
Hey guys! I have a problem where I got this error NameError: name 'person' is not defined , my code is basically this ```js
if minha == 0:
person = 'PEDRA'
print(person)```
minha is probably not equal to 0
@green flume You need to define person right above that conditional. I'd suggest None and some additional logic to handle if minha is not equal to 0
If it's long and advanced, maybe #❓|how-to-get-help is more appropriate
@bitter patrol It's definitely advanced. Zero code, basically a theoretical question you can say.
Do not define person above the if, just make sure you give it a value in all cases
Here's my question:
https://stackoverflow.com/q/62956639/11423360
If you can help me, just tell me here on Discord or post an answer on the link to get an upvote 🤷♂️
Maybe a separate DB for users and a separate one for django stuff. Though you don't get the orm then
That's a nice idea but I'll still need to restart the server after making migrations
thats because of how django works with its ORM as a fundamental in that case
so lakmatiol would be right in saying no orm
Well, my idea was to not use django at all for the second db and just manage it separately. There may be a way using django though
sadly not hot reloading for django
But in the end, I'll use the forms via Django. So even if I use something else for updating the DB, I'll still need Django to recognize the changes.
Basically, (I know it's sketchy) I'll modify the models.py and makemigrations from there.
Actually, is there a way to have Django as the backend and another framework or something as the front end.
So even if Django is reloading, the frontend still serves the webpage
Or maybe there's no point in using Django at all. Just switching to another framework
Well, you could just serve static files from a non-django route and.load all django data through JS, so when django would be restating, there would just be loading. But you lose templates then.for.quite a few things
Oh?
look into django rest framework
@twilit zenith Already using them.
which FE framework are you using?
But then it would be twice as much workload. Basically managing two servers at this point. This was the first idea that came to mind
which FE framework are you using?
@twilit zenith Not using one yet. I was hoping you guys could suggest one.
yeah, its very time consuming
i use Vue.js and Django rest
its kind of hard switching between 2 languages
i use Vue.js and Django rest
@twilit zenith oh? Doesn't Vue run separately than Django?
you can use CDN to run it within django templates
or CLI (which runs seperately
i use CLI
Oh.
cuz i want to make single page app
I think using the CLI actually is the way to go.
Since you're using CLI, I'm guessing the Vue FE is a standalone and not dependant on Django. Which means even if Django reloads, you still have Vue front end running
Or am I getting this wrong?
Oh.
vue can serve frontend, but no data will be displayed without API
I got an idea but I don't know if it will work.
Basically, host a separate server in using Node.js and Vue as front end and sends and recieves data through Django Channels.
This way, even if Django reloads, the we socket connection will be broken until Django is back online.
And while the socket connection is broken, I can just display like a waiting message using Vue
ah idk
And everything works normal when Django is back online and Vue starts reccieving and sending data
i don't get what you mean
what does it mean method not allowed?
you have diffrent http methods
like GET, POST, PUT, DELETE
if a method isnt allowed
it means youre trying to use a Method (GET, POST, etc...) that the endpoint has specified that you're not allowed todo
can anyone recommend a good web dev udemy course?
ok thanks
Thats kinda offtopic I guess but I don't know where to ask for this
I tried to install phantomjs and when I add the file to my %PATH% and echo it
It shows a "?" that I didn't type (checked 3 times)
(on windows obviously)
hello
please
can someone explain briefly what class Meta is in django?
I've been looked through so many resources but cant get it
@unborn dawn
Does anyone know how to run a python script from JS? I want to pass form inputs to a python script when the form is submitted.
Look into flask
I'm using Flask and I want to steam a numpy array and display it as a image in the browser (at 5 fps). I managed to achieve this using PIL to save the array into a buffer in PNG format, sending it to the client using a generator inside a direct Response (as a stream). However the method PIL.save is taking too long to save in the buffer. Is there a better method to stream a 2d numpy array as an image?
@tight rivet you might switch strategies to sending the data to the browser and using JS to visualize. Here's a starter reference: https://github.com/grebtsew/Visualize-Realtime-Data-Stream-Chart-in-Flask
I ran a websocket server on my DO droplet and then was timed out of the terminal. I need to terminate the server but I can't find it in the ps or top lists to do so.
Is there another way?
are you sure it's running? how do you know it's running?
It still allows me to connect to it in the client.
And if I try to run it again, the client acts as though it is interacting with older code.
As if it was the previous version.
Well, let me ask this: if I run "python server.py" am I looking for "server" in the list?
lsof -i:$PORT
will show you the processes listening on that port
you can get the pids from that
then you can kill $PID from there
anyone know if it's possible to use Jinja2 syntax inside a .css file
yup, totally possible
take a look here https://jinja.palletsprojects.com/en/2.11.x/intro/#basic-api-usage
you can do:
>>> from jinja2 import Template
>>> template = Template(open(cssfile, 'r+').read())
>>> template.render(name='John Doe')
yeah, i know, just wasn't sure if you could use it in css
oh
well i'm using flask as well
yup, it's very general
but i assume it's basically the same but with flask
eh, if you're using flask's static file serving, I don't think you can do it through that
you'll have to be serving the assets yourself
i'll give it a go
doesn't seem to complex though, their view function for static files just do this https://github.com/pallets/flask/blob/65a0a4b585781b5dd3db4009de3195e2ac7f049f/src/flask/helpers.py#L1052-L1065
and they add the url rule when you construct the App object https://github.com/pallets/flask/blob/master/src/flask/app.py#L578-L583
Hi guys, i'm just wondering how it's possible to do fingerprinting server side? I'm looking through fingerprintjs pro site: https://docs.fingerprintjs.com/pro/pro-vs-free and they say the fingerprint is never exposed in the browser. How is that possible? Doesn't a script need to be run locally to get a fingerprint?
Also, I guess in the same vein, how does stuff like google analytics/adwords and Facebook Pixel work? It's just a script tag on your website, how are they able to access user session data?
I'm just a noob btw, working on bot detection.
Hello, I need some help, I was following a flask tutorial because im trying to learn, but i ran into a problem even though i copied the tutorial's code line for line and couldn't find a working solution anywhere
This is the python/flask code:
from flask import Flask render_template
app = Flask(__name__)
@app.route("/")
def home():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug = True)
And this is the html file:
<!DOCTYPE html>
<html>
<head>
<title>Hello World!</title>
</head>
<body>
Hello World!
</body>
</html>
This is the exact error code: "Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application."
@terse trail you should be looking at the error in the python console and not the browser
It doesn't output anything? @rustic pebble
@terse trail what they mean is that wherever you are running flask from (the console for example) should spit out the error
it doesn't
I can see a missing comma here
from flask import Flask, render_template
idk whats the problem
ty for pointing that out and i fixed it, but it still gives the same error and no errors in the console
Hello everyone - does anyone know how to change your website's embed and how that appears across the internet? I am a beginner at web development and have no formal education so I'm not even sure if I'm asking the right question here. But I'd like to make my site's embed look a little nicer:
(also if this is the wrong place lmk)
I’m been using React and Vue for a while and want to narrow down “need”, is learning Flask a good way to get familiar and learn Python?
Does anyone know how to deploy a django + celery app with just 2 docker containers? (heroku limit for free service)
Thats my best
@frozen python I can't say, I've been using django and it's primarly OOP / functions
@native tide is Python narrowed down a bit compared to JS? JS, it’s integrated at time with HTML and CSS that can be “anything”, so I’m wanting to be more dedicated as a need
I like oop/functions in React/ JS
I learned HTML, CSS, and bootstrap to healp with design. I learned some JS as well and was unsure about what the pcross/difference woulb be like switching to python. With python and something like flash/django you still need HTML, CSS. You just use some logic in order to ulpload the pages and send people going to a url to a function that returns that html
It's way better to be honest, I got pretty burnt out making mock websites all the time. Also there isn't a lot of hard coding or anything. It's more using simple code for functional use to deliver webpages etc
and with something liek django it's just all made for you
@native tide ok, but is it a little bit narrowed down to what your doing? HTML/css.... ok here’s a box, ohhhh I don’t like the size or color..:: the font isn’t what I want..... haha.
Ok 👍 I’m going to start with flask, or should I start with Django?
@native tide I like JS with creating objects in React/Vue. It’s kinda gets weird here and there with useState. But I like the interaction and functionality of things
Yeah it's not as wide of a skill set that you need to worry about. It's from start to finish the same sort of process with each project. It's primary URL to returning HTML. If you are full stack or solo then you would need to concern yourself with the design otherwise you don't. Also you make things called MODELS that represent THINGS on your website. It's like a class. You'll use those models to render it into your HTML pages. aside from that everything else is extra
with js and front end there's so many frameworks and things to learn man..
@native tide is a model like a “component”?
@native tide so far, it seems like Py goes back to “vanilla” HTML, css.... your back to creating a HTML page for a template?, and other things
It's like a class. It represents something like a person etc
@native tide like a def? Int?
I mean you don't have to create your html page with just html, css. you can use bootstrap or another framework with it
def?
@native tide ok, I like React and Vue... are the objects similar to how you create things in them?
correct
Ok, but how do you place things in python/flask? In React/Vue it’s “<Navbar />” “<Box />”
And it connects to the component page you made
I think you're talking about components you've made showing up on your html page? If so it's some code like this {{ some_code }} that you can write right into your html page
sry if that's not what you meant I've never used react/vue
language barrier
Yes, components. But it’s not just HTML written on one page. React and vue, make it so there’s not a long list of code on a single page, it’s components that are brought in “represented “ to be placed on your page
Oh i see. I looked up a photo. Yeah It looks like there's some hard code in there or something. In django all that code is on a seperate file in your project. You integrate it by using variables that represent larger pieces of code in another file. you might write a for loop or something with a single variable or even multiple variables
@native tide yes 👍 I looked up models and yes that’s what it looks like what I’m referencing to. So far
Person = {
‘Name’ : ‘Bob’
},
Is similar to a object in react/vue, then you have
<h1>{ this.name }</h1>
To use it
But also, in React/vue, with components there’s class/functional components, you can also define height, width, color.
@native tide
Hahaha
@native tide “dictionaries” is what reminds me of objects in React, but models seem more like it
@native tide should I even be thinking of Django like a front end/design? Or is that strictly made by a framework like bootstrap, vue, React?
Jinja kinda seems redundant in python.... you can add things like that with React/vue, why use it from python?
server side rendering vs client side rendering
they present different solutions to the same problem, and end up giving you different sets of problems to worry about
Ok 👍, Django and Flask, seem as if it’s a style framework in a way.
HTML/CSS, it’s the structure and style.... then JS is the functionality....
What should I think of python/flask/Django as?
@frozen python python is a language, flask is a micro web framework built using python, django is a web framework built in python, which has a lot more builtins and libraries available you to out of the box
@dark hare ok, so when you create routes in flask, as in a navbar, what’s different than a front end to do that? Also, between objects/classes.... what’s the difference between flasks & React? Thank you!!
I think you are trying to learn and take in too much stuff at once. I would reccomend understanding one thing at a time.
react and flask are frameworks for a certain purpose, react which is built using javascript, flask is python
@dark hare so basically web vs desktop?? But that is, with info/data for a website to work?
I would reccomend learning how the web works first, I dont know what you mean by web/desktop, there is client/server, browser/server, and I dont know what you mean by info/data
You should watch these videos @frozen python https://www.youtube.com/watch?v=e4S8zfLdLgQ&t=12s
How does the internet work? Most people really don't have to know, but web developers have to know more and more as they grow in their career. These 2 videos cover how the internet works from a web development perspective.
Also, check out part 2: How the internet works from ...
theres a part 2 as well i believe
Don't worry about the python code, I'm only querying if the html/css is reasonable
What framework is the best here: https://geekflare.com/python-asynchronous-web-frameworks/
Hi, I'm starting to program with python for web, I ask for your guidance
guys what conecpts of web development are very important to know?
hello
i am beginner to flask and i get this error. i have installed everything correctly i guess but i get this error. anyone knows help. Ping me
Tanks.
@fair light ```py
from flask import Flask
If I use the FormView mixin in Django, how can I pass in paranaters and a context?
@tough star if your just starting quart is good because it's basically async flask
Viboa is pretty dead
Hasn't been maintained for 2 years
Sanic is pretty good but lower level that quart and you'll find yourself doing custom middlewear more often but it's a framework I use that I enjoy a lot
Fast api is good for API type stuff but Ive never used so couldn't say
in a django project should I put settings.py file in gitignore?
no
You should store any secrets somewhere else though. Environment variables for example
thank you
this is my login using oauth
and when it reaches login
it says
cannot GET /login
how to fix this
ping me
Hey guys, I'm new here and a completely begginner with Django and Firebase. I have a real time chat application, created with js and Firebase. You need to be authenticated to use this chat, but I wanted to use the specific auth of my django project. I was thinking to make an OAuth from my django project to the chat, but I have no idea how to do it. If anyone could help me to sort this out or know a better alternative, it would help a lot!
@fair light run flask in debug mode with app.run(debug=True) and check if there are errors logged to the console
@eternal frigate i did run like that and it showed no error in the console
/ redirects to /login?
Well I don't know flask, but if there is an error while accessing the url it should be logged by flask. Also it does not returns 404, right? It seems to be an error in the url routing
nop it does not return 404
Create a new endpoint like /hello and return hello world to see if other urls works
when i change that 127.0.0.1:5500/login to 127.0.0.1:5500/botlist.html (one of my webpage) it redirects sucessfully
but as it returns , i cant see if does function proper or no
Flask does not prints anything to the console?
Try to get /login, it should log the http request
it says cannot GET /login and that was the error.... how do i get /login now
That error message does not tells anything really, it should tell why
I have doubt if you are really running in debug mode
..
export FLASK_ENV=development
flask run
You did it?
no
if py is above 3.6 its not required to do i guess.. idk i found something like that somewhere
hello guys 🙂
i need this php code to python syntax .
<?php
$fname = array(1 => "scot", 2 => "john");
$lname = array("scot" => "smith", "john" => "doe");
echo $lname[$fname[1]];
?>
and want to publish frontend by jinja2(django3).. help me please
@snow sierra ```py
first_names = ['scot', 'john']
last_names = {'scot': 'smith', 'john': 'doe'}
print(last_names[first_names[1]])
Dictionaries are pretty much the equivalent to associative arrays
How can I add the appropriate escape sequences to a link? (i.e. hello world => hello%20world)
pretty sure urlib has a feature inbuilt todo that
@quick cargo Ok, thanks. I'll check it out.
guys do you know how to create table in flask???
https://cdn.discordapp.com/attachments/105765765117935616/734091339515428894/unknown.png
i am using the particles.js library
and for each element i have, the things move down
how can i fix this?
@glass sandal i want to build table for many to many relationships but i am strugling a little with it xD
hi friend, so i found this template powered by boostrap 4 on the internet. Is it legal if i just go ahead and add it to my project ? sorry if my question sounded stupid but i am very new to web development and i am a terrible at the front end
i just want to know if its good programming practice to take others ppl work and add it to your project
0
I want change css. when i change continer height for oncklick function, after 1 second returns the same size, and when i have error console refresh in 1 second and i can't see. how fix? i turn off livereload plugin.It refreshes everything in 1 second.
please help me
does anyone know why i get an import error when i try to import setup_test_enviornment in a shell?
Circular import error?
ima check
the thing is i just started my shell tho
lol
im so dumb
i cant spell
Oof
imagine not being able to spel lol
Hello everyone. Can anyone tell me how to highlight the current tab using Dash/Plotly Bootstrap? I'm finding tutorials on how to do this in CSS, but not quite sure how to implement it in Dash
Does anyone know if it's possible to authenticate in Firebase through django authentication? Thanks in advance
I would be kind of integrating both databases
Hi, I need some help in Django!
https://github.com/CoreyMSchafer/code_snippets/blob/master/Django_Blog/11-Pagination/django_project/blog/templates/blog/home.html
{% if page_obj.number == num %}
<a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a>
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
<a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a>
{% endif %}
{% endfor %}```
Can you, explain me the add -3, and 3 part?
I'm totally lost 😄
@faint abyss I guess it adds -3 to the current page number as well as adds 3 to create a range of page numbers for display, that are also clickable and will reroute you to that page by number
Anyone know how to manually resize a button/toggle switch/checkbox in dash/plotly?
This what I'm trying to do, but it doesn't change the size of the actual checkbox, it instead increases the size of the box that the widget is in
How about linking a custom CSS to individual components in dash?
I am trying to build a News Feed Web-App. I have made a scrapper and set it on cron job. I am thinking about to use API to send the data to the APP so that it can use the data and display it. What should I use? DRF or Flask?
DRF?
Django Rest Framework
It's difficult to suggest one or the other without more info on the requirements your app has.
I tend to favour the simpler things if possible. In this case, that'd be Flask.
If you need to leverage some of Django's batteries-included features (like forms, ORM, etc) then use Django
If you wanted to write purely an API (so no rendering of web pages), then I'd suggest a "micro-framework" like Falcon @hearty tendon
hllo
@proper hinge Thanks! Since this NewsFeed Web-App is simple. The Web-App starts with login page and once you are logged in then it displays the news title, description, etc. (It also has page numbers in the bottom to allow browsing through pages).
I have made the scrapper to yield JSON file so my next task is to use Flask API.
hi
hello
hey is here anyone who uses the Django crash course book by greenfeld and can help me out for a sec? I'm traing to set up my cookie cutter project and then my anconda cmd said that i havent git installed, but i didnt skip any part so i'm confused and stuck
@remote ruin We can deff help you out with that.
Mr kimchi man
git --version if you're on mac
git --version
Oh wait
alright so do i do that in my normal windows 10 cmd?
no it's not installed
@native tide would you mind joining a vc with me?
my wifes laying next to me at the moment. I'm not too sure how it would be downloaded other than that though anyways
in terminal
I can tomorrow but I'd have to look into it. You use mac or windows?
i'm using windows 10
but hey thx, i will just look up a video
i appreciate your help
alright
i got it now ^^
In django, I want to add more items to my context in a DetailView, any ideas how I can do that?
@limber laurel override the get_context_data method https://docs.djangoproject.com/en/3.0/ref/class-based-views/generic-display/#django.views.generic.detail.DetailView
Found it in a stackoverflow post, but thanks anyways. 🙂
Does anyone know where I can find a good tutorial for a real time chat application, using django?
yo !
Guys, how do I get form.item to have bootstrap styling?
or styling in general?
Looking it up gave me a result called crispy forms
pip install django-crispy-forms
can someone hop over to me in vc, i'm struggling a little bit with connecting postgreSQL with my django project
does vibora have a own discord server?
can someone hop over to me in vc, i'm struggling a little bit with connecting postgreSQL with my django project
@remote ruin do you have psycopg2 installed?
users = People.query.all()
for user in users:
print user.name
@sinful stone That's because sqlalchemy is an ORM, you could communicate using sql directly without using sqlalchemy but the communication protocol of your database vendor
Guys, how do I get
form.itemto have bootstrap styling?
@icy sparrow https://docs.djangoproject.com/en/3.0/ref/forms/widgets/#customizing-widget-instances
You can change the attributes of the form's html elements through widgets
Hey guys. In request.authorization from flask, is it possible to except from request headers include a "organization" and"password" pair instead of "username" "password"? So I can get the organization name with
auth = request.authorization
print(auth.organization)
how can i set my stylesheet with flask?
I actually have a smiliar question, except with Dash (which is based off Flask I believe)
Hey @sly vessel!
It looks like you tried to attach file type(s) that we do not allow (.css). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .m4v, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg.
Feel free to ask in #community-meta if you think this is a mistake.
css file
How would I reference this in my Dash app for a bootstrap toggle switch component?
I've tried setting "className" to every one of those classes in the dash app, but it's not picking up the style correctly
Where can you learn to optimize queries
Maybe there is some youtuve cpurse or some documentation someone can link
Or personal advice?
Maybe I shpuld be puttibg this in databases, but it is in relation to developing web application
Hello, each time I am trying to do something related to manage.py file (like running the server or doing a help command) I get an error, I am trying to develop a website in Django.
Hey guys, how can I get the "nome" ? I tried this aluno1 = { "nome": "Cauã", "nota1": 8, "nota2": 6 } print(f"Alunos: {aluno1.nome} ")
aluno1["nome"] @green flume
@thorny geyser Thanks
np
Hello, each time I am trying to do something related to manage.py file (like running the server or doing a help command) I get an error, I am trying to develop a website in Django.
@stray sorrel You can run it from the command line, no need to start python's shell
@native tide I tried to run it from cmd shell and I got this:
It is pretty similar when I try to do python manage.py runserver
Do you think that the issue is caused because I am in the virtual environment? Or it doesn't matter?
Ohh, thank you so much for your help 🙂 !
np
Hello. I'm trying to figure out what I'm doing wrong here. I created a custom CSS toggle switch in an online generator and I'm trying to implement it in my Dash app.
Here's the CSS file:
What exactly am I supposed to change to get the CSS to show up in my code correctly? Right now the server runs, but the page is all jacked up and doesn't show anything close to what I'm trying to achieve
Here's the cleaned up code...
Hey guys, how can i get all fruits I tried a lot of ways, but i can't get the expected result. EDIT: I want get the result using for ```python
foods = {
"fruits": {
"fruit1": "Apple",
"fruit2": "Banana",
"fruit3": "Watermelon",
},
"vegetables": {
"veg1": "Broccoli",
"veg2": "Lettuce",
"veg3": "Tomato"
}
}
for fruit in foods:
print(fruit)```
for fruit in foods['fruits'].values():
print(fruit)
thanks
hello can someone explain me what is the need of forms.py file when working with user models
on django
hey how do I compare two uploaded text files in Django?
@native tide hey i'm going to bed soon. i read your solution for my postgreSql problem, so i will have a deeper look at it tomorrow and maybe turn back to you. i appreciate your help
<div class="form-element checkbox">
<input id="tnc_optin" type="checkbox" name="tnc_optin" class="css-checkbox" onclick="refresh(this)">
<label for="tnc_optin" class="css-label ">
What's the value of a checked box for this HTML element? Not sure at all
@native tide If the value attribute was omitted, the default value for the checkbox is on, so the submitted data in that case would be tnc_optin=on
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox
Does anyone know if you can render json serverside in a github page?
thanks! @native tide
@quasi hawk github pages are static sites so no
Can you use jinja2?
Nvm its dynamic too i think
What do you think would be best way to do a onetime rendering?
@native tide Sorry, one more question.
<div class="button-container">
<input type="hidden" name="recaptcha" id="recaptcha">
<button type="submit" class="button red large">ENTER NOW</button>
for a button like that, what is the value for a clicked button?
Like im using json for cleanliness but then render it when I want to deploy it to my static page
I'm struggling to extract post data in Sanic. I have a simple html-form that posts data to the same site (right now it's just returning the data as a json, but the goal is simplpy to extract the POST data). The html looks like this:
Test <input type="text" name="test_text">
</form>```
And the Sanic code looks like this.
```@app.route('/test2')
def index(request, methods=['POST', 'GET']):
if request.method == 'POST':
return response.text('POST request - {}'.format(request.json))
elif request.method == 'GET':
return response.html(q_html)
app.run(host="0.0.0.0", port=8000)```
But I just get an error because the request ends up being empty. I've tried a bunch of permutations and looked where I could find info, but clearly there's something fundamental here that I don't get. the only thing I can think of is if I'm supposed to do something specific with the "action" part in the html, but I can't find any info on it. Any ideas?
(oh and the q_html is just the html string above
I'm struggling to extract post data in Sanic. I have a simple html-form that posts data to the same site (right now it's just returning the data as a json, but the goal is simplpy to extract the POST data). The html looks like this:
Test <input type="text" name="test_text"> </form>``` And the Sanic code looks like this. ```@app.route('/test2') def index(request, methods=['POST', 'GET']): if request.method == 'POST': return response.text('POST request - {}'.format(request.json)) elif request.method == 'GET': return response.html(q_html) app.run(host="0.0.0.0", port=8000)``` But I just get an error because the request ends up being empty. I've tried a bunch of permutations and looked where I could find info, but clearly there's something fundamental here that I don't get. the only thing I can think of is if I'm supposed to do something specific with the "action" part in the html, but I can't find any info on it. Any ideas?
@static moss @app.route('/post', methods=['POST']) in the decorator
Not in the function defenition
@native tide Oh I see. That fixes the issue of not allowed POST, but I'm getting the same error I had on a different permutation (see below) where it fails to parse the body as a json (as far as I can tell the request is empty)
def index(request):
return response.html(q_html)
@app.post('/test2')
def return_post(request):
return response.text('POST request - {}'.format(request.json))```
Anyone know how to change default page of a github page? i.e. change it from index.html to somethin else
in mkdocs.yml
@native tide Oh I see. That fixes the issue of not allowed POST, but I'm getting the same error I had on a different permutation (see below) where it fails to parse the body as a json (as far as I can tell the request is empty)
def index(request): return response.html(q_html) @app.post('/test2') def return_post(request): return response.text('POST request - {}'.format(request.json))```
@static moss I think form data is being posted and not json data? So try request.form
@open tinsel What does mkdocs.yml do?
dope ty
@static moss I think form data is being posted and not json data?
@native tide I (probably wrongly) assumed it just came out formatted as json data. If I doreturn response.text(request)I get<Request: POST /test2>but not the input data, how would I extract that?
I think request.form.get(input_name)
any recommendations on static html page generators in python?
Will MkDocs do what you need? How complicated is your site? RST is more powerful but more work.
I think request.form.get(input_name)
@native tide Will you look at that. Thanks a lot dude!
Np
Get started writing technical documentation with Sphinx and publishing to Read the Docs.
Can you show me an example of rendering json to html?
yeah gimme a sec
<div class="text-center">
<ul id="filters" class="filters mb-5 mx-auto pl-0">
{% item in items %}
<li class="type active" data-filter=item.filter>item.content</li>
{% endfor %}
</ul>
</div>
<div class="text-center">
<ul id="filters" class="filters mb-5 mx-auto pl-0">
<li class="type active" data-filter="*">All</li>
<li class="type" data-filter=".python">Python</li>
<li class="type" data-filter=".placeholder">placeholder</li>
</ul>
</div>
where does the json come from?
a local json file
its just for organization's sake
Im building a portfolio website using github pages
and want to keep project information in a json file to render
so I would just be rendering the html locally any time i add projects
<div class="button-container">
<input type="hidden" name="recaptcha" id="recaptcha">
<button type="submit" class="button red large">ENTER NOW</button>
What's the value for this button that will send the POST to the server? Thanks
@quasi hawk Markdown is a lightweight markup language. You are looking for more functionality, so https://python-markdown.github.io/extensions/ (especially third party) or some other platform.
I'm not sure there is an extension that will process json - I didn't check the third part list
ah i see, thanks for the help!
I've just had a look and I can't see anything that will process json. If you process it you can still get MkDocs to process the document.
There is a tutorial in their wiki for extensions
@native tide you need to add a form
<form action="/some-route" method="post">
<button type=submit></button>
</form>
Can any guru offer an opinion whether I've designed the html/css structure properly? It is a markdown preprocessor extension which formats captions with generated numbers: https://github.com/flywire/caption/issues/3#issuecomment-660130402
Sample output: https://cdn.discordapp.com/attachments/366673702533988363/733876989366108160/unknown.png
hey how do I compare two uploaded text files in Django?
Can anyone tell me what it is I'm doing wrong here? I'm trying to use a custom generated CSS toggle switch in Dash and I'm assuming it has to do with how I'm implementing the class name from the CSS file, but I'm not sure...
Here's the code and CSS file:
👍
Guys just come over to django
We can go to disneyland together with django tshirts and ride the t cups
how to learn django as a beginner in python
@keen lily Python? If that's what you mean
@proud frigate You go to youtube and watch everything and then again. It's the hustle baby
And udemy
React, Angular, Vue or what
suggest some channels @native tide
00:00:00 - Introduction
00:00:15 - Web Applications
00:02:07 - HTTP
00:04:58 - Django
00:11:10 - Routes
00:28:46 - Templates
00:53:06 - Tasks
01:00:31 - Forms
01:32:09 - Sessions
This course picks up where Harvard University's CS50 leaves off, diving more deeply into the desi...
DONATE :) - https://www.paypal.me/thenetninja
Hey gang, in this Django tutorial I'll introduce you to what exactly Django isand why we would want to use it as web developers.
----- COURSE LINKS:
- Python tutorials - https://goo.gl/xD2AvX
- Course files - https://github.com/...
And this guys playlist is pretty good but a very few things are outdated but overall its still good.
ok brother
@proud frigate Just pound em out like hotcakes
Just pound em out like hotcakes@native tide not a native english guy brother" so pls make it simple
What's your native language?
USA, California
this are my tables
class Project(db.Model):
__tablename__ = 'project'
id = db.Column(db.Integer, primary_key=True)
project_name = db.Column(db.String(120), nullable=False)
project_tickets =db.relationship('Ticket', backref='project_ticket', lazy='dynamic')
class Ticket(db.Model):
__tablename__ = 'ticket'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(120), nullable=False)
project_id = db.Column(db.Integer, db.ForeignKey('project.id'))
comments = db.relationship('Comment', backref='ticket_comments', lazy='dynamic')
history = db.relationship('Ticket_history', backref='ticket_history', lazy='dynamic')
class Ticket_history(db.Model):
id = db.Column(db.Integer, primary_key=True)
details = db.Column(db.String(500))
ticket_id = db.Column(db.Integer, db.ForeignKey('ticket.id'))
class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True)
details = db.Column(db.String(400))
ticket_id = db.Column(db.Integer, db.ForeignKey('ticket.id'))
i am trying to figure out how to delete all data related to a project from the database for example:
project name = Item
and i want to delete Item with all Tickets related to Item, all Ticket_history related to Tickets in Item and all Comment related to Tickets in Item
i have tried alot of sqlalchemy query codes and i cant yet figure it out.
@bleak bobcat thanks man
@bleak bobcat im new into sqlalchemy i didnt know it had cascades🤦🏽♂️
That's fine, now you know 🙂 pls don't ping me every 5min
hey guys
im trying to reverse proxy using nginx
on my docker django application
which serves static files on port 8000
i want port 80 to redirect to port 8000
ive tried what i could
but its not allowing me so
upstream apex {
ip_hash;
server apex:8000;
}
server {
listen 80;
server_name _;
location /static {
autoindex on;
# static files
alias /app/static/; # ending slash is required
}
location /media/ {
# media files, uploaded by users
alias /app/media/; # ending slash is required
}
location / {
proxy_pass http://apex/;
}
}```
this is my nginx.conf
Hello! I have followed this series up to the deployment part. https://www.youtube.com/watch?v=goToXTC96Co&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH&index=13&ab_channel=CoreySchafer
In this Python Flask Tutorial, we will be learning how to deploy our application to a Linux Server from scratch using Linode.
If you would like $20 of free credit towards a Linode account, then you can use my link here to sign up:
https://linode.com/coreyschafer
We will be ...
Corey deploys it on lineode, but I am unable to afford an account over there. I have got student account from Github which allows me to use Heroku.
Is it possible to deploy this on Heroku?
I have used sqlite as well.
Why not try and see where that gets you ?
@bleak bobcat I do agree with you, but I was trying to save time since I don't get much time after the job to do the project.
Yes you can host it on Heroku but don't ask me how I've never used it
Okay, thank you!
hey
anyone can help me on flask?
i want to display something on my pre build webpage. i am using oauth to take user's name . i can return it . but i dont know how to display it on a specific webpage (like: index.html)
i tried render_template
it dont work
maybe because i dont know
can someone guide me?
@sturdy pike u know how to work with oauth2? and display some details about user?
@sage thistle No I'm sorry. I shouldn't have opened my mouth. 
Not sure where this question fits exactly, I am putting here since the whole project is a web application.
We are building a stock screener. It's basically a page where you can select certain criteria and filter out stocks meeting those criteria. We have some 200 criteria and over a 1000 stocks across 20 years.
And some of the criteria can span multiple years, like, give me stocks whose annual profit growth has been > 5% every year over the last 10 years
The data is stored in Mongo db
Overall, running this kind of criteria takes a very long time. So We have loaded the entire data (~12 GB) into a Pandas dataframe and keep it loaded into the memory at all times
But this doesn't seem like a feasible approach for the long run
Can anyone suggest some ways as to how operations on such datasets are handled in other projects?
So that it doesn't take 10 minutes to run a complex query
seems like something SQL would be more suited to if the data is tublar
@merry geode thats for u^^
@fair light Use render_template(some_kwarg=user_name)
in the template html you can do {{ some_kwarg }} and jinja will replace that with the kwarg name with the value you give it
I know. It's just that a lot of processes are tied up with how the data is stored. So changing to SQL now would basically mean a complete overhaul of the project. That's not possible, unfortunately
Just throwing something out since i have no real input but could you chunk the data set by combining it with python generators in some way?
if you can rework the db you're probably gonna need to work with a compiled lang and chunk the data ig
tho you're probably still gonna have to cache it
Make some workers that will calculate these “rollup” metrics and store them in a separate collection so that you have these metrics easily in your database but only need to calculate them once and then in the webapp you just query the rolled up metrics
@quick cargo why i get like this
are you doing {username}
do you render it as a template?
and do you do something like username="some thing" in the render_template() bit
yes i guess
hmmm
..
1 sec
i need to double check something
are you just in debug mode using the dev server?
i named it the html folder templates at first
i changed to template
but still
same
i should be tempalates
so you're going to the server -> what ever endpoint
and its serving that
should be templates by default
i really dont know why thats going what its doing
whats your html code and full endpoint code?
you're missing a html close tag btw
Do you have a template engine ? ...
and body really should be outside head
i would imagine he has the engine considering Flask has one by default
aah i was just doing it in a hurry
Ah alright, I thought flask came without one
ok now?
Not as streamlined as it says then
I mean pallets who made flask are the people who made Jinja which is pretty much the only decent templater
are we going out of topic?xdd
not really lol
okay lol so what should i fix now?
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
ok
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template("login.html", username="bob")
if __name__ == '__main__':
app.run()```
this works for me
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ username }}
</body>
</html>```
yes
ok done
and add:
from jinja2 import FileSystemLoader
from jinja2 import Environment
template_env = Environment(loader=FileSystemLoader(searchpath="./templates"))
def render_template(name, **context):
template = template_env.get_template(name)
return template.render(**context)```
then try go to the template with the dev server
name means web name right?
it just means the template name
dw about the param name
it will just mean when you do render_template('some.html, **kwargs) it will call that function
when i used that code
make sure the above code is just after where you define app
should i remove this one?
no
lol
litterally stick it just bellow app = Flask(__name__)
huh?
you should leave all your original code
except just remove the import render_template
and just put that code bellow app = Flask(__name__) but before your endpoints
are you just doubling clicking the html files by any chance?
whats your code now
i mean lemme try this https://discordapp.com/channels/267624335836053506/366673702533988363/734755466235871314
OMG
i tried that same code and not working
🤔 you must be doing something seriously jank
:/
what python version are you on?
idek tbh
and its not raising any errors either?
🤔 that is fucking weird man
actually tired lol 3 days trying for this shit
What's the url in your browser ?
Hi I need help from Django rest framework expert,
Does anyone know what's the difference between APIviews and ViewSets?
I started using APIviews and I can acomplish everything I need with them
(Sending requests to serialize/deserialize models)
But what I'm missing is having routers for APIviews(so that I can see the whole structure on RestFramework 'dashboard') as well as a nice way to send requests from the webpage
So my question is can I use APIviews and ViewSets interchangebly and gain routers that way or am I gonna lose something by using them?
is a websocket basically a port that a user can connect to?
websocket allows bidirectional communication, so a server can also send data to client. websocket runs on 80/443 server-side and on a browser-dependent port client-side (a different one for each connection)
that makes more sense now, thanks
other option is event stream, which is one direction from server to client and pure HTTP
guess i'll need to look into other types of connections because - like you just said right now - there def exist one way connections
Hello! I am trying to deploy my app on Heroku. I was using SQLite but moving to postgresql on Heroku.
I am getting this error in activity log while registering on the deployed website : sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "user" does not exist
This is my models.py :
This is my create_app in __init__.py:
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
with app.app_context():
db.create_all()
bcrypt.init_app(app)
login_manager.init_app(app)
mail.init_app(app)
from NewsFeed.users.routes import users
from NewsFeed.posts.routes import posts
from NewsFeed.main.routes import main
from NewsFeed.errors.handlers import errors
app.register_blueprint(users)
app.register_blueprint(posts)
app.register_blueprint(main)
app.register_blueprint(errors)
return app```
I am unable to point out the reason. Adding __tablename__ = 'users' to the User class works but then it gives error in ForeignKey.
what is your table named in postgres?
Django
Django @errant garnet
Laravel's good too. It's personal preference.
i mean theyre two diffrent language frameworks lol
also Laravel really isnt very performant
I mean, neither is django compared to SPA.....
Sanic or Django ?
Django question: I have some built-in Django authentication views that call database objects (background images stored in the database). When I change the images in the admin panel, it requires me to restart the server before the database changes apply to the views. Is there a way to easily get around this without sub-classing since having to restart a working web server in production will not really be a viable option?
@midnight needle that depends they're two very different frameworks
And oriented at two very different styles aswell
hello there
i am working with discord on my bot dashboard
and i need to make sure the user has the appropriate permissions to do so
you can view some information about it here: https://discord.com/developers/docs/topics/permissions
i am using flask, but jinja doesnt support operators in it such as & so im going to have to do it in the python application
i have:
for guild in guilds:
if (guild['permissions'] & 0x20) == 0x20:
so far
but i need to pass a var in my html to only display the servers with that permission
please help
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
For anyone asking, learn django
how can I specify an HTML input field that looks for a duration with HH:MM:SS ?
tried it with <input type='time'> but that is seems to a) ignore seconds and b) include am and pm when the system is using am and pm. I dont need or want either for a duration.
fixed it by slapping a few fields together
is it a good idea to learn HTML, CSS, and Javascript if I want to go further on with Django web Development?
or is it not necessary?
I completed Corey Schafer’s flask tutorials, but how can I support Markdown for my posts?
if you want to do any frontend or full stack, beyond required Orbit
Also if I were to create a normal website with articles instead of blogs, would I still store the articles in a database like we stored the posts?
We don’t just use separate html files for each page?
Sorry these are extremely beginner questions but
I just wanted to say that I commend you guys for being able to learn web-dev without destroying half the universe alongside your brain cells
@cold anchor I am very new to this. Do I need to create it over there? I have added the procfile, wsgyi, and changed SQLite db to postgres using the environment variable DATABASE_URL which is linked with postgres on Heroku.
did you make tables on your heroku database?
Nope.
that's something you need to do
with app.app_context db.create_all()
It won't create table?
ah just read that, I guess it will
it looks like you're running into naming issues though
you're calling a table both user and users
sounds like your Post table should reference users.id and not user.id as a foreign key
@cold anchor Actually I have users route:
It’s not your route it’s your table name in postgres
Making the foreign key users.id
sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship User.posts - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.
I think I need to modify posts in Users and add foreign key posts = db.relationship('Post', db.ForeignKey('post.id'), backref='author', lazy=True)
And it didn't work
Django django
@coral raven if you use django, you can see your data in django admin
I need HELP !
Using flask rn
I've never used flask before, but there should be some way to access the database objects. Does Flask have a shell? @coral raven
@coral raven
Either you u use cli and import your models then you check
Or you download SQLite browser
Remember that with flask you can’t migrate the dB easily, so I guess you have to delete the SQLite.db into your project folder if you make any change to your models
There's a module to migrate
@coral raven support you have a user model in the cli you do from flask import models the from models import user
Flask_migrate, which gives django like commands
I never used it ^^’
That I know, I wanted like a table representation of the table
So try sqlie browser for viewing your dB
Sqlite that’s what I used to check my dB I suggest you to give it a try
So I have a issue with flask socketio, i looked up on the web how to do it and found an example, i was going to test the example then change it up for my needs, it worked perfectly fine for the person that made the example but i cant seem to get it to work
import sys, os, time
from threading import Thread
from flask import Flask, request, render_template, redirect, url_for
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = """"""
socketio = SocketIO(app)
thread = None
def background_thread():
"""Here is where you'll perform your installation"""
count = 0
# Call Install function 1 using time.sleep(10) to simulate installation
time.sleep(1)
print(1)
count += 1
socketio.emit('my response',
{'data': '1 installed', 'count': count},
namespace='/test')
# Call Install function 2 using time.sleep(10) to simulate installation
time.sleep(1)
print(2)
count += 1
socketio.emit('my response',
{'data': '2 installed', 'count': count},
namespace='/test')
# Call Install function 3 using time.sleep(10) to simulate installation
time.sleep(1)
print(3)
count += 1
socketio.emit('my response',
{'data': '3 installed', 'count': count},
namespace='/test')
@app.route('/')
def home():
return render_template("home.html")
@app.route('/result',methods = ['POST', 'GET'])
def result():
if request.method == 'POST':
thread = Thread(target=background_thread)
thread.start()
return render_template("result.html")
elif request.method == 'GET':
return redirect(url_for('home'))
socketio.run(app)```
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>...</title>
</head>
<body>
<h1>...</h1>
<div id="log1"></div>
<div id="log2"></div>
<script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
namespace = '/test';
var socket = io.connect('http://' + document.domain + ':' + location.port + namespace);
$('#log1').html('<br>Installing Software');
$('#log2').html('<br> > ...');
socket.on('my response', function(msg) {
$('#log2').html('<br> > Received #' + msg.count + ': ' + msg.data);
});
});
</script>
</body>
</html>```
all i simply need is to be able to change text without refreshing the webpage and this is the best way i found'
Hmm, so what seems to be the problem?
just fixed the issue
turns out the tutorial version of ajax was out dated
i changed this
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>
to this
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.6/socket.io.js">
hey all, I have been struggling with this for a while now and cant find a fix
Can someone take a look at it and help me find the fix please
Basically, I am making a web-based visualization for a simulation tool used in energy supply optimization for communities
I code this module: https://github.com/rl-institut/mvs_eland/blob/feature/plots-with-plotly/src/F2_autoreport.py
So I am using plotly and dash to produce the visualizations
I am also providing the functionality to save the html page as a pdf
On the browser based viz, everything is fine. But when I save the pdf, there is a huge whitespace after every plotly chart that is almost the size of a page
I could not identify which CSS property is causing this issue
anyone that has experience with django-filters and more specifically django-property-fields, is it possible to make an OrderingFilter, based on properties?
without hacking around too much
Hey, how can I use a open-source python project as an API to serve my Flutter application?
