#web-development
2 messages · Page 56 of 1
What kind of use cases @lofty matrix ?
I make and host different projects for different clients. They are all generally based around the same code base, but with client specific needs implemented on each. Each client has a subdomain of my domain like client1.example.com. This points to an AWS load balancer, where the hostname is used to route traffic to the corresponding target group. Each project has one or more EC2 instances in a target group. It's working, but I have some concerns with load balancers not having the ability to reference an infinite number of target groups, some clients want to use their own domain, which requires a certificate to be added to the load balancer, and EC2 load balancers have a limit of 20 certificates. Also there's the issue of being able to patch, do rolling deployments, etc across all of these different but similar projects in the same infrastructure in a manageable way
At some point I'd look into Colo instead of cloud
A cluster can work a lot more efficient than a lot of cloud servers tied together
Also, instead of reverse proxy, you can use IP forwarding, effectively not having to worry about the certificate limit
BUt then each instance is under more load
Is this Python wsgi servers or php, fastcgi?
well the load balancer is proxying traffic to the EC2 instances, then each instance runs nginx to proxy to the application
So a mix of Layer 4 and Layer 7 balancing
The first load balancer is Layer 4, it ip forwards, the one behind is layer 7 as it fetches the website for the client
each client has a different version of the same application?
not the same application, which makes it confusing. They share libraries I've written that handle a lot of the common functionality between projects
I'm confused on why you're using the same domain/LB at all if they're different apps
@cold anchor It is very common, the client can still put another domain on it as cname or A/quadA record
At my last job, we had something similar, a bunch of webshops running off the same code
But we used a Linux cluster with roundabout 20 servers
IN a Colocation setup
FUnny enough, I work now in that very datacenter they have colo in
😄
That happens when you refuse a raise
but 😛
sorry
One reason is cost; it's cheaper to have 20 clients on 1 load balancer than to have 1 client per load balancer. Each client individually doesn't have much traffic. There's also a gateway instance in the VPC that handles some of the configuration management/deployment esque tasks
It's good enough to have one load balancer to serve many clients
if it can handle the load
But something you've never said: Where is your bottleneck?
I can give you general advice, but I am curious where your issue is right now
also re: limits on the number of target groups, here's some info https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-limits.html
Learn about the quotas for Application Load Balancers.
looks like 100
It's not really a performance bottleneck. I want to be able to continue taking on client projects without worrying that at some point, I will hit a limit of how many taget groups/certificates/domains I can have, and I will have to re-think everything. It's also that I would like to manage all of them in the same way
I don't know how much you make, but at some point look into having root servers, but it increases the administrative workload
pros and cons
and further down the road colocation in a data center nearby
WHich requires an investment of a lot of money
alternatively if you can turn the differences in client implementations into just something you or they can configure, you don't need to use new servers for each or worry about load balancer limits
What do you mean by root server, scorcher? DNS?
@lofty matrix Dedicated root, it means you rent the whole hardware and the server hardware is exclusive to you
You only get an OS supplied by the DC it is in
Colocation means you put your own hardware into a rented rack
rdbaker do you mean similar to a product like gitlab, where each enterprise client has their own configuration of roles and things like that, but the product is just "gitlab"? I've thought about that, but I don't think I could make the functionality generic enough for that
scorcher, each client uses one or two of some of the cheapest EC2 instances, so it's like $20/month to host, and the clients absorb that hosting cost. I think in this case dedicated hardware would just add complexity
It's something to consider and you need to make that call. A whole dedicated root server costs about 40€/month plus traffic and an IP, but it may be worth it
but again, I can only give pointers
If cloud is still enough, then stick with it
Since nobody responded yet, ill just drop it here again for relevance :'D sorry
Django:
- When i use the .save method of my ModelForm, i think the .save method of my reference Model gets called.
I already overwrote the save Method of my Model which worked perfectly. Now i want to make the ModelForm call a "first_create" method that is an extended version of my overwritten .save method of my Model. This does not work though. (https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/#the-save-method) i couldnt find anything about this here. - Is there a way to pass a javascript variable back with my form without displaying a formfield ? Like a hidden field i can populate with javascript, depending on on site conditions that then gets submitted with the rest of the form ?
@lofty matrix yeah, sort of like that- it's what I did on the last whitelabel product I launched (https://www.drift.com/product/landing-pages/) and it made these types of issues disappear because all clients used the same backend, just a highly configurable version of it
rdbaker, so you're just running one application (accross multiple server/instances), and clients have separate logins and api tokens and billing and such, correct?
yeah exactly
then the app they interact with is just static JS hosted by a CDN and the configuration is fetched based on the domain and we point *.ourdomain.com to the CDN
Yea, unfortunately I can't generalize my use cases like that
dang, then yeah, the last time I had to do something similar we ended up creating new "stacks" per customer and would build the expense of it into their bill, lucky for us though, customers were high-touch and paid a lot
cough
Since nobody responded yet, ill just drop it here again for relevance :'D sorry
Django:
- When i use the .save method of my ModelForm, i think the .save method of my reference Model gets called.
I already overwrote the save Method of my Model which worked perfectly. Now i want to make the ModelForm call a "first_create" method that is an extended version of my overwritten .save method of my Model. This does not work though. (https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/#the-save-method) i couldnt find anything about this here.- Is there a way to pass a javascript variable back with my form without displaying a formfield ? Like a hidden field i can populate with javascript, depending on on site conditions that then gets submitted with the rest of the form ?
@onyx crane
is there something wrong with my flask route?
@app.route("/bookmarks/<int:id>/delete", methods=["DELETE"])
def delete_bookmark(id):
I keep getting 404, all of my other routes are working fine except for this one.
Let me know if I should provide any other info
@tranquil robin No error?
127.0.0.1 - - [30/Apr/2020 20:41:28] "DELETE /bookmarks/1/delete HTTP/1.1" 404 -
So there is no error? That might mean your function code is incorrect.
its not seeing my route at all, thats the problem
does the flask routes command show your route correctly?
god, guess I need to take a break, it was an extra tab indentation -,-
Where?
i have been trying to fix it for 1 hour -,-
in the line of code before the route -,-
jinja2 fail.
I tried to have it programmatically generated. so I didnt even have to write the conditions more than once and could easily change the values of the bottons and icons. But ehh... Seems like jinja2 doesnt know how to render jinja2 given to it to render after it is done rendering the first time.
Looked a little something like this
You live and learn
Its probably one of those situations wheere you try to not repeat yourself and avoid hardcoding to the extent that you waste time on something you will never change or want to change.
(...maybe)
how do i setup a ddos protection loading page
that tells the user to wait 5 seconds
you know.
I'm pretty sure its more effective to monitor server logs and set up automated ip bans.
Not that i know how to qualify what deserves that...
Unless you're just trying to make people look at ads. 😛 But that isnt to protect against DoS
can some one help me i cant disable flask's anoying logger
ex. 127.0.0.1 - - [2020-04-30 22:32:30] "GET / HTTP/1.1" 200 2255 0.015633
the code i tried:
website_app = Flask(__name__, static_folder=path.abspath('./libs/templates/static'))
log = getLogger("werkzeug")
log.disabled = True
website_app.logger.disabled = True
nvm i have fixed it
changed
http_server = WSGIServer(("0.0.0.0", SETTINGS["PORT"]), website_app, backlog=False)```
to
```python
http_server = WSGIServer(("0.0.0.0", SETTINGS["PORT"]), website_app, backlog=False, log=None)```
you could also remove the logging handler:
website_app.logger.removeHandler(website_app.logger.handlers[0])
thanks
do you guys now how can i catch KeyboardInterrupt
Traceback (most recent call last):
File "C:\Users\coolguy\AppData\Local\Programs\Python\Python37\lib\site-packages\gevent\_ffi\loop.py", line
234, in python_check_callback
def python_check_callback(self, watcher_ptr): # pylint:disable=unused-argument
KeyboardInterrupt
2020-04-30T19:41:35Z
i have tried
try:
http_server.serve_forever()
except KeyboardInterrupt:
print("")
error("closing!")
_exit(0)
its working actually but when closing it just prints that
do you want to catch a keyboard interrupt or an OS level kill signal?
keyboard interrupt
hey all, I got a pretty stupid query that is giving me a lot of lengthy response times, especially when on heroku.
I'm wondering if anyone have tips to optimize?
that has the generated query, the view, and the models
How can i save this information on my server somewhere?
Write it off to database
How lol
@tiny siren What are you using for this app, flask/django?
any of u huys know how to use pyngrok in termux
ngrok works fine but pyngrok raises The ngrok process errored on start error
@feral minnow django
@tiny siren I don't have experience with django but you can have a look here https://docs.djangoproject.com/en/3.0/ref/databases/ you can search to see what the easiest one to start I think its sqlite because I use it in flask, I didn't dive to deep with databases but sqlite is fine and simple for now, anyway if you're a beginner with web development I would recommed flask because people says that flask will teach you how things works , but django will save you more time and I think its easier than django.
I am interested in making a website using Python. But the one thing that I am not sure to use is Django or Flask. I am more of a beginner as I have only been learning Python for about 5-6 months. If anyone has some suggestions or advice for me, please tag me.
@sharp plaza Flask is better to start than django, its easier im saying that from my experience with flask and what I read about them, so Flask is more straight forward and will make it easier to understand how things work, Django has more built-in functions so it will save you some more time , So go on start with flask and after spending sometime with it you can move to Django
Ok, thank you very much! 🙂
Welecome 😀 , and if you don't know where to start here's a tutorial https://www.youtube.com/watch?v=mqhxxeeTbu0&list=PLzMcBGfZo4-n4vJJybUVV3Un_NFS5EOgX, I started with it his explainstion is pretty good
Welcome to the first flask tutorial! This series will show you how to create websites with python using the micro framework flask. Flask is designed for quick development of simple web applications and is much easier to learn and use than django. If you are less experienced wi...
Amazing! Tech with Tim! I was just going on his channel to look for Flask tutorials! 😄
Good luck man 😄
Just finished that series - it's pretty good but he sucks at naming things
Also what are everyone's thoughts on Django vs flask?
Flask is simple and a nice place to start for beginners
Django is complex, but completist - it covers most everything in some form
That said, Flask has a lot of add-ons that allow its functionality to be expanded
@long forge
I see. How does a plug in equipped Flask compare to Django in terms of security?
Assuming you run security plug ins
I'm using django-import-export library,
when the user uses the import function, I want to ignore all new records, any ideas ?
example :
https://ibb.co/sq8QpB6
some how i need to override django-import-export library so I can skip the new "records"
hey, I have a flask project that worked quite well but the virtualenvironment was full of libraries that werent necessary anymore. so I deleted all dependencies and only installed those again, that are necessary for the project
Now I redeployed it again and everything works in production and uses less ram. But on my local machine i cannot open it for testing
this is what i get in the cmd:
127.0.0.1 - - [01/May/2020 12:14:21] "[32mGET / HTTP/1.1[0m" 302 -
127.0.0.1 - - [01/May/2020 12:14:21] code 400, message Bad request version ('Ð\x96U\x8a\x02ÛÀ\x15µ¿\x04Vö]\x8b\x8bü«÷Ôc³k\xadOÜ{C\x16¶0\x9a\x00"**\x13\x01\x13\x02\x13\x03À+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x00')
127.0.0.1 - - [01/May/2020 12:14:21] "[35m[1m üï¼Êå]Nð«sÍíX`cêZÀµK ÐUÛÀµ¿Vö]ü«÷Ôc³kOÜ{C¶0 "**À+À/À,À0̨̩ÀÀ / 5 [0m" HTTPStatus.BAD_REQUEST -```
i guess something is wrong with the SSL but how can I fix it so that I can also run it on my machine without SSL?
Do I need some local environment variable that bypasses the HTTPS?
I don't see any ssl there.
It runs on http, so if there is no reverse proxy or something on top of it - there is no ssl to worry about.
Do you have nginx or something on top of it?
well I do have ssl in production. and there everything works. but locally I can not run the app anymore.
I use flask-talisman with this code:
'default-src': [
"*",
"'unsafe-inline'"
]
}
talisman = Talisman(app, content_security_policy=csp)```
What do you perform requests with?
now i can make it work if I comment out the talisman line.
what do you mean with requests? If I use http or https?
Oh. Talisman:
Forces all connects to https, unless running with debug enabled.
So set it to debug mode for local dev and you should be fine.
Welcome.
You are very welcome.
Hi anyone knows how can I extract the price on this website https://eu.shop.battle.net/en-gb/product/call-of-duty-modern-warfare
by xpath
I have a PHP script that works for simple xpaths
for example on Amazon I use this xpath for the price: ``` //span[@id='priceblock_ourprice']
and it's works..
but the battle net is different.. //span[contains(text(),'59.99')]
:/ aand it doesn't works.. any idea?
Which is more easier flask or node js
Using Flask and
@app.route("/login", methods=["POST", "GET"])
def login():
if request.method == "POST":
user = request.form["nm"]
return redirect(url_for("user", usr=user))
else:
return render_template("login.html")```
Django is no joke haha
like relearning a new language 🙂
Anyone here switched from a framework such as Laravel to Django and found any benefits?
Does anyone know if I can use Flask to render a game from pygame onto the web?
Does anyone know if I can use Flask to render a game from pygame onto the web?
@cold socket you can't do that
How come when i press this button locally it works and when i upload it, it doesn't?
pygame & web applications are whole different things
Can anybody help me with this issue
lol u mad @tiny siren
youre going to have to do some troubleshooting on your end
open chrome/ff dev console
track down whats going on
can I ask a WAMP question here?
@tiny siren you can try posting the errors, but without any code or errors not much can be done
WinAmp was my favo mp3 pllayer
nvm, found my answer
.Can anyone here help me with formsets on django?
['ManagementForm data is missing or has been tampered with']
Getting this error...been trying to troubleshoot but no luck yet
Does anyone have any idea on how to solve this 👇
https://stackoverflow.com/questions/61548485/django-import-export-how-to-skip-the-new-rows-and-only-update-the-existed-one
I think there is a builtin onchange() function that might be worth looking into
Hello, i'm trying to save a file which is uploaded using FileField (Flask), heres my code video_form.video_file.data.save('uploads/' + filename) But it says AttributeError: 'str' object has no attribute 'save'
Any help I could receive?
yes .data is required because otherwise this will be in the traceback instead
AttributeError: 'FileField' object has no attribute 'save'
Im reading the doc but im not seeing anything about data
I got my code from this stackoverflow https://stackoverflow.com/questions/14589393/how-to-actually-upload-a-file-using-flask-wtf-filefield
tho its 7 years old
you want to save the file to somewhere in the clients device ?
or you want to give them the option to choose?
so something like recive a file from the client or download it directly from another site
mate its a website, they upload the file and it will do a post request and my server gets the file in the request and downloads it and stores it on my end
just use .save try it I don't think you need .data
I did and this was the response
AttributeError: 'FileField' object has no attribute 'save'
im trying to open lots of tabs on chrome as i need the random string at the end of the website any way i can do it out of chrome
@cerulean pelican maybe this will help,https://stackoverflow.com/questions/27611827/attributeerror-filefield-object-has-no-attribute-file
I'm new to Flask. I wanted to create a very basic site which allows to upload the images.I found the manual, however I wanted to make it slightly different. Here's my code:
###main.py
import os
f...
@lament moss What you mean with random?
You can get the url string without opening the taps, but if you want to do both you can or you meant a random string in the website content?
Anyone here good with formsets?
Hello, does someone know a website that store covid datas ?
API or website @solar hatch
does anyone know if data from admin.py gets sent or is just representing data from the db because im trying to query it and for some reason i cant use .filter() or any of that, the only thing that works is .all()
django btw
I have this Resource:
class RatingsResource(Resource):
def get(self):
try:
ids = request.get_json()['articleIds']
except Exception:
ids = None
rating = Rating.objects(article_id__in=ids)
return rating.to_json(), 200
The JSON returned is being escaped:
"[{\"_id\": {\"$oid\": \"5eab76b49121a126eed50eef\"}, \"user_id\": \"854c9a9b-4a4a-410f-867c-9985c17878d8\", \"article_id\": 1, \"created_at\": {\"$date\": 1588280739226}}, {\"_id\": {\"$oid\": \"5eab7c279121a126eed50ef0\"}, \"user_id\": \"854c9a9b-4a4a-410f-867c-9985c17878d8\", \"article_id\": 1, \"created_at\": {\"$date\": 1588280739226}}, {\"_id\": {\"$oid\": \"5eab8a709121a126eed50ef1\"}, \"user_id\": \"854c9a9b-4a4a-410f-867c-9985c17878d8\", \"article_id\": 2, \"created_at\": {\"$date\": 1588280739226}}, {\"_id\": {\"$oid\": \"5eab8b389121a126eed50ef2\"}, \"user_id\": \"854c9a9b-4a4a-410f-867c-9985c17878d8\", \"article_id\": 2, \"created_at\": {\"$date\": 1588280739226}}, {\"_id\": {\"$oid\": \"5eac4fbd9121a126eed50ef3\"}, \"user_id\": \"854c9a9b-4a4a-410f-867c-9985c17878d8\", \"article_id\": 1, \"created_at\": {\"$date\": 1588280739226}}, {\"_id\": {\"$oid\": \"5eac7e08d5f3c28020d0755d\"}, \"user_id\": \"854c9a9b-4a4a-410f-867c-9985c17878d8\", \"article_id\": 3, \"created_at\": {\"$date\": 1588354045805}}]"
Anyone know why?
This fixes it: json.loads(rating.to_json()) - but does not seem good
hey guys, just made it
Link: https://github.com/ngeorgj/fast-flask
it's an far cousin of django for flask projects,
it create an editable structure with the boring part
hope it's useful to you guys,
please rate it if you can
@native tide Can help with your wtforms question if you still had some!
yes pls @outer apex !!
ok so i want to do a form that uses selectField
so like dropdown
yup
ok so
class TestForm(FlaskForm):
unit = SelectField('Unit Type', [DataRequired()], choices = [('python','CITS1401'),('dsa','CITS2200'),('ai','CITS3001')])
testtype = StringField('Type', validators=[DataRequired()])
i've got this
i just dont know
how to access this in jinja2
{% block content %}
<form class="login" action="" method="post">
<h2>Choose your test</h2>
<h4>Select from the below options</h4>
<div class="field">
{{ form.unit.label }}
<span class="form-error">{{ error }}</span>
</div>
```
what you mean?
Oh, just {{form.unit}}
Well, label is handy too, since you'd want to label it
We've seen people writing wtforms on the Python side and not harnessing its power in the template. I think @tired root was referring to an instance like that.
oh ok
appreciate the help!
btw
for QuerySelectField
what import does that fall under?
<form class="login" action="" method="post">
I hope you are adding some path to the action here
Hi people, I was asp.net programmer at 2000. I used mostly vb.net. I did a long brake for programming.
So nowadays i want to return to web development for my personal website. I want to learn & use Python.
But i have some questions before starting & i couldn't find any answer for these on the internet.
So here are the questions:
1- Is it possible web development with Python "without installing frameworks"? (for example Django, Flask or whatever)
I want to install only Nginx and Python. Is it possible?
2- In PHP coding in HTML possible, but is it possible in Python?
For example is there a syntax like this in Python?
<html>
<title>Hello World</title>
<body>
<?php echo "Hello World!"; ?>
</body>
</html>
3- If these are possible where can i find tutorials? When i tried to find tutorial all of them was Django or any other frameworks.
Note: Sorry for my bad English. I know it's not well and i sorry for that : )
1-no 2-yes 3-corey schafer
thanks a lot : )@polar nova
I have a problem with Jinja and Flask-wtf: Is it possible to use a variable inside a variable?
{{ form.keyword(class_="single-input-primary", value="{{pre_keyword}}") }}
{% else %}
{{ form.keyword(class_="single-input-primary") }}
{% endif %}```
In this case I check if the variable pre_keyword is passed to the template. if it exists the input field should be prepopulated with it -> value = {{ pre_keyword }}
Unfortunately it literally renders "{{pre_keyword}}" in the template since the whole input is a variable
how can i prefill the form with a variable?
Was wondering about logging best practices for a Flask application that ideally should be deployed on GCP. I'd like to gather some opinions on:
- Logging directly to Stackdriver
- Write/find a handler to log to a MySQL db
- Log to a file written inside the container
Stackdriver or DB, containers should have nothing in them that isn't instantly disposable
@zealous siren Forgot for a moment about that golden rule.
I'm leaning towards dropping a text file in a storage bucket vs. Stackdriver
that's fine too
it's less useful then stackdriver but probably less costly as well
hi how do you make a redirection in django
I was just wondering if it is possible to make an online game using Flask? When I say online game, I mean games like surviv.io, agar.io, krunker.io, etc.
Cifer, not really
You can write backend but you need JS for browser part
And you need Websocket support so hopefully Flask supports that
I am new to flask and I'm trying to pass form data from one route to another... Here's what I have: ```py
@app.route("/index", methods = ["GET", "POST"])
def index():
coffeeForm=CoffeeForm()
if coffeeForm.validate_on_submit():
return redirect(url_for("order"), coffeeForm)
return render_template("index.html", form=coffeeForm)
@app.route("/order", methods=["GET", "POST"])
def order(coffeeData):
return render_template("order.html", form=coffeeData)
The order.html will just display the order in a table.
Would it be better for me to create a list containing the data from coffeeForm and pass that, rather than trying to passing the actual form?
@knotty seal if you want to get data from another function you gotta use "sessions"
so something like this session["coffe"] = coffeeForm.theformyouwanttogetdatafrom.data
then you will go to order
coffe = session["coffe"]
and if you want to use a list you can also
So do I need to pass the data to the view function
def order(coffeeData):
return render_template("order.html", form=coffeeData)
Or is the form global?
you put the form in index.html right?
That's right
def index():
coffeeForm=CoffeeForm()
if coffeeForm.validate_on_submit():
session["coffe"] = coffeeForm.theformyouwanttogetdatafrom.data
return redirect(url_for("order"))
return render_template("index.html", form=coffeeForm)
@app.route("/order", methods=["GET", "POST"])
def order():
user_coffe = session["coffe"]
return render_template("order.html", form=coffeeData)
I have actrually changed the index view function now to create a list...
@app.route("/index", methods = ["GET", "POST"])
def index():
coffeeForm=CoffeeForm()
if coffeeForm.validate_on_submit():
coffeeData = [coffeeForm.drink_type.data,
coffeeForm.milk_type.data,
coffeeForm.sugar.data,
coffeeForm.extras.data,
coffeeForm.email.data,
coffeeForm.username.data,
coffeeForm.payment.data]
return redirect(url_for("order"))
return render_template("index.html", form=coffeeForm)```
yup you can create a session and store a list inside it two, so session is like a "variable" that you can get its data from every function.
coffeeForm.milk_type.data,
coffeeForm.sugar.data,
coffeeForm.extras.data,
coffeeForm.email.data,
coffeeForm.username.data,
coffeeForm.payment.data]```
Do I need to install Flask-Session for this?
from flask import session
Hmm. Okay
I didn't install it but maybe you have too idk
I think it was downloaded automacily when I installed flask
This will be interesting. I'm just testing it
yup its useful
@feral minnow I love you and would like to have your babies.
😛
Also, thanks - I got it working.
wtf
Ah np... Welcome (:
https://www.shadertoy.com/view/WsXfDN
Mandelbrot using reflect transformation WebGL
Hello, I'm wondering of how I could get this piece of code but inside a FlaskForm? ```
{% for genre in genres %}
<option value="{{ genre.name }}">{{ genre.name }}</option>
{% endfor %}
thats inside my html file which contains my jinja2 syntax
this is my form
class VideoForm(FlaskForm):
"""New Genre Form."""
title = StringField('Title', validators=[validators.Length(min=3, max=75)])
# genre = SelectField('Genre', [DataRequired()],
# choices=[Genre.query.all()])
description = StringField('Description', validators=[validators.Length(min=10, max=250)])
video_file = FileField('File')
submit = SubmitField('Upload')
If i send somebody my html code would they be able to fix it for me? I've been trying for a day
( The problem is that when i upload the file to host, the dropdown context button stops working, and idk why )
@tiny siren Just send it here
I'm relatively new to Flask. I have integration tests. In node apps I have written, I can prepend NODE_ENV=test onto the test command. In python with unittest, can I do this?
Currently I am using flask.config.from_object
The button doesn't work
@cerulean pelican What are you trying to achieve? Are you trying to render the choices for genre as dropdowns?
I am using Django 3.0.5 with a PostgreSQL database. I want to rename the field called first_name to fname. I believe I have to use the AlterField() operation, but I am not sure how to do so. Anyone have any experience with this?
class Contact(models.Model):
first_name = models.CharField(max_length=50)
https://docs.djangoproject.com/en/3.0/ref/migration-operations/#alterfield
@candid gull You could create a new object with config relevant for testing, and get your app's instance to use that.
https://flask.palletsprojects.com/en/1.0.x/config/#development-production
@outer apex I have done this.
class Config(object):
DUBUG = False
TESTING = False
MONGODB_SETTINGS = {
'host': 'mongodb://root:example@rating-service-db:27017/rating?authSource=admin'
}
class ProductionConfig(Config):
pass
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
TESTING = True
MONGODB_SETTINGS = {
'host': 'mongodb://root:example@rating-service-db:27017/rating-test?authSource=admin'
}
However, how do I tell my tests to use the testing config? I currently have this:
if app.config['ENV'] == 'production':
app.config.from_object('core.config.ProductionConfig')
elif app.config['ENV'] == 'development':
app.config.from_object('core.config.DevelopmentConfig')
else:
app.config.from_object('core.config.TestingConfig')
Can I change the env in the base test?
@native tide How about using migrations that comes with Django?
https://docs.djangoproject.com/en/3.0/topics/migrations/
that's exactly what i am using
anyway, i think i found the answer
gonna try now and will report back
@candid gull How are you instantiating your test client?
@native tide Good luck. Back up if data is important!!
@outer apex I am using Docker - So I am running the tests inside of Docker. This is the issue - I am setting FLASK_ENV to dev - and I dont want to keep restarting the container when testing. In node, I can just prepend NODE_ENV onto npm run test as an example... Can I do this in Flask/Python?
Am I making sense?
@candid gull That makes sense. I think you could set app.config directly, like app.config['ENV'] = 'testing', before you run the tests
@outer apex So I did this:
def setUp(self):
app.config['FLASK_ENV'] = 'test'
Does not work though...
@candid gull Looping back a little, what are you hoping to happen after updating ENV? What are your expected results?
How is app defined and are you importing it from the module it is defined in?
@outer apex I want to change the database connection
My app:
app = Flask(__name__)
api = Api(app)
if app.config['ENV'] == 'production':
app.config.from_object('core.config.ProductionConfig')
elif app.config['ENV'] == 'development':
app.config.from_object('core.config.DevelopmentConfig')
else:
app.config.from_object('core.config.TestingConfig')
init_connection(app)
init_routes(api)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
I see. You're using the instantiated app to run your tests. So setting the ENV here won't update the remaining config variables.
You could update the database connection directly.. app.config['MONGODB_SETTINGS']. Not "clean" but get's the job done..
If you just want to change specific config, changing it directly works. Like this database connection scenario.
You could also adopt the factory pattern. Put all this instantiation process into a function, and wherever you need that app, call that function
app_factory
def create_app():
app = Flask(__name__)
...
return app
main
from app_factory import create_app
app = create_app()
test
from app_factory import create_app
app = create_app()
Note how you can create different app instances, and pass in args to this function to make it use different config object if you wish.
Hey guys, so I have a flask web application , I want to do some route testings
Any recommended libraries ?
I’m new to unit testings
Yes
I use Powershell Pester but I'm familiar with it
I want to throw some requests parameters to the routes and test for 200 statuses
unittest would be best?
I’ve been trying to go on YouTube but there is no good explanations
unittest has ton of documentation, not sure if it's best for web testing
you will have to build requests to rest endpoints
which is why I use Powershell
that's built in for me
good rest testing should throw a simple sanity check at it
def get_json_data(uri: str) -> dict:
"""Returns JSON Data in dict format"""
try:
response = urllib.request.urlopen(uri,timeout=60)
urldata = response.read().decode("utf-8","ignore")
jsondata = json.loads(urldata)
return jsondata
except:
return None``` Quick and dirty hit URI and get rest method back, if it fails, return None
needs import json import urllib.request
as someone who is at a company that builds REST API for a living, my recommend I picked up from them was making a ping function on your rest API that touchs some of our other functions for quick sanity check
if any of them return false, barf HTTP Exception 503, makes monitoring really easy
@molten kite Try asking your electron.js question here
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving.
• Be patient while we're helping you.
You can find a much more detailed explanation on our website.
@outer apex ```python
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contacts', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='contact',
old_name='first_name',
new_name='fname',
),
]
that is my custom migrations file that i had to create
So im starting with Electron.js and I dont actually know if its the css which is kinda empty or I have to configure it but any ouput from the html + css doesn't extend fully in the screen.
it's gotta have something to do with the html and/or css
why do you think it should extend fully in the screen in the first place?
ok take a look into other electron js app for example:
the content is extended, I tried with padding and other css variables but still doesnt extend to the full screen.
i know nothing about electron.js 😦 you'd be better off asking in the webdev discord
i think reddit has one /r/webdev
but it's definitely the html/css for sure
as javascript is just for interaction
although maybe it's something you do in electron.js that alters the html/css
It's definitely something to do with your css
IIRC by default electrons <html> and <body> elements cover the entire horizontal space, but maybe not vertical
thank you!
IIRC by default electrons <html> and <body> elements cover the entire horizontal space, but maybe not vertical
@native root I feel dumb it was in front off my eyes all the time. lmao thanks anyways
In django, is the norm to use class based views or function based views?
any works, but I prefer class based views as there are some pre-built ones which can be quite useful
like listview, detailview, etc
I see. So I assume there is no standard, just depends on what the company (or should I say engineering team) prefers?
kinda but class based views are cleaner as well
as each section is split into methods
like 1 method for get requests, and another method of post request, etc
more info here
oof I can see how it's much better than if request.method == 'GET' and etc.
Awesome, thank you! @marsh canyon
🙂
https://paste.pythondiscord.com/rutetijile.py
can anyone see why i am getting empty list as response however one similar function is returning a list as requested just fine. Thanks.
okay so the problem is i am entering data in my db manually but it's not updating
Hello, I'm wondering of how I could get this piece of code but inside a FlaskForm? ```
{% for genre in genres %}
<option value="{{ genre.name }}">{{ genre.name }}</option>
{% endfor %}
thats inside my html file which contains my jinja2 syntax
This is my form
class VideoForm(FlaskForm):
"""New Genre Form."""
title = StringField('Title', validators=[validators.Length(min=3, max=75)])
# genre = SelectField('Genre', [DataRequired()],
# choices=[Genre.query.all()])
description = StringField('Description', validators=[validators.Length(min=10, max=250)])
video_file = FileField('File')
submit = SubmitField('Upload')
I'm trying to render the choices for genre as dropdowns.
form.genre.choices = [ (genre,genre) for genre in genres ]
and genre should be before adding choices something like this genre= SelectField("Genre", choices=[], validators=[DataRequired()])
@cerulean pelican
so for the first one form.genre.choices you will put this at the function where you want to add choices and form here stand for whatever variable you give it the value of the class Videoform()
So what would my jinja 2 syntax look like? @feral minnow
if you mean the html file
yea
you will put this {{ form.hidden_tag() }} {{ form.genre }} in the template that you want the selectfield to be shown to the user
what is form.hidden_tag?
its something for the csrf_token like secuirty I don't know much about it I just put it in my forms
I think it will generate a hidden csrf_token
ahh okay
lemme try it out 1 second
its empty
this is my code
video_form = VideoForm() video_form.genre.choices = [(genre, genre) for genre in Genre.query.all()]
class VideoForm(FlaskForm):
"""New Genre Form."""
title = StringField('Title', validators=[validators.Length(min=3, max=75)])
genre = SelectField('Genre', [DataRequired()],
choices=[])
and it also doesnt look anything like my other dropdown
Genre is a model
class Genre(db.Model):
__tablename__ = "genres"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
def __repr__(self):
return '<Genre %r>' % self.name
but you want to get the id or the name?
Namecheap
@feral minnow fixed it but it still doesnt look like my other dropdown
oh can I see you code
for the html and form
sure
<div class="form-group">
<p class="help-text">
Video Genre
</p>
{{ form.genre(class_="custom-select", name_="video-genre") }}
<select class="custom-select" name="video-genre">
<option value="0" disabled selected>Select Genre</option>
<option value="Test">Test</option>
</select>
</div>
class VideoForm(FlaskForm):
"""New Genre Form."""
title = StringField('Title', validators=[validators.Length(min=3, max=75)])
genre = SelectField('Genre', [DataRequired()],
choices=[])
description = StringField('Description', validators=[validators.Length(min=10, max=250)])
video_file = FileField('File')
submit = SubmitField('Upload')
so now its adding the values but you want it to edit the style i believe?
oh give me a sec let me see my code
aight 🙂
<form method="post" name="ch" action="#choose-start" style="margin: 0 auto;">
{{form.hidden_tag()}}
{{ form.startChapter(class="custom-select") }}
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="sumbit">Start Chapter</button>
</div>
</form>
</div>
so in my code I put it in a form which is inside a div
and added the bootstrap classes that I want
are you using bootstrap btw or you just styling it yourself?
Bootstrap
How would I assign a name variable to my genre field?
e.g name="video-genre"
you mean the value
ye
because I tried this
{{ form.genre(class_="custom-select", name_="video-genre") }}
but it doesnt recognize the name_="video-genre"
ohhh
you wanna get what user choose?
the name="video-genre" is a styling part i believe
fixed it
nvm
Thanks for all your help (:
Welcome,glad to help 😄
But I still have a problem with one of my models
I have this inside my Video model
genre = db.Column('Genre', backref='video_genre', lazy=True)
and it gives me this error
TypeError: Additional arguments should be named <dialectname>_<argument>, got 'backref'
class Genre(db.Model):
__tablename__ = "genres"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
def __repr__(self):
return '<Genre %r>' % self.name
Genre model
databases class
Huh?
__tablename__ = "genres"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
def __init__:
self.name = name
def __repr__(self):
return '<Genre %r>' % self.name```
you have to give it a value which is name
still get the same error
TypeError: Additional arguments should be named <dialectname>_<argument>, got 'backref'
class Genre(db.Model):
def __init__(self):
video_genre = self.name
__tablename__ = "genres"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
def __repr__(self):
return '<Genre %r>' % self.name
put it under the Colums and I forget to tell you that you need to add def __init__(self,name)
class Genre(db.Model):
__tablename__ = "genres"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
def __init__(self, name):
name = self.name
def __repr__(self):
return '<Genre %r>' % self.name
its must be self.name = name so you will set the self.name to the value name
still same error
TypeError: Additional arguments should be named <dialectname>_<argument>, got 'backref'
From where the error is coming?
genre = db.Column('Genre', backref='video_genre', lazy=True)
You have to classes for databases?
what do you mean
I mean im not seeing ```genre = db.Column('Genre', backref='video_genre', lazy=True)
5 votes and 2 comments so far on Reddit
that genre = db.column
is on the video
model
class Video(db.Model):
__tablename__ = 'videos'
# Values which are important
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), unique=False, nullable=False)
description = db.Column(db.String(250), unique=False, nullable=True)
views = db.Column(db.Integer, default=0, nullable=True)
genre = db.Column('Genre', backref='video_genre', lazy=True)
class Genre(db.Model):
__tablename__ = "genres"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Genre %r>' % self.name
sorry if it was a bit confusing
im not too good with databases so what backref does here?
not completely sure, I copied it from a example
oh
So I don't wanna say something I don't know and break your code but try to delete if it didn't work try ask people at #databases
yes i'm sure almost everyone here has
what
Heroku free hosting
What is Dyno
i would highly recommend at least reading the pricing page of a host you plan to use
Oh
why is installing and using uwsgi with python so goddamn painful
I have a problem with Jinja and Flask-wtf: Is it possible to use a variable inside a variable?
``` {% if pre_keyword %}
{{ form.keyword(class_="single-input-primary", value="{{pre_keyword}}") }}
{% else %}
{{ form.keyword(class_="single-input-primary") }}
{% endif %}
In this case I check if the variable pre_keyword is passed to the template. if it exists the input field should be prepopulated with it -> value = {{ pre_keyword }}
Unfortunately it literally renders "{{pre_keyword}}" in the template since the whole input is a variable
how can i prefill the form with a variable?
This is my SearchForm:
place = StringField('place', render_kw={"placeholder": "City / District / Address"}, validators=[DataRequired("Please enter a place.")])
radius = IntegerField('radius', render_kw={"placeholder": "Radius in [m]"}, validators=[DataRequired("Please enter a number between 1 and 100000"), NumberRange(min=1, max=100000)])
keyword = StringField('keyword', render_kw={"placeholder": "Keyword"}, validators=[DataRequired("Please enter a keyword.")])
submit = SubmitField("Search")```
@tired root
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
i am inheriting from base.html
and the main webpage is home.html
i added both to jsfiddle
try using it on a device toolbar
for example an iphone 6
when u press the menu it goes behind the picture
the poster
I am, I am resizing the result window
did it work?
oh the menu
the hamburger
Fixed it
nav ul{
float: right;
margin-right: 60px;
z-index: 9999;
}```
with the z-index the menu will stay on top of things
it messed up the look on desktop
how do i do that? (sorry i am a newbie)
i only know the bootstrap stuff
i am new to css
ok
This will apply the z-index on screens not wider than 720px
yes
float: right;
margin-right: 60px;
}
@media only screen and (max-width: 720px) {
nav ul{
float: right;
margin-right: 60px;
z-index: 9999;
}
}```
ok
Mhh, you can also use an extra selector
Probably cleaner
nav ul{
float: right;
margin-right: 60px;
}
@media only screen and (max-width: 720px) {
.on-top{
z-index: 9999;
}
}```
then add on-top as class to the <ul> element
Do you have <meta name="viewport" content="width=device-width, initial-scale=1.0"> in the header?
<input type="checkbox" id="check">
<label for="check" class="checkbtn">
<i class="fas fa-bars"></i>
</label>
<label class="logo">Flixnet</label>
<ul class="on-top">
<li><a class="active" href="#">Home</a></li>
<li><a href="#">Projects</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
<li><a href="#">YouTube & Discord</a></li>
</ul>
</nav>```
yes i do have it
wait you already have a media query which breaks at 858px
add the on-top class to that and remove the new one
how?
just add it to the media query you already have
I mean, you wrote it, you must understand it
then please learn some basic css first
@media (max-width: 858px){
.on-top{
z-index: 9999;
}```
Okay
Seriously, learn css from scratch
Hello, i M developping a website with django and I want to use JavaScript to make forms without refresh. I M beginner with js. Can you advise me to do this task ?
@native tide using boostrap ?
@native tide its OK I fixed it, also yes I was using bootstrap
return redirect('contacts:login')
the above code works fine, but if i remove contacts:, and leave only login in there, it stops working. why?
here is my route:
path('login/', views.loginPage, name='login'),
p.s. contacts is the name of my app
Django
How can i change the 'selected' choices of a ChoiceField in a ModelForm through JS?
I added the "selected" class to the parenting list element, which is all a natural selection does. Still it does not get displayed in the field and does not get used when i submitt the form.
Also. Could i not visibly render a choicefield but still have it "there" ?
@onyx crane for your first issue, i don't exactly understand the question. for the second question you can use hidden form fields
Django
I have a mapping for a API and my DB that looks like this
# my db field: the api field
DEVICE_STORE = {
'device_stores_id':'id',
'name':'name',
'description':'description',
'record_status':'recordStatus',
}
My model for this looks like follows
class DeviceStores(models.Model):
device_stores_id = models.CharField(max_length=255)
name = models.CharField(max_length=255)
description = models.CharField(max_length=255)
record_status = models.CharField(max_length=255)
i do a get or create when i get the object like this at the moment
obj, created = models.DeviceStores.objects.get_or_create(
device_stores_id=item['id'],
name=item['name'],
description=item['description'],
record_status=item['recordStatus'],
)
Is there a way i can do some sort of mapping or transform the API response to map to the correct item from the mapping contsants i created above.
@native tide set display: flex
make your container's display flex
or use bootstrap and add d-flex to classes div
or use grid system bro
Guys I am quite new to wordpress php and the likes and I have a question:
When I create a child theme folder in WP, do I have to copy all files from the parent folder or are they created automatically? I.e. my folder contains style.css functions.php and some other folders but not footer.php, I then changed the footer in WP editor and expected it to create a new folder in my child theme root directory, but it did not. It also did not overwrite the parent footer.php --- where is the data stored then?
What is the difference of writing flask rest api for a Todo and doing it the normal way
Are there any disadvantages
I know this is a stupid question
YES
guys
ya
is there a tutorial to upload images through flask into a server?
i just started like 5 min ago
ah alright
thats cool
yeah
html is the front-end
i am beter in python so i did it in python
oh thanks i'll try to do it following this tutorial
oh you can do <a href="https://discordapp.com/"> type something here </a>
that will be a text but you can turn it into a button by bootstrap
the aesthetic like a button, you can import bootstrap by putting this into the head
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
and this at the bottom before closing the body
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>```
UH ok
then
besides href at "a" tag you can put the class parameter
like that class="btn btn-primary"
there are all the buttons that you can use
through bootstrap
ok
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route("/")
def home():
return "Hello! this is the main page <h1>HELLO<h1>"
@app.route("/<name>")
def user(name):
return f"Hello {name}!"
@app.route("/admin")
def admin():
return redirect(url_for("user", name="Admin!"))
if __name__ == "__main__":
app.run()
lmao this is all i have
it's okay you will get improved, i'm also very noob lol
lmao
File "website.py", line 20
return f"<button type="button" class="btn btn-link">Link</button>"
^
SyntaxError: invalid syntax
@app.route("/Test")
def test():
return f"<button type="button" class="btn btn-link">Link</button>"
create a template folder into the folder of your app in which you are programming
then create something like "index.html"
into it put all the html code
then into the route test
add at the bottom return render_template('index.html')
you can call the file how you want
from flask import Flask, redirect, url_for
here add also render_template so
from flask import Flask, redirect, url_for, render_template
add this to the main page or the index
this to the main page into the back end
you just have to add render_template besides the other things
create a folder in that folder
oh
name it "templates"
ok
then put index.html into it
ok
and for the index.html i put
<button type="button" class="btn btn-link">Link</button>
in it
yeah but you have to put the html code as well so
wdym
<doctype HTML>
<html>
<head>
</head>
<body>
</body>
</html>
and put that button between the body tags
btw from which tutorial you're learning flask?
uh tec with tim
and others
<doctype HTML>
<html>
<head>
</head>
<body>
<button type="button" class="btn btn-link">Link</button>
</body>
</html>
like this
yeah it's fine now you can do
ok
ok
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route("/")
def home():
return "Hello! this is the main page <h1>HELLO<h1>"
@app.route("/<name>")
def user(name):
return f"Hello {name}!"
@app.route("/admin")
def admin():
return redirect(url_for("user", name="Admin!"))
@app.route("/test")
def test():
return render_template('index.html')
if __name__ == "__main__":
app.run()
yes it's good
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
it is in localhost i cannot see it
mm is there a debug?
by the way you have to add
render_template besides url_for
where you have from flask import etc
hmm
you have to put another comma and type there render_template
uh ok
try to run now
ok
"from flask import Flask, redirect, url_for, render_template" instead of "from flask import Flask, redirect, url_for"
from flask import Flask, redirect, url_for, render
mmm position what?
the button
where is it?
top left
try to <center> before it and </center> after it
<doctype HTML>
<html>
<head>
</head>
<body>
<center>
<button type="button" class="btn btn-link">Link</button>
</center>
</body>
</html>
yeah
mm i don't know the right tag but try to put three or four <br> after <center> tag
uh ok
<doctype HTML>
<html>
<head>
</head>
<body>
<center>
<br>
<button type="button" class="btn btn-link">Link</button>
</br>
</center>
</body>
</html>
like that
ok
<doctype HTML>
<html>
<head>
</head>
<body>
<center>
<br><br><br>
<button type="button" class="btn btn-link">Link</button>
</center>
</body>
</html>
yeah it's good
yeah technically
no problem!
well what does ur website look like
it is a bit long but not so much xp
it is, flask is more flexible at most times and doesnt follow like a pipeline on how to do it I believe
flask is more lightweight which can mean simpler
or it can make life very hard because you are manually doing things that Django could do for you
Agree with @zealous siren, Flask forces you to learn to build things that are built-in in Django
DJango is best for building bigger website where you don't want to write a ton of HTML, Flask is better for smaller ones or where you will be embedding, FastAPI for where you simply building REST APIs for SPAs
that's generic recommendation, obviously every use case varies
Guys how I can upload a zipfile
using flask
I tried send_from_directory and send_file
but they are not working
def upload():#Send files
print("hi")
path=session["file_path"]
dirPath=os.path.dirname(path)#Get the path for the dir
baseName=os.path.basename(path)#The file name
return send_from_directory (os.path.abspath(os.path.dirname(path)),f"{path}.zip", attachment_filename=f"{path}.zip", as_attachment=True)```
uh people how do i make a button clickable
@ember kayak what do you mean?
like i can click it
<doctype HTML>
<html>
<head>
</head>
<body>
<center>
<br><br><br><br><br><br><br>
<button type="button" class="btn btn-link">Discord</button>
</center>
</body>
</html>
where do i put the link
I would personally go for something like
<a href="http://www.discord.com/"><button>Discord</button></a>
you mean the button?
yes
@ember kayak https://www.w3schools.com/cssref/pr_text_color.asp
you can style it inline
?
like with #1efi34
ok
Another flask question :)
Is there a way to access the label from a SelectField to output?
e.g. I have the SelectField py milk_type = SelectField("Milk", choices = [("fullCream", "Full Cream"), ("hilo", "Hi-Lo"), ("skim", "Skim"), ("almond", "Almond"), ("soy", "Soy"), ("none", "None")])
After the user has selected their milk type, I want to output to a table in another view function.
At present, it's displaying the value, rather than the label
you mean you want to get data to another function?
I can do that
@app.route("/order", methods=["GET", "POST"])
def order():
myData = session["coffeeData"]
print(myData)
return render_template("order.html", data=myData)
you want to get what user choose and display it as a label?
So - myData is the input that the user has made. I am sending it to order.html which is just a table at present.
Output is as follows:
So rather than having flatWhite and fullCream being output, I want "Flat White" and "Full Cream"
Which are the labels from the different SelectFields
At present I am saving the inputs as a list. Would it be better as a dictionary?
It depends at what your trying to do
but if it will make the code more cleaner this would be nice
But dict really help it saved me 60 line of code or more
lol. That would have annoyed me... 60 lines of code.
Okay. So at present I am saving the user input as: py session["coffeeData"] = [coffeeForm.drink_type.data, coffeeForm.milk_type.data, coffeeForm.sugar.data, coffeeForm.extras.data, coffeeForm.email.data, coffeeForm.username.data, coffeeForm.payment.data]
If you want to make a dict you can add a key for every value e.g {"drink_type":drink_type.data}
True, but I just realised that won't help. Am I allowed to say [coffeeForm.drink_type.label] instead of [coffeeForm.drink_type.data] ?
I just tested. You can, but it didn't work the way I wanted
milk_type = SelectField("Milk", choices = [("fullCream", "Full Cream"), ("hilo", "Hi-Lo"), ("skim", "Skim"), ("almond", "Almond"), ("soy", "Soy"), ("none", "None")])
The label is "Milk"
If you want to put what user choose as label you can do this return render_template("coffe",label=coffeForm.drink_type.data)
html:
@feral minnow - I have figured it out. It was more simple than I expected
drink_type = SelectField("Drink", choices=[("Flat White", "Flat White"), ("Cappucino", "Cappucino"), ("Black", "Black"), ("Mocha", "Mocha"), ("Hot Chocolate", "Hot Chocolate")])
Cool,you just changed the names?
nice
Now to make it a little bit pretty and add pricing 😛
I am wondering if it would be better to just use bootstrap
For design yes
I use in my website without it my website will look like websites in 1999
but if you're a very good designer this is another thing
nope, is it a framework like bootstrap?
oh i just searched for it, its something used with bootstrap
Yeah. Icons and stuff
which commad do we run after git add . ?
im not sure but maybe git commit
okay
Uploading zipfiles is workinggg
what do i wanna put in my .gitignore file if i want to ignore a directory inside my project directory?
okay ..thanks
$(".learn_talent").on('click', function(event){
if ($("option:contains('" + this.name + "')").is(":selected")){
$("option:contains('" + this.name + "')").removeAttr('selected');
$(this).parent().parent().attr('class', 'card hoverable blue-grey darken-1');
alert("?2");
}
else if (!$("option:contains('" + this.name + "')").is(":selected")){
$("option:contains('" + this.name + "')").attr("selected", true);
$(this).parent().parent().attr('class', 'card hoverable blue-grey darken-3');
alert("?1");
}
});
Just quickly need a second pair of eyes to spot the obvious ...
I want to select and unselect an option. This works fine once(select, unselect, select) but then im stuck in the else if for some reason and i can't figure out why
@onyx crane Not sure, but how can you check if !...is(":selected") if you remove the attribute?
previously i had the attribute set to false, but that ended in the exact same behaviour
Anybody familiar with Wordpress?
I’m trying to host only a database on their and connect it to my website that is on another server(Heroku)
$(".learn_talent").on('click', function(event){
if ($("option:contains('" + this.name + "')").is(":selected")){
//$("option:contains('" + this.name + "')").removeAttr('selected');
$("option:contains('" + this.name + "')").attr("selected", false);
$(this).parent().parent().attr('class', 'card hoverable blue-grey darken-1');
}
else if (!$("option:contains('" + this.name + "')").is(":selected")){
$("option:contains('" + this.name + "')").attr("selected", true);
$(this).parent().parent().attr('class', 'card hoverable blue-grey darken-3');
}
});
Is that possible?
@onyx crane Why not if/else? Is there a third/multiple case(s)?
@queen bough if/else had the same issue. I was wondering if i just missed a case with else and used a second conditional.
<option value="1" selected="selected">Bogen-Talent</option>
This is where it's stuck
and normally by clicking the button again, it unselects again
i just cant see a reason why it would work once but not twice
<div class="card-action">
<button class="waves-effect waves-light btn learn_talent" name={{talent.talent_name}}>Erlernen</button>
</div>
The other classes are just css styling classes from a framework
i iterate over model instances, create a card with a button, and every button on every card calls the method to modify its parenting card, and add the responding element to the selection of my <select> field
Can you create a minimal demo with just the failing elements so that I can quickly test a few things? I think this is an issue with the selectors or (less likely) that the click event isn't being called as you assume.
@onyx crane ^
Pardon me if you've already seen it.
no actually i didnt :D
mb
Actually im not sure how to create a minimal demo for this reall quick, since there are so many dependent things involved in this view.
Would you want to hop into a stream and id show you what i got ?
(@queen bough , thanks already for the effort :) much appreciated)
np
Would this Be a Good place to ask for help in regard to Processing a JSON array returned by an http request?
Basically I'm pigning an API endpoint and I can get what I need from a single array item, but I need the Data from every item in the array so I can biuld a tuple
I fugired out how to iterate the arry, but not how to make it construct a tuple
Yo, does anybody know of any JS lib I can use to make a datepicker like that?
wisper, you could construct a list to start then cast into tuple
it's just matter of python x = tuple(list)
is this the spot to ask about Django?
@fair agate yes its for web development go on and ask you question (:
sweet! I'm getting a syntax error on this def str(self): I tried to implement and I'm not really sure why as everything looks fine in terms of syntax to me
i'll paste in
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics'
def __str__(self):
return f'{self.user.username} Profile'
returning syntax error with def highlighted
oh shit
no closed ) on the previous line
my bad
ok
so i am useing flask
i am portforading my computer
but the link does not work
@zealous siren It was an issue with how janky the data structure was, I got it solved in a Help channel
guys I scrape a website to get a list of img but it put all img elements at one index how i can split them?
when to use justify-content ?
nvm,I created a for loop to itereate over the items then put them into another list
just a random comment: why CSS is so annoying?
Some times I get frustrated. I rather download a template and modify it than go from zero
thats what id actually recommend, use a css framework like bootstrap, makes everything so much easier IMO
I'm reading about tailwind css, have you heard about it?
nope, seems decent tho from a quick look
it is, still getting to know it. can't have a final opinion rn
<form method='POST'>
{% csrf_token %}
<div class="row">
<tr>
<th>{{ form.pc_name.label_tag }}</th>
<td>
{{ form.pc_name.errors }}
{{ form.pc_name }}
</td>
</tr>```
Im rendering my ModelForm like this currently to get acces on how and where the different form elements are displayed.
How can i go even further and adjust the classes of the input elements itself instead of just modifying the wrapper around `form.field` ?
Hey so I made a simple program that takes api from Spotify to create a playlist. I’m trying to learn framework so I can turn it into my first simple web app. I really only need a home page that lets you authorize through Spotify, maybe a loading screen and then a success page for now. Is flask a better option than Django?
@elder wyvern Flask will be a whole lot less complex than Django for something that basic, yes
ModuleNotFoundError: No module named 'import_export'Django
although I did install it
and added to settings
this's so weird
@shy holly you have to tell us more about the problem you are having
@empty pivot what do u mean ?>.>
I tried to install django-import-export library .
and now I'm getting this error.
It's better to master CSS than use a framework
it's kinda messy with bootstrap
and if you already know css and want to use a framework you have to learn bootstrap which is a whole nother CSS
Did you do
$ pip install django-import-export
@empty pivot YUP
Share your code here please otherwise it's hard to say what your issue is
and if you already know css and want to use a framework you have to learn bootstrap which is a whole nother CSS
@native tide yeah, it's tedious
noob question but
what would be the best way to allow for the shadow on the right panel
to go beyond the margin of the panel?
I cant seem to fix that
maybe postion absolute?
I am wondering how you could assign values to items in a SelectField in flask.i.e.
milk_type = SelectField("Milk", choices=[("None", "None"), ("Full Cream", "Full Cream"), ("Hi-Lo", "Hi-Lo"), ("Skim", "Skim"), ("Almond", "Almond"), ("Soy", "Soy")])
Let's say I wanted to assign a float to each of those items for the price
@cerulean vapor thanks. At what point is django a better option than flask?
Django:
For some reason every button that i have inside my <form> tags is trying to submit the form :D The initial button has the type="submit" and value="Save". The others don't ..
How can i make it so when someone goes to an ID (forgot what its called) it highlights the element? e.g if ive got a div element called "part-1" and you go to example.com#part-1, how would i make it change the background colour of the div?
set up en event listener
ok
youd need to listen for something like mouse click on maybe theres an onEnter event
then youd call the function to change the color
using JS
I am working with Jinja2 templates and I need to conditionally apply css attributes. So far I've managed to achieve that by applying condition to element creation:
{%- macro render_listing(listing) -%}
{% if listing["has_highlight"] %}
<div class="job_listing" type="highlight">
{% elif listing["has_custom_color"] %}
<div class="job_listing" type="custom_color" style="background-color: #00FF00">
{% else %}
<div class="job_listing">
{% endif %}
<span class="job_title">
{% if listing["has_logo"] %}
<img src={{ listing["company_logo"] }} id="company_logo">
{% else %}
<i class="fas fa-briefcase"></i>
{% endif %}
<a href="{{ url_for('board.get_job', job_id=listing['id']) }}">
{{ listing["title"] }}
</a>
</span>
</div>
{%- endmacro -%}
How do I apply conditions in the type attribute? I'd like to cut some stuff and avoid creating a new <div> each condition
Hello, i'm wondering for how I could possibly get the information of a user with jinja2 e.g i have comments which have the user_id of the user who wrote the comment though i dont know how to do a request and get the information of that user
@cerulean pelican if you can get the id
then you do ```user_filter = youclassname.query.filter_by(user_id = theuseridfromcomment).first()
then try doing user_filter.name
what i said is for sqlite
Hello
I was tasked with creating a CMS for our university website using python. I have built a API using flask before. Should I go along with Flask or pickup django?
I also had a question about which library should I use for using jwt with flask? authlib or python-jose?
Django is probably more "Out of the box" for CMS
There is nothing you cannot do with Flask
though learning curve obviously
I personally hate Django tbh, I find it clunky and convoluted
Flask is quick and simple
I didn't say that, but with Flask, you might be re inventing the wheel instead of just "buying" it
If I need more, I can add packages as I need them
I'd prefer to use flask cause I already got the hang of it
without knowing your skill level and like
it's possible that flask will get the job done quicker
or it might be faster to learn Django despite slow build up time
I'd prefer to use flask cause I already got the hang of it <-- can be dangerous mindset to get into, learning new things is important
I've intermediate knowledge of python. But I'm only a beginner for web dev. I find flask simple as it's a route+function=done.
sure but Django has tools to build the content of the webpage
are you just building backend or both?
so SPA JS frontend with REST API backend?
Yes what you said
So I wondered upon jwt, which seems better than just a username password model.
Which kind of auth should I use?
I'm kinda confused on that part.
JWT like in Java Web Tokens?
JS web tokens yes
we auth against AzureAD, which returns a token, you send that token to API which validates it and stores token into Azure Storage Table storage for lifetime of token
Web Tokens are just here to say "I have passed the authentication method, I am this person"
As username/password is an authentication method
They don't really serve the same purpose
JWTs are used behind the scene in most case
to put in passport terms, you go get a passport from trusted provider (Authentication server) then you go elsewhere with your passport, you present your passport to third party (rest of application) to valid yourself, that third party calls up Trusted Provider and says "Hey, is this passport number valid?", gets yes/no and proceeds accordingly
stateless auth is what I described, browser stores the token, likely in a cookie
@zealous siren oh I just remember, I could use firebase auth?
Stateless auth would use JWTs
you will have to work with JS developer on whatever you want to do