#web-development
2 messages · Page 64 of 1
can you link me a request
I mean a doc
sorry
this core library will get quite big
hehe
This?
This is my current tree
at is my project
and autotek is the base of my django
Yes, I think so
just 'dracoengine.draco'
ok
ImportError at /order/5933921/
Module "dracoengine" does not define a "draco" attribute/class
oh, right. Drat.
you can try from dracoengine import draco, or there's another solution but that one's much cleaner
works
Yeah, in django all imports start at the "project level" -- or immediatley inside your outer autotek folder
the reason import_string failed is it expects a __init__.py file I believe
should i maek a init.py
I'd move the load_module to before all the views probably
ahh
it indicates to python that the files in that directory should be considered available for import
basically, from folder import file works but not import folder.file iirc
ah
what if draco engine is in /autotek/dracoengine/subdir/draco.py
would it be from dracoengine/subdir import draco
from folder.folder import file
You can use appconfig.ready() to call something when django's about to be ready
See the green note as well, this should let you "start" a discord.py bot and run django at the same time, mostly
ive been trying to compress my requests body using zlib (post request)
What I did was:
garageString = zlib.compress(bytes(garageString, "utf8")) and I changed headers = {"Content-Type": "application/x-www-form-urlencoded"} into headers = {"content-encoding":"gzip"}.
For some reason my request still isnt working because it gives back the error "invalid request".
I strongly believe that this is because it recieves the request in the form of a b string with the b still in it 🤔
Any help would be appreciated, thanks!
Anyone here use flask-sqlaclhemy? I'm trying to use Float data set, but unable to.
from flask_mysqldb import MySQL
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import FLOAT
"Incorrect column specifier for column 'product_price'")
class Orders(db.Model):
__tablename__ = 'orders'
id = db.Column(db.Integer, primary_key=True)
seller_id = db.Column(db.Integer(), nullable=False)
order_id = db.Column(db.String(50), nullable=False)
order_date = db.Column(db.String(50), nullable=False)
payment_method = db.Column(db.String(50), nullable=False)
total_paid = db.Column(db.Float(50), nullable=False)
product_name = db.Column(db.String(100), nullable=False)
product_price = db.Column(db.Float(100), nullable=False)
product_file = db.Column(db.String(50), nullable=False)
delivery_status = db.Column(db.Boolean, default=False, nullable=False)
buyer_email = db.Column(db.String(200), nullable=False)
buyer_ip = db.Column(db.String(30), nullable=False)
what do you put on a Portfolio website's footer
personally I put my website name, and social links
checkout other junior developers portfolios and decide from there
yeah and copyright
seems pretty empty
that's why i asked
oh i guess if it's a company website it gets filled with a bunch of links.
not portfolio Ok
@past cipher what's the db schema? that's a mysql error being bubbled up to sqlalchemy so it's likely a mismatch between the data model in python and the table schema in mysql
InnoDB
I switched it to String for now, since it will work that way
I just weren't sure why float wasn't working
what does describe orders; return from the mysql shell in that db?
I suspect that Float(50) is the culprit
I'm not sure what the precision limit of the your mysql server is, but the docs here suggest it doesn't like values greater than 53 https://dev.mysql.com/doc/refman/5.7/en/floating-point-types.html
so your Float(100) might be what it's rejecting
try 53 instead
oh there's a float 100, missed that
Will test now
Yep that fixed it. I was getting confused. I had 100 on float as I was thinking of the max character count
Thanks!
happy to help!
I'm trying to convert an existing python script I've written into a web app using flask. I've never used flask before and I'm having trouble formatting everything correctly. I think the bulk of it is correct but I have a table that generates from data that I can't get to work/don't know how to format in the code
Anyone able to help me with this? Can post code
Can I post a couple text files? It's too long lol
!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.
ahh!
!paste
can I send another one?
oh I see
I know it's very wrong but just got no clue how to make it do what I want to do
Where do i store javascript file in my django project?
What you're looking for @balmy olive is jinja templates
You write your template file like this:
might want to delete those pastes and make new ones that don't have the client_id in them
you should keep that private
<html>
.....
{% for streamer in streamers %}
<div>{{ streamer.name }}</div>
{% endfor %}
Then you load it into your pythono and call template.render(streamers=streamers)
just follow this tutorial from their docs https://flask.palletsprojects.com/en/1.1.x/quickstart/#rendering-templates
There's what I was looking for, thank you
Ah good point. Thanks, will try that
I'm a little confused. I have the jinja template setup but how do I actually pass the info from the different lists into it and get it to iterate through to generate the table?
return render_template('hello.html', mylist=mylist) will "render" the template and give it the variable "mylist", from here we can check the jinja documentation for looping
{% for item in mylist %}
{{item}}
{% endfor %}
I might be going at this a bit backwards, sorry. I'm self taught. I need data from 3 different lists to create the table
<html>
<head>
<link rel=stylesheet type=text/css href=index.css>
<title>Who is live?</title>
</head>
<body>
<img src='stv.png' alt='logo'>
<table class='center'>
<tr>
<th>Streamer</th>
</tr>
<tr>
<td>
{% for streamer in streamers %}
<a href ={{link}}>{{name}} is live!</div>
{% endfor %}
</td>
</tr>
</table>
</body>
</html>
!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.
I realise I'm not doing anything with that client actually but I'm also not sure how to get that to work either
I need to add channel = client.streams.get_stream_by_user(streamers[x]) in there somewhere but again, not sure where to put it
Sorry if I'm not explaining very well
is {{link}} and {{name}} part of streamer list ?
if so it should be
{% for streamer in steamers %}
{{streamer.link}}
{{streamer.name}}
{% endfor %}
No, sorry. I'll send the full script that I'm trying to convert to the webapp
okay tag me, i will take a look
@past cipher https://paste.pythondiscord.com/sawazerisu.py
Hi guys, does anyone know of a useful python library that can help to validate the shape/datatype of request parameters?
If it helps I can try and explain what the goal of the code is and how it works in that script I sent
This could be wrong since I have never used multiple for loops of list, but maybe:
{% for streamer in streamers %}
{% for name in names %}
{ % for link in links %}
{{streamer}}
{{name}}
{{link}}
{% endfor %}
{% endfor %}
{% endfor %}
do I stick that between the <td> tags in the jinja template?
If it's easier I could probably work with it just being the links there instead of everything
<td>
{% for streamer in streamers %}
{% for name in names %}
{ % for link in links %}
<a href ={{link}}>{{name}} is live!</div>
{% endfor %}
{% endfor %}
{% endfor %}
</td>
I think anyway
It's throwing an error
jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'endfor'.
File "/usr/lib/python3.8/site-packages/flask/app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
That's the first useful one, there's a load being thrown
probably the space in
{ % for link in links %}
maybe? just a guess
Yup! That was it
hooray!
Nice
It's not actually getting the data to generate the table though.. I've got no idea how to make that work
can you send a screenshot of what you mean, I'm not understanding
sorry if this question is a bit general, but how would I make an account system for my website?
that is very general
do you mean a login system
flask? django?
Javascript
lel
from OY: https://discord.gg/VxXs4Y
a pseudo login? Or are you looking for like a production website?
ah it's not working because i've not added the code, but not sure where to stick it
for x in range(len(streamers)):
channel = client.streams.get_stream_by_user(streamers[x])
channel = str(channel)
if channel == 'None':
print('not live')
else:
webpage.write(" <tr>")
webpage.write(" <td>")
webpage.write(" <a href="+link[x]+">"+names[x]+ ' is live!'"</a>")
print(names[x])
webpage.write(" </td>")
webpage.write(" </tr>")
this is the code that I was using to ping the twitch.tv API to determine if a streamer from the list is live. it uses the channel = client.streams.get_stream_by_user(streamers[x]) to get that info then depending on what's returned it writes a line in the table or just prints something in the console
I apologize, I thought non-python was allowed in this channel and just saw some people talking. Won't ask any js stuff here again
It's obviously different now but I'm not sure what to stick in the part to ping the api to get the data for the table
If you use pure JS, you can just add, like, an input and check if that input is == user password.
Otherwise you need a DB and I would use something like php.
but yeah, you'll get more help on a non-python specific server
@balmy olive append it all to a list, and then render the list with the template
okay, thanks
Will try that, thank you @past cipher !
I'm actually here to ask a question too, lol.
I'm using Django and MySql. I am converting my JSON methods over to a MySql db.
I have a list of strings "inventory" and need to store this data in MySQL somehow. Any have any ideas as to what the best way to do this is?
My current plan is to save it as a string == "[item1, item2, item3]", but this seems sloppy
Can you elaborate? I am very new to this sort of stuff (as you may already know haha)
I don't know what invetory means
like inventory of what but if it's a user inventory, you have a table called inventory, it would have userid and inventoryid (or itemname)
it is a list of all the items a user has in my DD style game i.e inventory == ["sword", "potion"]
so inventory table with userid and itemname or itemid depending on how you structure it
items should be it's own table
basically all that needs to be stored is that string (the name of the item) for now.
it will belong to a class Character that will be many-to-one to a user
ok
what would be the best way to keep track of which items a Character has in its inventory?
ok. In this case each player will have several characters, each character having an inventory.
Would this be fine for performance then? if I have, say, 50 characters each with their own inventory?
ok, ty very much!
What do you mean by indexed? (I will be studying DBs today lol)
meaning the database server keeps internal check so it quickly answer select against that table without doing full table scan
ok, ty.
When this is done, I'll owe you a credit LOL
@past cipher I've added a loop that appends 0 to a list if a channel isn't live and 1 to the same list if the channel is live. Can I pass this to the jinja template then it will create a table row if the value is 1? And with flask, does it run the function to generate the page each time someone will load it?
{% if variable == 1 %}
do something
{% endif %}
Hmm it's not creating the tables. Code looks like this
https://paste.pythondiscord.com/mivenajuzu.py - python
https://paste.pythondiscord.com/isebezoroc.py - template
It's not throwing an error. Just not creating the table
Or the rows for the table
why are you doing
client = TwitchClient(client_id="CLIENTID") and passing CLIENTID as a string?
is that just your placeholder?
CLIENTID is the placeholder but I am passing it as a string
have you read the docs?
for the twitchapi? No, but the issue is not with the api call I think. I've been passing the clientid as a string and it's been working properly
@past cipher That didn't work, still not generating the table
why are you doing {% if live == 1 %}
live is a list of integers
not a single integer
you are appending strings
but then comparing a list of strings to a single integer
in the template
OY just said that, I changed it to {% if live == '1' %} and that still hasn't worked
do you know how for loops work?
Yes, I see what you're getting at now
have you got any tests ?
No
What would be best way to implement server side form verification while using vue on front end ?
looks to me as if you're making a very big step
why dont you get rid of all of your logic
and just get one single request and streamer displaying on your screen first
you are making too big of a step
I've done that. I've got the whole thing working. I made this script yesterday and it generates a html file but because I want to host it as a web app I am now trying to migrate it to flask to make it all work
Yeah my bad, its a list. So you should be checking if 0 or 1 is in the list.
{% if '1' in list %}
those for loops are not going to work how you expect
you should look up how for loops work
what does error mean?
error: 'myFirstWebsite/' does not have a commit checked out
i was trying to do git add .
was tryna post my flask website i created years years ago to github
I know how for loops work. I'm now trying to get it to work in jinja. I didn't know what jinja was 2 hours ago, @past cipher has been helping me with it but that change hasn't worked either
@native tide make sure it is in a git repo, you may want to "git add *" to add everything.
I think that error is that there is no local repository
@native tide did you run
git init?
^^
does tb selenium work for windows 10?
If that was done, did you run
git commit -m "commit msg" ?
its the tor browser library for selenium
i did run git commit and git init
everything fails
did you do git init first?
ok, grand
i figured out to do it via githb
nice, I figured better to reply late than never haha
but i think the whole things donefor
haven't used it in years and i didn't comment my py files to know what to do so
it's a pretty crappy website too tho. my complete beginner website😅
Does anyone know how to run tor browser with selenium on windows 10
Using Django
User registers to site. However, if they go to create a post they are unable to it. It throws an Exception when the submit button advising that Author cannot be null ( it's linked by a foreign key).
Here is my models file:
User = get_user_model()
class Author(models.Model):
""" Inherits the auth user model """
user = models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self):
return self.user.username
class Category(models.Model):
""" Generic entries so posts can be filtered """
title = models.CharField(max_length=20)
def __str__(self):
return self.title
class PostView(models.Model):
"""Uses PostCreateView """
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey('News_Post', on_delete=models.CASCADE)
def __str__(self):
return self.user.username
class News_Post(models.Model):
"""Inherits Category & Author Models """
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
date_modified = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
categories = models.ManyToManyField(Category)
featured = models.BooleanField()
post_img = models.ImageField(default='default.jpg')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post_detail', kwargs={
'pk': self.pk
})
def get_update_url(self):
return reverse('update_post', kwargs={
'pk': self.pk
})
def get_delete_url(self):
return reverse('delete_post', kwargs={
'pk': self.pk
})
def update_author(self):
np_auth = News_Post.author = Author.user
return np_auth
This is the Exception message:
IntegrityError at /create_post/
(1048, "Column 'author_id' cannot be null")
This is the stack trace also:
http://dpaste.com/2FC440W
The only hacky way around this would be creating an 'Author' via admin
The issue may be that you updated your model while it already existed in the database. So django is seeing that the Foreign key does not exist and cannot complete the table.
I literally just had a similar issue. I do not have any Users, but am trying to test my models, so I commented those lines out until I am ready to specify a User.
Did you resolve it?
Oh one sec, I just re-read your question
In this case, wouldnt your author BE the user?
this is how I have mine
Since your author essentially IS a user, I think this way makes more sense.
So drop the 'author' class then?
Or is there some way to instruct Django to populate this field?
I believe that is the best way.
The way I have it is: The User signed in at the time owns the post and is the author
The author class seems redundant to me, unless you plan on expanding on it.
I was thinking of maybe extending it to probably include like a 'profile' photo down the line
Or maybe I'll not bother
In that case, you would probably still want the User to be the foreign key, not an author
I have a separate profile for extra info, but the user "owns" the profile and also all the posts
Ah yes, I also do have a profile sort've model too
This is the result
so, I should just reuse the profile model?
The top left is just the username, but you can use djangos "jinja" to make it a full name or whatever.
or should I say, reference the profile model
User on my profile model is like:
user = models.OneToOneField(User, on_delete=models.CASCADE)
I think maybe just using the user from it then as the substance of post creation then 🙂
I use this for profiles, but this just allows the user to change their picture. The User
Oh that's cool I like that
I just referenced it in mine like {{user.get_full_name}}
Didn't use the str method
but that's a good way to also do it
You could probably force the Author to work in the foreign key, but I do not think it is worth it given what you are trying to accomplish
Yeah maybe not
also Corey Schafer on youtube is the hero of our generation.
I come from a Python 2 background, so this can be a bit perplexing at times too
lol, I feel it.
tbh I'm learning Django now, I just happened to be confronting a similar issue.
Yeah, it's an interesting tool. I've done web stuff with other languages involved, Django is great though
I love Django too much. That admin page alone makes me so happy every time.
Yeah it's quite good, I use regular Python a lot in work but mostly scripts
guys i need some help
docs for flask login are kinda confusing to me
so basically what every login fuction needs???
function*
def form():
form = LoginForm()
users = Users.query.filter_by(name=user)
if form.validate_on_submit():
user = request.form['username']
if users is not None and user == users:
login_user(users)
else:
return 'user is not found'
else:
return render_template('login.html', form=form, user=users)```
i know this is messy and user is undefineed
undefined*
but this took me more than 7 days qwq
if anyone knows what i need just ping me
Anyone using vue i need some help with forms validation ?
@balmy olive did you fix what you need to do
Yup I have it all working properly! Thanks so much for your help earlier 😄
just if you're curious
{% for x in range(names|length) %}
{% if live[x] == '1' %}
<tr>
<td>
<a href ={{link[x]}}>{{names[x]}} is live!</a>
</td>
</tr>
{% else %}
{% endif %}
{% endfor %}
That's what I had to do
Nice! Glad you got it all working
@fickle fox yes user is undefind, it looks like you want to get a username from your form object, you should fo form.name or w/e you called your variable and pass that in instead of name=user. Furthermore even after you do that you would still have to finish your query. Fx user = Users.query.get(form.username) If the username from the form is your primary key for the users table. Or if it's not your PK you should do user = Users.query.filter_by(name=form.username).one_or_none() and then check if user is None
herro herro herro...
there is something that i've been wondering for a fairly decent time now
when you make a back end web app, and post it to a hosting site... how does it launch?
depends greatly on the hosting site
seeing as how normally in dev i have to type like...
node start or whatever i have the command as
i'll be using mainly github
not really. I myself use an ec2 instance, but that's pretty low-level
?
heroku is pretty slick
an ec2 instance is just a plain old Linux box
I didn't say it's the "best bet"; I said it's nice
try it and see
ah... got ya
there are probably 1,000 other hosting providers that I don't know about
Hey guys I'm getting a 502 Gateway Error with Google Cloud Platform when deploying my Flask app
Anyone know how to fix this?
Hi, my goal is to learn django (to become a developer) and I am unsure as which resource to pick to learn - there is too many to pick from online I enjoy learning from books, but am open to videos as well. Any suggestions?
@burnt night I personally use digital ocean myself for hosting my backend
Idk what the pros/cons of amazon ec2 vs digital ocean vs heroku are
I like to learn mongoDB to make an API for my React project, should i start with Flask or Django ? Is another alternative for mongoDB ?
flask vs django is ultimately preference, django comes loaded with a bunch of things that you can add to flask manually or via community libraries
mongoDB's alternatives include any database (such as any flavor of SQL)
i have professional experience with .NET and pgSQL so i want to learn noSQL with python
so flask is smaller than Django and is better for start practicing ? If i gain experience with flask cna i learn DJango easily or the gap beetween the frameworks is too big ?
the fundamentals transfer pretty easily no matter what
and mongo is a great db to do nosql with, pymongo is the official library for that
Thanks!
So I have used this to create a route
@app.route('/hi')
Def hello():
return "Hello World"
But now if I go to mydomain.com/hi is works good but if I go to mydomain.com/hi/ it throws a 404 error any idea
If I wanted to do a website with Django for people used to work with CMS (Wordpress) and FTP, would it work if I would set up an FTP server and let them change html templates files that would contain only html but no logic at all? What are the problems to such an approach?
@app.route('/form', methods=['POST', 'GET'])
def indexx():
login = LoginForm()
if request.method == 'POST':
if login.validate_on_submit():
ph = PasswordHasher()
username = login.username.data
password = login.password.data
user = Users.query.filter_by(name=username).first()
if user and ph.verify(user.pw, password) is True:
login_user(user)
return redirect('/')
else:
return 'Error in Login'
return render_template('login.html', form=login)```
i get error at login user(user)
AttributeError: 'Users' object has no attribute 'is_active'
what might cause this?
nvm it
but guys how can i sort posts by data (newely created data)
basically when i create new posti get firstly older data
i want to change it
Is this "id" a keyword?
Hey. I am trying to process paypal payments for multiple users. The plan is to get a seller to sign up. They enter their paypal email. When customer purchases their items, the money goes straight to their paypal. I see Adaptive Payments is no longer available for new sign-ups. Can anyone point me in the right direction so I an achieve this
Is this "id" a keyword?
@pseudo lantern it is a built in function, but it is used as an attribute name here
I think PayPal still have a payment API, but I never worked with it OY
They have an API however I think its just for you to process payments; no way to send direct to someone elses email
I found the payouts API, but that means I must receive payments, and then send to the seller. With this it would mean I am facing the chargebacks etc. I want to send direct to the seller
Good morning all, I have a question regarding LAMP installation on a digital ocean droplet.
When they say add your_domain I added example_domain when my actual domain address is: example-domain.com
I did that for everything in this tutorial: https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-ubuntu-18-04
Does this mean I have to go back and change it all?
For example, /var/www/my_domain is ok for the folder, but when its asking me to put it into config files, should I have used my-domain.com ?
ehh god
guys i have again problem with post undefined even if i defined it :v
return render_template('posts.html', posts=all_posts)```
{% for post in posts if post.pinn.True %}
<h2>{{ post.title }}</h2>
{% if post.author %}
<h3>By: {{ post.author }}</h3>
{% else %}
<h3>By: N/A</h3>
{% endif %}
<p>{{ post.content }}```
hey guys, i have this project in mind but i have no idea where to start
anyone hav an idea how to create custom groups in django from group
I'm using flask-httpauth for a server, and I'm messing around with bearer tokens
Here's my code:
from flask import Flask, jsonify
from flask_httpauth import HTTPTokenAuth
app = Flask(__name__)
auth = HTTPTokenAuth(scheme = "Bearer")
tokens = {
"token1" : "abc"
}
@auth.verify_token
def verify_token(token):
if token in tokens:
return tokens[token]
@app.route('/test', methods = ['GET'])
@auth.login_required
def test():
return jsonify({'haha' : 'noob'})
if __name__ == '__main__':
app.run(debug=True)
I'm using postman to test it, and using the authorization section. When I use the key "abc", which is what it is in the code, I get an unauthorized error
Anyone here used Django Rest-Framework?
def post_feedback(token):
form = FeedbackForm()
check_token = Feedback.check_access_token(token)
if (not form.validate_on_submit()) or (not check_token):
flash('Something went wrong. Please try again')
return redirect(request.referrer)
class Feedback(db.Model):
__tablename__ = 'feedback'
id = db.Column(db.Integer, primary_key=True)
seller_id = db.Column(db.String(10), nullable=False)
order_id = db.Column(db.String(50), nullable=False)
access_token = db.Column(db.String(500), nullable=False)
rating = db.Column(db.Integer, nullable=True)
comment = db.Column(db.String(200), nullable=True)
timestamp = db.Column(db.String(50), nullable=True)
def add(self):
db.session.add(self)
db.session.commit()
def update(self):
db.session.commit()
@staticmethod
def check_access_token(token):
query = Feedback.query.filter_by(access_token=token).first()
if not query:
return False
return query
Can anyone see what's wrong with this
hello guys anyone here used flask and jss to create an website application ?
i'm stuck at a problem
__init__() takes from 1 to 2 positional arguments but 3 were given
check_token returns <Feedback 1> so its not False. However when using if (not form.validate_on_submit()) or (not check_token): this is where the error occurs
Actually its form.validate_on_submit() that is causing the issue
nvm I fixed it. My form had inputrequired() instead of input_required()
hey guys sorry to bother with my stupid as questions i am very new to web dev, when i import usercreationform then i create an instance of it what am i creating exactly? is it a dictionary with missing values
btw is acquiring a post request
im so confused, i mean my code is working and everything but im trying to understand whats truly happening under the hood
what's the code for usercreationform ?
So currently I have a grid set up like an excel document. I have a title row on top with the data below. To create the sheet used:
grid-template-columns: 1.5fr 1fr 2fr 2fr 1.7fr 3fr 3fr 3fr 3fr 4fr .6fr 2fr 1fr 1fr 4fr;
I used this line both in my title class and my data class so they are the same size, then I populated the info.
I added resizability of the title with resize: horizontal. The issue I have now is i need the data class dimensions to mimic the title's dimensions so it resizes along side it
I don't want them to have the option to resize the tables from data, only title. I just need the data columns to be the same size of the title as the title expands/shrinks
I think that'll have to be done with javascript
how so?
this looks helpful https://stackoverflow.com/questions/25679784/how-to-detect-resize-of-any-element-in-html5
doesn't look like there's a standard way to do it
Ah. Well thanks for pointing me in the right direction!
anyone here who could help with django admin override?
i have created a new custom view for updating some fields of a model, it's kind of a change_view but there will be 3 or 4 of this views, with different subsets of model fields
the thing is that in add_view as in change_view, the datetime widget is admin styled, but when i create a custom view inside admin, the datetime field is nonadmin, (the difference is really anoying, admin style datetime has 2 separate inputs for date and time, the nonadmin has only one char input field with no browser widget for date or time)
thanks in advance
Hello guys! I have read that using MongoDB with Django might not be an optimal approach. Does the same apply for Flask?
is there a simple time zone conversion package?
@simple meadow idk about flask but usually postgres is the best option for python
I am new to django and was having a bit of issues in my
code
from .forms import SignUpForm
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
def register(request):
if request.method == 'POST':
print(request.POST)
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
else:
form = SignUpForm()
return render(request, 'bankapp/register.html', {'form': form})
def logout(request):
try:
del request.session['email']
except:
pass
return render(request, 'bankapp/login.html', {})
def login(request):
if request.POST:
email = request.POST['email']
password = request.POST['password']
user = authenticate(email=email, password=password)
if user:
return render(request, 'bankapp/home.html', {})
return render(request, 'bankapp/login.html', {})
@login_required
def home(request):
return render(request, 'bankapp/home.html')
firstName = forms.CharField(max_length=15)
secondName = forms.CharField(max_length=15)
email = forms.EmailField(max_length=254)
password = forms.CharField(max_length=30)
def clean(self):
cleaned_data = super(SignUpForm, self).clean()
firstName = cleaned_data.get('first-name')
secondName = cleaned_data.get('second-name')
email = cleaned_data.get('email')
password = cleaned_data.get('password')
if not firstName and not secondName and not email and not password:
raise forms.ValidationError('You have to write something!')```
from . import views
urlpatterns = [
path('', views.home, name='home-page'),
path('login/', views.login, name='login-page'),
path('register/', views.register, name='register-page'),
path('logout/', views.logout, name='logout'),
]```
The register page works perfectly
but the login page does not
I use @login_required but after logging in it still redirects me back to the login page
Please help if you can
hello
I have an api
I use heroku to host
but the problem is the 512 Mb Ram is not enough
but I do not wang to pay 7$ for a bbby version
whatrs a cheap and better host for an api built on Open Api v3
I used the Fast Api lib
im crying
how to heroku flask
istg im so done
Hi. I am making a Dash app and using Heroku for deployment. I’ve been trying to deploy it for so long but it shows the following error. 2019-06-26T07:24:54.619101+00:00 app[web.1]: Traceback (most recent call last): 2019-06-26T07:24:54.619129+00:00 app[web.1]: File “/app/.he...
im getting the exact error
as here
but
its a big rip for me
no solution posted
hello
i have a problem
with jquery
when i select the first option listed in jquery
it does what i coded it to
but
when i do it to the second one
it doesnt
heres js
$("#id_rank_choices").change(function() {
if ($(this).val() == "dev") {
$('#div_id_dev_name').show();
$('#span_id_dev_name').show();
$('#div_id_dev_email').show();
$('#span_id_dev_email').show();
$('#span2_id_dev_name').show();
$('#span2_id_dev_email').show();
$('#div_id_dev_ign').show();
$('#span_id_dev_ign').show();
$('#span2_id_dev_ign').show();
$('#div_id_dev_age').show();
$('#span_id_dev_age').show();
$('#span2_id_dev_age').show();
$('#div_id_dev_timezone').show();
$('#span_id_dev_timezone').show();
$('#span2_id_dev_timezone').show();
$('#div_id_dev_time_spend').show();
$('#span_id_dev_time_spend').show();
$('#span2_id_dev_time_spend').show();
$('#div_id_dev_why_staff').show();
$('#span_id_dev_why_staff').show();
$('#span2_id_dev_why_staff').show();
} else {
$('#div_id_dev_name').hide();
$('#span_id_dev_name').hide();
$('#div_id_dev_email').hide();
$('#span_id_dev_email').hide();
$('#span2_id_dev_name').hide();
$('#span2_id_dev_email').hide();
$('#div_id_dev_ign').hide();
$('#span_id_dev_ign').hide();
$('#span2_id_dev_ign').hide();
$('#div_id_dev_age').hide();
$('#span_id_dev_age').hide();
$('#span2_id_dev_age').hide();
$('#div_id_dev_timezone').hide();
$('#span_id_dev_timezone').hide();
$('#span2_id_dev_timezone').hide();
$('#div_id_dev_time_spend').hide();
$('#span_id_dev_time_spend').hide();
$('#span2_id_dev_time_spend').hide();
$('#div_id_dev_why_staff').hide();
$('#span_id_dev_why_staff').hide();
}
});
$("#id_rank_choices").trigger("change");
$("#id_rank_choices").change(function() {
if ($(this).val() == "mod") {
$('#div_id_mod_name').show();
$('#span_id_mod_name').show();
$('#span2_id_mod_name').show();
} else {
$('#div_id_mod_name').hide();
$('#span_id_mod_name').hide();
$('#span2_id_mod_name').hide();
}
});
$("#id_rank_choices").trigger("change");
hey
I'm currently working on a pipeline for a php web app and I've got some issues with php caching resolved symlink paths.
I was wondering, do Django or Flask also store realpath of symlinks in a cache?
can someone help me figure this out.
I want a user to be able to post a embed link to my flask website
and i want it so whenever its posted, it gets shown as an iframe embeded video
how would i go about doing that?
so i need a form so a user can post the link but how would i make it so that the link the user has posted is put inside of an iframe
I use WTForms, in my form I return a custom error called LoginError, how do I make it register as a field error without making it into a ValidationError?
I have a question about flask_httpauth how can I authenticate user using flask_httpauth?
guys, how to center this boat in the list line
it's a bit up of the middle
tried margin top
but it makes the line bigger
padding not working too
give the wrapper element display: flex; align-items: center; is probably the easiest way to vertically center
Is it possible to host a flask website using github pages?
give the wrapper element
display: flex; align-items: center;is probably the easiest way to vertically center
@cold anchor thanks! worked!
I'm honestly very surprised that works
also I don't understand the question
oh I see, you want it to replace the random characters?
you can't do that from flask by returning more every time, once you send data, it's sent
actually i used the code partially
haha
but found the error at my code
i'm stuck with a 2x4 table
it's oversized
to to make it fit?
how*
tried width
the container is fixed width, if you remove the width or max-width from the styles it should just fill to container the elements
the font is a little to big, i will certainly make it smaller,
the container is a bs4 card
do you have any customer styles on the embarques card container?
no, not really, just in the table itself
i tried to hardcode it directly in the table
but i have an custom.css file to add stuff if needed
as a sidenote: I don't think cards are semantically made to contain things like tables, so I understand this issue happening
what are the classes on the card container?
wow, actually that's a huge guess, i'll remove the card
hahaha
i was putting everything inside cards
but i guess it'll be better off the card
1 sec
it's definetely better, but still oversized
yeah if you're just trying to make a table with a container, title and border with a slightly different background color just do that
Error: TypeError at /register/RegistrationForm() missing 1 required positional argument: 'UserCreationForm'
Code: https://hastebin.com/debanusiyo.py
Full Traceback: https://hastebin.com/tedawinido.sql
Can anyone help me to connect to db2 database on my django project please? Is it even possible I wonder?
does any one know js?
Hey I wanna create a website for my business model, I wanted to ask whether choosing multiple products from other websites (such as Amazon , Ebay) and adding them to your own website to create a monthly subscription box ... I am thinking of selenium and web scraping to add the items to my website , and place the order automatically each month to any given customer , is that possible? If not , is there any other way of doing it?
ping me if someone comes up with an idea , thanks!
People who use flask, how do you make headers/navigation bars?
does any one know js?
@native tide
Yeah
Can anyone help me to connect to db2 database on my django project please? Is it even possible I wonder?
@opal yarrow
Did anyone help
I also want to know
Hey guys. I am scraping a site with bs4. The element is like below. How do I find it using find() ?
soup.find("span",itemprop="name")
Probably
Or a better way could be:
soup.select("span[itemprop=name]")
@tame hatch @opal yarrow https://www.ibm.com/support/producthub/db2/docs/content/SSEPGG_11.5.0/com.ibm.swg.im.dbclient.python.doc/doc/t0060891.html
This is the first result for "db2 django". There's a django example at the bottom
Hey, I have a question about flask. Previously have I used local static images and looped over into a render template and that works fine. But Now do I like to do the same but with a list of urls to img (ex imgur hosted) but I cant find any way to do that. Is that my google skills that failing me or is that not a proper usecase?
@soft trellis How are you getting the urls, Is it via context or just in the code or what?
@quick cargo right now do i have them in a json file that I loading
hmmm okay well you probably wanna pass it via context, as a dict or somthing
and just have src="{{ images.image1 }}" which would represent images['image1']
I will give that a try, thx 🙂
@quick cargo With a little bit of fixing si it now working as planned. thx!
I'm using "djangorestframework-simplejwt==4.4.0" for the authentication. It uses a scheme which gives user two jwt, the access token and the refresh token. The access token is valid for small amount of time and must be provided for each authenticated call. The refresh token must be used to receive a new access token when the current one has expired. The access token is valid for 10 minutes, the refresh token for 1 day.
- 1 day seems short, I don't want my user to have to login every single day. I'd think that something like 30 days seem much more suitable. Is it a good idea ? My previous job would use 1h access token and 30 days refresh token.
- When should I refresh the access token ? When I get a 401 response ? When I notice it's expired as I'm checking it regularly ? I'm going to develop a front with Angular and I don't think it enforces anything on that aspect.
Hey could anyone give me a good reference about django rest framework?
Anyone knows if I can scrap multiple currencies from amazon? for example, scrap price from amazon by USD and EUR for a specific product
Using Flask SQLAlchemy, I have a table and it has a column called rating. Inside is a float. I have about 10 records. I want to make a query which returns 3 rows with the highest float value inside rating. Any idea how I can achieve this?
nvm I achieved it with User.query.order_by(User.rating.desc()).limit(3).all()
How can I get flask form data with javascript and put it inside of an “SRC=” attribute for iframe?
so, i want it like this..... User clicks on submit > get the form data > create "iframe" element > put the form data inside of "src" attribute
sounds .. dangerous?
you're saying you want someone to fill out a field and then on the next page, what they put in becomes part of the src attribute of the iframe? Taking that kind of data from the user and then turning around and embedding it in your site allowing them to call an iframe ... scary. Make sure you sanitize all those inputs.
oh now that i think of it.. it actually does sound scary
ill think of something else then 😅
#1 rule of web dev -- don't trust ANYTHING from the user.
oh lol.. Yeah, I'll keep that in mind from now on! thanks 😄
that's of course me saying all this not knowing your use case, I can imagine some legit reasons too
Let's say your user fills out a "name" field and you want load an iframe on the next page with src=mycoolanimationpage.com/?name={{form.name}} or something .. contrived example, but say the iframe just takes the name and animates it. And its via iframe cause the animation thingy is on another site. I guess? LOL. Just making this up.
So you CAN do this, just you would obviously want to sanitize the name, make sure they aren't passing anything nefarious, etc.
But ultimately I'd go "Hmm, do I really want to do it this way?"
or the form element is the location of a restaurant and you're dynamically passing the location to a google maps iframe, that's legit, still handle with care, but legit
etc
yeah, i am going to try and keep it simple and try to see if there are other ways I can do this. sanitizing everything the user puts in seems hard lol
Hiya, did anyone have a problem where logging into Admin page (django) loads it without the CSS?
May someone please give me some advice? I’ve been trying to program in python I like it but I heard PHP is easier.
So should I switch to PHP?
why? are u trying to get hired?
It’s not a necessity. I only just started learning python more seriously and consistently lately tbh.
Plus Google says that python is easier for novices anyways.
I'm confused, what is your goal
I’d like to get into AI and data science but the light at the end of the tunnel feels too far away. I’d like to maybe get into algo trading one day but that maybe a crapshoot. On the positive side I could in theory be self taught. Unfortunately those are all advanced subjects.
Plus Idk if I’d like AI and data science.
For all Ik I could dislike it.
Those two fields would be very difficult for someone with no advanced maths background to break into.
Let alone someone with no industry experience.
It just doesn’t sound like a realistic goal for me to have anymore.
Unless I become like Elon Musk and study my bum off.
Is anyone working with Vue on front end ?
However in theory anyone could get started with AI.
“Ik that it works but not entirely how” mindset
@oblique tide do you have a degree or education in that area?
Nope.
And that’s my point.
Plus Idek if I’d like to actually do it.
Sure the satisfaction is in achieving that big goal.
But I mean.
Can I and should I?
hmm..I think getting a first job doing data science or AI related is unrealistic unless you have a project that clearty demostrates you have built something showing off those skills
That’s my point
Let alone without an advanced maths background.
Linear algebra, statistics, and calculus
whats wrong with going into web dev first using python? then maybe look to it in the future?
Nothing. I was just wondering if PHP is easier?
but i dont understand your goal? is it just to get hired?
No. To learn the basics and make stuff.
python is known as one of the easier languages to learn for your first language
Oh ok. Then I’m on the right path.
Someone on YouTube suggested PHP.
So I suppose I was wondering if he was suggesting that it’s easier.
thats all you need
I have a pinned post in the careers channel if u need more help
Good luck
Then look for what companies are looking for in your area, what languages and skills and career progession
dont learn x y or z language because some guy on youtube said
learn what is realistic to you!
Yeah. I just wanna start small.
Then you wont go far wrong with python!
Plus. Once I can get some stability in my life in the future and experience, getting into more advanced fields would be more of an achievable goal if I’m still interested.
Exactly!
But that goal won’t likely be achieved until 10 years sadly 😂
I’ll likely live a fairly monastic life until then.
If I get married and have kids
I likely won’t ever achieve other things
Unless I’m a time management pro
There’s just so much to life.
That’s nice!
20
if i could be 20 again, holy s***
the things i would of done differently
If you want a career in programming then get stuck in, you have more than enough time to do what u want to do! You will be years ahead of me thats for sure
I have learned that nothing worth learning happens quickly, which is why good developers get paid so much money
Yeah. I heard they are even constantly learning new things.
I dont want to try and persuade you, all I can say is python has changed my life in the last 2 years, and im almost 30. If you learn python well enough you will never regret it
Thanks! I’ll definitely take your advice seriously since you’re almost 10 years older than me lol.
Because I was a laborer and delivery driver for years and years and I suffered from serious mental health problems for years because of it
and someone close to me send me a job advert for something called python I had never heard of
I had zero IT experience
read my post 😉
Your story sounds pretty inspiring ngl
My advice would be, if you want a 9-5 job and have a stable income then programming is great, if you want to earn bigger bucks and overtake people that are years ahead of you then you have to dedicate more time to it
its a very competitive market
Yeah. I definitely wanna go big. But honestly a stable income and living is also a really nice goal to achieve. Unfortunately in this society, at least in the US, the social safety net isn’t as good as it could be.
I live in UK, i plan to move to USA in next few years
Unless you’re a monk, you may not be happy with an unstable low income.
Or you’re rich to begin with
😂
Why would you move to the USA?
True. Plus you probably pay very high taxes.
I pay 40% right now
Idk if that’s a lot. Sounds like it.
Yeah and I hate UK mindset
completely risk-adverse and non-entrepenurial
depends
How important is leetcode really
I just landed my first job as a software dev, but I didn't have a leetcode problem \
I would reconsider your decision to move to the US if I were you. There is no synthesis between capitalism and socialism. Plus the rioting, racism, and police. It may only get worse over here tbh.
how old are you @dark hare
29
What countries are you guys from
The USA
you are exactly 10 years older thanme
Ahh i am the little brother of the equation
Canada here
hahah
you got a job first time last year?
@sand oasis we are around the same age lol
2000?\
yeah u should check out my post, pinned in careers channel
that was meant to be towards @dark hare sorry lol
are you in college @oblique tide
I maintain several apps built using python/django, one is in flask. I also build features for them. They are mainly user facing websites with an ecommerce part to them
plus internal systems for moving data around
i.e. using lambdas and data transfer etc
`Command 'sqlite3' not found, but can be installed with:
sudo apt install sqlite3` weird doesn't Sqlite come by default?
that sounds neat
how grueling is the work on a daily basis
@dark hare
one thing i'm scared about of my upcoming job is how stressful it'll be\
but idk if it'll really be as i imagine
@sand oasis my job is easy as piss, easier than learning python from scratch thats for sure
obviously that doesnt speak for all companies
but i do a lot of extra learning outside of work hours to make my job easier and improve my own skills
All the best, ofcourse my advice is biased against my own experience
but theres no such thing as knowing too much 😉
@sand oasis yes I am.
you look for some internships this summer? @oblique tide
Covid kinda messed the process up big tim
Nope. I’m still learning the basics.
ah i see
Could python in any way help with web devellopment? I didnt think so but Ive heard
django and flask are two main frameworks
I'm doing a few external API calls from my django server, would it be better to call the APIs and insert the data into a DB, and serve locally, or cache the api calls and serve from the cache?
whats the average turn around time for getting questions answered on this server?
Depends on the question and how it's asked/phrased. A fairly simple question about standard library python should get answered quickly. But trying to figure out complex code with a library not everyone is necessarily familiar with could take awhile.
I see, is the flask web framework not used by many people?
sorry i must not be asking the right questions at the right times,
been on this discord for about a day and so far, havent gotten much traction in the help channels
maybe im asking at the wrong times?
maybe people are off to lunch? asleep? or just not near there computer?
I'm not intitled to a response but the frustration and lack of progress is starting to catch up with my patience
Well, what is your question, exactly?
Its in the help-boron channel
How do i make a file or something to make a website?!?
does anyone have good beginner resources for posting data to django backened via ajax/jquery?
@valid crane You have a lot of freedom to design your APIs how you'd like when using ajax or jquery. Do you have any further requirements? I typically go for Django Rest Framework to build restful APIs easily and then integrate with those but that partly depends on your needs.
i have just encountered an error with my code and it seems that the yt tutorial that im following isnt applicable for django
Free RESTful API to use for practice!: http://rest.learncode.academy/
In this jQuery AJAX Tutorial for beginners, we're going to be adding new data to our backend server with the jQuery ajax post method. jQuery ajax post allows us to send data for the backend to save. When ...
@valid crane Sounds like you have a specific question, maybe try #❓|how-to-get-help
sure, thanks
I have a function called login for my LoginForm, my question is, how can I make them the correct form of field errors, so for example if the passwords dont match under my password field it will say so
Hi, I'm wondering if it is possible to use the app.route decorator as a normal function.
Specifically, I want to know if something like this is valid
def setup(app):
app.route("/favicon.ico", lambda f: send_from_directory(os.path.join(app.root_path, "static"), "favicon.ico"))
instead of this
def setup(app):
@app.route("/favicon.ico")
def favicon():
return send_from_directory(os.path.join(app.root_path, "static"), "favicon.ico"))
The only reason for this is to silence the error about favicon not being used in my editor 🙂
Mareks, what are you using?
nvm, app.add_url_rule seems to work well
Is there a way I can setup error handlers using flask.views and make it class base?
@opal radish Flask and WTForms
Oh damn my grammar in that sentence is uhh sorry to whoever read that lol
in my django models i want to be able to select a list of actors and generes
atm i can only select one
you want ManyToManyField
@fading vortex
ForeignKey is for many-to-one relationships i.e. one actor can be in many movies, but one movie can only have one actor
how can i get the first li in the ul with py bs4?
@vestal hound okay thanks
class Point(models.Model):
class Meta:
db_table = 'Point'
account = models.ForeignKey(User, on_delete=models.CASCADE, related_name='pointAccount', db_column='pointAccount')
latitude = models.CharField(max_length=50, null=False, db_column='latitude')
longitude = models.CharField(max_length=50, null=False, db_column='longitude')
name = models.CharField(max_length=50, null=False, db_column='name')
description = models.TextField(db_column='description', null=True, blank=True)
def __str__(self):
return self.name + " (" + self.latitude + ", " + self.longitude + ")"
Gives me this error:
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option:
Anyone know why? The tables are empty.
It doesn't really matter, the ORM will ask you to use a one-off default in case another database somewhere have some objects in it
You can use a random value I guess
thing is it works perfectly fine in this model:
pointA = models.ForeignKey(Point, on_delete=models.CASCADE, related_name='pointA', db_column='pointA')
pointB = models.ForeignKey(Point, on_delete=models.CASCADE, related_name='pointB', db_column='pointB')
I mean, if you try to add a pointC key in it and make a migration, it will ask you for the default
No, since the table is empty..
Alternatively you can get rid of the whole migration file, but you'll have to create a new database
It doesn't matter
The migration history is like a git history, you need to be able to go back and forth, no matter what the database contain
Well, delete the migrations folder, make a new one, and delete and recreate the database on your dev server
Nice!
should i desgin my contact form inputs with labels or with placeholders
Hey, i learn Django so i need help with django forms.
models.ImageField works correctly, but forms.ImageField does not work at all
same with DateTimeField
https://i.imgur.com/dxYwbMz.png
https://i.imgur.com/Yv4YQT3.png
https://i.imgur.com/rj1Mh7S.png
@vestal hound when i add another movie the items stay tho?
I'm following the Django Girls tutorial, and have come unstuck with the post_detail section.
In my urls.py I've got got this:
path('', views.post_list, name='post_list'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
]
Which is exactly what it says to do in the tutorial. However whenever I click on a link, it tries to go to:
````http://127.0.0.1:8000/{% url 'post_detail' pk=post.pk $}```
and thus gives me an error.
but I'm not sure what I did wrong.
that tutorial just follows the django docs
is that urls pattern in your main app
i try to make another movie but the relationships with the actors carry onto it
from the first movie
those are all the objects of that type that exist
LOOL im sorry
@gloomy acorn views.py has (the relevant bit at least), this:
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {"post": post})```
Which I've checked against the tutorial and that's what they've got as far as I can tell.
the link is:
<h2><a href="{% url 'post_detail' pk=post.pk $}">{{ post.title }}</a></h2>
I'm like 95% sure
something is wrong with your template
I don't actually use Django templates, but it's not your urls.py that has an issue
that wouldn't surprise me tbh, HTML is the thing I've learned least-recently so is probably the most likely thing for me to botch 😄
because basically
what is happening is
the link that is generated by your template is wrong
think of it this way
URLs are addresses, and views are the buildings that appear at each address
i.e. URLs answer "where is this thing" and views answer "what does this thing do"
what's happening above is that you are getting the wrong link
not that you have the correct link but it's doing the wrong thing
and the reason for that is that your template should be generating the right link, but it's not
yeah, not sure where all the %7B% stuff is coming from. IIRC %20 is a space character?
if you look at the URL in your a, it looks like this: {% url 'post_detail' pk=post.pk $}
yes
it's basically a way to encode URIs (URLs are a type of URI)
@abstract python i ll give u my example
<a style="text-align:center;" href="{% url 'articles:detail' a.id %}"><h2 style="margin-top:30px;background:#79AEC8;">{{a.art_title}}</h2></a>
urlpatterns = [ path('', views.index, name = 'index'), path('<int:article_id>/', views.detail, name = 'detail'), ]
def detail(request, article_id): try: a = Article.objects.get(id=article_id) except: raise Http404('Page Not Found') return render(request, 'articles/detail.html', {'article' : a})
okay I think
I see the problem
you have an $ where you should have a %
right before the closing }
wellll that's incredibly embarassing 😄
that's my guess, based on what the logical syntax would be
yeah, that works fine now. Sorry for wasting your time.
probably should've noticed that myself heh.
@fading vortex
Hey, i learn Django so i need help with django forms.
models.ImageField works correctly, but forms.ImageField does not work at all
same with DateTimeField
https://i.imgur.com/dxYwbMz.png
https://i.imgur.com/Yv4YQT3.png
https://i.imgur.com/rj1Mh7S.png
@gloomy acorn
i dont understand rn im sorry doing my own work
@abstract python no problem
if you were comparing it to something from a tutorial
one thing that can help is to copy-paste from the tutorial and ctrl-F in your code
ok then
@vestal hound Aye, I was stubbornly refusing to copy and paste and work it out on my own, when in reality doing that after 10 minutes or so just to find any differences would've saved a lot of time!
no, no
you should work it out on your own
typing the code out yourself is good for your learning
but when comparing to a source ctrl-f is helpful
yeah, that's what I mean. Writing the code myself = good. Refusing to copy and paste even to ctrl+f to see what's different in my code = bad.
@abstract python Haven't been following, but do you know how to do a diff?
I know it's a thing, but I'm not totally sure on how to do it.
Good editors have a way to do it built in, but point is it's a way to see differences between code without relying on just your Spot The Difference skills
I want my app to work on 80 port but I don't wanna run the entire program as root. Is there a way I can make 80 port nonpriveleged or something
no
but you can change permissions to allow certain binary ability to do it
cap_net_bind_service is what you are looking for
most people wouldn't recommend it
But if I set it for python interpreter all programs willbe able to use a priveleged port
if you want to run something like Flask/Uvicorn or like, run Nginx in front then proxy incoming on port 80 to whatever high port you select
ok gotta learn about nginx
or docker
basic nginx as proxy is really easy
I think config file will be like 7 lines
Yeah, recreating your prod environment is generally a good idea
Docker look into docker
Is webscraping against Reddit's TOS?
Hey. So I'm working with flask, and I have a question. I have a javascript file called main.js which I use for every single page. I load by using include. Now I have /edit-product and it gets passed a list from the backend called product. If I include a script tag at bottom of my page, I can use the product variable like: alert('{{product.name}}'). However if I do the same in my main.js file, it doesn't work.
How do I pass variables through to the main JS file ?
@rigid mist use the reddit API
@past cipher I would generally discourage of making frontends in flask that needs this, however it can be done:
You almost had it yourself,
In your main.js just make a setup function that you call from your HTML after you include main.js that takes the thing you want as a parameter.
How is python used in web dev? It is in the web page or it running on the server and does things on it or with the page?
I do REST APIs as well
people do make full web sites with Python using Flask/Django but that's not "new" hotness
@zealous siren what framework do you like for REST API's?
I think Flask is pretty good for this. I‘ve seen some people using it for REST APIs
That's what I use too, and have been for the past 2 years, but I think I'll try Fast API next time :-)
FastAPI
@crisp saddle would you mind sharing why you would discourage it?
I managed to fix it by doing inline script styles
I thought I could of used {% with %} but turned out I couldn't
I really do need to learn Javascript soon though. I'm having nothing but problems..
It's just so easy to get going with FastAPI
{% for item in codes %}
<script>
document.getElementById('digital_codes').append('{{item.code}}');
</script>
{% endfor %}
This seems to only append the first item, but I'm not sure why
and I know its going to produce multiple script tags, but I have no idea how I would do a for loop inside a script tag while looping through a list
Get all elemenents by id
Like that you are selecting only first "thing" with that id
Hmm
it should append each item.code to the text area
but its only appending the first code
it creates the script tags though, just doesn't append:
https://gyazo.com/762d844d2831abc13cc3c43a16949d83
and no error in console either
so I have been working on making a flask blog that is decent for a beginner I'd say(4 weeks). Now I am thinking of learning Django. Is that a good idea or should I keep learning more about Flask?
hard to answer.
If your goal is to just learn for the sake of learning, then yes: they're both popular frameworks, and it'd be interesting and useful to know how they're similar, and how they're different
but if you just want to serve up some simple web pages, and flask is working, then ... maybe not
hmm. I feel like I want to learn more about Django and maybe how flask/django are similar. I think im going to give it a shot
They are overall quite diffrent
One is a very Heavy framework which controls how you lay stuff out heavily (django)
The other is a micro framework where you have much better low level control but the framework does less for you (flask)
Yeah, I feel like I kind of plateaued with my flask project, dont know what more to add or what more I CAN add. So maybe its time to check out django
I'm using flask. How can I have bearer tokens work for only certain endpoints? So say I want token 1 to access /test, and not be able to access /hello, and token 2 to only access /hello, and not /test
Are you using Flask Restplus @onyx gulch ?
Well the answer is kinda the same, you just make a decorator that requires it for an endpoint, and leave it out if the endpoint doesn't need token auth 🤷♂️
Error:
TypeError at /register/RegistrationForm() missing 1 required positional argument: 'UserCreationForm'
Code: https://hastebin.com/debanusiyo.py
Full Traceback: https://hastebin.com/tedawinido.sql
can somebody please help me?
@native tide it's telling you, you are missing a required argument.
I have no experience with that framework but the overall design pattern is the same I would assume.
With rest plus can you specify which token is needed for the endpoint
can you show me an endpoint that has auth?
So I could have more than one token
alr
one moment
from flask import Flask, jsonify, request
from flask_httpauth import HTTPTokenAuth
app = Flask(__name__)
auth = HTTPTokenAuth(scheme = "Bearer")
tokens = ['abc']
@auth.verify_token
def verify_token(token):
if token in tokens:
return token
@app.route('/test', methods = ['GET'])
@auth.login_required
def test():
return jsonify(databasemanager.getAllProducts())
if __name__ == '__main__':
app.run(debug=True)
So the reason you wanna do this, is because you don't want to develop user roles?
I see, well you could make a decorator that is decorated by @auth.login_required
and in that decorator decode the token and see if it's of the type that you need.
sec
actually what's wrong with your verify token @onyx gulch ?
no i was just wondering if i could have different tokens access different enpoints
endpoints
so verify_token is the decoded token? 'abc' ?
in that case you just create two type of tokens, user-role#somerandomstrings
and then check the role when you verify it?
can i access which route is requested via verify token
I haven't developed a site in flask yet, is it like WAY easier than Django?
Been working on this Django site for like 2 months (because I'm learning from scratch and want to make sure I understand everything) and I barely feel like I'm making headway
I broke the site once by referencing objects by IDs and then had to change them all to reference by PKs instead
I don't know why it worked... But it worked
Before I go further into things, do I HAVE to reference HTML files that are in apps instead of just a folder in the main directory?
I'm writing a blog and e-commerce app, but they all live in a single web app
Ideally I'd like for a user to simply make ONE account that can access the other apps in the project
The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.
Does anyone know a better host to use? I don't really like this one
What do you mean by host? Framework? An alternative to Django?
I've never used any managed hosting service, only cloud services (GCP/AWS). I've heard good things about heroku though.
Hey guys im trying to refresh a webpage from my flask app every five minutes but I cant figure out how. Basically it is webscraping and uploading it to the webpage for real time data. However I cant figure anything about refreshing. Anyone know how?
@signal pasture you can do it in pure html :-)
@signal pasture
<meta http-equiv="refresh" content="300; URL=http://www.yourdomain.com/yoursite.html">
if it's the same page you can omit URL
@onyx bough try PyCharm
@crisp saddle i see thanks
Why is base.css cancelled, btw i'm using django
@crisp saddle Will that change the values of the variables from the flask app because when i refresh it gives the same data
Can I get invite to djando server or this is it?
dm me @reef pendant
@native tide I don't understand?
hey guys just starting to learn docker with django in vscode, and I am having a weird issue.
debugging the default django launch everything works fine on the admin page.
however if I do docker-compose up and look at the site it seems to be missing the css things for the admin side
Oh that issue
I used to have the same this when the site was in debug mode it would load it when it wasn't it couldn't
I assume I am just missing something here, what do you do to fix it?
does anyone here have experience in selenium?
How do I import a html file in a html file, for example an navigation bar in my base file without it overwriting other things?
{% extends %}
If I do that with my nav bar to my base html file I only see the mav bar
{% extends filename %} to be specific
And nothing else
You have to put blocks
Like {% block navbar %}
{% block body %}
You define these in the navbar code
and write it in another page
Just learn a bit more Jinja2
Ok, ty
np
If I have fir example block content defined in a different file I ahould call it differently just like a variable right?
{% block blockname %}
And then like this :
{% extends "index.html" %}
{% block head %}
<title>Hello</title>
{% endblock head %}
Ty very much everything works now, had an error for a bit and I had forgotten to use "" when extending 😅
np
Guys why does Flask have less job opportunities than Django?
Just curious
Like flask could do anything that django does
It's more flexible
and ...
I'm fan of both btw
You need more different libraries than Django, for example an admin pannel, in flask you would need to make it bacically yourself, but Django already comes with things like that
For bigger applications it often makes more sense to use Django
That is from what I have heard, as many of the flask libraries are made by different people and there is no guarantee that they will keep developing them for example 3 years from now
But tht is from what I have heard, haven't had real world experience with this myself, but I often see when searching how to do something with flask that with Django there is already a tool for that
How do I await in aiohttp_jinja2 templates?
Guys is there a way to save search history locally on device in flask
what kind of search history?
like what they're typing into a search bar on your website?
@haughty root You normally have to await the render
@limber laurel But flask is flexibility god
And you make everything you want in any way you want
Flask is a sandbox. Django is a sandbox with a few sandcastles already there, but you can just remove them...
Guys i need to improve my webdev skills so what are good exercises orprojects?
@quick cargo I use it through decorator, like ```py
@routes.get('/{name}')
@aiohttp_jinja2.template("hello.jinja2")
async def hello(req: web.Request):
return {'name': req.match_info['name']}
Which framework is this?
aiohttp
I heard only about flask, django and aiohttp
Quart is legit just async flask
And sanic?
Its a lower level Async framework thats much faster but you have to do alot of the stuff yourself
O, I also heard about vibora, is it good?
But on the @aiohttp_jinja2.template("hello.jinja2") IIrc that decorator a should get awaited by the original call
I havent used it directly, I know some of their bench marks are a lil sketch
Looking at their github aswell development seems to of stalled
Hey where all do you suggest I go to learn the ins and outside of Django? I've done the polls app in the docs, but then what?
More projects
Like a todo app, social media site, quiz app
Go through the model query page in the docs, they come in handy
Guyz how to paste our code here??
There is not an item with id 2
This is django documentation
I got this one from there
But I don't what we r doing in it?
Cause you didn't add any item to database
Do you have sqlite installed on your laptop/pc?
Yup
Ok so open the database (the .db file) in sqlite3