#web-development
2 messages Β· Page 62 of 1
Yeah
You just gotta practice
@native tide Exactly
Btw @earnest osprey I suggest https://www.youtube.com/playlist?list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p
i found a book again.
Post it here
@native tide I have watched already
so..? didn't it help
I want dig deep down@native tide
Oh i understand
Google Drive is a free way to keep your files backed up and easy to reach from any phone, tablet, or computer. Start with 15GB of Google storage β free.
I'm new to django
i'm new to web dev in general xD
Ohhhk
Thats a great video@native tide
I thought you were also a beginner
Sorry mate and you're welcome
checkout this book @earnest osprey https://djangoforprofessionals.com/
Learn how to build production-ready Django websites.
if you like reading
@native tide Thanks
Thanks
I will sure give it a go
i saved it too
so i'll check it out when i learn
the basics and practice
Thanks for the help guys
Bye
Hi, a little confused by the action attribute in my <form> in flask. After I submit the form it renders the index page but it doesn't have my flashed message, it just says "Hello Index Page." I have the index page as the action, so shouldn't it display my flashed message?
def login():
form = RegistrationForm()
if form.validate_on_submit():
flash('Registration requested from user: {} and remember_me: {}'.format(
form.username.data, form.remember_me.data
))
print("True")
#return redirect("/index")
print("False")
return render_template("login.html", form=form)
@app.route("/")
@app.route("/index", methods=["GET", "POST"])
def index():
return render_template("index.html")```
index.html
``` <body>
<h2>Hello Index Page</h2>
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
{{ message }}
{% endfor %}
{% endif %}
{% endwith %}
</body>
</html>```
login.html
<body>
<form action="/index" method="POST">
{{ form.csrf_token }}
<p>{{ form.username.label }}<br>
{{ form.username(size=32) }}
</p>
<p>{{ form.password.label }}<br>
{{ form.password(size=32) }}
</p>
<p>{{ form.remember_me() }}
{{ form.remember_me.label }}
</p>
<p>
{{ form.submit() }}
</p>
</form>
</body>```
I had more of a design question relating to user authentication/authorization rather than a programming one. Is there still a use case for session based authentication? I know that JWT / OAuth2 is fairly mainstream for larger applications, but I was thinking about using sessions for my smaller (pretty much a SPA) project.
I assume since I am only consuming the backend from 1 source (the web app), and since there will be not many users, session based auth would be okay for my use case but wanted to see what you guys thought.
@blissful lion Absolutely.
Guys why aren't u guys chatting bout Django?
@glass sandal Because everyone is using Flask
Because it is often overkill for tasks where you need little overhead
There is no "this is better", there is only "this is more suited to the task" in professional IT
gotta leave emotions out and concentrate on facts and requirements
π
Django is a 1 package including all not like flask_admin , flask_sqlalchemy and ...
Django does this itself
And since it's rated 2nd in top backend frameworks , it's better than flask that is 5th
@glass sandal What is your problem here? Do you want to sell us on something?
I stand by what I said
Why are you arguing at all? If you came here to stir up trouble, then this is the wrong discord for that
I just said it's cooler and you didn't accept
Then you aren't here enough
I've been here for last 8-7 months
but anyway, I am going to stop replying, this discussion is pointless
Yeah sorry for taking your time anyways
@tired root - I agree. I find myself going down rabbit holes when I'm trying to learn a topic, or I'm bombarded with this framework , that framework, or package and it just confuses the hell out of me and I end lost and lose interest
Yeah that happened to me alot too
We have to stick with a topic
Again, it's all about requirements. There are cases where Django is the choice and there are cases where Flask is the choice. To compare them head on is pointless and moot
Agree
Flask is really light-weight and runs nicely on my pi for example, for my radio project
for a big website I'd go with Django
It's all about Fit for Purpose
Want a Medium - Big project ? Go for django. Have a small - medium Project? Flask is the choice
I get it now
My radio for example was made in Flask
Nice !
That is nice. I like the color scheme
It runs on a Pi on my nightstand with a touch screen and it also serves the interface to my network
@tired root, You got my gears spinning now for Pi projects
No, flask is only used for the web interface and backend
The bars come from Javascript Media API
well, it's a HTML5 canvas
Ik I mean the backend
but I load the stream with javascript and use the fft acquired from media api to display those bars
I am not a developer at all
Backend
no
I work in a data center as Network Administrator, I mostly deal with cables, routers and traffic
The most challenging part was the system level scripting actually
to make the networking changes etc
Oh
and fix the lazyness of radio stations
The low level stuff is done with C/C++ . How did you do it in Python?
Oh I see
A specific user can run certain scripts with sudo without password
that is all the magic
I am really not. I am just an idiot with too much free time
And in that free time , you turned into a developer
Quarantine has created some free time for many of us
Lol yeah
But school holds me back a bit
Like we have final exams
So
Anyways
nvm
well, data centers are critical infra, so.. I still have to go to work
Oof
can't put it new optics from at home π
I see
@tired root offtopic but what type of background is needed for that line of work?
@blissful lion I'd say that depends on the company. I have a normal IT background, no special training. Should have some networking knowledge though. Like subnetting, IPV4 , IPV6, know how to read tcpdump and other things
maybe also have worked with real routers/switches
as in, Cisco/Juniper
gotcha, I'm going to school for a BS in Info Systems and an MS in Comp Sci, I really enjoyed my networking course and was thinking about getting some cisco certs myself
and know your way around Linux. Nobody uses Windows in that field
I have my own dell r710 server at home for some general automation, seems like a really interesting field to get into
ah, you do more networking gotcha
well.. it's called Network Admin for that reason
haha true
I manage switches and routers and their components, there is no copper in what I do, only fibre
I wish I could find an internship for a datacenter just to get a feel for it, but I'm not sure any companies would really have those :P
And about 8000 of them
dang thats pretty cool
we have data centers in multiple European Cities and POP all over Europe
that's awesome.
Cisco certs are kind of overrated IMHO. From what I know, nobody in my office has CCNA
but then, we are using Juniper
yeah, I kind of feel like some of the certs aren't that useful
it depends on why you do them. If you really want to learn, they are great. but many places offer brain dumps, only teach what is to know to beat the test
so I guess if I wanted to get into that field I'd probably just want to get a few routers / switches to mess around with eh?
Most only have them as decoration for their CVA
You don't want to get the routers we use
first of all, they are loud as fuck
yeah i bet they get pricey too
second, they set you back a couple of ten thousand
sheesh
That is one sexy fucking router
And just to nit pick.. Layer 2 is never routing. But I should really stop the off topic π
fair enough π
Off topic but CCNA is not something Iβd recommend. More and more is going SDN
@zealous siren Maybe in the developer world, not in the networking world
In general, Iβm from sysops SRE field
The infrastructure on which all your virtual stuff runs, is old fashioned networks, because the Internet runs on it and needs it. All the things like SDN is layer 7 additions
So, if one works in the data center world of networking, these things are meaningless because my job ends before any of my cables come near any server
Ot2?
sorry I stop
Does it make sense to obfuscate API calls between a framework like Angular and flask? I'm trying to figure out a way for users not to abuse the API.
@pale radish no
Because you need to deobfuscate it in js anyway
and js is user side
so save yourself the trouble
better idea is to cache, than to limit
use e-tags, so the content is only updated and resent if something actually changes
otherwise 304 is sent
Thank you, I'll take a look at this. Have never made a production site but am trying to.
agingbones, if abuse becomes a big problem, you will have to build anti abuse systems like looking for consistent calls, also requiring tokens and doing token expiration helps as well
drop the first tcp packet of every incoming connection
at your firewall
it must support flows though
We found websockets help just because they are harder to automated
another Syn is sent?
correct
but only if the sender was serious about the connection
ddos tools don't work like that
or amplification attacks
that's dumb as anti abuse setup and most requests libraries will handle that
it maybe dumb but it's very effective
Hmm, okay, I'll just have to research more into it before I release to production. I don't have any users or sensitive data, but I don't really want all of the data I manually inputted to be mined instantly.
I think they are worried about people using the APIs outside a browser
it will be
selenium will see to that easily
How do people protect against that or do they not?
it's pretty difficult to stop
I just imagine there's a lot that I don't know about in regards to web frameworks that I'll massively fuck something up when I release
But I'll just research into more flask restful prod guides
and caching
We do SPA with REST API, caching/token expiration
there is also API Gateways that will help but they cost money
useful for business, not so much individual
SPA is all Javascript so anywhere you have static HTTP engine
@pale radish Speaking of amplification attacks, make sure there is no path that release mass amounts of data
because otherwise it will be used for amplification
Good idea, thank you, I'll research into protecting against that as well because I do have a few API calls that have quite a bit of data being returned
Looks like Heroku does have Mongo, but barely any space...
Another idea is also to generate a key based on IP and a web beacon, such as the famous browser pixel
and use that one as a api key
it may not stop the real hackers, but the script kiddies probably
How do you all do storage in the cloud? without spending a fortune?
not sure how effective that really is though
My cloud server costs 5 bucks a month with 20 TB traffic and 20 gb storage. Not sure how much you need
you can get 100 gb for about 4 bucks
1 tb for 40
Using Blob Storage
Anyone know why i cant used ma.Nested with flask_marshmallow
How i can use this in Django? https://github.com/ColorlibHQ/gentelella
@static nightgentella modified for Django https://github.com/GiriB/django-gentelella
Thx
Guys how would you create login system without wtforms?
With wtforms it seems more complicated than it should actually be
You can use a JWT
user puts credentials -> you verify credentials -> you said a JWT -> you use the jwt to identify the user
I was wondering will basic input field work?
I have database
I have registrate page
That works
of course
And now i have to chabge everything cuz of log in
Or at least because every tut is done with wtforms
How?
I would start looking on how JWT (json web tokens) work
Trying to post a file with form data with requests.post
My payload is: {'batch': 1, 'file': opened_file} with opened_file from open.
requests.post(upload_url, files=payload)
But I'm getting error 400 and investigating with Wireshark I see
Content-Disposition: form-data; name="batch"; filename="batch"
And I don't want to send batch as a file. Just as a form item.
Wait would sending a int trip it up?
Nope, sending a stringified int didn't change it.
Still trying to send batch as a "file"
@pulsar ivy Try reading what a jwt is
Okay there we go. You're supposed to use the data keyword arg for other form data.
Does anyone by chance have a link to a very detailed walk through on setting up a flask app on heroku? I keep having issues and it wonβt start up the web process and not sure where Iβm going wrong
@native tide Yes to both of those
my heroku cli is actually telling me my Procfile is mis-cased
but it's spelled correctly and only the p is capitalized like it should be...
YOu cant even push on heroku or you get that H10 error on tails ?
yup, the application error screen
type heroku logs --tail
in ur terminal and see what eerror u are getting
if its H10 its prolly ur gunicorn set up sorry i have to sleep its really late just google the error u get from terminalk
How to extract absolute xpath from a webpage without using selenium driver find by (looking for methods like beautifulsoup,lxml)
Hey hello guys
Any one online?
I am getting an error django is not recognized as an internal or external command
I know this is repeated to some path related issue
But can someone help me out
I know this is repeated to some path related issue
@native tide definitely path related try to install again with command line
If doesn't worked got to installed directory, find django-admin.exe and add it to path or open shell there and run your django-admin.py startproject command there
Hi I want to use htmldom or advanced html parser to get back xpath from webpage is it possible ?
would anyone be able to help me with this issue with flask not saving session keys when switching routes?
https://stackoverflow.com/questions/62054818/flask-sessions-is-not-being-saved-when-switching-routes
When trying to do ''flask run'' in powershell I get the error ''Fatal error in launcher: Unable to create process using \path\to\env\pyton.exe & \path\to\env\flask.exe ''. Yesterday it worked just fine, but today I get this error. I don't think I did anything differently. Anyone has any idea?
well that does work
thank you
I don't understand why "flask run" worked yesterday though
but now it doesn't
So I am trying to use a cli command, but for some reason when I say flask command-name, it says that it couldnt find any command with that name
are you just writting flask command-name
?
@native tide What did you do to get that error message, be more specific
I hope this is the right channel. Has anyone got any experience using django-chartjs?
https://github.com/peopledoc/django-chartjs
@verbal obsidian Yes
Did you have a look at https://flask.palletsprojects.com/en/1.1.x/cli/?
No, but I will do now.
In the project this is from, this worked, I have the same command just with different imports
hi peeps
is there a way for django to communicate with java?
like
i have django on a webserver
and
i want it to communicate with my gameserver via java
how can i do it?
except using databases to communicate
Well, you can do a web request to do that
Requests are following the same standard across languages
ive made a django rest api before
working as it should
but then
it would make alot of web requests
so i removed it
on my mind
i want it to communicate like this:
web: hey someone bought smthing, can you execute the following command(s)?
java: yeah sure. Executed successfully.
Jacob Jedryszek is a Software Engineer who started and shipped Azure Mobile app, and helped Microsoft to build and ship the Azure Management Portal. He is also a speaker at conferences around the World.
this may work
I'm learning Flask and have come across url_for() which indicates is better than hardcoding a link. I don't quite understand why it's better because if you change the name of your function in your routes don't you also have to change it in your url_for()?
In Jinja2 template name uses unix style path irrespective of platform?
if something is "app-level", does that mean it's INSIDE of an app folder? or does it mean that it's in the same folder that app folders are in (a.k.a. NEXT TO the app folders)
In Jinja2 template name uses unix style path irrespective of platform?
I am getting "/" style template name even on windows
Got answer
jinja2 FileSystemLoader uses .replace(os.path.sep, "/")
Hi
If I wanted to have a dropdown selection that would query data from a DB and populate matching terms in an HTML table, how would I do that?
I already have a DB that does plenty of queries, saving to and from the DB. So the DB and most other functionalities, like an admin page, forms etc. They all work on my Flask project along with templates.
I use SQLite, Flask, wtforms
I just don't know how to do the opposite of that, which is, have a dropdown selectfield, that once chosen, would populate a table beneath it with matching results.
@stark mauve maybe this will help https://www.youtube.com/watch?v=AHcBPlPMqtc&list=PLgCYzUzKIBE_dil025VAJnDjNZHHHR9mW&index=28
Free website building course with Django & Python:
https://codingwithmitch.com/courses/building-a-website-django-python/
In this video I show you how to build a searchbar for your websites using Q lookup. The search bar is in the top navigation bar for the website. The searc...
ah wait, just realized you're using Flask. it's probably similar though
@half bough Yes, but function names should be changed very rarely anyway. API should be stable, routes can be more fluid
Hallo
I need help here! The problem I installed djangorestframework in anaconda and I don't get the path django-admin
It says no directory and file
What path I need to add in cmd
Will anyone know?
i hope u ran
py manage.py collectstatic
have u added djangorestframework in installed apps?
if not
add 'rest_framework',
did u do pip install djangorestframework?
i havent used anaconda
app.config['MAIL_PASSWORD'] = os.environ.get('EMAIL_PASSWORD')```
why is this giving me an authentication error
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials m33sm5709484qte.17 - gsmtp')
but when I use my real email and password instead of the environmental variables, it works fine
@distant trout Print them and see if there are any trailing spaces or something.
ok I misspelled my email on the environmental variables π¦
1 letter mistake and had me stressed out
may you help me? ^
who me?
someone
π
Is it possible to change the scopes with django-allauth?
I'd like to request other permissions such as guilds, and remove email,
Hi, I heard you can make django accessible in the network by using python manage.py runserver 0.0.0.0:8080 or simiar, but I dont get it to work. First time I tried there was a firewall popup which I allowed, program didnt have any issues. But I cant access the server, no matter if I try on the same machine or on my phone for example.
(windows)
I've downloaded a website so why does this look like this
Downloaded a website?.. What?
Could someone possibly help me with a question I have about flask?
whats up?
so from the tutorial I have seen after writing the app.py to start a local host, the adress comes up in the terminal. But when I run my file nothing happens π I don't even get an error so I am not sure what happened
slap this at the bottom of your file:
if __name__ == '__main__':
app.run()
(assuming "app" is the name of the Flask app variable you created)
this might be better suited for a help channel, then
as I'm not sure I really understood what's happening and I'd ask to see the app.py file and the command you're running to help more
okay, do I just go into one and claim it?
yeah, follow the instructions at #βο½how-to-get-help
username = StringField('username')
password = PasswordField('password')
@app.route('/form', methods=['GET', 'POST'])
def form():
form = LoginForm()
return render_template('login.html', form=form)
{% block head %}
<title>Log in</title>
{% endblock %}
{% block content %}
<div class="container">
<form class="form-signin" method="POST" action="{{ url_for('form')}}">
<h2 class="form-signin-heading">Please sign in</h2>
{{ form.csrf_token }}
{{ form.username.label }}
{{ form.username }}
{{ form.password.label }}
{{ form.password }}
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
why i dont see forms????
@fickle fox is this from a tutorial?
yes qwq
if so, this seems kind of confusing. I recommend you watch Corey Schafer
im following his flask tutorial
and i have learned so much
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...
here is the playlist
oh okay 

cs50w edx harvard
why i dont see forms????
@fickle fox
Do you see them in inspect element or view source?
I have a database with articles. Like, Articlename, Price, Description, Photos etc. Now im using flask with jinja-templating. When I want to display each article, I just do:
{% for item in article %}
item.item['articlename']
item.item['articleprice']
<img src="https://loremipsum.com/{{ item['articlephotos'] }}">
{% endfor %}
Now when I have more than one photo I run into problems.
Right now I have Links of these photos in the DB like this:
(All links in one attribute and with comma seperated)
/static/images/artikel_1.jpg, /static/images/artikel_2.jpg, /static/images/artikel_3.jpg
Of courseI can seperate all these links and add to a new List but then they are not assigned to a single article anymore. All links of whole table are in that array.
Should/must I make a new attribute for every photo in my table?
What grant_type is better to use with django DRF + oAuth Toolkit? ROPC or Authorization_grant. Also could someone explain why.
how I can add a load animation to my page when the user click something I tried this ```html
{% if load == True %}
<p style="font-size: 15px;">Downloading</p>
{% endif %} ``` but its not working also im using flask
@terse surgeI did it still not working
or its not going to work if I add else statment already?
if request.method=="POST":
print("hi end")
session["endChapter"]=form.endChapter.data
print(session["endChapter"])
return render_template("endCh.html",load=True)
return redirect(url_for(re_direct))```
here's my flask code
<form method="post" name="ch" action="/endChapter">
<label>End Chapter</label>
{{form.hidden_tag()}}
{{ form.endChapter }}
{{form.submit}}
</form>
{% if load == True %}
<p>yo</p>
<p style="font-size: 15px;">Downloading<div class="loader"></div></p>
{% else %}
<p style="font-size: 15px;">Downloading<div class="loader"></div></p>
yo
{% endif %}```
Im trying to add the animation to it
no
even if the user is not downloading it
it will be displaying downloading
which you dont want to
could result in loss of users
I mangaed it in a way so when the user come to this point it must be downloading
with django we add {% load static %} to load static files, so what you need to do is make a template tag and load it {% load templatetagnamehere %}
then
in ur template tag
you define load
i dont have time rn
ok np,thx for the help I will try to fix it somehow
Thanks u 2 (:
Is flask around as good as javascript for web development, or is it kinda' janky and roundabout?
Dang it! I figured I might not know which was for which purpose but I took the risk anyways and I look more stupid now than if I had just asked π€¦ββοΈ
Hi guys, I made some changes in one of my template files(html) in my flask app, while the app is running, how can I restart and apply this changes
?
for now I just see the same as was before I made the changes
I tried to restart nginx but it's doesn't affect it
I just changed text
I tried to reload on incognito mode and it's still didn't made the changes
now I rebooted the server and it's works
but I have to reboot each time?
I founnd that I can set a configuration of ```py
TEMPLATES_AUTO_RELOAD = True
I did it but it's not helping
maybe my python files don't affect aswell till I reboot?
Im using AWS so it's actually just pressing a button the reboot
@pliant falcon you are using aws with a forwarded domain?
can you tell us more about your setup? AWS EC2 instance running both nginx and flask (gunicorn? waitress?) server to serve your flask application?
any cloudfront to serve static files? is nginx using a cache? is flask using a cache?
Has anyone ever used Flask w/ Bootstrap & Autocomplete via JQuery? I am having issues with the styling of the StringField / SearchField.
hf with your mute
@cold anchor Im using lightsail server linux-ubuntu, nginx and gunicorn installed I never setted a cache in any way with this app
hey peeps
I have a issue
It says no module named flask
even thought when I do pip install flask it says requirment already satisfied
so I know I have it installed
whats the name of your file?
what editor are you using? vscode?
yes
and does it give you an issue when you run it or just in the intellisense thing?
You using a virtualenv?
vs code is good
yeah
hey
I get this issue
virtualenv : The term 'virtualenv' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct
At line:1 char:1
- virtualenv env
-
+ CategoryInfo : ObjectNotFound: (virtualenv:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
PS C:\Users\Julia Frank\Desktop\Flask Introduction> virtualenv flask
virtualenv : The term 'virtualenv' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct
and try again.
At line:1 char:1
- virtualenv flask
-
+ CategoryInfo : ObjectNotFound: (virtualenv:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
can anyone explain me what format this cookie is in and how to convert to string?
Hi guys, where would the best place be to add a styles folder for .css in your Django project?
static
how to remove excess whitespace
@native tide Depends, but you might be looking for strip()
can you show me an example
' okay '.strip()
how do you remove excess blank space, for example
i tried making the margin zero but it doesn't work
@native tide Did you close the tags?
Guys how to make "download" and the animation in the same line?
position:relative;
width:48px;
height:48px;
margin: auto;
}
``` the main css code
<div id="circularG_1" class="circularG"></div>
<div id="circularG_2" class="circularG"></div>
<div id="circularG_3" class="circularG"></div>
<div id="circularG_4" class="circularG"></div>
<div id="circularG_5" class="circularG"></div>
<div id="circularG_6" class="circularG"></div>
<div id="circularG_7" class="circularG"></div>
<div id="circularG_8" class="circularG"></div>
</div>```
html
Would web-scraping questions fall under python web-development?
@wild yew I see people ask about that here so I think its fine
guys how can i render the datetime from the data in the database to the data of the user who is watching the page? (i'm using flask)
need help with selenium webdriver
Is it possible to change the scopes with django-allauth? (discord login)
I'd like to request other permissions such as guilds, and remove email?
Is the only way to get a variable from python into my htmp file using the custom variables whem rendering?
@thick cove yes it is, check the discord docs
@rustic pebble I'm using django-allauth for the verification
They dont provide a method to change the scopes as far as I can see
how do i post data w headers?
@thick cove I believe you can
@rustic pebble Can you reffer me to where I would do that, or the documentation for doing so?
127.0.0.1 - - [30/May/2020 12:44:22] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [30/May/2020 12:44:26] "GET /home HTTP/1.1" 404 -
when i run my flask project
no errors
when i go to the localhost itself, it gives me 404
hmm, im following a tutorial and i might have missed something ill just double check everything
Currently I'm experimenting, and I've made a couple endpoints for User and Group objects using the django rest framework's tutorial. I wanted to make a frontend list view that uses the user endpoint instead of directly using the User manager. I did get this working using the requests library. However, there's an incredibly large speed difference between hitting the endpoint directly in a browser, which returns in something like 20ms, and the requests.get('<endpoint url>') which takes something like 2-3 seconds. The relevant snippets of code, though I've done the requests.get() call in a terminal and also got the same speeds, so I imagine that specific line is the issue.
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
# permission_classes = [permissions.IsAuthenticated]
class TestConsumeJson(ListView):
template_name = 'quickstart/list.html'
context_object_name = 'user_list'
def get_queryset(self):
response = requests.get('http://localhost:8000/users.json') # Why is this part so slow? 2 whole seconds?
users = response.json()
return users['results']
I guess for completeness, the template is just this simple thing, which functions as expected and I don't expect it's problematic:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lists</title>
</head>
<body>
<h1>Lists works</h1>
{% for user in user_list %}
<p>{{user.username}}</p>
{% endfor %}
</body>
</html>
Any ideas on why this slowdown is happening, or ideas on what I can check to investigate?
Additional information: The headers sent with requests.get are {'User-Agent': 'python-requests/2.23.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}, and send a request to http://www.google.com with requests.get, using the same default headers, is not slow. I tried sending Connection: close due to a stackoverflow post I saw, but that didn't seem to help in my case.
Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for.
Guys what is the best website to find HTML and CSS templates
Cause I don't like to waste time coding front end
Ummmm this channel is dead ?
Might be dead, might be that nobody knows of a website like that off hand
if someone is familiar with flask and ajax, I could use some help figuring out why i'm getting dulicate POSTs sent
How can i stick on some background music on my website
And have it play automatically
@glass sandal templated.co
if someone is familiar with flask and ajax, I could use some help figuring out why i'm getting dulicate POSTs sent
@wet yacht Give us some context & code
And have it play automatically
@tiny siren https://www.w3schools.com/html/html5_audio.asp
I have an input in my html file (doesn't make a difference if it's in a form or not)
<input type="search" class="monster-search" name="monster-search" id="monster-search">
I get each character typed by jquery
$('.monster-search').on('input', function() {
var monster_id = Number($('#monster-search').val());
console.log('.monster-search called with id ' + monster_id);
//Send value to database and get monster information
$.ajax({
url: '/',
type: 'POST',
contentType:'application/json',
data: JSON.stringify(monster_id),
success: function(response) {
console.log(response);
//generate html to show result list in a div
},
error: function(error) {
console.log(error);
}
});
});
In my app.py I get the data
if request.method == 'POST':
monster_id = json.dumps(request.get_json())
...do stuff with it and return...
return jsonify(monster_result=monser_data_reformatted)
hmm. it seems that adding event to the ajax function call and
event.preventDefault();
event.stopImmediatePropagation();
fixed it but why would it be posting in addition to the ajax call when there's no form being submitted?
@verbal obsidian That doesn't play automatically
Just adds music controls to the web page
ok here's an easy one:
<input type="hidden" name="csrf_token" value="IjJkNjgzZDExOTBjMTQ4MDJhNjIzZThkZTNhMGNiZmY0ZDVhOWU5YTgi.XtLYDg.MhTAe2BvGrut_ZCS30ixkAR83P4"/>
but $('#csrf_token').val() is showing undefined
why is it undefined and not the value of the csrf_token input?
#csrf_token looks for something with the id csrf_token. Your input has that as a name, not an id
Have you tried the autoplay attribute of the audio tag?
Keep in mind: users are not particularly fond of autoplay music or videos. And browsers are moving to disable allowing it (if they haven't already).
When youβre displaying image content with headers and you send the url (for example web.site/image.php)
Discord will show the image as intended. But it also caches it regardless of any cache headers. Any way to stop that?
change the url to something like /image/randomstringlikeanuuid
then configure your routing to serve the image to any requests starting with /image or whatever you chose
there's also a clever method using url parameters for example
/thisthing.jpg?time=unixtimestamphere
Hello everyone, can someone explain me or give some resources about hosting a web app made in flask? I have previous expierience with PHP programming making websites ant hosting them is very easy and not expensive, but now I fell in love with python and flask and i tried to host my app on raspberry pi using docker (following advice form user from this discord) but it seems it is not possible becouse of some docker modules aren't aviable on raspberry pi. I started to look for some other solutions and it looks like its only possible on big services like azure aws etc. but they are pretty expensive, and i wonder why is that? Is there a cheap way to host/deploy a flask app? Wish you all health!
@normal vapor Check out, digitalocean, scaleway and companies as such's tutorials, they have many tutorials on how to deploy apps in vpss, these
are rather cheap, I use them alot for testing, can be as cheap as 3.5β¬ per month
Also you can definetely deploy flask apps in your raspberry pi, I'have done that many times
When you deployed on raspberry pi, were you using docker or just on the base system?
Docker
as of right now, I have 1 discord bot, 1 ngrok instance, 1 postgreesql cluster and 1 django app
I tried to deploy an app with 3 containers, one with app, one with mysql db and one with phpmyadmin, but i couldn't istall them on raspi becouse of the arm
what coulnd't you install of those three?
the arm shouldn't be an issue since there are versions for arm
with just a quick google search
I was looking on docker hub for those and didn't found, but now i see there are some actually, i will try again, thank you for advice!
You are welcome
had a question regarding django transactions, the documentation states that I cannot use try and except blocks within a transaction, however in my use case I'd like to be able to display an error specific to the nested transactions.
movie = Movie(title=title, plot=plot)
with transaction.atomic():
movie.save()
with transaction.atomic():
for a in actor:
actor = Actor.objects.get(name=a)
scene.actors.add(actor)
# how do I catch an exception here to show actors failed to be added
with transaction.atomic():
for s in studios:
studio = Studio.objects.get(name=s)
scene.studios.add(studio)
# how do I catch an exception here to show studios failed to be added
Can almost everything thatβs written in Js with websites be replaced with Python?
Iβm have decent python experience but like no JS or web experience
Right, Iβll work with that
you could look into brython tho
i want to ask sth too guys
for a simple web site which designed with fe langs(htm,css,js and more)
How should i proceed creating an website in Python ? I've just heard about Django in general
and serving tihis site which one i should better to use
Django, Nodejs or Laravel
or others maybe
Django vs Brython?
brython is for frontend whereas django is used in the backend
@native tide yes, it is a tradition
when you open a site and press f12 or similar you can see a lot of stylesheets
index.html ->index-style.css
help.html -> help-style.css
.. -> general.css
.. stands for all
have fun π
well π np
@marsh canyon do you have experience with any of these similar python/js things iv heard about jython too but man it looks like meme to me . I could understand a one time use for something really simple but how hard can it be to learn some jquery then to get minimal reactivness ...
I am sorry, I don't
even better π
!paste
Code : https://paste.pythondiscord.com/iperajutol.py
Error : I'm getting None
@native tide yes
Jython: is a Python library for writing java-like python code, its real :d
and you want to use python and javascript both
?
what about jsthon
is there even such a thing
@native tide i know what it is iv asked because someone was posting questins about it and @marsh canyon gave and answer so i tough he had some experience wiht it
I have just seen people use it(or try it), example travery media on youtube has a video on brython, I just watched out of curiosity
About django user, should i use allauth or develop from scratch a custom user model. Allauth has a lot of features, and save time. I can allow users to login with socials network, email system features, built-in views, and more... But is it worth? Or should i develop from scratch? I dont know... someone can help me?
Im reading about it, and seems to be a nice ways to manage users
Donβt do it from scratch if you donβt need to. If allauth provides what you need, use it
Good practice in django is to always use a custom user model before your first migration to make it easier to customise later on down the line. You shouldnt be writing a user login library from scratch, allauth provides pretty much everything you could want
do you guys use camel case or snake case for writing javascript
Camel case is the norm for javascript
But since my apis are python I end up dealing with snake case api data anyway
ahh okay, thanks
How fast would my website be if i compiled all of the web pages into a single html file
depends if youre loading it all at once with no AJAX or other bits of stuff it'll be slow as shitballs
and code will be messy af
Also depends how you define βfastβ
How could i use mardown in HTMl
Soo, im wondering if there's a way I can host my python script on a website, so i can access it anywhere?
It's also terminal based
sure
there are so many ways, it's overwhelming
the way I do it: I "rent" an "ec2 instance" (just a virtual Linux machine) and just run the thing
tons of other ways though
oh cool
ideally im looking for something free, it's just a little hobby thing im doing
I think ec2 has a "free tier", but I bet there are others
I wouldn't expect a free setup to last more than a month or two, though.
unless the service is run by some long-haired commies π
(i.e., an open-source project or something)
https://www.pythonanywhere.com/ I found this and it looks ideal
Host, run, and code Python in the cloud: PythonAnywhere
What's best practice when it comes to Django/flask? Like where do you keep your web app's code itself. Currently on my first project I have my code in my flask's main.py file where I also hold my flask routes etc. Is it okay to keep it in there or should I split it off into it's own file and then import that into my main.py file?
I ask this because I'm trying to transition to using django but have no idea where to put my code. Models, views, etc.. im a lost man
vid_src = article.find('iframe', class_='youtube-player')['src']TypeError: 'NoneType' object is not subscriptable
What does 'NoneType' object is not subscriptable mean?
Good practice in django is to always use a custom user model before your first migration to make it easier to customise later on down the line. You shouldnt be writing a user login library from scratch, allauth provides pretty much everything you could want
@dark hare Ok thank you, i appreciate! @dark hare do you use allauth? And can you suggest me good reference?
Hi, how can i disable directory listing?
@tiny siren That's usually a function of your web server
@tiny siren I'd search the web server's documentation
Ok
Hello, i need some help auto playing music in html, nothing works
Django:
How can get "simple" user input without using forms. For example a button that increments a value in my database.
Would even that be done using a form or whats the normal procedure here ?
@fiery tapir Flask I'm not sure on since I've only done a bit of it and have a narrow experience, but django has a pretty decent tutorial on the website. It'll walk you through a small project and should help you get a feel for what stuff goes where. It's sort of a lot initially, but give it a go and come back with questions!
Greetz. I am looking for some EMT Dispatch software. My requirements are minimal just weekly dashboard and I can code/add options like moving events/trucks around the timeline
@onyx crane button that calls an ajax that calls a view that incrementes a value of your desired model.
@native tide
Subscriptable means whether they implement the _getitem()
method
using [ ] calls that method
in that context
Most likely because vid_src = article.find('iframe', class_='youtube-player') returned None, It didn't find it
Can any one help me to host flask web app to heruko?
What's your issue
Hi everyone! Is there any web app project on GIT that you could suggest for wrapping my head around all the basics? (Flask, SQLAlchemy, Werkzeug...)
This is going to be my first Python project, I eventually want to delve into ML after getting comfortable with the language though... so perhaps a WebApp with a bit of extra zing for added inspiration?
@native tide django
dont want to bust ur balls but ml is really hard
if its ur first python project then maybe something a little easier?
up to you
@quasi ridge That is not really true, splitting up the views and the functions into services, helpers, views and more is crucial to building a correct hierarchy in which you can develop and maintain the product without having to go through hours of understanding your code. Having a main.py file contain only a small number of lines that really just launches the web server is ideal
@native tide Maybe https://github.com/OctoPrint/OctoPrint
def create_test_user():
test_emp_name = 'test_employee'
β
try:
test_user = User.objects.get(username=test_emp_name)
except User.DoesNotExist:
person = create_full_person()
test_user = create_user(person, default_role_name='Product Manager')
view_track_tool_tab_perm = Permission.objects.get(codename='can_view_tracker_tools_tab')
view_track_tab_grp_perm = Permission.objects.get(codename='can_view_tracker_tab_group')
can_assign_items_perm = Permission.objects.get(codename='can_assign_items')
β
password = test_user.__class__.objects.make_random_password()
test_user.set_password(password)
test_user.is_superuser = True
test_user.user_permissions.add(
view_track_tool_tab_perm, view_track_tab_grp_perm, can_assign_items_perm)
β
test_user.save()
β
return test_user, password
β
class ViewTests(TestCase):
β
client = Client(HTTP_HOST=settings.TESTING_URL)
test_user, password = create_test_user()
def setUp(self):
self.client.login(
username=self.test_user.username,
password=self.password)
β
def test_enforce_kit_assign_limit_country_level_user_no_perm_with_tracker_setting(self):
can_override_max_assign_items = Permission.objects.get(codename='override_max_assigned_items')
β
self.test_user.user_permissions.remove(can_override_max_assign_items)
self.test_user.save()
β
self.test_user = get_object_or_404(User, pk=self.test_user.id)
I would like to reset the permissions of my test user in order to test what the view displays when the given user does not have the specified permission. I am removing the permission as shown in the code above and then refreshing the database object. However, when I step through the code with a debugger, the test_user still has the permission I am trying to remove.
Is there a way to change this behaviour?
This is in Django by the way.
I follow along with Django Beginner tutorials
and with every single one of them that i follow along i get stuck here
python manage.py runserver and get this error ImportError: DLL load failed: The specified module could not be found.
before i ran python manage.py runserver i ran the following commands pipenv shell django-admin startproject personal-project .
i learned about pipenv hours ago
Hi guys,
CONTEXT:
I'm looking to contribute in a flask open source project some what beginner friendly.
CHALLENGE:
What I've fund so far are either no longer active for a year+ or not beginner friendly
NEEDED HELP:
Please share a link of an active ones that you know that helped you when you first started with flask.
thank you
with the html placeholder attrubute
Like :
<input type="text" placeholder="Username">
just like that
Hello, is here anyone that made a webshop/stock counter with python, flask and mongodb as database? please dm me asap
@native tide
autoescaping is enabled for all templates ending in .html, .htm, .xml as well as .xhtml when using render_template().
from https://flask.palletsprojects.com/en/1.1.x/templating/
Since you brought up .txt
ohh let me look at thi ty
all i was really looking for was a way to make it visually obvious from looking at files what is being included how. I use inheritance, overriding blocks, and inclusuion
Ah, gotcha. Then yeah you'd want to pay attention to the extensions.
Would a better way not just be to to batch markdown all the mds at runtime and then include generated html to avoid that
having to do autoescaping
that is
You can enable escaping as well
@native tide
https://flask.palletsprojects.com/en/1.1.x/api/#flask.render_template / https://jinja.palletsprojects.com/en/2.11.x/templates/#autoescape-overrides
{% autoescape true %}
Autoescaping is active within this block
{% endautoescape %}
Hello! Is there any better/more simple way to count and display anonymous users browsing than with cookies? Using Django
@toxic marten https://learndjango.com/tutorials/django-allauth-tutorial
WS Vincent is a fantastic resource.
The source code is good to take a look at once you understand urls-->views-->models etc
https://django-allauth.readthedocs.io/en/latest/
https://github.com/pennersr/django-allauth
Tutorials and courses on web development with Python and the Django Web Framework.
I think its possible that Flask takes it out of the ballpark with homerun win for error messages that are never helpful and full of useless information lol
what errors are you getting?
Its typically issues with templates. i think.
Otherwise they arent that bad.
Im not having any atm but they arent very descriptive. They have a way of showing me something completely unrelated to the problem, and a lot of what they show is code i didnt even write so if tits the problem then there is something wrong deeper than my implemenation
sometimes you can make sense from it if you only read the top [art and ignore everything else it shows you
it might be more accurate to say that is a jinja2 thing
@native tide You should run pip directly in the terminal, you are currently inside of the python repl.
You can type exit or press control + D to leave it.
I just ended up hacking it by adding a script on top of it that finds the spot in the document model and fucks it around
its hacky but whatever
I cant find templates
hey, am struglin to allow users to upload images inside posts with flask can anyone give a help ?
I can help with that, are you using wtforms?
yes
i got how to let the user upload a profile pic but when i begin to work on how to add images to content i struggled
you've defined a tuple named errors on (I think) line 3.
See it?
Then later you use it as a decorator, Lord only knows why.
decorators gotta be functions, not tuples.
π
π
I want to make a module that uses flask or aiohttp (or both) that will expose the public ip of a machine, taking over port 80 for it and handle certain requests sent to it
Does anyone know of a way to expose flask/aiohttp, assumedly the target machine will have to have a static ip registered in their router
Hello everyone, Hope you are doing well.
I am building a website with django which will be used to view different documentation related to the construction industry, in an easy to use and share format.
The main viewer page will have a vertical nav bar with different chapters and sections. And the right side will be the content.
What I am trying to figure out is instead of doing a hardcoded HTML css static file, use the database to create a html file . What do you think is the best way to go about ir. I thought about it a lot and the problems I see is where there are lists/tables/images in content. I am having a hard time deciding what models should I create.
i have a custom login/register page in php in laravel... will it work in core php?
um @tiny siren this is the Python discord not The Coding Den or a php server
You need to implement allow_migrate so that migrations only run on one or the other database
I'm facing an issue where I want to run a method that's bound to my app context, to return dynamic values to a FlaskWTForms SelectField... Does anyone have some ideas on an implementation..?
how to center text vertically
@import url('https://fonts.googleapis.com/css2?family=Montserrat&display=swap');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
header {
text-align: center;
width: 100%;
}
.navbar {
background-color: #2f2626;
}
.nav-logo {
margin: 0 10px;
color: #c5aa6a;
border: 2px solid #c5aa6a;
padding: 10px;
font-family: 'Montserrat', 'san-serif';
font-size: 20px;
}
.navbar ul li a {
color: #c5aa6a;
text-decoration: none;
text-transform: uppercase;
font-family: 'Montserrat', 'san-serif';
}
.navbar ul li {
display: inline;
font-size: 20px;
padding: 10px;
margin: 0px 20px;
}
``` css
<!DOCTYPE html>
<html>
<head>
<title>Website</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" type="text/css" href="styles.css">
<!-- CSS only -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
<header>
<nav class="navbar">
<h1 class="nav-logo">NAV LOGO</h1>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Projects</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Donate</a></li>
</ul>
</nav>
</header>
<!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
</html>
html
vertical-align:center
Green is navbar ul
if you set margin-top and bottom to auto
perfectly centered @native tide
I don't think vertical-align would do it
tho
Hello everyone.
A quick question: I'm developing a website/app with Flask with dozens of pages. What's the best way I can keep a consistent css style? Like have themes, be able to change colors quickly, compile colors from a palette.
I have had previous experience with drupal and scss, I don't know if it's applicable here.
i have a couple of colours and want to generate a scheme from them, any good suggestions on tools to use?
guys, can i specify a maximum file size besides FileAllowed?
class UpdateAccountForm(FlaskForm):
email = StringField('Email', validators=[DataRequired(), Email()])
pic = FileField('Carica l\'immagine di profilo', validators=[FileAllowed(['png','jpg'])])
cover = FileField('Carica la cover del profilo', validators=[FileAllowed(['png','jpg'])])
submit = SubmitField('Aggiorna')
done i think but i've another issue
picname = secure_filename(form.pic.data.filename)
pic_path = os.path.join(app.root_path + '/static/profile_pics/' + picname)
form.pic.data.save(os.path.join(pic_path))
current_user.image_file = picname
the image that i upload saves itself with its own name as i was not using secure_filename
picname = secure_filename(form.pic.data.filename) pic_path = os.path.join(app.root_path + '/static/profile_pics/' + picname) form.pic.data.save(os.path.join(pic_path)) current_user.image_file = picnamethe image that i upload saves itself with its own name as i was not using secure_filename
@cloud path what secure_filename should do is just remove reserved characters and make the filename safe for storage (ie. remove slashes and so on). Were you intending to do something else?
oh no i thought it was a number generator for the filename
but
what if a user uploads two pictures with the same name?
You're probably looking for a uuid or hashing function (+timestamp) then. I would go for the former.
Some docs here https://docs.python.org/3/library/uuid.html
thank you
@strange pawn Thanks for the Octoprint suggestion ! Hit the nail right on its head
Wasn't sure about that. But it's a webforntend in python that I use regulary and (at least plutgin dev) it's easy to learn. π
hello i've question what is the different between flask-restful and flask-marshmallow
guys, about jinja
i want to reference the profile pic of the user using the username,
I tried to do something like this :
<img src="{{url_for('olympo.static', filename='images/{{current_user}}.jpg')}}" class="user-image-twt"/>
but it's not working
hi, sorry if it's a bit of a random question but does anyone know how I can get this?
the preview thing when you send a link on a discord with a red bar to the left and all
@jagged lark @verbal obsidian Ok thanks guys it worked! btw how do you do that green part
it would help me
it's the equivalent of putting print's everywhere to see where you are at
it's not pretty but it works
just add inline style background-color = "whatevercoloryouwant"
@native tide
This is 'inline style' btw
<div style="background-color: red"></div>```
guys, about jinja
i want to reference the profile pic of the user using the username,I tried to do something like this :
<img src="{{url_for('olympo.static', filename='images/{{current_user}}.jpg')}}" class="user-image-twt"/>but it's not working
@wild thunder
does anyone know how to implement a discord preview thing
@verbal obsidian Thanks! i thought of using a text editor that does that automatically, so instead of sublime text i just found out brackets does it!
sorry if that was really unclear
i'm using flask, it changes anything?
@wild thunder
@coarse surge
trying to do something like the box that's showing under here
i'm using flask, it changes anything?
@coarse surge
@wild thunder u could try atleast
Hi is there anybody in here that uses a Mac that can help me with some Warnings I'm getting?
Is it possible to make a e-commerce website using only django? Or do I need to learn JS aswell
@gritty barn Ideally you need to learn javascript as well in order to make good user-service interactions
can someone help me understand how does deploying your flask website work?
i thought it was simple as taking my flask project folder and putting it in a cloud hosting sevice
@rustic pebble aight, thanks :)
@distant trout what service are you using?
@rustic pebble i was thinking of digitalocean free
oh
ill look up a tutorial for that
also do u know how does deployment work in general
like I need a cloud service and what else
For flask?
yes
You just need a web server service
and thats guinicorn, that flask uses?
gunicorn yes
awesome, thanks
@distant trout explore a bit about wsgi, then you will understand what gunicorn actully is and why u need it, its kinda interesting too xD
Hey all, anybody familiar with Django, I have a question about an error I am receiving while trying to edit models in the admin interface
<@&267629731250176001>
Just put down your question and we are happy to help
you don't really need to ping mods
!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.
@severe mica don't ping moderators to ask for help, somebody will help in time
ok will do in the future, my question is as follows: So i recently attempted to add another row to a model I created. I ran the makemigrations command as well as migrate and registered my model within the admin.py file. My question is why when I log into the admin page on my local server and go to add rows to my column, I am recieving an operational error which is telling me that one of my columns does not exist
my bad on pinging the mods as well, I am new to this group
can you show the error page and code
this is the error
Is there a possibility that I need to move the durations column into the 0001 migrations file
no
delete the migration files and the db.sqlite3 file then further do makemigrations and migrate again and see if it works
did you delete the database file
the db.sqlite3 file? sorry I am very new to Django, ill send a pic of the project im working in as I have just been following along from plural sight, so there is no db.sqlite3 file in the current app Im working in
there will only be 1 db.sqlite3 file in the entire project, so delete that one
makemigrations generates all the sql code and then migrate executes it all into the database
ok ill delete that and the 0001 file and try again
kay
do i need to create another superuser account after doing this
yep
ok one sec
ok that worked, thank you. also in the future am I able to simply edit my model class and add another column without going through this process
and then run the makemigrations and migrate commands
yes
Hey, is there a way to check how much time it takes to complete when a function runs in a flask server? I can create a decorator and add every function to it, but is there any easier and neat way?
@minor horizon Can't you just put a datatime variable at the start of the function, then one at the end, and subtract the two then print the difference?
Yea I mean there are too many functions and I'm going to do it for every one of them. Sorry I forgot to specify that
is the function a view route?
I use this in all my apps:
def register_response_timer(app):
"""Add a response timer and logger to the app."""
@app.before_request
def start_request_timer():
g._request_time_start = dt.utcnow()
@app.after_request
def end_request_timer(response):
ms_elapsed = round(
(dt.utcnow() - g._request_time_start).total_seconds() * 1000,
2
)
Logger.info('finished request in {} ms'.format(ms_elapsed), extra={
'ms_elapsed': ms_elapsed,
'status_code': response.status_code,
})
return response
Hi, I'm learning Python Flask and followed a tutorial on how to make a blog (by Corey Schafer). Now I want to do an own beginner project. Does anyone have a suggestion?
@compact hedge make a Pokemon application using the Pokemon API @ https://pokeapi.co/
An open RESTful API for PokΓ©mon data
hey im not like sure where to put it so ill put it here but i have a vps that i want to run a python website from with flask and i've install all it's dependencies but when i go to run the py file it says not module named... and so i was wondering if i would have to put this py file in a directory or something
Hey
im running ubuntu-16.04-x86_64
I am on a web project in django and I need a guide, can you help me please?
@heavy patio what do you need help wit
@solar obsidian
Part of my project is presence control and I want to generate a qr code that will contain the geographic coordinates of the presence control place.
Then I want to recover the coordinates, by scanning the code, and compare them with the coordinates of the one who scans the code (its geographical position).
I was able to write the qr code by inserting the coordinates of the presence control place. I also wrote the code to retrieve the user's contact details. But I still don't see how to make comparisons and approximations to manage this properly.
im not that good
quick question I am currently running the makemigrations comman to try and migrate the new models I just created and it says no changes detected after I run it. I have already registered my models within the admin.py file and am curious as to why it is not detecting my models
nvm just realized i forgot to install the app in settings LMAO
im having trouble making a "delete account" button for my flask website, id appreciate sum help
i mean i got the button down, i just dont know how to make it so it deletes that currently logged in account from my Flask SQLAlchemy database
@distant trout i can't really help you.. i just wanted to say that it looks cool
oh thanks lol :p
@distant trout , make an Ajax post request to your flask server with userID and perform the delete from the SQL database there. Can't help with the SQL query though sorry
oh okay ill try to do that, thank you @empty mantle
In flask you will want something like
@app.route('deleteAccount',methods=['POST'])
def delete() :
id=request.data["ID"]
# do delete
make sure you authenticate it! don't want users deleting other users' accounts
If I have a question about initializing a sqlite db from json in django, is that better asked here or in the databases channel?
Do people have recommended resources for learning about things like WSGI, Gunicorn, etc, basically anything deployment related? I've written Flask sites for personal use but never anything deployed.
(I know some tutorials cover basic setup for hosting, but I'd like to learn more background if possible.)
I refered to this one while I was learning, quite satifactory article
https://vsupalov.com/what-is-gunicorn/
he has bunch of articles on django, you can find the links at the bottom of his page
π
this is a great video too
https://www.youtube.com/watch?v=WqrCnVAkLIo
WSGI is the foundation of most Python web frameworks, but there's a good chance you've never had to interact with it directly. In this talk we'll explore why it exists, how it works, and what the heck it's doing in your stack.
A great web framework abstracts away all the low-...
@lapis stump
π
Hi all, I am creating a twitter based app and want to let other people authorise their account to be used by the app. where do I find good code implementation
Implement OAuth for that
Hi everyone) I`m creating web-app with chat with DRF and channels2.
I have a question: how I can add message to db and return to frontend new serialized message?
P.S. Sorry for my english
can anyone help me with flask installation?
Sure, what's up?
i did a pip install but i am not able to run flask
when i do pip list it shows flask but when i try to run it says command not found
you dont need todo flask run
an alternative is todo
if __name__ == "__main__":
app.run()```
which will achieve the same thing if flask isnt in PATH
@quick cargo thanks when i added if name == "main":
app.run() at the end of file it worked
π
@young grove please don't offer money here, keep things in the server and free.
see #rules, specifically rule 6
I'm close to using my mac to smash my own head in
I've been trying to use flask to create a landing page for the last four/five days.
the only resources I can find online seem to either be for login pages or to do apps.
I'm trying to get information from a form using post
and then save it in a sqlalchemy data base is that correct?
@tranquil steeple django is popular these days
@silent knoll so you'd recommend using django over flask even for a simple email capture landing page.
?
depends; if you can't find any resources then you could use your time to build the app in django rather than flask
Who can help me with a stock/inventory system for my python flask website. I prefer the database mongodb. Please @ me or dm me if you know how or you already have a system
I mean, I'm sure there are tons of flask resources for such a simple task
@tranquil steeple Is that all your landing page does? Form -> Save to db?
@young grove Do you have any specific question?
Yeh i want a stock inventory system
So i have a checkpoint on the atc button and on the checkout page where he checks the stock
If it is instock the user can purchase if he is out of stock the user canβt
@verbal obsidian
how can i join all ManyToMany field's values(name) in Django?
@young grove Okay that's great, any specific question or issue tho?
@stiff totem by join you mean associate?
@verbal obsidian well, i got these models
class Artist(models.Model):
name = CICharField(max_length=600, unique=True)
class Track(models.Model):
artist = models.CharField(...)
artists = models.ManyToMany(Artist, ...)
sometimes there is artist value is None so i have to write manager method that gets artist value, if not i have to return artists name joined by space
@verbal obsidian i have to begin but i donβt know how so i ask here help to someone that already made a system like that or something like that
I currently am trying to make a simple form
<form action="form" method="POST" class="formone">
<input type='text' name='name' placeholder='John Doe' /><br/>
<input type='text' name='message' placeholder='Your message'/><br/>
<input type='submit' value='submit' />
</form>
however, I am not completely sure how I can make the form text boxes larger
Is there anyone that has alot of experience using Flask?
ok this is probably a very noob question but why doesnt the transition work https://jsfiddle.net/rtfv5po8/1/
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
hello, can someone experienced please DM me, i need answers to a couple of questions. THX
Well, I'm a beginner in programming and I have an idea for a project. But my doubt is whether I should use Python or JS.
Basically I want to make a website where a user writes a letter and sends it, without knowing to whom
And only one random user receives it
and so on
Can I do this with Django?
@sour mulch Django and Flask are popular python options
fotea, you can use either JS or Python
u can do it easilywith flask
JS is worth learning even if you use Python framework for backend
i tried flask and django and i like django more
then do it with djanfo if u are more comfortable with it
i dont want to use multiple languages since im a beginner
do you wantt o be a web developer?
i can make the front end with django too, right?
if so, JS
that will work
ok, what tutorials should i follow for getting to learn JS and make a basic website for understanding, before i start with my idea?
find a JS discord server
i did
@zealous siren Thank you, sorry I didn't see this channel at all.
<a class='btn btn-danger btn-md' data-toggle='modal' data-target='#deleteModal' href="{{ url_for('users.delete_account', user_id=user.id) }}">Delete Account</a>
can someone tell me why this is not working
my user table https://i.imgur.com/lRrYAKp.png
@shadow hornet wow that server useless
are corey's tutorials still good on JS, or are they outdated?
i just pasted the one that you put down
well thats the biggest one i managed to find
Okay, so I'm super new to web development and I want to see if the website I'm going to have to refactor is able to use Django. Right now it uses ASP.NET and I'm unsure what I'm doing, how would I find out if it supports Django?
(As a note, Google really isn't helping me and despite my best efforts, I'm really not the brightest in terms of web development.)
.Net is Microsoft language and does not support Django
Microsoft has web frameworks, there is C# server that could probably recommend some
you'll have to be patient @limber spade. you can't expect an answer immediately
Are there any resources to teach me about website domains and frameworks (at a definitive level) you guys would recommend?
frameworks are so unique that wikipedia article is about in depth as you need before you go with set of frameworks
Right, I'll try to look through it then.
Guys is role required module secure or nah?
@turbid glen did you find the answer for you transition??
@nova sandal no, I tried to change the css many times but still doesnβt work
I tried yours but the black circle moved. I want to hover the black circle and the cube move
@turbid glen ohh
Sry, didnβt make it clear lol
Strictly using CSS?
What you guys use for REST apis ?
Hello guys. I am a bit desperate for help. I need to figure out how to represent one to many relationship using Django Rest Framework with ImageField. Basically I want one of my objects to be able to have a list of images as his field.
I can program in html
Is there anyone that can explain to me how to pass information from my user through to a function i have created in my flask app?
What do you mean @peak dirge ? Is this information comming from a form ?
I'm really new to all of this, but essentially it will be connected using AJAX
the form will be a match 3 game
which when the user clicks, will send the location of the 'gem' they clicked on
gem ?
like in candycrush
oh I see
Well the ajax doesn't matter really. What you want is to look at the request data. Let me show you two examples, one using GET and the other POST request.
from flask import Flask, request
app = Flask(__name__)
@app.route('/get', methods='GET')
def using_get():
data = request.args
return f'Data: {data}'
@app.route('/post', methods='POST')
def using_post():
data = request.form
return f'Data: {data}'
This is a really naive example but should help you getting started
cheers thanks for the help π
you can find documentation here: https://flask.palletsprojects.com/en/1.1.x/quickstart/#accessing-request-data
Using Django here, and two of my paths use the same view. I want to modify one based on a user by user basis. What would this be called, and can someone point me in the way of docs for this?
so for example /posts/ and /profile/posts both use this same view
Guys i have spent 5 hours trying to solve this Here is my signals.py
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete= models.CASCADE)
bio = models.TextField()
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
@login_required
def update_profile(request):
if request.method == 'POST':
user_form = UserUpdateForm(request.POST, instance=request.user)
profile_form = ProfileUpdateForm(
request.POST,
request.FILES,
instance=request.user.profile,
)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(request, 'Profile is updated')
return redirect('/profile')
else:
user_form = UserUpdateForm(instance=request.user)
profile_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'user_form': user_form,
'profile_form': profile_form,
}
return render(request, 'users/update_profile.html', context)
I have found that the error is coming everytime i add this
instance=request.user.profile
Please if someone found the mistake mention me
Django
views.py
def logout_request(request):
logout(request)
messages.info(request, "Logged out.")
return redirect("main:home")
This works fine, as long as my current url is a basic one. For example website/faq. But whenever i got a dynamic url like : website/user/tickets/ticket_id
i get an error: website/user/tickets/ticket_id/logout doesnt exist.
@finite shell if you need nothing besides REST APIs, I highly recommend taking a look at FastAPI
@late gale none of that code you have written implies that already present user objects will have profiles created until they are edited
As a result, the object does not exist, error
@native root I was following a tutorial and each user who registers have a profile and i did the same as he did and it didnt give the same error for him but for me
In this Python Django Tutorial, we will be finishing our user profile page. The final page will allow users to update their information and also add a new profile picture. We will also learn how to resize this image when it is uploaded to save space on our web server. Let's ge...
In the comments is the same issue
when . you create your initail database it comes with a default admin user
whcih crucially never gets a profile created
The comments suggest either recreating it or creating a new superuser, but I suggest having a simple check to ensure the profile object exists before attempting to access it
but creating a new super user or creating user from the database is impossible because i wont make a profile for each user i just want it to be done programmatically
@receiver(post_save, sender=User)
happens when a user is first created or edited
your current admin user was last created or edited before this code existed
Therefore it never ran, and therefore there's no profile associated
so that only happens when i create a super user
Only on the very first development one
I believe if you restarted your db at the moment it would start working, but that's not a very elegant solution
what about if i want a user who just registered from the registration form to have a profile
They would with what you have
I dont understand
You're following this tutorial right?
Yes