#web-development
2 messages ยท Page 50 of 1
flex: 1 1 var(--pixels)px; are those good defaults to start with? Not sure I understand what the first two are affecting yet. I know its grow and shring.
btw is that legal css with the var() .. I noticed that it works sometimes when I do it and not always
I never use var tbh
ah, I love them
for color values and numbers i use a lot.
This is exactly what I need to make my damned thing i was making earlier.
I was resorting to just... stuffing classes and properties to make things match.
Then media querying when they dont work at a size
Like this is still not lined up the way it should be haha. But its fine for now.
I settled for "forgot" because everthing longer than that took up too two lines of space for some reason
I'll probably move it down below later. tired of fiddling with it.
put it as a link below the login button, spanning the width of the form
does not have to be a button
yeah, that's how it originally was. I was just playing with different things earlier with it. I learned some stuff but I also learned that I need to learn some more stuff. I put those things in at least 6 different arrangements trying out bootstrap classes in various combinations. ha. It ended up being the simpler approach was better.
I got a random question. How would you approach this. This is a screen cap of me zoomed out in my browser to demonstrate the experience of people with the modern absurdly large resolutions of today.
How would you go about checking that the size of the screen is pushing the top menu too far to the left and then push it back the other way so that its more aligned with the header?
Or do you think its fine like that? I dont use that large of a res anyway but people do.
It has something to do with a position setting and coordinates im sure
Also my colums are not spaced equally because I am fixing them ha
is it like normal socket on flask?
It's weird for sure
It says: The application must serve a page to the client that loads the Socket.IO library and establishes a connection:
But it does not load my template
so there is no connection being made
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
@app.route("/")
def index():
return render_template("index.html")
if __name__ == '__main__':
socketio.run(app)
the only thing ive really ever done with sockets is open them, listen on ports for transmission, and receve them from another script haha. Good luck
how do i stop elements from overlapping eachother when i shrink my browser?
give me a fiddle with the problem @native tide
what? @tired root
a minimal example using jsfiddle
flex, grids, media queries, and possibly by using bootstraps col system if you cant figure those out.
But yeah. That.
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
what do i do with the fiddle?
You make a minimal example that illustrates your issue
css and html are way too complex to give you an answer based on your previous question
oh ok
sorry, pretty new to this
yeah, you just copy your html yo html part, the css to the css part
and then click save
you get a url and show it to use
can't i jiust send my html and css here
Then someone would just be having to make fiddles for you. Might as well learn to do it.
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
sorry
its all good
its like pastebin
cool
Im gonna take the time to master this flex and grid stuff before I sink away a lot of time just tinkering with what css I know. There are too many conditions for things to go wrong to not approach it with perfect best practice i think
im tired of the one little thing that i cant figure why it does that.
So im learning this stuff.
It seems more robust than cramming properties everywhere.
@tired root any luck?
if you resize, his content is covering up his bio link
https://jsfiddle.net/xo5s42vz/6/ this didnt exactly fix it
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
But its maybe going to get you started ...
i put that html tag iin there for you
The whole css is also only using static sizes
Which is bad when you deal with different screens
Hi, I'm the django beginner. I want to know how to let the pdf file show on the webpage. I have a index.html that can show the content: title, abstract, year and others so far. And I've made the title became clickable to another web address. But how can I create a new page for this address and showing the pdf content? Thanks
PS. I have a sql table storing the pdf file path.
@heady ore Use pdf.js
is there anyway that is wasy to do that? I dont have any experience in front end
so it might be a huge gap
That is the easy way
so I think the first step for me is: create a page that shows the file_path after I click the title
but actually I dont really know how to start
Showing the file path on the server isn't a very good idea
The question is, what you want to do here
if you want to display a pdf in your web page, use pdf.js
i know. but at least it allows me to link two sql table
i dont know how to do this yet
This does not make any sense
How does displaying a pdf make you "link two sql tables"?
i have two tables. one has the info of doi, title, abstract and others. another has doi and file path, the doi is the foreign key
so now i only able to show the content from the first table
and want to know how to link to another based on doi
Use a sql select with a where statement
SELECT doi, file_path FROM tablename WHERE doi=?
i know how to do that in sql command, but how can i implement that in django?
https://docs.djangoproject.com/en/3.0/topics/db/ if you havent read this pretty thoroughly, it will help you deal with databases thru django
I use postgresql
the models system is the most useful thing about django, there is an entire ORM for interacting with a database. You run queries through python after setting up your models and then merging to your database. Then you can use those queries in logic (usually under views.py) where you can send context (variables from the logic) to the template to render however you wish.
not sure if django is the part that you are struggling with or if front end.
actually, both. I know how to get data from api, sql, mongo, selenium. but haven't known deeply in django.
yeah... i had to construct the polls app (documentation tutorial) and then make corey scahfers django class blog project before it really started to click. It is so big that its overwhelming. But it just takes reading and then doing.
It is very different from anything i had done before as well.
And tbh
I still dont know all the intricate details of django. I know the basics.
There is too much to know, you basically have to work with it for a long time to be very versed with it
basics are not too bad though you just need to read the docs
if the HTML is the hard part for you... might want to do that as well. Templating engine isnt very powerful without it
too many things to know to build with django
I would say web dev is generally like that I think no matter what you get into it. And probably all dev really in a way.
sigh
css is some hacky bullshit sometimes. Ive probably been doing it for too long. need break
what do you mean with host?
as in, create a new vhost in apache?
I mean which address the website is running under isn't really the job of the framework
You need to elaborate on what you want
What are you using for publishing?
As in, server software
nginx, uwsgi, apache etc
Generally, a subdomain is the servername in the software you use and the sub domain also needs to be announced via the dns
How would I handle a Cyrillic string in Flask's flashed message?
It's complaining whenever I flash() a Cyrillic string
Yes, that is the A record
the IPV4 forward zone
Other records in DNS are ptr reverse zone and AAAA for IPV6
at the very least, you should have an IPV4 forward zone and a reverse zone
You need mod_wsgi for apache
yes
Which OS?
Debian derivative?
okay, that makes things simpler
go to /etc/apache2/sites-available
touch projectname.conf replace projectname with whatever
nano projectname.conf
or vi, I don't care
are you using tls?
lets'encrypt?
I dont have my test server encrypted but i also dont have a domain name... and its not open to the web. There is a thing called self signing but I dont really understand what the point of that is
It means there is already something running on port 80
Is there a nginx or so running?
yeah, well then you can't run a second webserver
You need to configure this with nginx
nginx is running as a service dude
systemctl status nginx
ok, then lets setup django on nginx
since it runs on a subdomain, the mail can stay on :80
What do you want to use to run django? We can use apache and nginx as a reverse proxy or something like uwsgi and nginx as reverse proxy
either way, we need a middle man
i would nmap 127.0.0.1 on slightly unrelated not to see what you got open. Is it normal to run a mail server on port 80?
It's the web frontend
ahh
no mail server runs on 80
yeah
REmove apache, then use uwsgi and serve it on 127.0.0.1 and an arbitrary port above 1023
Then configure nginx to act as a reverse proxy
Which means, it fetches the pages from 127.1 from the uwsgi server and serves it to the user
I gave you the docs for uwsgi
I can't do it for you and I can't guide you step by step
you need to learn this stuff
HOw are you going to maintain it otherwise?
getting postgres up on a test server was the hardest thing i ever did i think. Its not that it was that hard really. Its that the things i didnt know prevented me from understanding what i needed to do. I finally figured that out though. I would love to be able to have one of my servers be actually online. But the only way i could do that would be dynamic dns and port forwarding and locking down my router and i just dont think im ready ha.
btw I just nmaped my localhost ip and then nmapped my specific local 192.168.x.x ip
What is the explanation for the variation going on with the open ports.
It was not what i expected and scared me at first but the not 127.0.0.1 address gave back what i expected to see
@tired root port 631 CUPS 2.2, port 3306 MySQL 5.7.29 1 service unrecognized despite returning data. If you know the service/version,
If I run the same command nmap -sV <ip> on my local ip, its nothing except what I expect to be there. But if I run it on localhost, there is stuff I dont know what that is (the stuff I named).
the fingerprint it cant identify seems to be my postgres server's open port.
To my knowledge im not running mysql on anything...
I might have um... I might have mysql workbench that i never use but tried out one time. Lets see. But still, why does it show on localhost and not literal ip...
<td>#{{lbcount += 1}} {{x.userid}}</td>
how would i do this in a flask template
cause += throws an error
its inside a for statement
huh, you can't do += in flask? Odd
ikr
well lbcount = lbcount + 1 might work
iirc those templating systems are separate languages that just happen to resemble python
but differ from it in surprising and annoying ways
expected token 'end of print statement', got '='
damn
i just ended up doing loop.index
>>> u = UserAccount.query.first()
>>> u.email
'asdf@asef.com'
>>> u.email = "asdf@google.com"
>>> db.session.commit()
Is this all it takes to update the database?
Flask, SQLAlc
@native tide Yeah afaict you can't do assignments like in python
Yea i dont like how you cant do alot of python related things in jinja templates
i had to define len() lmao
i was like wtf i thought that would atleast work
there's another template language called "moustache" that I like (in theory; I've never really used it) because it doesn't even pretend to be a python-like language
Is this how you would return a JSON response with an aiohttp server?
btw is this how you return a JSON response?
ok = {"status": 200, "error": None, "successful": True}
def json_response(_json: dict = None, status: int = 200):
if _json is None:
_json = ok
return web.Response(body=_json, status=status, content_type="application/json")
looks reasonable
https://docs.sqlalchemy.org/en/13/orm/extensions/index.html
Which of these Flask ORM extentions are the best to learn and why?
Association Proxy
Automap
Baked Queries
Declarative
Mutation Tracking
Ordering List
Horizontal Sharding
Hybrid Attributes
Indexable
Alternate Class Instrumentation
association proxy is useful for many-to-many relationships
echo $THAT >> notes.txt
hahah
the names make it hard for me to tell what theyu are for
yeah the names make them sound scarier than they are
a declarative system basically allows sqlalchemy to map classes to database tables
Does it not already do that? I was just reading about that one.
it does that if you use the feature
you import the declarative base and create models with it
if you do that, then yes
What I mean is I have a models.py file with classes that become tables as far as I know. The only thing I use to make my models is db.Model, UserMixin, essentially db = SQLAlchemy(app)
the mixin comes from flask_login
But
I did just try to add a property to a class that the database did not have
and it did not like that
ahh ok
drop everything
yeah the database schema is set in stone
if you change it, you have to do migrations
in django its easy to migrate
yeah, ive looked at those migrations py files
so
what is the manual process of migrating?
#databases or here? they might know a lot about that huh? but maybe not webdev orms
i'm not sure about flask-sqalchemy, but for sqlalchemy, you'd typically use alembic
ive heard that from someone. Is migrating a task that is worrisome and liable corrupt data you care about?
i know that ideally you plan to not need to do that.
yeah you typically don't want to do migrations too much, but it should not be too worrisome to do one
some practice on some dummy data and you should be fine
mm. I'm just not sure what the process entails. I suppose when I really wantto do it I will read up. Right now Im more interested in learning fundamental design done right from the beginning
I think im going to stop using sqlite and turn on my postgres server and see how much more difficult it is to work with it. Ive already done it with django. not sure how difficult it will be with this.
Hello
good luck!
I have a domain name and I want to connect my flask server to run on it
that's harder than it should be, in my experience ๐
I've done it but it took time and $
Tell me how please :O
well what I did -- certainly not the only way -- was I got an El Cheapo EC2 instance from Amazon AWS
got a static IP address (free, surprisingly); pointed the domain name at that address, installed nginx, figured out how to get that working, &c &c
result: => https://teensy.info
Oh I think I only needed nginx because of SSL -- if you don't mind not using SSL, you don't necessarily need it
but you really should use SSL
x l n t
I just want to know how to connect my flask to it
so really you could run your flask app right now and it'd probably work
well what's the server?
apache? nginx?
in either case, they should have docs explaining how to use it as a reverse proxy.
Should I type specific thing in app.run?
Or you could just shut that down, and run your flask app to listen on the same port (probably either port 80 or 443)
I have no idea
oh
maybe the port number
5000?
up to you
So It's okay then
if you use 5000, chances are your flask app can peacefully co-exist with your existing server
you might need to do something special to allow incoming requests on that port -- in ec2, for example, you have to add an entry to your "security group"
Oh
probably depends greatly on your hosting service
Debian
I doubt that's your hosting service; that's probably just the linux distro you're using
I got you
"hosting service" is "people who actually run the physical computer for you"
aws?
It is
ah there you go
no?
Sorry xD
oh ok
well vultr might have something similar, where you have to explicily tell it "please allow incoming TCP/IP traffic on port 5000"
when you tried www.example.com:5000, did you browser say "connection refused"?
refused to connect
Yup
so either
- shut down apache, and have flask listen on port 80, since we know that works already; or
- tell vultr to open up port 5000
hint: if you do the first thing, you'll have to run your flask app as root, which sucks
All ports are opened
then maybe flask isn't listening on port 5000
if it were, it'd say so when it started up
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
do you have messages like those?
here is simple login page of blog site anyone can help me redesign it?
Yes!
@native tide this channel is in use; type !f to find a free one
Exactly
ok, fiddle app.run and tell it to listen on 0.0.0.0
And keep the port as 5000?
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
* Restarting with stat```
sent an invalid response.
im having trouble actually with getting other devices on my network it respond to 0.0.0.0 even though my local machine loads it
well but you should at least see spew from flask acknowledging that it got a request, and responded ... ?
Yup!
ok now you just haveto debug your app.
yep
I see
you need to export FLASK_ENV=development if you are in development
I can't think offhand what mistake you could have made that would cause your browser to complain about "invalid response" though
that isnt the solution to that tho
I might continue with google..
@oblique hemlock mind sharing the code?
do you have a firewall? OR does your browser block ports maybe?
do you have a firewall? OR does your browser block ports maybe?
@native tide I don't know I will check
what is your os
Debian
@app.route('/convert', methods=['POST'])
def convert():
def long_time(url):
#clear directories of previous songs
clear_directories()
#downlaod the audio from the link given
yield download_from_youtube(url)
#convert downloaded song in sample audio to 8d and save out
wav_mono, wav_stereo, sampling_rate, tempo, beat_frame = song_features('./out/test.wav')
yield "Loaded Song"
wav = rotate_left_right(wav_mono, wav_stereo, tempo, sampling_rate)
yield "Rotation"
save_song('./out/in.wav', wav, sampling_rate)
yield "Saved to Path"
add_effects('./out/in.wav')
yield "Added Reverb"
return Response(long_time(request.values['url']))
yield doesn't work with flask, and you don't need to return Response()
yield means you are sending multiple requests to a client
I will edit that
is there a way to pass app.run() keywords that tell it the conditions of flask run
like the host, the port, etc
so i dont have to use command line options
I think those yields are fine
they're in an internal function, not the function decorated with route
I commented them but the same
what error
the response will be built from a list of things
sent an invalid response.
...there is... reading answers to questions while asking them
156.194.47.19 - - [28/Mar/2020 18:00:30] code 400, message Bad HTTP/0.9 request type ('\x16\x03\x01\x02\x00\x01\x00\x01รผ\x03\x03รรฒรฑ\x9aY\x06ร1รฆยต\x1bยบรรณ\x89\ยชยง2รฒS\x98\x052|รoรยง\x84Oร')
156.194.47.19 - - [28/Mar/2020 18:00:30] "รผรรฒรฑ๏ฟฝYร1รฆยตโรรณ๏ฟฝ\ยชยง2รฒS๏ฟฝ2|รoรยง๏ฟฝOร รs๏ฟฝรฅ_๏ฟฝรฎยพ,๏ฟฝยดรฃ|K๏ฟฝtรรu9รข{=ยพยณยงร๏ฟฝ4ร"รรร+ร/ร,ร0รยฉรยจรร๏ฟฝ๏ฟฝ/5" HTTPStatus.BAD_REQUEST -
156.194.47.19 - - [28/Mar/2020 18:00:30] code 400, message Bad request version ('n\x00"zz\x13\x01\x13\x02\x13\x03ร+ร/ร,ร0รยฉรยจร\x13ร\x14\x00\x9c\x00\x9d\x00/\x005\x00')
might be SSL
Um-
is your browser going to https://your-site.com:5000?
I don't think so
if so, make it http://
how are you accessing your flask site?
serving https is a lot harder than http
you almost never want Flask to serve HTTPS
that's not Flask's job
you don't need it at all unless you're in production - in which case, you should be using nginx to service your users (nginx will handle https), plus a worker manager like gunicorn
I think you could put nginx in front of flask safely. I think.
You can
But generally, Flask won't be able to handle more than one user at a time
Even though each transaction will probably take milliseconds
when you have a bunch of people accessing your site at once, you'll probably need workers to keep things fast
that I can believe
I personally would put up with that, for the sake of simplicity; I'd switch to e.g. gunicorn only if it was clearly necessary
It's best to do the right thing first really
Then you can pretty much set it and forget it
I'm really confused now
This is one way to do it
it called the proxy pass.
nginx is known as a reverse proxy, yes
Thanks!
its a bit of a learning curve the first time i admit.
ther sysadmin that is
with the sysadmin stuff, when you get an error that is like, "Yo, the server said nah" which is like a 502 or something like that, you'll want to learn quickly to check logs. Things will work in development that wont work in production server. you have to get used to restarting gunicorn and editing various files in very specific ways. Small things like having a file in a directory that shouldnt be there will cause it bork and not tell you why (directly).
But in the logs is the answers usually
the web server config was not as hard for me as the database auth permission granting and denying.
but i got it eventually
Servers dont give obvious error messages. they hide them in files
how do you write a postgres url to a remote server's database that requires auth? I typically do psql -U postgres -h 192.168.123.456 -p 5432 -d the_database -W but for Flask I need something like postgresql://postgres@192.168.123.456:5432 ..but i also need to put a password and a database name to connect to somewhere in that url string right?
postgresql://user:password@host/database
Generally, yeah
I uploaded my secret key to my first django test project's repo ๐
not that it mattered but thats how i learned
Note: Flask-Migrate makes use of Flasks new CLI tool. However, this article uses the interface provided by Flask-Script, which was used before by Flask-Migrate. In order to use it, you need to install it via:
Would you skip Flask-Script and just use whatever new CLI tool... I'm learning Alembic and migrations with Flask-Migrate.
class Result(db.Model):
__tablename__ = 'results'
id = db.Column(db.Integer, primary_key=True)
url = db.Column(db.String())
result_all = db.Column(JSON)
result_no_stop_words = db.Column(JSON)
def __init__(self, url, result_all, result_no_stop_words):
self.url = url
self.result_all = result_all
self.result_no_stop_words = result_no_stop_words
def __repr__(self):
return '<id {}>'.format(self.id)
I see some people frequently skip the traditional __init__ method for setting attributes when they write Flask-SQLA models. I'm not sure why or why not. The properties are eventually accessible through q = Result.query.first() and then q.prop -- but is the difference that those values are from the DB and not attached to the instance at all? The syntax is otherwise the same for calling a prop from the db as from the instance. It doesnt cause any problems to do both does it?
class UserAccount(db.Model, UserMixin):
"""
Account Holding User
"""
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), unique=True, nullable=False)
image_file = db.Column(db.String(20), nullable=False, default="static/default.jpg")
password = db.Column(db.String(60), nullable=False)
account_created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
agree_over_18 = db.Column(db.Boolean, default=False)
is_admin = db.Column(db.Boolean, default=False)
player = db.relationship('PlayerProfile', uselist=False, back_populates="user")
def __repr__(self):
return f"User('{self.id}', '{self.email}')"
def __init__(self, id, email, image_file, password, account_created, agree_over_18, is_admin, **kwargs):
super(UserAccount, self).__init__(**kwargs)
# Initialize Attributes
self.id = id
self.email = email
self.image_file = image_file
self.password = password
self.account_created = account_created
self.agree_over_18 = agree_over_18
self.is_admin = is_admin
# Create Row in DB When Created
db.session.add(self)
db.session.commit()
# Apply a player profile to users on creation
new_player = PlayerProfile(id=self.id)
# Commit to DB
db.session.add(new_player)
db.session.commit()
this is my actual user model
Im not sure if the self.prop = prop lines are superfluous
ty
I would argue, however, that the super call should set all of them by default so they're probably superflous
thants what it was thinking but not sure. I barely understand that super() thing to tbh. I know what it dose sort of but the syntax is confusing to me.
I put it there because it worked
it has variations that are more than just super().__init__()
I prefer not to have it in this code, it does seem extra.
@native tide super isn't extra - there's a reason it's necessary. Your class's __init__ is overriding the parent classes __init__s. To ensure that all the __init__s are called, you use super.
https://www.programiz.com/python-programming/methods/built-in/super
https://realpython.com/python-super/
oh no, I get that part. I mean extra as in all the property saving that isnt necessary apparently. I get why you have to inherit the base classes traits. What confuses me is when the syntax looks like this
def __init__(self, **kwargs):
super(UserAccount, self).__init__(**kwargs)
what are those positional args?
Print them and see!
Oh you mean what **kwargs do - https://book.pythontips.com/en/latest/args_and_kwargs.html? Also, to print them simply use print(kwargs)
Not sure what the purpose is in this context.
Oh, I know what keyargs do. Its the clarification of super(ClassName, self) that i dont get. Ive always seen it called with no arguments.
And to be honest, I dont know why Im using it here. I know why you typically want to inherit traits from a base class, but in this case, I literally just put it here because thats what Corey Shafer did when he wrote his user class and he didnt explain why. In fact he didnt add it at all until he discovered there was some error on a production server.
if i recall
I still dont even know what a Mixin is haha, i just use it.
Ill get to that soon
thanks to everyone for the the guidance btw
read the django tutorial
How can one model polymorphism in django 3.0? I.E. I have a class Vehicle then I have the classes Plane, Car, Tank, Bike that all inherit the Vehicle class. Now I want to be able to select all Vehicles (aka getting the objects of all subclasses ( Plane, Car, Tank, Bike )) and set a subclassagnostic foreign key to Vehicles
Basically I either want django to recognize the Relationships OR I want to mirror all changes to tables of subclasses up to the Vehicle table.
I was referring to this one
pretty concise and teaches you the basics
It has <10 parts so it is not all that much to work through
Yeah i used to read this
Which one you prefer django or flask
And of course have you studied any type of book to learn django?
django and I learned by making an exploration project in my freetime and then building on that.
So I wanna move this content box to that red line down anyone can help with css styling?
here is the css stuff for these content boxes
.content-section {
background: #ffffff;
padding: 40px;
border: 1px solid #dddddd;
border-radius: 3px;
margin-bottom: 20px;
}```
@manic frost Can you help?
Please don't ping random helpers.
Sorry, I'm not an expert in CSS
Have you tried searching how to do that?
idk how to define It on google
but now I've too much gap between two posts
Could you post the code via pastebin?
Or maybe jsfiddle or something like that
So that I can manipulate the css in real time.
just the css one?
sure
Try delete that margin bottom once
Might work
If the css file is the style of the posts itโll probably work
I did this and It worked css .content-section { background: #ffffff; padding: 35px; border: 1px solid #dddddd; border-radius: 3px; margin-top: 70px; margin-bottom: -90px; }
๐
v_gz I messes up with jsfiddle xD
Ive never seen nicer than this
It was just an experiment xD
๐๐ฟ
@nimble epoch okay but I messed up with something else
can you help?
yep
not sure but TRY ME
wait 1s I think messed too much
๐
Can I DM?
Sorryy what
can I explain that in DM's?
Explain
whatever xD Its gonna be too long
Man you are a genius
lol why? what did I do?
I mean it Looks ok, no?
did you notice the about stuff in background?
yep Its not a css thing
Dude I'm a tech geek thats why + I'm a fast learner
Wow
Its my first month of coding
ty but can I ask you for help later?
Of course
I did some codeacadmy stuff but not my thing
yep Its too boring
I think theres another wabsite like codeacademy
I like only Scrimba cuz of their technology xD
But thatโs different
which one
In codecademy You can learn by coding yaself
I think that was the best place
But Scrimba doesnโt look bad
yep Scrimba is kinda interesting
Yeah but i have never tried
okay I gtg
Ok
Yo, does anyone here use Quart?
Never heard of it๐
It is basically an async version of flask
Nvm found it, there is an extension that allows you to patch things like res = make_response('') to res = await make_response('')
Sorry๐ Nope
yea I figured it
How'd I approach creating the lines between text here?
I had a functional login page for my blog site and I wanted to redesign It and I did now Its not working can anyone help me to make It functional?
Oh I fixed It but somethin else happened XD
How can one model polymorphism in django 3.0? I.E. I have a class Vehicle then I have the classes Plane, Car, Tank, Bike that all inherit the Vehicle class. Now I want to be able to select all Vehicles (aka getting the objects of all subclasses ( Plane, Car, Tank, Bike )) and set a subclassagnostic foreign key to Vehicles
Basically I either want django to recognize the Relationships OR I want to mirror all changes to tables of subclasses up to the Vehicle table.
@native tide maybe use an image?
Anyone know of a way I can create a type of flow map kinda drawing? similar to this.
It's not going to be static, it will grow, shrink, and change depending on whats stored in a DB.
I looked at jsplumb, but would like to stick with just something in python.
Hi guys i need some help. I set up SQLAlchemy and made a model class for users and one for SchedulePosts and I have a form that accepts one day of the week and the event. I need help setting up the view and schedule page template so that the users info gets posted to the same page as the form. Any input would be great, thanks!
*update i set up the view now im getting an error when trying to import the table but ill try and figure that out tomorrow
i made a repository for my website on github
and initilazied on my mac
and everything
and commited fil
but when i try to access the website through the github pages
it sayas 404 page not founf
I cant stop getting
File "/home/virufac/Projects/shell_hacker_game/venv/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 877, in apply_driver_hacks
if sa_url.drivername.startswith('mysql'):
AttributeError: 'NoneType' object has no attribute 'drivername'
when I try to do anything with my database as postgres. le sigh. I think im too exhausted to even write up the problem tonight.
if I have environment variable exports inside of ~/.profile on Ubuntu based Linux, they should export right? For some reason I have to keep redoing that also every time i leave a shell.
I should probably call it a weekend. Im at the stage where my mind is mush now. I wish that never happened and I could just go on working for infinite time.
that happens to even the best of us, a fresh mind the next day usually finds the problem
yeah, its best for me especially to be self aware about it so i can mitigate the possible damage to my work i sometimes do after exhaustion sets in if i dont face it for some reason..
So i try to do not do that ha
How can I show the pdf content with FileResponse? I have the following code so far:
In views.py:
def pdf_view(path):
path = str(path)
print('PATH++++++++++++: ' + path)
with open(path, 'rb') as pdf:
# response = HttpResponse(pdf.read(), mimetype='application/pdf')
# response['Content-Disposition'] = 'inline;filename=some_file.pdf'
response = FileResponse(pdf, content_type='application/pdf')
return response
from paperPath.models import PaperPath
def get_path(request, pseudo_doi):
pathInfo = PaperPath.objects.get(pseudo_doi = pseudo_doi)#.path
pdf_content = pdf_view(pathInfo)
return render(request, "paperInfo/detail.html", {'pdf_content': pdf_content})
and
In html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>PaperPath</title>
</head>
<body>
{{ pdf_content }}
</body>
</html>
It's showing <django.http.response.FileResponse object at 0x7f9999267c88> now
@native tide I got something working with ::after
https://codepen.io/mislavperic/pen/MWwZMRN
Still I'm hardcoding the margin-left which I'd like to replace
i want to make a tic tac toe game
what should i use div,table
button
which is the easiest
hi, I made a blog site in this site If I click on a posts author name It refers me to users other posts, I know how It works but the question is how do I refer it to authors profile I already have users profile template, what should I do?
Are you using Flask or Django?
Django
@native tide
So, inside of an href you will use {% url 'blog-home' %} 'blog-home' is an example of a name for view attached to the urlconf like this
urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
path('user/<str:username>/', UserPostListView.as_view(), name='user-posts'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/edit/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('about/', views.about, name='blog-about'),
]
<a href="{% url 'password_reset' %}">Forgot Passoword?</a>
I wanna refer It to the authors profile not the users own profile
@native tide also you can create a url that redirects it like redircet(โprofileโ, id=user.id) in the main page that you want to click on the username
in url conf you make a url configuration that takes a variable
for example look at this one
path('user/profile/<str:username>/', ...etc
and then just set up a view that takes the argument and redirects there
I might not be the best at explaining it because i dont use django very much
So I need a separate template for authors profile?
Yeah
Yes, not for each profile, but in the template youll use jinja to display content based on which user it is
Is jinja a separate library of django?
oh well actually, its just similar to DTE.
Theyre slightly slightly different
Django originally used jinja i think
and then made it thier own a little
I guess I already have It in Pycharm
I have an error in the web browser that is blowing my mind. PyCharm says it finds no error
AttributeError
AttributeError: 'str' object has no attribute 'c'
And I know that sounds like a typo... but I cant find it
Its simply a spell mistake
else:
table = cls.__table__
if declared_columns:
for c in declared_columns:
if not table.c.contains_column(c):
raise exc.ArgumentError(
"Can't add additional column %r when "
"specifying __table__" % c.key
)
self.local_table = table`
its referring to this as c I think
sorry for that ugly code
its from the debug browser
Its some error on my models file because I barely understand what im doing
SQLA is so much more complicated than Django ORM
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Its blowing my mind too ๐ cuz I'm not too much familiar with all things yet
https://paste.pythondiscord.com/limuhigovi.py this is the code where something is wrong
its all good, web frameworks are.. a lot.
im new also
totally stumped
i made too many changes to the models file without checking what it would do
like I said I'm not getting It but you really mean cplayer here?
omg haha
an extra set of eyes is a good thing
ty
OH FUCK is it what you were looking for?
yeah thats definitel it haha
i was just looking for 'c'
that was weird
Dude I'm doing coding for only one month but now I guess I'm getting it
Good feeling when you can help someone, i know how it is.
yep
I will say, Django is definitely a steep curve for only one month in but if thats what you want you can do it
Its my first project but If you wanna see I can show you Its fully functional now I'm just improving it
damn maybe thats not it... Im going to have pour over this code. I might be too sleepy to do well rn ha Ive been awake all night...
Sure
same
well I'm gonna look again If I can find anything
but are you still getting the same issue?
I mean the same error?
yeah
Traceback (most recent call last):
File "/home/virufac/Projects/shell_hacker_game/shellmancer/__init__.py", line 33, in <module>
from shellmancer import routes
File "/home/virufac/Projects/shell_hacker_game/shellmancer/routes.py", line 3, in <module>
from shellmancer.forms import RegisterForm, LoginForm
File "/home/virufac/Projects/shell_hacker_game/shellmancer/forms.py", line 6, in <module>
from shellmancer.models import UserAccount
File "/home/virufac/Projects/shell_hacker_game/shellmancer/models.py", line 119, in <module>
class CharacterSheet(db.Model):
File "/home/virufac/Projects/shell_hacker_game/venv/lib/python3.8/site-packages/flask_sqlalchemy/model.py", line 67, in __init__
super(NameMetaMixin, cls).__init__(name, bases, d)
File "/home/virufac/Projects/shell_hacker_game/venv/lib/python3.8/site-packages/flask_sqlalchemy/model.py", line 121, in __init__
super(BindMetaMixin, cls).__init__(name, bases, d)
File "/home/virufac/Projects/shell_hacker_game/venv/lib/python3.8/site-packages/sqlalchemy/ext/declarative/api.py", line 75, in __init__
_as_declarative(cls, classname, cls.__dict__)
File "/home/virufac/Projects/shell_hacker_game/venv/lib/python3.8/site-packages/sqlalchemy/ext/declarative/base.py", line 131, in _as_declarative
_MapperConfig.setup_mapping(cls, classname, dict_)
File "/home/virufac/Projects/shell_hacker_game/venv/lib/python3.8/site-packages/sqlalchemy/ext/declarative/base.py", line 160, in setup_mapping
cfg_cls(cls_, classname, dict_)
File "/home/virufac/Projects/shell_hacker_game/venv/lib/python3.8/site-packages/sqlalchemy/ext/declarative/base.py", line 190, in __init__
self._setup_table()
File "/home/virufac/Projects/shell_hacker_game/venv/lib/python3.8/site-packages/sqlalchemy/ext/declarative/base.py", line 544, in _setup_table
if not table.c.contains_column(c):
AttributeError: 'str' object has no attribute 'c'
i think it has something to with me refactoring stuff
This is all stuff im trying to figure out so i should have done so much to the code without testing it
ill find it
Read these two lines carefully
if not table.c.contains_column(c):
AttributeError: 'str' object has no attribute 'c'
``` @native tide
maybe i just need to stop all the data and restart...
i thought i did that
i should just take a break from this, im starting to forget silly things
i hope thats it
I guess Its not defining this 'c'
haha well i cant even get into the shell to drop it
yeah that is not my code, that is a lib so it measn...
something i have done has broke stuff
and its not obvious what except that maybe dropping all the data will work
that cant be it because... i put in an entirely different database. same error. It has to do with my relational mapping being horrificly bad.
that is what it is lol
SQLA is hard
to be fair my database is a little overly complex for a first database but whatever
Dude I tried but yet Its not my thing xD
its all good i think im too tired to deal with it now, It involves going back over everything i added and removing it or waiting for database expert to correct me. ha
thanks tho
can i ask a question about flask here?
i'm trying to make a registration form but i'm failing miserably ๐ฆ
!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.
so
feel free
i've defined the form in forms.py
class UserRegistryForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
email = StringField('Email', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
submit = SubmitField('Register')
like so
right?
this is mine
class RegisterForm(FlaskForm):
email = StringField(email_name,
validators=[DataRequired(),
Length(min=4, max=32),
Email()],
render_kw={"placeholder": email_name})
password = PasswordField(password_name,
validators=[DataRequired(),
Length(min=8)],
render_kw={"placeholder": password_name})
password_confirm = PasswordField(password_confirm_name,
validators=[DataRequired(),
EqualTo('password')],
render_kw={"placeholder": password_confirm_name})
submit = SubmitField('Sign Up')
wait
i just need to get a really basic one going first
right, so what isnt working about it?
@app.route('/register', methods=['GET', 'POST'])
def register():
registerForm = RegisterForm()
if registerForm.validate_on_submit():
flash('Registration requested for user {}, remember_me={}'.format(registerForm.username.data, registerForm.remember_me.data))
return redirect('/index')
return render_template('register.html', registerForm=registerForm)```
then i define this in routes
and then i have a register.html file
{% extends "index.html" %}
{% block body %}
<body>
<h1>Create an account</h1>
<form action="" method="post" novalidate>
{{ registerForm.hidden_tag() }}
<p>
{{ registerForm.name.label }}<br>
{{ registerForm.name(size=32) }}
</p>
<p>
{{ registerForm.email.label }}<br>
{{ registerForm.email(size=32) }}
</p>
<p>
{{ registerForm.password.label }}<br>
{{ registerForm.password(size=32) }}
</p>
<p>{{ registerForm.submit() }}</p>
</form>
</body>
{% endblock %}```
Unrelated but you should use f-strings instead of .format when you can. im looking and comparing it to mine hold on
Internal Server Error
mm
ok thanks!!
does that happen when?
does it happen as soon as you load site or when you click submit to register?
I'm not seeing what you're doing wrong other than little things tbh but im moments away from passing out.
good luck
welp, with my problem
the only thing that fixes it is removing this of all things
class CharacterSheet(db.Model):
"""
A character sheet is issued by a GM to a campaign and as a result to every player
who rolls a character in that campaign. The character sheet is a blank template for a character.
"""
__table__ = 'character_sheets'
character_id = db.Column(db.Integer, primary_key=True)
player_id = db.Column(db.Integer, db.ForeignKey('player.id'), nullable=False)
I have no idea why but i know that im done for now. wayyy too tired.
"fixes it"
the database is still trash but it loads again
Hey, so I am facing an error concerning an OAuth login system. Basically I am trying to add discord as primary auth means for my website
this is my code. I am getting invalid OAuth2 redirect_uri
from flask import Flask, redirect, url_for, render_template, session
from requests_oauthlib import OAuth2Session
import oauthlib
import os
app = Flask(__name__)
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
os.environ['FLASK_DEBUG'] = '1'
client_id = os.getenv("CLIENT_ID")
client_secret = os.getenv('CLIENT_SECRET')
app.config.update({'OAUTH1_PROVIDER_ENFORCE_SSL': False})
authorization_base_url = "https://discordapp.com/api/oauth2/authorize"
token_url = 'https://discordapp.com/api/oauth2/token'
scopes = ['identify', 'connections']
@app.route('/')
def home():
return render_template('index.html')
@app.route('/user')
def user_settings():
return render_template('user-settings.html')
@app.route('/login')
def login():
oauth = make_oauth()
authorization_url, state = oauth.authorization_url(authorization_base_url)
session['oauth_state'] = state
return redirect(authorization_url)
@app.route('/callback')
def callback():
oauth = make_oauth()
oauth.state = session['oauth_state']
try:
token = oauth.fetch_token(token_url, client_secret=client_secret, authorization_response=request.url)
except oauthlib.oauth2.rfc6749.errors.InvalidClientIdError:
return redirect('/')
#HELPER FUNCTIONS
def make_oauth():
return OAuth2Session(client_id, scope=scopes, redirect_uri=url_for('callback', _external=True))
if __name__ == "__main__":
app.secret_key = os.urandom(24)
app.run(host='localhost', debug=True)
How to use async views in Django dev?
Is anyone available to help with a question related to Flask and SQLAlchemy?
Maybe i can
Maybe i can help
do you know how to do the flask-wtf registration page?
Ye
omg
amazing
i just want to do a really basic one
like not linked to any database or anything
so in forms i have this py class UserRegistryForm(FlaskForm): name = StringField('Name', validators=[DataRequired()]) email = StringField('Email', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()]) submit = SubmitField('Register')
Ohh seems easy
that look ok?
then in routes i have this ```py
@app.route('/register', methods=['GET', 'POST'])
def register():
registerForm = RegisterForm()
if registerForm.validate_on_submit():
flash('Registration requested for user {}, remember_me={}'.format(registerForm.username.data, registerForm.remember_me.data))
return redirect('/index')
return render_template('register.html', registerForm=registerForm)```
Ye
(nts about that ^)
and then i have this html sheet
called register.html
{% extends "index.html" %}
{% block body %}
<body>
<h1>Create an account</h1>
<form action="" method="post" novalidate>
{{ registerForm.hidden_tag() }}
<p>
{{ registerForm.name.label }}<br>
{{ registerForm.name(size=32) }}
</p>
<p>
{{ registerForm.email.label }}<br>
{{ registerForm.email(size=32) }}
</p>
<p>
{{ registerForm.password.label }}<br>
{{ registerForm.password(size=32) }}
</p>
<p>{{ registerForm.submit() }}</p>
</form>
</body>
{% endblock %}```
Your form name in the route is not same as your form name
:0
๐
shitt
Ohhh shiiit
ok 1 sec
@nimble epoch
i still get internal server error
when i click on the button that should lead me there
What?
Wait a sec
oki
First i think you didnt add remember me field to ya form
oh
Did you add?
If debugger is not on
yeh stil internal error
Can i see the form
sure
class RegisterForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
email = StringField('Email', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
remember_me = BooleanField('Remember Me')
submit = SubmitField('Register') ```
Can i see ya whole files to make sure everything is alright?
yeh
app.route('/register', methods=['GET', 'POST'])
def register():
registerForm = RegisterForm()
if registerForm.validate_on_submit():
flash('Registration requested for user {}, remember_me={}'.format(registerForm.username.data, registerForm.remember_me.data))
return redirect('/index')
return render_template('register.html', registerForm=registerForm)
looks fine?
oh fuk
i didnt import it
Yeah of course you did change the form name, Didnโt you?
No the flask form
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
remember_me = BooleanField('Remember Me')
submit = SubmitField('Sign In')
class RegisterForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
email = StringField('Email', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
remember_me = BooleanField('Remember Me')
submit = SubmitField('Register')
```
heres the entire form file
And of course you did import the forms to your routes file
from app import app
from flask import render_template, flash, redirect
from app.forms import LoginForm, RegisterForm
@app.route("/")
@app.route("/landing")
def landing():
return render_template("landing.html")
@app.route("/index")
def index():
site_title = "Site Title"
welcome_string = ""
return render_template("index.html", welcome_string=welcome_string, site_title=site_title)
@app.route("/about")
def about():
name = "Nobody"
return render_template("about.html", name=name)
@app.route("/login", methods = ["GET", "POST"])
def login():
loginForm = LoginForm()
if loginForm.validate_on_submit():
flash('Login requested for user {}, remember_me={}'.format(loginForm.username.data, loginForm.remember_me.data))
return redirect('/index')
return render_template('login.html', title='Sign In', loginForm=loginForm)
@app.route('/register', methods=['GET', 'POST'])
def register():
registerForm = RegisterForm()
if registerForm.validate_on_submit():
flash('Registration requested for user {}, remember_me={}'.format(registerForm.username.data, registerForm.remember_me.data))
return redirect('/login')
return render_template('register.html', title='Register' registerForm=registerForm)
yep
good news is
i dont get the internal server error anymore
๐ฅณ
What?
like i click register
i doesn't change to a register page
well the URL changes but the page hasn't changed
<li><button class="plain-button" onclick="window.location.href='/register';">Get Started</button>
thats the button
You mean when you click on the register it dosnt bring you to the register page?
yeh
Give it a link
I always use <a> tag and give it the class to make it like a button
Did it work?
it works fine for the login button using this method
whats the error for register
Ob
Im not sure about this one because i dont have your files
i can send them if you want
where?
def register() request.method="GET":
registerForm = RegisterForm()
if registerForm.validate_on_submit():
flash('Registration requested for user {}, remember_me={}'.format(registerForm.username.data, registerForm.remember_me.data))
return redirect('/login')
return render_template('register.html', title='Register' registerForm=registerForm)````
likes o?
IndentationError: unexpected indent
Ok that didnt work
Of course
Hey, what django model type does postgresqls json equal?
Nevermind! django.contrib.postgres.fields.JSONField
If anyone knows or can give me a hand
Has anybody ever setup AWS RDS with flask_sqlalchemy?
I've used sqlalchemy with AWS RDS aurora Postgres before
It behaves no differently from a normal postgres database
You just have to make sure you can access it from the VPC it's in
If you're trying to get to it from your local machine you can set up an ec2 instance in that VPC to be an SSH tunnel proxy for your local running code
how hard would it be to make your own vpn?
If you know basic routing, not very difficult
You can try it out with your computer and a phone
dont even need an app
However, what gets sold as VPN these days, isn't really the definition of VPN
to me, VPN means "encrypted"
VPN means a private connection between two trustworthy networks over an untrustworthy medium
So, connecting to a VPN server to feed internet into the other side, which is untrustworthy, isn't really a vpn
using HTTPS is enough encryption
yeah, I no longer really care for commercial VPN anymore.
I dont particularly like my ISP (or any ISP), but I'm not sure that modern VPN sold by proprietary businesses is really in the spirit of privacy exactly.
It has a use case... but its not a cure all for ownership of your home and what goes on it or anything.
If its contrary to profit, they will not uphold privacy, not unless they take it a little more seriously than they seem to.
They are essentially just middle men holding on to this data and I'm not seeing anything that verifies no logging and frankly not feeding whatever to machines to process for further business ha.
But yeah, I had PIA about a year ago and they have been bought out by scumware.
I like this https://www.vpngate.net/en/ because it's run by an educational instittuion at primarily a Japanese university in attempts to spread Internet and info to places where it is being supressed.
They are good for temporary use cases if you need a proxy IP for some reason. But overall, its not a perfect privacy solution at all.
You are just giving your browsing behaviour to the vpn provider instead of your ISP
exactly
at least your ISP is in the same country and you can sue them should violations occur
and if they are just another corporation becoming just as big and evil then same thing
I am using end-to-site VPN for free Wifi
that is for example a good use
I connect to my router at home, so at least people in the same wifi can't spy on me
Thats true you def have to pay attention to where you geta VPN service from
and due to my work, I see what kind of traffic comes out of some vpn providers
can't go into specifics, but it's awful
Its hard to use those commercial VPNs because they are so constantly getting shut down. People act like you are the shadiest around for using it. I dont care for that sentiment either. But yeah.
Like services are regularly fighting them is what i mean
you have to jump ips frequently
to keep service
VPN's use data centers, not ISPs
I like the idea in theory. But after paying for various services and watching their behaviour and looking at the reality of it, it is not something i would rely on if there was something truly grave that not be in data or something. If. There is a use case for it but... its not "got VPN am protected" kind of thing.
I typically will configure one of those proxies and use if i need to to get through some service that is being dildoish and then ill drop out of it after
tbh i dont typically need to do that
but it happens
yeah. I was paranoid about that. I did some tests that seemed like it was not when I was really into it.
I actually know almost nothing about ipv6
I can identify them from looking at them
but thats it
do they do local subnet ranges in ipv6?
I mean, yes, lot's of differences in the nitty gritty details, but overall, not something the usual guy worries about
Yes
fc00::/7 to fdff::/7
I see 2600 in them somewhat frequently. My friends from hackers.town seem to reference 2600 often.
they are just white hats btw
@native tide so blueprints are a way to organize your routes
imagine blueprint to be a small instance of app which can make routes and such
and they are registered back into app
Is there a way I can hide scrollbars inside some elements?
this is not the corner of the page
how do you use flask-sqlalchemy inside a celery task
@shadow rock you can't, sqlalchemy is blocking and is sync
you can
i'm trying to access the db and do some changes while inside a task
apprantely you have to pass in flask configs
@rustic pebble you can use css
overflow:hidden
https://paste.pythondiscord.com/iguyepipuj.py
returns
jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got '='
it's driving me nuts because I can't find anything online. I know it has something to do with my {{ }} brackets but idk
This is wrong:
{{ url_for('static'), filename='main.css' }}
You're closing the parens early
@native tide
flask's syntax mirrors pythons
if you're calling the url_for function with those two parameters, what's wrong with your )?
I got it
<link rel="stylesheet" type="text/css" href={{ " url_for('static'), filename='main1.css'" }}>
i'm dumb. thanks
nvm i'm still not getting this correct/
main.css doesn't seem to be working. my editor shows my code in green on the same line
nvm got it
Asked a few days ago but I think it was late so just going to repost one more time then i'll shut up.. I'm tryin to almost like a connect the dots on one of my pages but the amount of dots that show will be dependent on a value im pulling from a DB. Something similar to this screenshot could be either like the top or bottom..
I looked at something like Vega, but seems to complex for my needs..
@native tide that is still not how it should work judging by ur screenshot
I know. i fixed it
@pallid loom you can use any framework depending on your use case. I personally like Vue, but in most cases django's template system is sufficient for me.
@white ermine tks
anyone here familiar with flask?
i've setup a login page using flask-wtf
how do i link the sign in button so that it redirects to a new page?
First you should use flask login extension
And you can use redirect() to for redirecting to other pages
@native tide The form action defines the target of the form
Just use url_for to direct the form action to the route handling the input
@nimble epoch so i should cancel the flask-wtf i've done?
<form method="POST" action="{% url_for("function_in_python_that_handles_the_route") %}">
{# wtf form vars #}
</form>```
thanks! @tired root
They are different
Flask wtf is your form
Flask-Login provides user session management for Flask. It handles the common tasks of logging in, logging out
for django rest serializers, woudl it maek sense to have two serializers iwth teh same model if you want sometimes for certain feilds to be required and other times not
Guys im trying to make a mp3 downloader website but when I put the download link <a href="{{filePath}}" download>download</a>
then I just click on the download link but nothing happen
and im using flask
#t1 { transform: translate(100px) scale(2,1); background:red; } #t2 { transform: scale(2,1) translate(100px); background:green; }
why the result for these 2 arent same?
both of them are width 50px height 50px, margin left 0
yes, its different, 2 <div>
@turbid glen Have you checked if the divs inherit anything from the parents that may cause it?
Chrome or Firefox debugger is helpful there
Guys Im trying to render my css file into the html file but its not working (im using flask) anyone can tell me why I put the right path and put on static folder but its not working?!!
Guys im stuck between django and flask
Which one is better and more common for a web application
?
hmm Im just a beginner with these stuff but I always hear that flask is easier to start than django so I think you have to start with flask then go to django its more professional
Django is very good if what you're doing fits the model it was designed for. E.g storing, querying, and presenting data to the user
Flask is better if you want to do extra things on top, or customise the way you do things
I think if your end goal is a web app with a database, then Django is probably easier to get started with - you don't have near as many annoying set up barriers
Hey, I see here keywords like Django and Flask. Possibly you could help me.
I have a question connected with dbs and Django orm.
from django.db import models
class Family(models.Model):
pass
class Parent(models.Model):
name = models.TextField()
family = models.ForeignKey(Family, related_name="members")
class Boy(Parent):
favourite_car = models.CharField(max_length=10)
class Girl(Parent):
favourite_doll = models.CharField(max_length=10)
actually I need serializer to present Family and it's members
class FamilySerializer(serializers.ModelSerializer):
members = ... ??
I've got an idea how to serialize separetly.. to make members = serializers.SerializerMethodField() but I cannot find out how to separate Boy from Girl
Actually as a result I want to receive something like:
# family object
{
members: [
{ # a boy
name: "Karl",
favourite_car: "Dodge"
},
{ # a girl
name: "Ann",
favourite_doll: "Barbie"
}
]
}
Yeeeah ok thanks guys
Hey, I see here keywords like Django and Flask. Possibly you could help me.
I have a question connected with dbs and Django orm.from django.db import models class Family(models.Model): pass class Parent(models.Model): name = models.TextField() family = models.ForeignKey(Family, related_name="members") class Boy(Parent): favourite_car = models.CharField(max_length=10) class Girl(Parent): favourite_doll = models.CharField(max_length=10)actually I need serializer to present Family and it's members
class FamilySerializer(serializers.ModelSerializer): members = ... ??I've got an idea how to serialize separetly.. to make
members = serializers.SerializerMethodField()but I cannot find out how to separateBoyfromGirl
Actually as a result I want to receive something like:# family object { members: [ { # a boy name: "Karl", favourite_car: "Dodge" }, { # a girl name: "Ann", favourite_doll: "Barbie" } ] }
@rich bobcat Is there any meta fields for example (Family()).mebmers.find_one().meta.class_name == "Boy" ?
@nimble epoch These kind of snarky comments won't get you anywhere
People here are often just idling while doing other stuff
But anyway, it is a matter of taste and usage. I like flask because it is simple and allows me to do things my way, while Django is more strict in my opinion.
I have worked with django and flask already
But not sure about popularity and of course about salaries im not sure
And django is not that hard
But i myself think flask in more fun
What does popularity have to do with it?
I've also never said Django is hard
Salary depends on where you're based. Look at local job postings
Djangoโs is more
If you're just looking to build a portfolio, it doesn't really matter which of the two you use
Django probably has a bigger community - but thats because it does more things. With Flask you need to branch out and use other libraries, you don't need to near as much with Django
although again, I'm not sure why it matters
You yaslef which one ya prefer
I already explained my approach to two
Flask is better if you want to do extra things on top, or customise the way you do things```
I use both, the right tool for the job
Ok thanks
Hey I would like to ask some question. Is there way to separate fields in DRF serializes to fields for serialization and deserialization.
It's like:
class MySerializer(serializers.ModelSerializers):
class Meta:
model = MyModel
fields = ("name", "last_name",)
deserialize_fields = ("id", "name" "age", "last_name",)
to make asymmetric parsing?
I have an assumption, but I am not sure. Are fields connected to serialization, but in the opposite way it will parse everything?
Hey guys I have this flask code ```
@app.route("/link-mp31")
def converter(file,fileName,folderPath):#File converter (from mp4 to mp3)
filePath=path(file)#Get the file path
video=VideoFileClip(file)#Create the object
video.audio.write_audiofile(f'{folderPath}\\{fileName}.mp3')#Convert the file
video.close()
return render_template("download.html", filePath=filePath)```
How I can give its arguments a value from another function/app
It sounds weird. Just call it as proxy:
your_vars = [file, fileName, folderPath] @app.route() def route_handler(): return converter(*you_vars) def converter(*args):or create decorator, or functools partial
Here.
@frosty mauve Can't you do this - once the input has been got from the user, create a model with a path attribute?
BTW, do you have the link I sent?
Well that is what I am getting confused with. I download an image and want to set the ImageField to the image but I think it has to do with like upload_to putting it in a weird place. I can manually override it with a static url and it will work but when I use save() on it creates a url that doesn't link properly
@frosty mauve As you can see, you can choose the folder (in the example's case it is cars).
I also was reading about how maybe just create a separate model named Images and link it to the car object, not sure if that is standard practice though
is cars in static or media though?
media I think. What was your problem again (sorry, I've forgotten)
guys how i can let the user download a file from a website using flask?
I want to create a new obj with a photo stored locally so I don't have to manually click upload image in a GUI over and over
Oh right, automatically add all the images as models?
essentially create a bunch of new cars with their respective photos
That's all?
Yes
newcar = Car(name='Stupid Car', photo='') and it actually work lol
It works fine if I use admin
So what's the problem with that?
Let me give you exact problem brb
Sure.
ok so if I set the image field = to the path of the image
and then save, then call image.url it gives media/originalpathtoimage
media in the front?
I see.
I think you can set absolute path?
One sec.
Can you send the code that you are using?
To create the model @frosty mauve .
class Book(models.Model): image = models.ImageField(upload_to='images/', default='example.jpg')
Hmm, I see your problem.
Can't you have the images in the media folder?
It's been a while since I've used media, but it is fine once you set it up correctly.
I could try that, I was under the impression through reading online that media is reserved for user uploaded content
So is the issue creating models or opening the files from Django?
Create an object from the model with the image field populated and working
MEDIA_ROOT this is the absolute path to the folder that will hold our user uploads. For example MEDIA_ROOT = "/User/Timmy/Sites/Pho/root/media/".
Is that set correctly for you?
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
OK, and you have all the files already in media?
I do
I had them in static but now I have them in static and media
oh
Okay, so it works when I use media to upload from
Yeah?
I used admin though
I see. Now it should be easy to replicate from shell
Do you know how to create models from the shell?