#web-development
2 messages Β· Page 33 of 1
after the call to $(e.target)
Well, e.target is the event's target
$(e.target) is the events target element
it seems that it's data is empty
it made the right amount of {} as the value is though
since the data is empty, .table becomes undefined
since table is undefined, if(table_body) does not run
Since e.target never changes throughout the loop, the if statement never runs
and add_row is never called
Right, so the loop is working, but the logic to fetch the row to add is not
so what causes my button with exact same code work?
my add row button i want to remove
Your #add-row element has a data(), your #travellingwith does not
no worries :P
i have 2 rows for selecting partner which is correct
and my button disappeared as it;s meant to π
but
it still doesnt like the consol log
?
That's logging the table
and means its working
You can expand it to look deeper, too
π
Django question.
So, I followed Corey Schafers' Django tutorial on youtube, in which he builds a basic blog. I have completed it and it's ready for deployment, but it's not what I'm looking to build (although I like that I have that app ready to modify and deploy if I want).
There's a tutorial for building a polling website on the official Django docs found here: https://docs.djangoproject.com/en/2.2/intro/tutorial01/
I would like to do both of these projects as different apps within the same overall project, which is currently called webhub.
The reasoning behind that is because my end goal is to have my own website that, when navigated to, forces a login before you can go to ANY page. I plan to be the only one who can access this website, basically. I want it accessible anywhere, but only by me via login. So, the plan is to have it log in, then bring me to a landing page with links to the apps within that landing. Sort of like how google chrome has that default landing page when you first open a tab.
With that in mind, I want to build this polling app from Django and try to tie both apps together, then create a landing that can navigate between them. Is this something that would work, or should I just not do that, and isolate each of these projects, then start work on my whole plan some other time?
Sorry, /novel lol...
Quick draw-up of what I mean
Anyone?
how do i simply add a script to a button with flask and python
all i need to do is connect a return redirect to a button
is anyone here experienced with flask and would be able to offer me some design advice?
Can't try if you don't give any details
ye, sorry just didn't want to spam if no one was available!
No worries, feel free to post anytime, it ain't spam
So, I'm making my own flask dashboard, so far it's been smooth but I'm a bit stumped about how to design my configuration page. The python backend also is connected to a gateway class which has a lot of configurations and one of the frontend pages is going to be handling those configuratoins, allowing people to see them and change them
What I'm unsure how to approach is how to get/save those values
the menus shown there are javascript/css right now
Well, first decision is if you want them to save-on-selection a la webapp style, or on a submit event
right, and they've got much clearer UX
I'd suggest just a regular post request
post new settings to a controlling endpoint, and have the endpoint send back a redirect to a "done" page
sweet, ill find a tutorial on that then
the url already switches to http://localhost:5000/config#lora1 for each module, would that then just require a app.route('/config#lora1', methods = ['GET', 'POST'])?
Thisβll make me stress less about deadlines then
You can also separate the methods
app.route("/", methods=["GET"])
and
app.route("/", methods=["POST"])
I believe
So, ex:
@app.route("/config", methods=["GET"])
def config():
return render_template("config.html")
@app.route("/config", methods=["POST"])
def save_config():
print(request.form)
@app.route("/config#lora1")
def func():
print("WOW LORA1?")
I tried to run this as a quick test and it doesn't seem to be reached
<a href="#lora1" class="list-group-item" id="lora1" onclick="sidebarfunction(1)">Lora Module 1</a> this is how it's being called
Two things there, I think
onclick= might suppress the navigation event
and an href to a # causes the browser to jump to the element with that as its id/name
You can change the url in the navbar separately from navigation without using #'s,
wouldnt i need seperate .html files then?
Not necessarily
window.history.replaceState() is a non-loading navigation event, but more importantly, the html files returned by flask are specified by you
Say you're on /config#laura1, and you have the following html:
<form action="/config-submit/laura1">
<input>
<input>
<input type="submit" value="Save Changes">
</form>
Clicking the "save changes" button will trigger a POST request to /config-submit/laura1
if you name your route "/config-submit/<config_name>", and take in config_name
then the last element of the url is passed into your function
Your function could then return a redirect back to /config#laura1, for example, to go back to the original page
However, considering that you've already got javascript hooked up
an ajax request to /config-submit with the relevant parameters might just be simpler
ah
Here's a simple jquery example:
$.post( "/save-config", { name: "Bast", time: "2pm" } );
The flask side, request.form['name'] would be "Bast"
I just threw that in
@app.route("/save-config", methods=["POST"])
def prase_request():
print(request.json)
get a name error for request, undefined
oh im missing a import, my bad
that did the trick
π
Hey @native root, took a break and got back onto it, right now I'm trying this:
@app.route("/get-config", methods=["POST"])
def return_config():
return_value = None
if request.form['module'] == "lora1":
return_value = {
"tx_power": 23,
"bandwidth": 100
}
return_value = make_response(jsonify(return_value), 200)
return return_value
and on the javascript side I got:
var lora_stuff = $.post( "/get-config", {module: "lora1"} );
when I look at lora_stuff, I get [Object object], tried json.parse() but that didn't help either
lora_stuff.tx_power ought to be 23, there
ohhh!
console gave me a hint it's
lora_stuff.responseJSON
{bandwidth: 100, tx_power: 23}
π thank you!
$.post( "/get-config", {module: "lora1"}, function(data) {
console.log(data);
}, "json" );
I'm trying to communicate between python webserver with websockets using the sockets library
but when I try to connect it to my javascript client using websockets, the connection fails
this is part of my code
the client:
Display.innerText = Address
var socket = new WebSocket(`ws://${Address}`)
socket.onmessage = function(event){
//This is called per message
//Message = event.data
document.getElementById("textarea").append (event.data + "\n")
return false;
}
socket.onopen = function(event){
//alert("Connected to server.")
}
function sendMessage(message){
socket.send(message)
}
the server:
server = open_socket()
while True:
sock, addr = server.accept()
thread = threading.Thread(target=client_thread, args=(sock,), daemon=True)
thread.start()
can anyone help me?
hi guys
i'm using django 2.2.3
and i'm trying to import models.py
news
βββ __init__.py
βββ __pycache__
βββ admin.py
βββ api
βββ apps.py
βββ fetcherHelper.py
βββ management
βΒ Β βββ __init__.py
βΒ Β βββ __pycache__
βΒ Β βΒ Β βββ __init__.cpython-37.pyc
βΒ Β βββ commands
βΒ Β βββ __init__.py
βΒ Β βββ __pycache__
βΒ Β βββ create_news.py
βΒ Β βββ feed.py
βΒ Β βββ get_main_feeds.py
βββ migrations
βββ models.py```
currently i'm working from get_main_feeds.py
i tried
from news.models import News
it didn't work
this is my os.sys.path
@native tide from .... import News ?
ValueError: attempted relative import beyond top-level package
yeah
i can do that
but i was wondering if there was a bettere solution
I would expect from news.models import News to function
Is news missing from INSTALLED_APPS?
nope
so i'm trying to create a custom django command which calls a class in the same dir which calls news.models import the model to add data to db
is there a bare news?
βββ Scripts
βββ django_project
βββ domain_monitor
βββ media
βββ news
βββ seed_data
βββ static
βββ todolist
βββ users
these are all the apps that i have
How are you running the command
hmn with ctrl+alt+n in vs-code
maybe it's the problem
i should use the manage.py shell
the fact it that that create_news should be indipendent from django shell
yes
That is the problem
django sets up its installed_apps imports when you call the django manage.py commands
This allows you to easily import and access other modules
if you simply run the script separately, the namespace is not initialized, and you get errors like the one you were experiencing
If you wish to have access to your django models, then it's pretty much given that your command should be run through the django commands interface
Here is a relevant guide, if it's not what you're doing
They are callable via python manage.py custom_command_name for custom_command_name.py
Hi, anyone ever converted a Flask application to exe? It's possible but I'm getting an error File "app\__init__.py", line 2, in <module> from flask_socketio import SocketIO ModuleNotFoundError: No module named 'flask_socketio' [9608] Failed to execute script app I've googled but I Can't find a solution, when I do pip3 freeze in my venv I'll get the following: Click==7.0 Flask==1.1.1 Flask-SocketIO==4.2.1 gunicorn==19.9.0 itsdangerous==1.1.0 Jinja2==2.10.3 MarkupSafe==1.1.1 python-engineio==3.9.3 python-socketio==4.3.1 six==1.12.0 Werkzeug==0.16.0 It looks like flask-socketio is installed... Anyone got an idea?
Did you activate venv?
Can anybody tell me why I should learn web development (html, css, javascript...) when there are now websites that can make it for you?
Someone has to make those websites. And fix all the broken websites those websites make. Go to fiver and search for "wordpress" if webdev was as simple a using a wysiwyg website there would be no need for all those wordpress devs.
Which is the best language for starting to learn about web develolment?
Hi. Anyone with HTML experience who might be able to help be troubleshoot my code?
I want to create a website where people can watch ads that gives me money and i give them something as return
But I don't know how to put ads
using django
@graceful summit use your ad provider's API
@unborn terrace sorry what does this mean
@graceful summit ad providers have an API, i.e. a set of interactions you can do with them from your code, for instance retrieving an ad to display it, information about these interactions and how to do them is available in documentation they provide
Django documents?
What is the best one
Google adsense?
Or what
I don't know, look them up
Okay thanks bro
@balmy forge Yes I did
I think you pinged the wrong person? xd
Hey folks, I want 2 ask if there's any way how do you enable google maps api
@honest flame You'll have to specify the question. Google has documentation on their APIs
Hi all
I have a problem with my website, it's on Django.
Core of the problem is that I have no clue how to debug this particular bug.
When I'm sending forms on the website, it works fine, there's validation that also tells me everything is fine.
If I fill a form from my main PC, I can see new objects in admin panel.
But doing the same thing from a new IP (my phone for example) doesn't show me any errors, yet objects don't appear in admin panel.
Yeah
I managed to fix the issue where it would display the error File "app\__init__.py", line 2, in <module> from flask_socketio import SocketIO ModuleNotFoundError: No module named 'flask_socketio' [9608] Failed to execute script app But now when I run the exe it won't return anything. Added some print files in the main file but it won't even print those when I run the exe
anyone has an Idea? Using pyinstaller for my flask application. Thanks in advance
!
Fixed it.
How?
Hello All, I am new here. And I an new to learning Python as well.
Currently I am trying to learn it through a small project where I am connecting to my IBM i server and showcasing some data in the chart forms..
I am using python and Dash by plotly as the dash-boarding framework.
I wanted to connect to some who has experience in building dashboard using Dash framework.
Thanks in advance π
guys I'm dying here I don't know the flow
I created a pycharm project with django and docker. Used postgres
if I run anything on the container it works
but if I try to use local manage.py or django console, I get an error
django.db.utils.OperationalError: could not translate host name "db" to address: Unknown host
I'm assuming this is because in my django DATABASE setting I put 'db' as the HOST
If I change it to localhost, it'll work in manage.py locally
but then break on the container
?!
How do I output an error in Flask, so that Apache picks it up and throws it into the apache error log?
just write it to std::err?
I believe you would need to return an error status code
Thanks. Do you know which one is suitable so that Apache still serves the content, but logs the error?
and how do I pass the message?
I mixed two things up. If you want your stacktrace to appear in the apache error log, then printing to sys.stderr should suffice
If you want apache to log an erroring page without displaying "Recovery" content--like on a 404, for example, you'd want to return the template with the appropriate status code
You can do that in a flask route via return template_rendered, status_code
I tried to raise an exception, Apache shows a 500, but the log is empty. I am going to try to write std err
This might be helpful: https://flask.palletsprojects.com/en/1.1.x/api/#flask.Flask.errorhandler
Printing to stderr does not work. Error Handlers are just custom error pages, aren't they? Apparently getting apache to pick up your output is harder than anticipated.
I am stupid, printing to stderr does work. Was looking in the wrong log π
forgot that I had 2 separate logs for frontend and backend vhost
@admin_app.route('/myerr')
def testerror():
print("Custom Error", file=sys.stderr)
return "Hello World"
Output:
root@host1:/var/log/apache2 # cat admin.error.log
[Fri Oct 18 06:17:36.115208 2019] [wsgi:error] [pid 8367] [client 10.10.10.1:49505] Custom Error
I was about to mention it :P
Generally practice is to return a "Internal Server Error", 500
5xx error codes indicate that the server had an error, and is useful for callers to get
But it's up to you and your needs honestly
Unless you want the app to continue operations. I want to silently log the error but keep going
Right
it's not critical
Then yeah, you're good
Thanks Bast π
Of course
@rare oar
That happens because it cannot find the database since it's in your container that is shut down
the container is running
its like it doesn't transfer to my local host
To fix I set a environment variable POSTGRES_HOST in the container
and in my code did something like:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'zclpassword',
'HOST': os.environ.get('POSTGRES_HOST') or 'localhost',
'PORT': 5432 # default postgres port
}
}
That cannot be right haha
Generally you use a local_settings.py file
Which is only present in your development environment, and is imported at the end of settings.py (which should have been done for you). This would allow you to override the DATABASES setting with the localhost one
ok I will go for that. I guess then just in the Docker I have to make sure to not COPY that over
yep
Hey guys, I have a quote model and I want to create a foreign key link to one of many different product type models. Is there a recommended way to achieve this? One idea I had was to create a base Product model, then have one to one links from instances of these to the various different product model instances. Finally linking my quote model instances to the parent Product model instances. I look forward to any thoughts or insight, it would be much appreciated
Are you using an orm?
What you're saying there is usually the way it's done, as far as I know
Sorry, missed out completely that I'm using Django
Hi guys!
I'm currently trying to convert my Flask application to an executable file.
When I run the normal .py file it works, but when I run the exe I get the following error:
Traceback (most recent call last):
File "testfile.py", line 4, in <module>
File "app\__init__.py", line 14, in create_app
File "site-packages\flask_socketio\__init__.py", line 245, in init_app
File "site-packages\socketio\server.py", line 108, in __init__
File "site-packages\engineio\server.py", line 130, in __init__
ValueError: Invalid async_mode specified
[13920] Failed to execute script testfile
I've google around but could not find anything helpful.
Maybe it's something with hidden imports?
Thanks In advance
!
this is my init.py
from flask_socketio import SocketIO
socketio = SocketIO()
def create_app(debug=False):
"""Create an application."""
app = Flask(__name__)
app.debug = debug
app.config['SECRET_KEY'] = 'XXXXXXXXXXXX'
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
socketio.init_app(app)
return app
This is where the errr occurs (line 14) ```socketio.init_app(app)
@ashen anchor Django supports model inheritance
class MyModel(models.Model):
some_shared_fields
class MyOtherModel(MyModel):
some_unique_fields
MyOtherModel.my_model would give the parent class instance
@native root why would inheritance be needed here ?
Gatt was describing a situation involving inheritance, as far as I could tell, with multiple model types that are all kinds of another model
Eg, a set of "products" specific to different vendors
each linking back to a parent "shared product" model
@ashen anchor why would you need inheritance as well ? π€
@dense hound see here https://stackoverflow.com/questions/54150895/valueerror-invalid-async-mode-specified-when-bundling-a-flask-app-using-cx-fr
@native root if I understand correctly, these βproductsβ would be prone to be dynamically created. Hence not suitable to model inheritance. More like having VendorProduct objects linked (by foreign key for instance) to a Product object
@native root yeah I'm reading trough it atm but don't think it will help me out
such an annoying error
Why do you not think so, its your exact problem?
Yeah, essentially the product types are very different but a known quantity so I've opted to create different models for each product type
The quote model however just needs to contain costs/prices per unit (among other things)
But I need it to link to a specific product instance, but obviously there's different product types so a standard foreign key won't work and it seems GenericForeignKeys aren't recommended
Inheritance is exactly what you need
@ashen anchor why make your different product types different models ?
Because each product type has completely different attributes/methods attached to them
How many different types do you have to work with ?
Around 6
class Quote:
product = ForeignKey(Product)
class Product:
stuff
class BobsProduct(Product):
stuff
BobsProduct.product gets you the product
and you can reverse it as well to go from quotes to individual vendors
@native root makes sense to me, what is happening in the background whilst doing this?
Is it essentially the onetoone link I was planning?
Django sets up a foreign key from BobsProduct to Product, and uses that when it loads BobsProduct for all the inherited fields as well
Yep
Excellent, any downsides I need to be concerned with?
Aside from the performance hit with joins (which won't be a concern in this case)
There's some interesting inheritance details with the metaclass, but if you specify everything normally it ought to simply make sense
The docs for that gotcha are here: https://docs.djangoproject.com/en/2.2/topics/db/models/#be-careful-with-related-name-and-related-query-name
Perfect, really appreciate your help
good luck
Thanks π
@native root apparently it worked to import ```from engineio.async_drivers import threading
import engineio
import socketio
import flask_socketio
import threading
import time
import queue
in my main.py
yep, π
pyinstaller goes and looks in all your files for imports to know what to include, but since engineio doesn't have a normal import threading inside it, it's missed and not included by default
I'm making a dynamic text boxes form: https://paste.pydis.com/ufikiqihay
How I can give for each text box, a dynamic number and, when I click on the plus button, add the new text box directly under the first main text box?
Hi, this is not strictly python related but is still very conceptual, so I feel like your input will be valid.
Hi, for my senior design project my team is going to be implementing a webapp that uses a kahoot.it - like room system to group users into a session together by a code, but I had some questions on technologies for implementing this.
We will have access to a webserver and webhost, and our backend will be Rails. What technologies or libraries can I look into for implementing this type of system. Right now, I am imagining running one application on the domain that handles all users up until the point they enter a code or create a room, at which point docker will spin up an instance of a different application to handle the rest of the app. All other users with the same code will be routed to this instance.
Note: I have not used docker, and am mostly wondering if this is overkill and there is a simpler application or technology that can handle this sort of room or session-based connection grouping?
@still talon That's heavily overkill, you can easily manage messages from multiple users within a single execution context. Those apps often work via socket.io, which has a rooms system that you might want to look at
Thanks, is there a name for this sort of technology? Just don't know what keywords to use for research (beyond socket.io now)
Looks like messaging, maybe?
I'm not sure. I know Websockets, and general chat howtos are quite helpful for this, at least for me. https://flask-socketio.readthedocs.io/en/latest/ is a good prototyping framework for python, for this, and might serve as a source for keyword fodder
Thanks!
I have a user model that has a ManyToMany for "DayOfWeek" where you choose any one or more of the days of the week.
When I query the DB against other users, how can I display any users that match? Like, all the users that match Monday, or Monday and Tuesday, etc.
If it's just one value, I can handle it, but what do you do in the case of multiple values?
is there any proper, short way in Flask to add an argument to use in Jinja2 templates during a request, for every path?
@app.context_processor
def process_context():
return dict(mode="Development")
example
mode would be injected into every template
@keen sphinx
thanks
so I'm building a websocket server
but when a user logs in, should a client send the raw password for the server to encrypt it and search the database for a match?
you mean in plain text?
if you're using HTTPS it should be enough
the server should just do the hashing part
HTTPS is a silver bullet
it is not unimpenetrable
hash the password client side before sending, apply salt and pepper on the server
@graceful canopy
Nice but how would the server check for matches in the database?
It is the same
digest with sha256, send, apply salt and pepper, check
make sure the base numbers stay the same and you will always get the same result
Okay thanks Iβll look into it tomorrow
an extra layer of security, I guess
but that wouldn't help if someone took control in the middle of the HTTPS connection, wouldn't it
yes it does
never heard of it before, do you have some paper or video about it?
so I can understand what it does in-depth
is this basically browser-specific?
all new browsers support it, if that is what you are asking
Made a working sample from the Mozilla example: https://jsfiddle.net/j4zvnmxf/
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
I guess I did understood but didn't find it that useful
but that wouldn't help if someone took control in the middle of the HTTPS connection, wouldn't it
this still doesn't click to me, if I'm the bad guy I can just tell the client to not encrypt the password at all
it's only useful if something happens to the server itself
(which I admit is not a totally pointless idea, but for most cases it wouldn't do much)
Hi, I'm using flask and have a few design questions.
So I have a mongodb database which has a list of devices and information recieved from those devices. If I want the first webpage to show a list of those devices, and then when the user selects one, it takes them to another page which is customized to show a certain type of graph there, how would you implement this? '~'
@app.route("/all")
def all_devices():
devices = Devices.query.all()
return render_template("all.html", devices=devices)
and below that make a route with id parameter in url
and query by url
Do you know any good Rich Text Editors for the Django? CKeditor is good, but when I asked about the license they said, that for order us to help you, you must first puchase the commercial lisence.
There is TinyMCE, which is available under the LGPL, and CKEditor 4, which is available under GPL3, LGPL, or MPL, or commercial, and CKeditor 5, which is available under GLP3 and commercial
I suspect there's a few others that I'm not familiar with
LGPL permits commercial usage
https://djangopackages.org/packages/p/django-ckeditor/ in there it says Ckeditor is under BSD.
Django admin CKEditor integration.
LGPL, is that where the code must be made public?
no
GPL is where code must be made public
LGPL is where your modifications of the lgpl code must be made public
https://djangopackages.org/grids/g/wysiwyg/ may be helpful
When I use pip install django-ckeditor, which one am I using Ck 4 or Ck 5?
CK4
Where can I check that?
This version also includes:
support to django-storages (works with S3)
updated ckeditor to version 4.9
I can't use the lastest version of the CKeditor, I need to put in the requirements django-ckeditor 4.9.0 or something. Right?
The lastest version of ckeditor is 5.7.1 So I can't use that one under the LGPL
django ckeditor is the python package that adapts ckeditor 4.9, automatically including it within django-ckeditor 5.7.1
CKEditor 5 does not have a stable, clearly installable django package at this moment
This is due to it's large changes: removal of LGPL, and a distancing from the html backend
Hmm... So If I modify the source code of ckeditor then it must be made public?
there is detail, and I am not well versed enough in the license to say
but I believe so
Thank you
I'm looking for a good intermediate-level Web site project that requires HTML, CSS, JavaScript, Python and MySQL. Preferably with the ultimate solution to help me through. Purely to learn. No more shopping carts. π
@dawn drift you can always make a stripped down version of something like facebook, for instance only having functionality for a feature like status posts/comments, or chat
something that implements elements of the page dynamically changing
@native tide Thanks!
make your own framework
Anyone here have experience using flask-ckeditor?
Hey, i am working on Restplus APIs with flask.......my login endpoint is working fine but on logging out .....the auth_token is getting no data
the code for logout API is this :
def logout_user(data):
if data:
auth_token = data.split(" ")[1]
else:
auth_token = ''
if auth_token:
resp = Enduser.decode_auth_token(auth_token)
if not isinstance(resp, str):
# mark the token as blacklisted
return save_token(token=auth_token)
else:
response_object = {
'status': 'fail',
'message': resp
}
return response_object, 401
else:
response_object = {
'status': 'fail',
'message': 'Provide a valid auth token.'
}
return response_object, 403
on logging out it says provide a valid auth token
def login_user(data):
try:
# fetch the user data
user = Enduser.query.filter_by(email=data.get('email')).first()
if user and user.check_password(data.get('password')):
auth_token = user.encode_auth_token(user.id)
if auth_token:
response_object = {
'status': 'success',
'message': 'Successfully logged in.',
'Authorization': auth_token.decode()
}
return response_object, 200
else:
response_object = {
'status': 'fail',
'message': 'email or password does not match.'
}
return response_object, 401
except Exception as e:
print(e)
response_object = {
'status': 'fail',
'message': 'Try again'
}
return response_object, 500
and this is login
where are you getting this data from
i'm guessing your frontend part of the app
it could be that on your logout part your frontend/whatever is giving wrong data
or somehow parsing it wrong
Hi all
Can I request a code review please? Trying to work out Django Rest + React. I'm learning Python with my friend learning React.
Seems like I've done my part (Django Rest) correctly, and he gets code 200 on his end, he can't properly handle the data I'm sending.
So I would like to make sure that I am actually doing everything right on my side.
The program itself is very simple, only 1 application with 2 models.
If anyone is willing to review my code, I'll share it in pm, since it also contains the way to access my local database.
@vagrant adder There is no frontend part i am working only on backend...i will share the controller file code..
@api.route('/userlogin')
class UserLogin(Resource):
"""
User Login Resource
"""
@api.doc('user login')
@api.expect(user_auth, validate=True)
def post(self):
# get the post data
post_data = request.json
return UserAuth.login_user(data=post_data)
@api.route('/userlogout')
class LogoutAPI(Resource):
"""
Logout Resource
"""
@api.doc('logout a user')
def post(self):
# get auth token
auth_header = request.headers.get('Authorisation')
return UserAuth.logout_user(data=auth_header)
Hey, what is a good site to read about workflow in flask?
Django:
template does not load views when the same template is called from other template django
what should I do?
@supple loom https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world is a good place to start
@pliant hound i need to know about workflow only.....i have created my endpoints and now i want to learn how to line them up one behind the other.
Okay
hye, wondering how do I return database that I want, for example name he will return table 1 and she will return table 2 ... right now when i give she it will return both table 1 and 2
even if I give he it will give all the database that already stored
so idk how to say it, but how do I iterate for each name will return their own table
i have a bootstrap form
to collect a user input for a webhook
then use that input to plug it in for
hook = Webhook(INPUTTED WEBHOOK HERE)
how would i do that
<form>
<div class="form-group">
<label for="get_webhook">Enter Webhook</label>
<input type="text" class='form-control' id='get_webhook' placeholder="Enter a Webhook">
</div>
</form
https://pypi.org/project/workflow/2.0.0/#description
does anyone know where to learn how to use this?
The doc seems pretty good, no ?
https://workflow.readthedocs.io/en/latest/
i found them a little hard π
or maybe it wasn't what i am looking for
what should i use for front end development for my API constructed with flask-restplus...any suggestions?
Hi. Does anyone have experience with the development of a multi tenant platform with Django ?
take a look at blueprints @supple loom
they are usually used to organize app a little bit
and for the frontend, you might take a look at vue or react, depends on what your website would do
@vagrant adder i am sorry but blueprints for which problem ?
You asked about a workflow in flask apps
Anyone know why I wouldn't be able to call init_app() on a flask extension?
scss = Scss()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
scss.init_app(app)
return app
``` Doesn't work
Sorry- Scss() comes from the flask-scss package
I keep getting the error:
scss = Scss()
TypeError: __init__() missing 1 required positional argument: 'app'
Take a look at docs, i think you need to specify the flask app as the argument
Never worked with scss but that is my assumption
Yeah, it was working before I tried throwing it in a factory function π¦
Not sure what the fix is now, though
Well, you should look if scss supports factory style
It doesn't look like it supports factory
Hey guys, is anyone familiar with django-scheduler or something similar? I need to make an sscheduling calendar web app in Django, but im stuck. I searched every whole, and it seems that they are lack of documantation for that. JS has "fullcalendar", and im wondering is there something similar for django? (That actually works)
no one? @sturdy sapphire
okay @vagrant adder
can anyone tell me what is the problem in my implementation of token based authorization ? .....coz i am stuck at logout ...logout function is ok but the problem is in token
Hi, anyone here uses django with tailwindcss ?
DJANGO:
What is a good book or web resource I can move into after finishing the Django Documentation tutorial series website, something that's not completely 100% beginner? I have a PDF for Two Scoops of Django but it still seems a bit advanced for me, and I'd like to bridge that gap with a different resource. Does anyone have any suggestions?
O'rilley books
if i need to pass two arguments in my get request .....what is the correct way to do that ?
@vagrant adder
in controller file..where we define routes
tell me later then
you got your code on github?
sure
the first part is route
second is function
idk how to pass two variables in get function
@vagrant adder Can you give me some examples, or at least the author's full name?
changed a bit
"message": "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. You have requested this URI [/movie/movieLanguage/x-men/english] but did you mean /movie/movieLanguage/<title>/<language> ?"
the error message i am getting
i think you put wrong string in your .route()
hi on instagram.com i am trying to scrape user profile data automatically however for the instagram highlights cover, how can i scrape these in their original size? i can only seem to get the size shown on page?
https://www.javatpoint.com/flask-app-routing
take a look at this article @supple loom
Flask App Routing with Tutorial, Environment Setup, python, overview, routing, http method, introduction, application, variable rules, url building, request, cookies, static files, file uploading, mail etc.
@native tide i think that's against ig's tos
Rules
5. We will not help you with anything that might break a law or the terms of service of any other community, site, service, or otherwise - No piracy, brute-forcing, captcha circumvention, sneaker bots, or anything else of that nature.
we cool π
are you allowed to tell if its its possible though lmao
because it would save me a lot of time
i'm not allowed, staff here is really strict about it
i can say you can most certainly acomplish what you want but i'm not allowed to help since it's illegal
oke then i am assuming its not possible π il just go further on without it i suppose
π
why illegal bw? i am not a lawyer?
going against site's tos is illegal
if they say automatization and crawling is forbidden, then it's not really the wisest idea to go against tos
oh i thought "if i can see it, i can use it"
it was just only a small project to enhance my data analitics rather
@vagrant adder i think you put wrong string in your .route()
yes that's what i think too....but idk how else to pass two variables to it
you did it partially correct
take a look at article i sent
you are not defining types of your parameters
CAn i get some help with Flask here?
yes, just say what your problem is
I wanna do something where you open a link and then it loops a string
Is it possible?
I attempted in 3rd route but failed...im assuming you need to return cause its a function
But can you return a loop of strings??
but you could make it return some javascript that generates all of it
yes
you could return it a lot of times, but you can't return an infinite loop without javascript
Does anyone have a working example of a .well-known/acme-challenge/ using Django in 2019 and Python3??
For ACME v2*
hey, i've been trying to setup a website run by flask, and i was wondering how i'd be able to make it publicly available
i know of stuff like localtunnel and ngrok, but ngrok has caps on the amount of users that can be on the site at once and localtunnel is extremely inconsistent (it goes down often)
i've considered setting up my own localtunnel server that runs on the same VPS that my flask site would be running on in order to make it public but there's no documentation or tutorials and the stuff that's available is just hard for me to understand since i'm a novice at all of this web development stuff
if anyone could help me out, i'd really appreciate it. just ping me so that i don't miss your message π
Do you mean public that you can asscess externally or public to the entire web @digital depot
on your host makesure the ports are open (80 or 443)
then pick and setup a webserver for flask (nginx or apache or ...)
then set your domain's A tag to the servers IP address
if you just open the ports you should be able to access the flask site as is going to the browser and typing in the ip address
i tried using the 5000 port and idk if i've been doing it wrong but it wasn't working
i'm using a windows VPS and i just added a windows firewall inbound rule with the specific port and it wasn't working
i'll try again using the 80 port
it didn't work, so i'm going to try using nginx instead
@vague seal do you have a guide for setting up nginx that you'd recommend? just wondering because for a beginner, a lot of the guides i'm looking at are a little bit tough
I have search bar inside admin/app/model . How do I get "GET" the search result. Well the url for the the search result is in the form of admin/app/model/?q=type and I have to put the url pattern : admin/app/model before admin/ which conficts with the model page itself. I just want the search result(query)>.
hey i've a dumb question about flask: if in enable the adhoc auth, i understand it's whack and not ideal because of the certificate changing issue, but will it at least encrypt stuff end to end? what i want to do is just build a secure login page for internal use where i know i can do get/post requests for the login stuff which isn't being sent in plain text
is there a flask community discord or irc that you know of?
There is
Both irc and discord
@digital depot
One question
Do you want to self host it or by someone else
@vagrant adder i ended up figuring it out, but i'm self hosting it
is it on freenode?
also what is it called on irc
and can you link the discord one as well
thank you
much appreciate it
saki i love you
#nohomo
in django how would you get a field that lists all fonts
eg. a post model, and one of the fields is a field where the user can select a font for the post
i'm thinking of using tkFont
π€
i would for loop through all the fonts i want to show taken from the context in the view and then put an id on each font when rendering
then grab the id from the backend
hmm i don't think i would put an id on each font
since you can just use the font name itself
eg. <font face={{ post.font_name }} color="green">This is some text!</font>
in template
you basically need to show all the fonts that user wants and then see which ones they wanted in the backend
so for loop to show all of them on template and then grab them by value or id or anything you want from the backend
as long as you know what they wanted in the backedn youre set
would you say that a flask project more secure than nodejs express project by default?
i don't know much about nodejs
how are you supposed to create a for loop, that iterates through the fonts and also lists them in the dropdown menu?
i want it to be a field
font = models.OnetoOne(fonts, other_fields)
def fontview(request):
return render(request, template, context=font)
#template
{% for font in fonts %}
<div id="font"> font </div>
{% endfor %}
something like that
@native tide
do you get what i mean?
yeah
but when the user creates a post i want them to have the option to select the font of the post via a drop down menu
and when it displays the post (in _post.html, the html file for a post) it will display the font the user also chose
{% for font in fonts %}
<select>
<option value="font">font</option>
<option value="font">font</option>
<option value="font">font</option>
<option value="font">font</option>
</select>
% endfor %}
thats html not python anymore
@native tide you got this boddy!
π
Hey I got the result after clicking on search bar in admin but I want to use this query set in diff views. How to do that??
Django.
Hey! I want to make a website with a user login system where users can add / remove / modify / lookup from a database. Is Django/Flask or other python stuff suitable? I want something really simple, I have a bit of experience with python but not web dev. Should i learn pythonic web dev or is there some other platform that fits better for my needs?
if you want something really simple and easy to work with, take a look at flask
corey schafer has a great series on yt
hey saki i am getting conflict in one function what could be the reason?
it worked
{
"title": "string",
"released_on": "2019-10-24T15:57:11.093Z",
"hindi": true,
"english": true,
}
this is my dto(as it shows in swagger UI).....this true value shows here is saved as false in DB also false is saved as same (means these values is not getting accepted )....and false is the default value(in my model).....capitalizing T and F gave me error....what to do?
i took a way around
what happens when the authorization token expires?
Hello!
I was wondering if I could get some input on this.
I've got an API and a Worker that I've just configured with Docker compose to run separately.
The issue I'm having is that when they run locally on my machine there is no problem using Django's file storage and the default_storage class to perform uploads and downloads.
However when they're deployed separately in docker they don't work
I made a post on this here:
https://stackoverflow.com/questions/58531963/how-to-use-django-file-storage-to-share-files-between-an-api-and-a-worker
I'm confused why I can't retrieve files from the storage file system using the default_storage
What is the idiomatic way for a worker to retrieve something from Django's file storage that does not involve retrieving from the database?
@last lily it depends, in django you can apply CRUD functions quite easily but you'd probably need to take a course to understand django and CRUD. There are a lot of courses for django on udemy and i'm sure there are a lot of tutorial series on youtube. For me, Django projects are very comprehensible even for a person unfamiliar with it.
Idk if this is that much web dev related But When I run my python script with a request.get() I get a remote disconnect Error over And over
It works for a bit And then it stops
Worked last week
I talked with the server owner And he said No issues were seen on his end?
Try requesting to the end point in a different way. Possibly worth checking out postman
i have a stupid flask question: what's the difference between server side session variables and just storing something in a global dict? i know global is normally a byword for 'terrible idea' but in this case it fits, if the user id's are unique, right?
Unless you're using something like flask-sessions, as far as I'm aware flask does not have server side session variables
Since flask applications are often single-namespace applications, then yes a global dict with unique user id's would function as a server side session manager
The session you get from flask is a client-side session stored inside a regular cookie passed back and forth between the browser and your flask application
the docs state
If you have set Flask.secret_key (or configured it from SECRET_KEY) you can use sessions in Flask applications. A session makes it possible to remember information from one request to another. The way Flask does this is by using a signed cookie. The user can look at the session contents, but canβt modify it unless they know the secret key, so make sure to set that to something complex and unguessable.
The key also by default includes a timestamp, preventing reusage of the cookie after (default 31 days) from that date
Hey guys, im just starting out with webdevelopment and have worked a bit with .NET Core for my backend and angular/ts for the frontend stuff. i also did some python before and rly liked the language so i thought maybe python would be a good alternative for my webdevelopment stuff.
i understand that there are a few popular frameworks like django and flask among others in python for this matter, but before i research every single one of them i thought i might as well ask you for recommendations and resources for beginners on that matter. maybe some of you worked with .NET Core and angular before and know of frameworks that would be easier to get into for ppl with that background.
I have worked a bit with .net
I liked flask because it feels like legos, you have a lot of extensions that do something, but you can write apps without much extensions
And django is like a big bag with every single wrench you'll ever(probably) need
Orm, forms, api-like tools etc
Try both then decide i'd say
so that is the "batteries included" thing with django then and flask does not subscribe to that philosophy?
and did one feel more familiar to how things are done in .net to you or are both about the same?
I think django has that .net feel but i really loved flask
You can write a server under 6 lines
ok thank you
so, django seems to be a rather old framework, at least it was introduced over 10 years ago... does that mean it is lacking in some way to newer frameworks or is it just frequently updated?
Nope
flask is amazingly easy to get stuff up and running in literally seconds with
just my 2 cents π
Django was introduced a long ago but dev team is constantly working on it
Both are very powerful and up-to-date.
A lot of big companies are using django
thats good to hear
Google, instagram
The only thing you may decide based on is if you want batteries included or want to build/collect/attach everything yourself.
And my last company used it for their admin panel :p
You'll really get far using django but you might give flask a try
And see what fits your needs
but if i understand correctly they are both backend frameworks, not fullstack
right?
they both do templating i think
Flask doesn't deal with templates afaik. You'll have to use jinja or something for that.
Django does have it's templating system included yes.
oh right, yeah it's through jinja2 but it works well
i mean, i don't feel like jinja was an extra thing i had to go out and 'get' to make flask sites work
Flaks and Jinja are 2 tools working well together. Django and it's templates is the same tool thats works well with itself... xD
Yes
Both are very viable, but I would go for Django if you want something moderately complex working well fast. Go for Flask if you need something very simple or something very complex (that complex so that even Django's customization doesn't cut it).
that is good advice, thank you
Also there are edge cases you may want to take into account.
Pretty often whatever module you use for Flask pretty often can be used with Django too.
On the other hand Django's ORM does not like to deal with document-based DBs like mongodb.
For obvious reasons.
So it very much depends on your particular use case.
i actually have a question about flask, i often see people say never use it in production, use a proper server, does that mean re-doing it in something totally different, or is it just i need to fiddle stuff to get the flask backend to use a different server framework?
im currently using ms management studio to manage my ms sql server if that is relevant @candid basalt
They probably mean don't use flask's development server.
And use some kind of wsgi-capable frontend like gunicorn instead.
Flask itself is more then ok in production.
ah okay
is the dev server just if i have debug on or that's different?
ah just looking at it now i guess not...
I believe so, yes.
The alternative way to start the application is through the Flask.run() method. This will immediately launch a local server exactly the same way the flask script does.
@soft chasm
When you do flask run, flask's own dev server starts and that webserver sucks and should never been used in production
You can use gunicorn to server that same exact app by gunicorn run:app
run -> run.py -> file name where there is Flask instance
And app is Flask instance
I should learn to use django tests, do you know any good tutorials for that?
Django official documentation should be a good start if you know what testing is.
Otherwise you may want to study testing overall first.
is there an up to date official roadmap for django? i found this one here but it is from 2015 and outdated
https://www.djangoproject.com/weblog/2015/jun/25/roadmap/
nvm, found it on their site under /downloads .. did not anticipate it there
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.```
how can I fix this error when I try to add a key:value session
in flask
Sessions are per-user, and as a result they apply to the current request by default
if you try to add to session outside of a request, which session should it apply to?
hi guys
i'm successfully creating a docx with some data on a django. Now i was wondering how could i create a link to make that file downloadable
i don't want the media folder to be exposed on the urls i want to give the user one time url which they will use to download the file
can someone give me what i should look into here
how to pass parameters in redirect() without displaying those parameters in URL?
current code is
@app.route('/check_user', methods=['GET', 'POST'])
def check_user():
uid = request.args.get("uid")
uname = request.args.get("uname")
avid = request.args.get("avid")
return "Your UserID: "+uid+'\nYour Username: '+uname+'\nYour AvatarID: '+avid
@app.route("/authentication")
def authentication():
#some stuff
return redirect(url_for('check_user', uid=str(userid), uname=str(username), avid=str(avatar)))
return reditect(url_for('some_func), page=1, something= "something2")
To not show in url?
Umm
You'll need to redirect to some url and then pass some json data
ok
how do you put a pygame application in a Flask webpage
i want to put my pygame project on my website
???
@native tide It does not work this way
for a game to work with a browser, it needs to written in HTML5
Python is like PHP - a server side language
not a client side one
oh noooo
However, have a look at https://gatc.ca/projects/pyjsdl/
ok, than i want to make a downloadable version. and put the APK on my website for people to download it
Then you have to use Kotlin or Java
Or Unity Engine etc
Maybe you should read up on how these things work
oh well
Have a look at Godot though
So that module
I think that can do Python and transfer to Android
But tbh, those are all just wrappers and you give up a lot of control
turns python code into javascript
basically yes
interesting
But if you want to put a game on Android, I really urge you to use Unity
There is a lot of things about Android you don't know about and Engines take these issues away from you
such as the metric fuckton of resolutions you have to care about
Unity abstracts this by working with relative units
Here, this is what a renderloop looks like in JS
Thought you might be interested
@native tide
it is, you just have to wrap it in requestAnimationFrame()
and there is no guarantee that every frame is rendered
but it is not a while loop, no
for loop it is
Okay, last try asking this..
This is my login code:
@admin_app.route('/admin-login', methods=['POST'])
def admin_login():
uname = request.form['admin-name']
pwd = request.form['admin-password']
user = User
if (db_get_admin_login(uname, pwd)):
user.is_authenticated = True
login_user(User(1))
return redirect(url_for('overview'))
else:
return redirect(url_for('login', il=True))
In the flask login documentation, it says I need to validate the "next" parameter:
https://flask-login.readthedocs.io/en/latest/#login-example
However, such a param does not exist, if I try to print it, it returns None. I am also not using the DB schemas coming with flask or SQLAlchemy. Can I ignore it then? Can someone shed some light here please?
The docs are assuming that you pass a ?next=/next/url to your login form, which allows it to redirect to a new, user-specified destination
you are not doing this, so you can ignore it
The reason they discuss it is if you do that step improperly (since you're not doing it all it doesn't matter for you) ?next=https://google.com/ might work, which would not be a good decision.
Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for.
THanks Bast. Took a load off my mind.
How can i make a html section 100% of view port
i want the #welcome-section element to be 100% of the view port
height = 100vh dosent really work
Hello all
I am new to Flask
I copied a project I began in a computer to my personal PC
i'm now trying to test the application, so I ran
python manage.py test
But I'm getting this error
Traceback (most recent call last):
File "manage.py", line 4, in <module>
from flask_migrate import Migrate, MigrateCommand
ModuleNotFoundError: No module named 'flask_migrate'
Do I need to re-download flask and other dependencies?
Ok. I had to re-install dependencies
How do I convert model.datefield into integer so I could substract 2 date to find the duration between that date
or is there any model that could simplify it? cuz I've been looking at the django model doc and ain't found any solution
@primal drift You can subtract two dates alone to find the duration between, and .total_seconds() the difference for it in seconds
still dosent work @tired root
if you run the free code camp test, the test is still showing up
@native root nvm, I just gave up and use time module, though it will consume lil performance and more code... but it works... thanks for the reply tho π
@marsh canyon you need box-sizing
your padding is adding to your height, making it 100% + 150px
box-sizing: content-box makes the width not contain padding or border
box-sizing: border-box does
if i remove padding how to make the text come down
okay
@soft chasm How do you know I am not?
Because what you don't see is db_get_admin_login and that function is defined like this:
#------------------------------------------------------------------------
def db_get_admin_login(user:str, pwd: str):
#------------------------------------------------------------------------
cursor = get_database().cursor()
try:
cursor.execute("""
SELECT id_pi_settings
FROM t_pi_settings
WHERE backend_username=%s and
backend_password=crypt(%s, backend_password);
""", (user,pwd))
result = cursor.fetchone()
if (result is not None):
return bool(result[0] == 1)
return False
except psycopg2.Error as err:
print(err.pgerror, file=sys.stderr)
return False```
Ah sorry right you are, didn't parse that there was a gen fn call there, my bad
so the only way to put a game on your website
is your game needs to be made with JavaScript
and your website shouldn't be build with flask
is that right?
how do i navigate in a section on the same page using django url tag
example localhost:8000/#section2
how do i get that section 2 and not getting navigate at the top of the page
I want to create a web dashboard for my bot. Is there any recommendation on which framework I should use? And should I write an API or directly access the database?
@native tide No, you CAN build your website with flask, but the actual game must be done in HTML5, which includes Javascript
The actual game is just within a <canvas></canvas> tag
@primal drift You need to set an anchor, like <a href="#section2">TEXT</a>
@azure gyro Either user Django or Flask. Wether you access the database or use a REST API, depends on the general design and if the connection/credentials to the database can be secured.
how to write games with HTML5?
can you give me some suggestions?
for tutorials and such
@tired root
Have a look at Phaser: https://phaser.io/
Desktop and Mobile HTML5 game framework. A fast, free and fun open source framework for Canvas and WebGL powered browser games.
It makes it a lot easier
@native tide
I also recommend typescript over directly using JS
Typescript compiles to javacsript
but allows for more strict typing and better programming
ooooof
What framework is recommended in Python community for Web development? It's kind of tough to choose. I hear about Django, Flask, Connexion, Tornado, etc. It seems like everybody has its own favorite.
hey i'm in an environment where i need to run my py scripts with python3.6 script.py, which works fine except when i try to use gunicorn to run my flask app, any ideas?
i can't seem to get it to point to that python version so a bunch of packages don't load
i have it installed in my pyhton3.6 dist packages
but from memory i also once tried to make my default python 3.6 via bash alias and that broke a bunch of stuff :/
try python3.6 -m gunicorn ...
hello guys
I am having a problem getting my data from my api
it returns null on my console
But I can insert data to my database through POST
console.log(response.data);
}):```
that service returns null
@signal karma
Django and flask are 2 of the most popular, i would say try both of them and see what fits you
@vagrant adder a requirement I am asked for is auto swagger doc generated, any of those 2 supports this well?
ok, any recommendation?
yes
This article outlines steps needed to create a REST API using Flask and Flask-RESTPlus. These tools combine into a framework, which automates common β¦
This is a good article
thx π
Django:
Can i get some logica help here, I need to create a list of objects from the past 12 months, but i need 1 point for each of the months. The currency_data contains a QS of daily objects of the past 4 years
this is what i currently have:
now = datetime.now()
first_of_this_month = now-timedelta(days=now.day-1)
one_year_back = now- timedelta(days=365+now.day)
current_year_filter = currency_data.filter(formatted_date__range=[one_year_back, first_of_this_month])
past_year = []
# get past year data
for i in range(1, 13):
if current_year_filter.filter(formatted_date__month=i).last():
past_year.append(current_year_filter.filter(formatted_date__month=i).last())```
This gives me 12 data points, but it is ordered incorrectly, so here is an example of what i get.
[Jan 19, Feb 19, Mar 19, Apr 19, May 19, June 19, July, 19, Aug 19, Sep 19, Oct 18, Nov 18, Dec 18]
And this is what i am looking for.
[Nov 18, Dec 18, Jan 19, Feb 19, Mar 19, Apr 19, May 19, June 19, July, 19, Aug 19, Sep 19, Oct 19]
Can't you do an order_by on the date column to fix that?
or will it not sort properly due to how the date is formatted?
(which would probably be a good reason not to store dates in such a format to begin with)
the formatted_date is a datetime object so the arrays are a list of datetime objects that i just made readable for the questiion. But i did try an order_by('formatted_date') now but it doesn't seem to work.
I've tweaked the QS a little and im getting better data back, just need do get the order sorted now.
I can't think of why the order_by would fail then
Yeah im doing something wrong somewhere, will add the updated code and responses in a little.
past_year = []
now = datetime.now()
current_day = now.day
one_year_back = now - timedelta(days=365+current_day)
current_year_filter = currency_data.filter(
formatted_date__range=[one_year_back, now]
).order_by('formatted_date')
# get past year data
for i in range(1, 13):
if current_year_filter.filter(formatted_date__month=i).first():
past_year.append(current_year_filter.filter(formatted_date__month=i).first())
gives me
[Jan 19, Feb 19, Mar 19, Apr 19, May 19, June 19, July, 19, Aug 19, Sep 19, Oct 18, Nov 18, Dec 18]```
and im looking for
```[Nov 18, Dec 18, Jan 19, Feb 19, Mar 19, Apr 19, May 19, June 19, July, 19, Aug 19, Sep 19, Oct 19]```
Ah
It's pretty obvious now I think
you use i as the month
and you start at 1
you append in the same order
so of course 1 corresponds to January
Riiiiight, very true, thanks!π let me see if i can work with that
Unfortunately my django chops are not that great
I wonder if distinct() works
but like with formatted_date__month rather than the entire formatted_date
Hmm, its worth a shot, ill have a look
I don't know how that would work with the ordering
if it would respect it and keep the first 1
Oh
oh thats neat.
thanks gonna try that out in the console a little and see if i can work with it.
Thanks @proper hinge Looking a lot better now! π
Np
this ended up giving me what i was looking for
year_dates = current_year_filter.datetimes('formatted_date', 'month')
# get past year data
for item in year_dates[1:]:
if current_year_filter.filter(formatted_date__month=item.month, formatted_date__year=item.year).first():
past_year.append(current_year_filter.filter(formatted_date__month=item.month, formatted_date__year=item.year).first())
hello guys
how can I delete data in my mongodb using model in python
@classmethod
def delete(cls, province_code =None, province_name=None, **kwargs):
self = cls()
province_id = ObjectId(kwargs["id"])
self.__province = self.__db.province.delete_one({'_id': province_id})
return self
that code above says
AttributeError: 'Province' object has no attribute '_Province__db'
@native root says gunicorn is a package and cannot be directly exectued
gunicorn filename:appinstance
@soft chasm
This is what I tried originally @vagrant adder and it fails for versioning issues
This is outside of the scope of web development, but has anyone run into issues with internet connection and the built-in firewall in MacOS Catalina?
The problem started out of the blue for me today. Spent two whole hours on the line with a senior tech who ended up having me ship off logs
While the firewall is active, my laptop is served a self-assigned IP address
the second I turn off the firewall, poof- everything works as expected
fair. Thanks fella π
please what is the equivalent for decimal(8,2) in SqlAlchemy?
I'm declaring models for tables
Would
db.Numeric(8,2)
suffice?
Hello?
Just a sec
The answer i linked is explaining what are those integer parameters
@ebon beacon
@vagrant adder thanks!
π
hello, I am trying to use this library https://github.com/nbubna/store and I am very confused as to why the code in "clear()" only works if i put it in "load()"
https://pastebin.com/qD5wGWf6
<script type="text/javascript">
function load()
{
var cart = store.namespace('cart');
var element = document.getElementById("ingall");
console.log(store.cart.getAll());
element.innerHTML = "Ingredients:".concat(store.cart.get("topping"),"\n\nAllergy Information:");
}
function clear()
{
var cart = store.namespace('cart');
cart.set('topping', "");
load()
}
</script>```
the pastebin is the entire page
The code should work in a onclick event as well
I don't see a reason why this shouldn't work.
he forgot ; on load in clear function but i'm guessing that doesn't matter
A question about CSS: if I set position: relative to the 1st image and position: absolute to the 2nd one, the 2nd image will use the 1st one as a reference, right?
No
Relative/absolute are relative/absolute to their closest non-static parent element
Hi there, I am trying to make a progress bar for my Flask App that is collecting tweets from the Twitter API (using Python). If a hashtag is entered and the user hits the submit button, I am hoping to have a progress bar while tweets are being collected. I have a cap to the amount of tweets being collected so my plan is to track the number of iterations for each tweet and divide that by the cap as my loading bar. I was just wondering how I would go about this, like is there a way to pass python variables into Javascript so that it could maybe update like every 10% or so (better yet continuously). For context, I'm very new to web stuff including Flask and have never touched Javascript. Thanks
Hello
I had a planned to go in Web Development.Do I need to learn the HTML,CSS,JS and OOP of python?
depends on whether youβd want to work with frontend or backend
html, css, and js are used in frontend web dev
so youd need to at least know the basics of those languages
all frontend python web dev uses some form of html/css
though python can be used in backend, along with js
Thanks @safe garden
@lapis stratus If you want to make stuff on your own, in a small team, or are aiming for a full stack job, yeah, knowing them all helps. But these arenβt small things to learn. You can pick up the basics quickly but you arenβt going to be a wizard at them all in a hurry. If youβre aiming more for backend development or any sort of python-specific job at a place big enough to have separate people doing front end and backend, then focusing on the python part is fine, specifically building REST APIs and such and mostly only have to care about the JSON youβre outputting or whatever
What is the error
Hello !, guys im doing a app that generates files based on a web form, for example, i ask the name of the web, generate a folder , a index.html, with the contents of the form.
but they have to load the page again, to make another file, how can i ask, how many pages do you need to create, and add a form asking data for each page?
So I have this, ignore the lines; https://gyazo.com/d02a7a17e87b96098200063b3d081fba
And I am trying to move it down
This is the element: https://gyazo.com/7bf6d69a72ae8efa1ec961234276a78f
This is what I have: (The top part is what I have and doesn't work.) The second part someone else did and adds the background to it
I selected the .widget-area, why is it not moving with top?
Possibly being overwritten by something else. Devtools inspector will tell you. Also not sure what you are trying to do but you probably want to use margins and not just positioning
@gleaming herald you get it working? what's the error?
Hi webdevsπ
What's the difference between id and class? When I'm using css they all look the same
like for example python div#menu { #stuff }
And python div.class_name { #stuff }
Forget the #stuff, I'm getting used to html5 comments :D
@native tide class can and should be reused across many similar elements, id you only use on one element
these days in practicality you should almost never be using ids
for modern js frontends and stuff you may use an id on the root element and that's it
but don't use an id if you don't have a reason to. even if it's for an element that you think "oh i will only have one of these on the webpage". still do not use it
only use it if you absolutely need to be able to target that one specific element for some functionality reason and will never use the same element again somewhere else (there aren't as many situations these days where this is the case)
it also makes css more difficult because there is different specifity applied to ids versus classes and you can get unexpected results
basically just try not to use ids haha
Thank you for the response, I'm gonna use classes now. The tutorial is from 2013 so I guess that's why he was using a lot of id's
oh gosh
i dont know the tutorial you are using but having said that i would probably never look at it again
so much is different, and better
i cannot begin to describe how frequently when debugging with someone it's because they are using a tutorial from a few years ago and everything changed since then haha
at best, you may be learning things that are valid but not necessarily current practices at all (the class/ID thing became especially important after frameworks like React came out... which was probably after your tutorial)
at worst, you could be doing things that just dont work anymore
(for css and stuff, it will all work still. but many newer things have come out since then that will make your life easier)
for myself, i usually filter google searches on tech-related things to results from within the last couple years
π that's good
I'm currently creating a flask tool. But I have tons of <input>'s that the user has to fill in. talking about 100+. And I need to save all those inputs in a database.
But is there a way to do this:
inputField= request.form['exampleInputField']
Much faster? Like instead of doing that for every single input?
@hoary spruce idk about flask, I'm just a newbie, but why don't you create a class for these inputs and then do what you want to do with them? You only need to say what's going to happen with this specific class once.
I guess the concept of classes is the same in any language
You could grab the whole requests.form as a dict I think
@hoary spruce https://stackoverflow.com/a/35625509/12159369
is there a way to extend the background color outside the container? Making just the background color makes it seem like it is getting cut off, I want the white background like 50 MORE pixels to the left and right
with css*
use padding to extend the container
@timid sphinx
padding-left: 50px;
padding-right: 50px;
I really want to advise you against using pixels though. Use percentage or vw/vh
how do i put text that is entered in a form tag in a variable
so i can use it in a python script
let me just say what i want to achieve:
i've made a script that sends emails with flask.
Hey could i get an opinon on this way of 2FA?
class Register(Resource):
def post(self):
parser = register_parser()
args = parser.parse_args()
email = args['email']
tfa_code = str(str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)))
match = mongo.db.registrations.find_one({ 'email': email })
if match:
print('Found')
auth = (mail_settings['MAIL_USERNAME'], mail_settings['MAIL_PASSWORD'])
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(auth[0], auth[1])
msg = EmailMessage()
msg.set_content('Your Authentication Token Is: {}'.format(tfa_code))
msg['Subject'] = "Your psty.io 2FA Code"
msg['From'] = "psty.io <support@psty.io>"
msg['To'] = email
server.send_message(msg)
entry_obj = {
'email': args['email'],
'2fa': tfa_code
}
if not match:
mongo.db.registrations.insert_one(entry_obj)
else:
mongo.db.registrations.find_one_and_replace({'email': str(email)}, entry_obj)
resp = make_response({'msg': '2FA Sent Successfully'}, 200)
resp.set_cookie('email', email)
return resp
class Confirm(Resource):
def post(self):
parser = confirm_parser()
args = parser.parse_args()
tfa_code = args.get('tfa_code')
cookies = request.cookies
if not cookies.get('email'):
return redirect('https://psty.io/signup', 200)
email = cookies.get('email')
register_obj = mongo.db.registrations.find_one({ 'email': email })
if tfa_code == register_obj:
resp = make_response({'msg': 'Logged In!'}, 200)
resp.set_cookie('authentication_code', auth_code)
return resp
else:
return { 'error': '2FA Failed!' }, 302```
from flask import Flask, render_template
app = Flask(__name__)
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAX_EMAIL_SENDER'] = 3
app.config['MAIL_USERNAME'] = 'testkenny00@gmail.com'
app.config['MAIL_PASSWORD'] = '###########'
mail = Mail(app)
@app.route('/')
def index():
msg = Message('This is a test send email', sender=('kenny', 'testkenny00@gmail.com'),
recipients=['hoftkenny3@gmail.com'])
# msg.body = "testing the email sender"
msg.html = "<b> this is a tested email for me to test testing</b>"
mail.send(msg)
return render_template('play.html')
if __name__ == '__main__':
app.run(debug=True)
you need a request parser
def register_parser():
parser = reqparse.RequestParser()
parser.add_argument('email', required=True)
return parser```
and then i call it like this inside my class:
class Register(Resource):
def post(self):
parser = register_parser()
args = parser.parse_args()
email = args['email']```
i want to take tha variable from my html script
yes
in your HTML
post the form to your URL with the endpoint for sending the email
have the variable be an input in the form with the prop name='email' or somehting so this would be the email argument
the name part i get, but the rest seems
Your 2FA code seems alright, although there are two issues from what I can see. First is that email is not the best--allowing attachment for something like lastpass authenticator or something might be better. The second is less opinionated, which is that you don't seem to have a reset/ratelimit. Someone can repeatedly try to guess the auth code without triggering a lockout or a code reset
Why not use TOTP seeds like the rest of the world?
(you don't have to answer, it might be a dumb question)
this is for free passwordless accounts that aren't paying for any special services except storing pastes for longer than 1 day, so im not really trying to make it that robust for features for that side. im planning on adding a subscription based account tier eventually with much more capabilities and that will actually have a password and what not so i would have OAuth options there for login with.. type deals.
also keeps the space taken up on my free mongo instance low 
I see, so it's not the kind of thing a lot of users would be willing to set up TOTP storage for.
Sounds neat, though - I gave Pastebin money, so it's a good business idea
https://psty.io (not tryna ad just show u) this is the site
psty.io is a free and open source temporary pastebin and file hosting service. Business plans available for permanent usage.
its basically just pastebin but with file hosting as well
and im about to do a huge overhaul, ive overhauled the backend so now im just adding new features and eventually new UI
dont trash the UI i made it in 45 minutes its trash ik
Neat!
So I have Billing and Shipping on the left, then payments on the right. I am using wordpress and swapped themes which caused this. At first it was Billing on the left, Shipping on the right, then payments below it. Is there a way using CSS to swap it so shipping is below them and shipping is NEXT to billing
Example, ignore the lines https://gyazo.com/cd13a9492fd98fa0c2400f5d9848d0e5
{% if data['format'] == "mp3" %}
<option selected value="mp3">mp3</option>
<option value="aac">aac</option>
<option value="ogg">ogg</option>
{% elif data['format'] == "aac" %}
<option value="mp3">mp3</option>
<option selected value="aac">aac</option>
<option value="ogg">ogg</option>
{% elif data['format'] == "ogg" %}
<option value="mp3">mp3</option>
<option value="aac">aac</option>
<option selected value="ogg">ogg</option>
{% else %}
<option selected value="mp3">mp3</option>
<option value="aac">aac</option>
<option value="ogg">ogg</option>
{% endif %}
``` Anyone got a prettier way to write this? I doubt it, but maybe I overlook something
Can you do something like
{% for format in ('mp3', 'aac', 'ogg') %}
<option {% if format == data['format'] %}selected {% endif %} value="{{format}}">{{format}}</option>
{% endfor %}```
not sure if you can define a tuple like that in a template
it doesn't handle your default case, though
so ununderstandable
@timid sphinx they are removed everynight at Midnight EST
so unless somebody fills up 1TB in 24hrs
im good
thats why i have rate limits lol
Is using pandas for data operations in a full stack web app a terrible idea? Let's say target data is complicated enough to be annoying to handle without dependencies, but wouldn't be impossible either
What is best way to do frontend for blog ?
I am using Flask as backend and Postgres as database and I need suggestions
Its been botering me and I cannot figure out what to use
I am scared of javascript tbh
You can do a blog in just plain HTML and CSS easily - use CSS grid and you can even make it responsive
really ?
I was thinking about combo of Vue.js + Bootstrap
since I really like to work database, server, backend
devops stuff
@native tide I recommend doing a static blog. The issue with dynamic blogs is, that your attacker has a lot of angles to attack you. I myself use Jekyll for my blog and it serves me well. I have basically my own github pages at home, with a git server on my NAS and a post commit script that runs Jekyll on my Pi to generate the site and then uploads the changes to my webserver via SSH. The attacker has no angle to actually attack my blog, since it is all HTML only. Sure, he can attack the web server, but that is out of my hands. The issue you run then into, is the search, but I have written a REST api point for that and Jekyll generates a SQL file with the content and there is a database for that. But it is so tied down with read only access, an attacker cannot insert anything, even if he got control of the user, because it has no rights to insert anything. So he needs to hack the server, if he wants to do bad things.
Overall, using a static blog served me well and I cannot recommend it enough
There are also static blog generators in Python: https://getnikola.com/
This is my automation script, in case you are interested: https://hastebin.com/cohoguqiki.bash
@tired root I would recommend you to use CI/CD pipeline and replace that script
Uhm, this script is basically a continoous deployment script
working π