#web-development
2 messages Β· Page 8 of 1
show me the search view
do you have a url for the view?
There is a my website. Lista ksiΔ ΕΌek = BookList view. I would like to write for example "Medaliony" in search panel and then my website show me this book or something like this
Yes i have it
path('search/', views.SearchView.as_view(), name='SearchView')
okay go to your base html
Okay i'm in
<form class="form-inline my-2 my-lg-1">
<input
class="form-control mr-sm-2"
type="search"
placeholder="Search"
aria-label="Search"
name='search'
value="{{ term }}">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
does the app that you are doing this in have a namespace?
yes, i have, plibrary_heart
thats the namespace?
yes
okay
okay, in the <form> tag, add action="{% url 'plibrary_heart:SearchView' %}"
In my base.html template?
ou okey
<form class="form-inline my-2 my-lg-1" action="{% url 'plibrary_heart:SearchView' %}">
I would like to send you Polish Vodka xD
im okay, im underage lol
Woah, nice. I have 25 years old and skill in django over 0
xDD
I need to learn much more then this moment xD
im still learning too
But your skill is very good i think :x Nobody can help me- just you π
there are some other really skilled django developers in this server :)
some more skilled than me
you're welcome :D
I have a one question. If my search panel dosen't find anything, can i write simple message, something like "There is not book named $$$" ?
yes
Can You tell me how? In form or search view?
let me think one sec
Okay
do an if else statement in the template
actually no
i think i would do something to get_queryset
one sec
π
{% if not posts %}
<h1>Couldn't find anything :(</h1>
{% else %}
{% for post in posts %}
<h2><a href="{% url 'posts:detail' post.id %}">{{ post.title }}</a></h2>
<h3>Posted by <a href="#">{{ post.user.get_username }}</a></h3>
<br>
<hr>
{% endfor %}
{% endif %}
theres an example
if there are no posts in the queryset, it says it cant find anything
if there are, it just shows the posts as usual
@native tide
you're welcome :)
anyone running django!, I am looking for a way to iterate over many to many field? any thoughts
Model.objects.get(foo=bar).name_of_the_many_to_many
thanks you @brittle copper
Anytime
Hi I got this error
Model.objects.get(foo=bar).name_of_the_many_to_many
Cannot resolve keyword 'SpritsUpload' into field. Choices are: gift, gorod, id, title
can you paste your model class for SpritsUpload?
@opal scaffold
actually, can you paste both models?
Hey guys, anyone with basic Dash experience deployed with Ubuntu Apache2 and WSGI around and have a minute?
Dash/Flask I suppose, although I think the issue is closer to in the Dash realm
there probably is, ask your question ^^
Well
Might be easier if I paste code.
I have been able to get the Hello World app for flask and Dash both working
But get errors when uploading my own simple Dash app
and yes Ive done server = app.server
Lemme paste bin
If you want the dependent file
save as NaturalTweets.txt
Code runs on the localhost development server on my computer
but im getting 500 server error
in deployment server
I have all the needed import packages installed, the file is in the same dir as the app
Does it have somehting to do with Linus permissions or something?
My linux is weak
I mean my programming is too, but my linux skill level is quite low as well
where are you deploying your app? and how?
Digital ocean droplet
Im using PuTTy and WinSCP
I just realized there were some weird tab/spaces indentations mixed up in there from when I was restructuring
weird that it ran on my local computer tho
does that mean it's working for you now?
Im not sure yet I just finished fixing it, Im uploading now
It must have happened when I used the edit->line->reindent
Yes still 500 error
what webserver are you using to serve your app?
Apache2 and WSGI
do you get any default apache error?
sorry, I guess if you get 500 error, that must be from apache
oh shit
wrong long
I didnt know this log existed
Sorry
weird
wtf
Hmm
[Mon Jun 11 01:06:43.709952 2018] [wsgi:error] [pid 31083:tid 139812824381184] [client 75.179.160.67:63416] import dash
[Mon Jun 11 01:06:43.709970 2018] [wsgi:error] [pid 31083:tid 139812824381184] [client 75.179.160.67:63416] ModuleNotFoundError:$
how did you install dash?
did you get any errors for dash?
are your your app in a virtual environment?
No
running your app-
No
All native
Im not really sure how to work the whole venv thing or how it works in the hierarchy
what's the command that runs the app?
once you point them to your app, yes π
I dont remember exactly where they are located, this is my first time doing this where ive actually gotten kind of close lol
most other times trying i errored out way early on
ok, did you create a .service file inside /etc/system/systemd/... (or something similar)
?
#!/usr/bin/python3.6
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/FlaskApp/")
from FlaskApp import server as application
is the WSGI
Is the .service the apache config?
ok, nvm that at the moment
in the terminal
It doesnt return anything
root@ubuntu-Flask:/var/www/FlaskApp# python -v
The program 'python' can be found in the following packages:
- python-minimal
- python3
python -v does tho
what does python --version return?
same hting
ok
- python-minimal
- python3
where that sites availble apache file at?
I forget
Found it
I think
/etc/apache/?
can you go look inside /etc/systemd/system and see if you remember if you created any files there for your application
?
It is empty
I remember doing a
..
<virtual host>
servername = mydigitalocean IP
server admin email = (etc...)
somewhere
I don't know apache but that should be somewhere in /etc/apache/sites-available or something similar
can you show me the whole .wsgi.py file?
I pasted the hwole thing in when I showed you earlier I thinm'
this is in the sites-available file
oops
i mean dir
sites-availble/FlaskApp.conf
<VirtualHost *:80>
ServerName MYDIGIIP
ServerAdmin
WSGIScriptAlias / /var/www/FlaskApp/FlaskApp.wsgi
<Directory /var/www/FlaskApp/FlaskApp/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/FlaskApp-error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/FlaskApp-access.log combined
</VirtualHost>
and your wsgi.py is #!/usr/bin/python3.6 import sys import logging logging.basicConfig(stream=sys.stderr) sys.path.insert(0,"/var/www/FlaskApp/") from FlaskApp import server as application
This is the whole thing
#!/usr/bin/python3.6
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/FlaskApp/")
from FlaskApp import server as application
its
#!/usr/bin/python3.6
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/FlaskApp/")
from FlaskApp import server as application
FlaskApp.WSGI
in the dir before my application init.py
www/FlaskApp
-------/FlaskApp/
-------FlaskApp.WSGI
www/FlaskApp/FlaskApp
-----init.py
-----NaturalTweets.txt
-----pycache
Is
Idk
can you try to change
from FlaskApp import server as application to from FlaskApp import FlaskApp as application
and see what happens?
yeah 1 sec
I saw that on stackoverflow, i forget if I tried it
Still same error
Do I have to dictate to Linux to use python 3.6 or something?
idk
Like i said, the hello world examples for both flask and Dash work
Like If i drag and drop an init.py with the dash bar graph example, it works fine
can you paste the link so I can see?
yeah 1 sec lemme put the dash example in
no I mean paste the link from documentation
o
yeah lemme find it
The first example
Its for running on the dev server local, like with flask
but I have the server configured obviously
But
yeah
idk
my droplet IP displays the example code
yeah, this way is fine too
Its one huge program all built in init which is probably not good practice
not huge but you know what i mean
yeah, I have a lot to learn about best practices too
π
in the flask documentation for mod_wsgi it says:
"from yourapplication import app as application
If you donβt have a factory function for application creation but a singleton instance you can directly import that one as application.
Store that file somewhere that you will find it again (e.g.: /var/www/yourapplication) and make sure that yourapplication and all the libraries that are in use are on the python load path. If you donβt want to install it system wide consider using a virtual python instance. Keep in mind that you will have to actually install your application into the virtualenv as well. Alternatively there is the option to just patch the path in the .wsgi file before the import:
import sys
sys.path.insert(0, '/path/to/the/application')"
it seems it either option not both
can you delete the sys.path ... line from your .wsgi file and try?
ok so I changed it
now I get 500 error for the hello world app
lemme move mine back over
yes still 500 error on my app
ok can you get the error and paste it?
OK, no, use https://paste.pythondiscord.com
No module named 'dash'
Thats why I wonder if like
idk
Am I not supposed to use pip3.6 install or sometrhing
or like
Does the server not know to use 3.6
but
fuck
idk
I ran the example program jsut fine
And its import statements are the following:
import dash
import dash_core_components as dcc
import dash_html_components as html
It must not like something in my specific python program or something
what I would do next:
remove server = app.server from the init.py file
remove the #!/usr/bin/python3.6 from the .wsgi file
delete sys.path instert line from the .wsgi file
use from FlaskApp import FlaskApp as application
sorry, that's all I got
π
if you try this, let me know
trying right now
if it (doesn't) works
@native tide still 500 error
in WSGI?
yeah
oh ty i forgot to do that
yup still error
so weird
why does the example work
with the other settings
the example works without changing .wsgi file and without changing the apache configuration?
can you show me the original apache configuration?
<VirtualHost *:80>
ServerName mydropletIP
ServerAdmin youremail@email.com
WSGIScriptAlias / /var/www/FlaskApp/FlaskApp.wsgi
<Directory /var/www/FlaskApp/FlaskApp/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/FlaskApp-error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/FlaskApp-access.log combined
</VirtualHost>
did you change this in anyway now?
Why did you decide to use Apache?
You should be using nginx unless you specifically need apache
Cuz thats the tutorial I followed lol
I dont understand the whole hierarchy of it, Which I wish I did
Any good tuts you know of?
Almost nobody actually uses Apache these days
Just cpanel users really
Well, tutorials aren't everything
Ive freakin tried doing this like 5 times in the past 2 days starting over from new ubuntu install each time lol
You need to split your task up
Don't try to find a tutorial for your entire stack here
Find a guide on writing your webapp
Which I assume is flask
And then find a different guide on using that with nginx
Flask/Dash
Do you mind giving a brief explaination of the stack?
Linux, obviously, op sys, Ngnix is just another webserver?
Well you usually have an application stack when you deploy something like this
At the bottom is, say, flask, your webapp
Above that you usually have a supervisor like gunicorn which runs multiple copies of your webapp, for performance and to allow more than one person to use it at once
Then you have the webserver, which takes requests from the outside and hands them to the supervisor
So that'd be nginx
I know nginx and gunicorn are used together, usually right?
What is the relationship there?
Quite commonly, yeah
Well, gunicorn starts a bunch of workers
So gunicorn is like load balancing
We use it here to start 12 workers
and ngnix is the webserver
And then nginx will load balance to those workers
It's pretty much automatic, quite easy to do
By "here" I mean https://pythondiscord.com btw
We use flask, gunicorn and nginx
No dash, I dunno what dash is
Im pretty new, so Ive never used bokeh
Ive heard of it
But
Idk
Dash is very simple
There's tons of them
Face-value
app.layout = html.Div(children=[
html.H1(children='President Donald Trumps most frequently tweeted words'),
dcc.Graph(
id='example',
figure={
'data': [
{'x': x_range, 'y': y_list, 'type': 'bar', 'name': 'Adj'},
],
'layout': {
'title': 'Adjectives'
}
}
)
])
builds this
sorry, I wasn't of use. don't know what else to try. it's like mod_wsgi is using a different Python, but don't know how π
Also, Im not a hardcore right winger, I just thought it would be funny to see
No dude thank you so much for trying
I learned a lot just through you helping
That's the story with Apache really
Like where my error logs are and such
lmfao
π
I was deploying an app to digital ocean today. flask, uwsgi, nginx
like a breeze
π
Im in the "Its doing something, I have no idea why" stage of most things lol
ugh
you make me cringe
I literally have been doing this all weekend
well
Not literally
We use docker a lot here as well
like 4-5 hours a day hto
But that's another story
yeah it is π
Cant learn too many frameworks at once lol
I liked Dash because its built to be compatiable with Flask, which I have been messing around with a little bit
supposedly
ok cool
Ty @native tide, you helped a ton
And thanks @brave mantle, I will look into properly structring the web app, and then deploying with Ngnix
good luck with solving this
Ty
You'll manage it
Don't forget that the entire stack should work on the machine you develop on too
nginx has wsgi built in?
yeah
Huh
There's like a wsgi_pass and a default set of wsgi params
I forget the details exactly
It's very easy though
Iβve always used gunicorn
As you should
oh
You do still need gunicorn
But you have to communicate with the workers using wsgi
Aka the Web Server General Interface
I was choosing between gunicorn and uWSGI and I've decided to go with uWSGI, because it has a native websocket support
You can do that, yeah
for gevent + gunicorn, don't you also need gevent-websocket?
yeah, I though if I use uWSGI, I have one dependency less
that was the only reason
π
Well realistically a proper websocket setup has an entirely different set of webapps
Because unless you write async from the ground up, the websocket will block the worker
gevent is basically just asyncio but with all the machinery hidden from you
Concept is the same
Although it's older than even trollius
@subtle tinsel, I'm out of ideas today and my brain is fried. I'll probably be here tomorrow, so ping me if you'd like. but if you're really set on deploying, I'd also recommend looking into nginx
Lol
I just re imaged my droplet and am following digital oceans guide to flask deployment
Gonna get the hello world to work, then work on my webapp
GF will be home soon so
idk computer time is precious
lmfao
But thanks again guys
come back if you have any trouble with following the guide
Will do ty
GDPRdude, have you ever tried haproxy as an alternative to nginx?
is it a viable alternative?
i'm not gdprdude but a friend of mine runs a moderately large website and he recommended haproxy for reverse proxying
Both are good. Nginx is more flexible and more web oriented
I usually use nginx because it can be used for more things, like static files serving and complex proxying rules. If I added haproxy that would probably be in front of nginx again
haproxy is better at load balancing, and nginx is better at webserver stuff?
load balancing is the major focus of haproxy. Being a fast, scaleable webserver is the major focus of nginx
so yes, exactly as you say
doesnt nginx also support loadbalancing though?
i recall that you can specify multiple application servers in the upstream directive and it will balance traffic between those if you proxy
yes, it supports it, but haproxy does a better job. Especially in metrics
i see
anyone got any pointers for deploying a flask app?
okay, thanks
i deployed mine on a do droplet with gunicorn and nginx
@native tide @brave mantle wow
?
nice π
jesus
that was like 6% the time i spent on apache2
Sweet. Let me update my linked in profile now. Full Stack Developer
π
xD
if you need a ssl certificate it's really easy with let's encrypt and cerbot, if you want to take a look at it
so you have https on your website instead of http
SSL is lke the cert the website gets you can see in browser right
Does it cost money?
I mean
Man
lol
nope, let's encrypt is free, but it expires every 90 days and you have to renew it
but that can easily be automated
Im interested in it, Ill pick your brain about it another time. Should probably work on structure of the dash app so its not complete garbage
Whats your education rixo?
high school π
.>
damn dude
your life is going to rock after college
I mean
College is fun
but after college isnt
unless you make bank
ooooooooooo
I got a job and I've lost interest in the diploma
I thought you meant you were still in hs
last job I was a django backend developer
than I quit
now I'm looking for a new one
well... after I grok docker
π
How do you feel about your skill level and experience vs other potential new hires?
Do you feel like "HS graduate" holds you back?
tough to say
I went to a coding bootcamp open house today and Im thinking of doing it, just unsure of how potential employers see that kind of "certification"
Im a Journeyman Electrician with 6 years of experience, so Im not much different than "HS graduate" lol
although my apprenticeship was certified through a community college
if you're a web developer, I think you can get by without a formal education
The bootcamp is for Java 'full stack'
So I imagine its less web dev and more actual software dev
good education can never hurt, though
Have you ever worked alongside anyone with bootcamp experience?
I've never been to a bootcamp
I mean, know anyone who has
I'm kind of sceptical about these
also no
not sure if you can get anything from a general purpose bootcamp that lasts 2 weeks
Im skeptical too but they have 89% job placement history after 180 days
its 14 weeks
8 hours a day 5 days a week
How do they calculate that?
Is it like unemployment statistics where they only look at people who are looking for a job?
let me look again
It's about trust. a clear, measurable and verified student graduation and job placement reporting framework for coding bootcamps and higher education
no its not
they said today it was literal graduates with full time positions in related industry within 180 days
might be contract to hire or w/e
but had jobs
I'd check those numbers twice, if those were the reason I'd want to sign up
Ive googled around about them and found a lot of positive reviews
I know someone who is afilliated with a company and they hire through them as well
The course is 14,000$ tho
thats the kicker lol
ouch
yeah
ouch hard
But
If i can land a job when I finish, for median salary
thats a 20% increase for me
which is about 75% of that 14,000
so
theoretically if I dont change lifestyle habits
I can pay it off in 2 years or less
which is good at 12-14% interest
lelll
on the other hand, you could almost pay someone to give you a job you want with that amount π
off topeek
I'm just asking before going for crazy things:
Is there a way/library in Flask to manage: paging, filtering, ordering, searching and ranges(dates)?
@signal karma what do you mean by searching? yes to the other stuff
@native tide string LIKE %stuff%
The flask-admin plugin can generate you pages with your tables, it has paging, filtering, ...
Depending on your exact needs it could be an easy solution.
Here's another alternative without flask-admin: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ix-pagination
(for pagination, ordering)
Is there anything along the lines of SXML for Python? Got a Flask frontend at work and there's a lot of tables, and because of that a bucketload of copy-paste .
For those who are wondering, SXML is more of a Lisp or Scheme thing, and it's a way of defining HTML or XML or whatever data as an S-expression.
Basically, SXML tends to look a bit like this (there's many variants of it):
`(html
(head
(title "Hello World 2.0")
(link ((rel "stylesheet")
(href "/frameworkly.css")))
(script ((type "application/javascript")
(src "/frameworkly.js"))
""))
(body
(div ((class "bodyly"))
"Hello, " ,(get-user) "!")))
So I'm thinking something that looks more like this might work:
html(
head(
title("Hello World 2.0"),
link(rel("stylesheet"),
href("/frameworkly.css")),
script(type("application/javascript"),
src("/frameworkly.js"))),
body(
div(class_("bodyly"),
"Hello, ", get_user(), "!")))
Why though π€
If you want to programmatically generate HTML, templating engines are what you want
Hello! I have a question to Django Masters. I need to create a simple Comment form and view in django 2.0 Somebody of You know how to do it?
well
i wouldn't call myself "django master" but I'll answer regardless π
you're probably looking for class based views
they do the majority of the heavy lifting
for creation and updating, you can use CreateView and UpdateView
just for viewing, use DetailView
bot.docs.get('django.views.generic.DetailView')
Sorry, I could not find any documentation for django.views.generic.DetailView.
found it myself - https://docs.djangoproject.com/en/2.0/ref/class-based-views/
bot.docs.get('django.views.generic')
Sorry, I could not find any documentation for django.views.generic.
wrong place for that :D
best kick start guide for python web development?
well there is no definite "best" as everyone learns differently, but this is good for flask in my opinion: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
"best" for me really just means whatever someone experienced in the field recommends anyways
sure, whatever floats your boat. take a look at that tutorial there then, it's got a bunch of stuff
Damn it, i thought i was in bot commands
Why though π€
If you want to programmatically generate HTML, templating engines are what you want
They're a bit too limited. Let me whip up a hypothetical example.
But before I do that: Flask is good, just be prepared to pull in a few other things, e.g. WTForms is probably going to be something you will need
It does give you the advantage that you don't have to bind yourself to a database, and you don't have to bind your database to it, and you don't have to bind everything that touches the database to it (Django I'm looking at you and I'm about to rip your head off)
OK, so what I've got is a pile of pages which have names, and each has a pile of tables which have names, and each has a pile of columns with their names, as well as a pile of rows which are key-value maps
Please excuse the horrible pseudocode:
(
for table in tables:
(
"<table>" + (
"<tr>" + (
for column in table.columns:
("<td>" + column.label + "</td>")
) + "</tr>" + (
for row in table.rows:
for column in table.columns:
("<td>" + column.formatter(row[column.key]) + "</td>")
)
) + "</table>")
)
That's the ideal.
If templating engines were what I wanted I would not be asking this question as I already have one and it shows the copious buckets of copy-paste between all the damn tables.
Or in not-pseudocode, but still not Python:
,@(mapcar
(lambda (table)
(with-slots (columns rows) table
`(table
(tr ,@(mapcar
(lambda (column)
`(td ,(render-column-label column)))
columns))
,@(mapcar
(lambda (row)
`(tr
,@(mapcar
(lambda (cell column)
`(td ,(render-cell cell column)))
cells columns)))
rows))))
tables)
Props to anyone who manages to translate that to Python by the way, it's doable if you use FP-function iterators and lambdas
is this a new application? if it is and you're having such trouble, would creating a rest application and utilizing a js framework for the frontend be an option?
does heroku support SQLite3, does anyone know?
SQLite is just a filetype, if you can download a library to read SQLite files then most likely?
just gonna copy this from TCD...
I am using Flask and trying to set static content using a blue print. [14/Jun/2018 12:57:30] "GET /static/css/style.css HTTP/1.1" 404 - Obviously it isn't locating it. I was having the same problem with templates because Flask was looking in the wrong directory so I needed to manually set it. I did the same thing with static except that for some reason it return 404 no matter what I change...
blueprint = Blueprint("general", __name__, template_folder="../templates", static_folder='../static')
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
https://cdn.discordapp.com/attachments/172055423774490624/456866987650449420/unknown.png
π
SQLite3 is almost not even a database lol
^
@native tide It does
okay, so I have my Flask web app deployed on heroku using flask-sqlalchemy, but when I make a post on my website (or i just want to update the db) it doesn't 'save' the data to the database
i've searched around for a while but couldn't find much
did you commit to the database?
my-app-throupy.herokuapp.com incase you're interested
I have some css linked similarly to that, I'll take a look and maybe I can help u
Ok.
where is the html file located? templates?
Yes.
The template load file
Just can't serve static content for some reason
and no google result work..
my hierarchy is very different, but in the filename part don't you need to go back a few dirs?
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
i mean
ohhhhh
hmm
<link rel="stylesheet" , type="text/css", href="{{ url_for('static', filename='css/style.css') }}">
maybe type is required?
i can't imagine that's the problem
That wouldn't have given a404
@strange sand Uhh, I just read something
Can you show your
Uhm
app = Flask part
If any
server = Server()
server.register_blueprint(general.blueprint)
server.register_blueprint(api.users.blueprint)
server.listen()
(Server is a instance of Flask)
Actually let me just link the SO answer
ok
From what I understand you can't have two different whatevers pointing to the same static root
app = Flask(__name__, static_folder=None)
And since it is in the __main__
It automatically selects the one from root
I don't tho?
Im only serving static content with one route and that is /index
and I am pretty sure I read that post too
π
Have you done the static load at the top of the template?
Which file are you running
running __main__.py
Remove the ../
In the blueprint init
Blueprint
You don't need the kwargs at all I think
{% load static %}
<img src="{% static "my_app/example.jpg" %}" alt="My image"/>```
Oh what was the issue then
jinja2.exceptions.TemplateNotFound: index.html
yea..
its fine
My code should work, I have another project similar to the way I set this up but it just doesn't want to load the static content...
<img src="{% static "my_app/example.jpg" %}" alt="My image"/>
That renders the static file link in jinja
The rendered link is correct already
It is not serving, that's the problem
url_for('static', filename='path/to/file')
I was using something like this which I assumed is similar and still wasn't working
You should set your static path in settings?
hm?
^ maybe π
Settings.py isn't a thing in Flask, is it?
not that I know of?
Whoops. I'm all about Django atm. π©
But there, you need to do {% load static %} anywhere in the html, then include the file using {% static 'css/style.css' %}
@still briar That isn't true because this work
and the code is very similar except I use blueprints.
I know.
href="/static/css/style.css" is in this source.
God damn it
@still briar And?
It works
the above code I posted I wrote
the project I am working on now is similar
I think it depends on how you run it?
just doesn't want to work
I am running it the same
See how confusing this is?
I swear it is a bug.
I'm a bit unsure what your current solution is. I see a lot of {{'static': ...}} stuff.
In what?
I don't need to use {{ url_for () }} to serve static content because all it does is generate the url
the url is correct
the path is correct
the file is correct
just does not want to serve it
I already confirmed all of that.
Post the html line where you try to load the css.
In your original question, you said you used <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">.
^ did not work
<link rel="stylesheet" href="/static/css/style.css">
But in your example that you say is correct, you use <link rel="stylesheet" href="/static/css/style.css"/>.
But your folder was called global, not static.
Flask tutorials say you can use the proper url_for('static', filename='style.css') if your folder is called static?
Are you working on "lmstfy" or some other project?
Ack, I'm really sorry.
I was just thinking if you could share your other project on github. It would be a lot easier finding the problem if we saw everything at once.
wat
the css file
Do you mean you get a 404
isn't loading at all
What does that even mean
No okay I got those
Did you look in
/src/static/style.css
Adding src to the first part
If it doesn't work
Do what golen said and imma try on my own
But the static folder is called public. π
I know
I changed because in lmstfy.tk it was called public
still wasn't working
just ignore that change
gonna change it back right now
I see your point though. It looks exactly the same.
exactly why this had my confused for the last 2 days :/
I'll admit it my first time using blueprints and like my 3rd time using flask but still
the code should work ....
and the fact that no google answers actually helped...
Yeah, some different kind of routine for the templates folder?
Maybe, I'll look more into it later.
I had quite some problems with static in Django because you really need to template the static folder. You cannot access it directly.
Thinking something similar has happened here with routing, etc.
hm?
i got you fam
π
gonna go lay down
bye, thanks for the help
π
@strange sand
π
class Server(Flask):
def __init__(self, **kw):
super().__init__(__name__, **kw, static_url_path='whatever', static_folder='../static')
def listen(self):
self.run(host=host, port=port, debug=debug)```
That's it
im about to leave lol
dm me pls then
Okay
Anytime
static_url_path='whatever'
what is with this tho @brittle copper
I was just testing stuff, you can just delete it and it would be the name of the folder by default
is it okay to ask for design feedback in here?
I'd go for #ot0-fear-of-python
alright thanks
To start learning web development with python and to eventually make a small website, is flask or Django better? I have tried Django but ran into a lot of difficulties during even the first project tutorial. Is flask any easier?
Flask is generally easier. Django is more robust.
One of my first Python projects was in Django, and it was a nightmare.
Okay thanks for the help ^^
Both frameworks are good for any projects
Both have their ups and downs
But if you are starting out, I recommend flask
^
I personally prefer Flask over any web framework in any language.
And believe me, I tried many.
Opinions on the search bar?
looks good. maybe the button shouldn't be the same color as create?
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Time to call it a day
Got a quick question regarding setting up a local facing API.
I have a website running via Flask, Gunicorn and NGINX, and a Discord bot, both run separately. I want to open up a second Flask server within the bot which can take input from the website and perform actions instantly. The bot API will only be accessible by the website.
Do I still need a way to serve Flask in this case, or will it work running on its own?
In terms of usage, we're working with a third party that hits a webhook on the website with data that gets saved into a DB, then the bot needs to be alerted of the changes (if there are any) and perform actions on Discord.
Depending on the amount of users registered with the bot, the API will be used a lot.
I want to open up a second Flask server within the bot what. why?
you probably want to look into websockets for something like this
or something like rabbitmq
http://flask-socketio.readthedocs.io/en/latest/ this flask extension may be of interest
it is absolutely not necessary with two flask servers in order to have your website communicate with your bot.
that said, this kind of thing can get a bit hairy.
and also, it is a problem that we've solved for the pythondiscord services
so if you take a look at https://gitlab.com/python-discord, you can find code that shows how this can be implemented
we use flask and discord.py rewrite and have them communicate over rabbitmq
Thanks for the link. I'll take a look
of particular note would be our rmq discord.py bot cog
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_socketio import SocketIO
from celery import Celery
from config import config
db = SQLAlchemy()
socketio = SocketIO()
from . import models, websockets # noqa
def create_app(config_name=None):
if config_name is None:
config_name = os.environ.get('FLASK_CONFIG', 'development')
app = Flask(__name__)
app.config.from_object(config[config_name])
db.init_app(app)
with app.app_context():
db.create_all()
socketio.init_app(app)
from .api import api as api_blueprint
app.register_blueprint(api_blueprint, url_prefix='/api')
return app
def make_celery(app=None):
app = app or create_app()
celery = Celery(
app.import_name,
backend=app.config['CELERY_RESULT_BACKEND'],
broker=app.config['CELERY_BROKER_URL']
)
celery.conf.update(app.config)
class ContextTask(celery.Task):
def __call__(self, *args, **kwargs):
with app.app_context():
return self.run(*args, **kwargs)
celery.Task = ContextTask
return celery
celery = make_celery()
from . import tasks # noqa
This is my init.py file for my flask app. Is this part ok:
with app.app_context():
db.create_all()
```?
is there a better way to do this? maybe with Flask CLI?
@deep cave Thanks again for the tips, learning about setting up RabbitMQ and it's insanely powerful
I'm thinking about getting into web development, because it feels like you can learn to write useful and fun stuff fairly quickly. I'm not exactly sure where to begin though, any tips?
Flask?
flask is a good place to start imo
he does a lot of flask tutorials
and a little bit of django
@modern acorn pick one of the main frameworks: Flask or Django, learn it, make some small projects with it, then learn the other one, make some small projects with it
Then you will be able to pick one or the other based on you preferences/project requirements
what's a nice framework for simple rpc server?
Go for it! #361429235241582593 seems busy at the moment.
alrighty
<script>
const serverElem = document.getElementsByClassName("servers")[0];
console.log(serverElem)
const max = Number(serverElem.textContent.substring(0, 3));
let countInterval;
let count = 0;
function server () {
countInterval = window.setInterval(
updateServerCount,
1,
);
}
function updateServerCount () {
count += 1;
serverElem.textContent = `${count} servers`;
if (count >= max) window.clearInterval(countInterval);
}
server()
</script>
that's the code i have for https://discordbots.org/bot/appbot - i want the server count shown in that site to go up from 0 like an animation but it doesn't seem to be working at the moment
pls @ me if you're responding
@fast saddle What are you currently seeing? Does it snap to the max, or does it not update?
Are you getting an error in the console
no
Where is your script tag located in your HTML file?
It works for me:
Only thing I can think of is if the value in "servers" is 0 to begin with
Note that the timing value should be in milliseconds, not seconds
yes
maybe it's because of the class?
i selected class[0]
but idk if on https://discordbots.org/bot/appbot
it's the first servers class
it looks like it'd be
oh by the way i'm looking at <span class="servers btn btn-orange btn-2x" style="cursor: vertical-text!important;">764 servers</span> for what i want to edit
Yeah I don't think it's actually running it
<p>function server () {
This is causing it to crash
wha
here's my code for the site tho
<link rel="stylesheet" type="text/css" href="https://codepen.io/Joshuliu/pen/eMqppw.css">
<iframe src="https://app-bot.000webhostapp.com"></iframe>
<script>
const serverElem = document.getElementsByClassName("servers btn btn-orange btn-2x")[0];
console.log(serverElem)
const max = Number(serverElem.textContent.substring(0, 3));
let countInterval;
let count = 0;
function server () {
countInterval = window.setInterval(
updateServerCount,
1,
);
}
function updateServerCount () {
count += 1;
serverElem.textContent = `${count} servers`;
if (count >= max) window.clearInterval(countInterval);
}
server()
</script>
Here's how it's being sent to the browser:
<script>
const serverElem = document.getElementsByClassName("servers")[0];
console.log(serverElem)
const max = Number(serverElem.textContent.substring(0, 3));
let countInterval;
let count = 0;
<p>function server () {
countInterval = window.setInterval(
updateServerCount,
1,
);
}
function updateServerCount () {
count += 1;
serverElem.textContent = <code>${count} servers</code>;
if (count >= max) window.clearInterval(countInterval);
}
server()
</script>
Looks like it's not intended to support script tags
It's converting your spacing into <p> elements, and converting rogue > elements into corresponding htmlentities
Also apparently adding <code> tags instead of ` characters
OMG
IT WORKED
but it was for the dumbest reason
<link rel="stylesheet" type="text/css" href="https://codepen.io/Joshuliu/pen/eMqppw.css">
<iframe src="https://app-bot.000webhostapp.com"></iframe>
<script>
const serverElem = document.getElementsByClassName("servers btn btn-orange btn-2x")[0];
console.log(serverElem)
const max = Number(serverElem.textContent.substring(0, 3));
let countInterval;
let count = 0;
// I removed the space here
function server () {
countInterval = window.setInterval(
updateServerCount,
1,
);
}
function updateServerCount () {
count += 1;
serverElem.textContent = `${count} servers`;
if (count >= max) window.clearInterval(countInterval);
}
server()
</script>```
That functionality looks liable to break if they figure it out
Including custom Javascript in a page like that is a pretty serious security vulnerability
they only allow javascript for certified bot developers who use their page
Well, that's their prerogative I suppose.
yeahh idk
I'm gonna go crazy
class User(AbstractUser):
class Meta(AbstractUser.Meta):
swappable = 'AUTH_USER_MODEL'
app_label = 'mainsite'```
AUTH_USER_MODEL = 'mainsite.User'```
INSTALLED_APPS = [
'mainsite.apps.MainsiteConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]```
All I'm trying to do is to extend the god damn user model
Do I change the swappable or something?
Hmm
Docs say I should've done it before creating the database
Or it would be harder
Hmmmm
@native tide did you figure it out?
? :D
sorry :)
Don't worry xD
So I did most of it
Can't register my user model under the authorization part in the admin page
Wanna add it to that part, not just admin.site.register
not sure if I remember this correctly, but I think you're supposed to extend the Django user model by creating a model of your own without inheritence and then link to the Django's user via one to one relationship
Naah that's not it
I used that in my old project for a smaller profile
Yet in the docs it says inherit from AbstractUser which I did
you're right, you can do that
Okay
from mainsite.models import User
from django.contrib.auth.admin import UserAdmin
admin.site.register(User, UserAdmin)```
I want it in auth and not in mainsite
@brittle copper, can you try:
from django.contrib.auth import get_user_model
User = get_user_model()
?
(and delete from mainsite.models import User)
hmm
I think you'd have to write your own UserAdmin too
let me check
yeah, I think so
from django.contrib import admin
from mainsite.models import User
from django.contrib.auth.admin import UserAdmin
class MyUserAdmin(UserAdmin):
morefields = (
(None, {
'fields': (
'theme',
'bio',
'is_author',
'is_confirmed',
'trophies',
)
}),
)
model = User
add_fieldsets = UserAdmin.add_fieldsets + morefields
fieldsets = UserAdmin.fieldsets + morefields
admin.site.register(User, MyUserAdmin)```
What I have now is this
can you try and replace
class MyUserAdmin(UserAdmin)
with
class MyUserAdmin(admin.ModelAdmin)
?
Yeah
- 647
- 3582
- 376
- 179