#web-development
2 messages · Page 57 of 1
some places do use signing as well depending on security requirements
we cannot since we have to be sure that user is still valid so security requirements require us to check tokens after an hour
Is username password model unsafe?
It's used in Oauth2 for example
@somber wedge no
But look into supporting FIDO sticks
username password model how?
Hm so what lib should I use for auth? Cause I need to handle some secure post requests for adding content.
what lib your auth provider supports
Step 1) Figure out auth provider
Step 2) Get libraries for auth provider
Step 3) Figure out authenication flow
Is there any way I can be auth provider
Username/Password
There is no problem with that
As long as you abide by common practices
@somber wedge
Common practices:
- Don't enforce patterns, this is the worst
- Don't limit to unreasonable lengths, encourage very long pass-sentences
- Use Salt and Pepper
- Use HTTPS at all times
- Hash with JS before you send
- Optional: Use hardware token such as phone or FIDO
Yes
You should actually revert the JS hash, then encrypt
That is the more correct way to say it
encrypt with salt, then pepper
In cryptography, a salt is random data that is used as an additional input to a one-way function that hashes data, a password or passphrase. Salts are used to safeguard passwords in storage. Historically a password was stored in plaintext on a system, but over time additional ...
In cryptography, a pepper is a secret added to an input such as a password prior to being hashed with a cryptographic hash function. As of 2017, NIST recommends using a secret input when storing memorized secrets such as passwords.
A pepper performs a comparable role to a salt...
But if I deploy the app behind a load balancer, do I need to setup https from LB to worker?
Depends on which Layer you work
There is OSI Layer 3 and 7 balancing
Layer 3 does not need a HTTPS cert, because it knows jack about that
Layer 7 balancing only needs https between the balancer and the client, but it would be good to have a tunnel between hosts as well
For now I'm using aws beanstalk without any LB and then rapidapi for https. There's no https between rapidapi to my aws beanstalk env. Is this bad implementation?
I have no clue how those work tbh, never used AWS
I use haProxy if I need it
and Apache
I mean amazon web services, to host the flask application.
I know what AWS is, but I've never used it
Okay. How do you host your flask app?
With Apache 2.4 and mod_wsgi, then enable mod_ssl
SSLCertificateFile /etc/letsencrypt/live/***/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/***/privkey.pem```
No I mean where is the application actually running? Like you need a vm with 24x7 uptime?
If you want to have it 24/7 available, yeah
Can also use a root
depends on your scenario
So you're self hosting? The stuff runs on your local rig?
Depends
some run on my pi
There is no "this is the answer", in IT it always depends on the use case
requirements are important for an answer
I can give you setups from a Raspberry up to a cluster with 20 RX DEll Servers
Okay. Mine needs to be up 24/7, as it'll be used as a backend for University site.
So I'd rather use something like heroku/aws
You need to do the math. How many requests/second, how big is one request then you have the networking requirement
don't forget the IP and Ethernet frame overhead
as well tcp handshake
Isn't cloud just better? It handles all of that into a single price?
most of the time yes
Yes, but you need to know how many vps you need and what kind of vps
is 1 gb/s enough?
Do you maybe need more?
2020
and using AWS for their compute servers
vps, instances, whatever, no need to be elitist
if you use web instances, they auto scale
that's reason not to use VPS, that whole scaling problem is taken care of
vps tend to be cheaper and if one vps is enough, then I'd go for it without the complexity of AWS
We have around 4000 students, and not all of them check the website. So I'd estimate around 500 requests per day at worst case.
500/day is nothing basically, should be good enough for heroku
you could do AWS just for learning if your university has AWS already in place
then stick with it, no need to regress
But my traffic from beanstalk isn't https
from beanstalk to where?
I am running beanstalk to rapidapi
Beanstalk outbound calls support HTTPS no problem
Beanstock doesn't care what your code calls
It's only the case if it's used behind a load balancer and the load balancer is using a https cert.
Mine is just a single instance without lb
you are confusing HTTP client with server
calls from Beanstalk application are whatever you want them to be, you are HTTP Client and you somewhat set the terms
calls to BeanStalk are as HTTP Server, you again can control and I'd be shocked if Amazon doesn't allow/force HTTPS
Azure does, I can't see AWS being that far behind
Yes but I also need to secure the calls to beanstalk? Aws doesn't provide https by default.
Teh beep
Unless I'm using a paid config with loadbalancer and api gateway or something like that.
I think heroku allows https by default
Ok, I guess Heroku or better cloud
I haven't used AWS in 2 years, when I switched jobs, I moved to Azure, they provide HTTPS natively
Heroku is still serverless, AWS just provides more options
VPS is regressing
yes it is, you have to put up with OS and all the updates
Sorry, but I know what I am talking about. VPS isn't regressing at all, it is our most sold product.
Okay please don't fight. I'll get more confused.
Sure, because it's what people know, doesn't make it right
or they have code that explodes in containers
trex, Heroku is fine
for web application
Hello, I'm working on a flask application and this is my route for deleting a comment
if current_user.is_authenticated:
if request.method == 'POST':
comment_to_delete = Comment.query.filter_by(id=comment_id).first()
db.session.delete(comment_to_delete)
db.session.commit()
return redirect(url_for('default_urls.watch_video', video_id=video_id))
however it doesnt work unless i remove the if request.method == 'POST': because for some reason the request is a get request
this is my html code
<li class="list-item movie-comment-remove" data-toggle="tooltip" data-placement="bottom" title="Remove">
<a href="{{ url_for('default_urls.delete_comment', video_id=video.id, comment_id=comment.id) }}">
<i class="fas fa-trash-alt"></i>
</a>
</li>
It's not a form
does it have to be a form?
does it change anything if its a get request vs post requ est
No
aight
You can make it a post request if you don't want it show up in the history though
so add a form with a hidden comment-id, which you then post to your function
It's a valid method
but also harden the function to recognize if the user sending the ID is the actual owner
you don't seem to be doing that right now either
Any logged in user could delete any comment right now from what I see
@cerulean pelican
yeah going to do that right now
Have anyone here made appointment booking systems using django ever? If you have, can you share what tools you used to build it?
@elder nebula haven't done it but you'll need a good ui toolkit like bootstrap or semantic UI. You'll probably want a good form library, and if your app is going to have any kind of reminders or timed features (common in appointment schedulers), then you'll want some kind of django cron library
Terabyte, there is a ton of third party that does this as well
and some online office suties include this feature, in particualr, Office365
Does anyone have any recommendations for a CSS framework with flask?
👆 +1 on bootstrap
Hey guys i'm very new to web dev and I wanted to turn a relatively simple python script into a web app, though It feels like I'm approaching this the wrong way. Is trying to transform a python script into a web app even a good approach? Or should you approach a project from a web app perspective first that uses python (if you get what i'm saying)?
Like my python script uses spotify api to create a playlist, but trying to integrate a function (for example) made in python that generates user authorization into a web app does not seem like a viable thing to do
Hi, anyone knows how can I use Sass with flask? How to install it till I have the scss file?
How can you fill out a form in python?
you can use selenium
Guys do sessions in flask have a limit for the string lenght in a list?
The list with numbers is the normal list, the list without numbers is the same list but as a session
anyone has any idea?
What are you doing
Hi!
I currently am running a Flask application and am using a session to store a couple of variables, however I've noticed I can't share session data between blueprints
from flask import Blueprint, session
bp1 = Blueprint("bp1", __name__, subdomain="bp1")
@bp1.route("/")
def main():
return session["test"]
from flask import Blueprint, session, url_for, redirect
bp2 = Blueprint("bp2", __main__, subdomain="bp2")
@bp2.route("/")
def main():
session["test"] = "Hello"
return redirect(url_for("bp2.main"))
when running the code and going to bp2.mydomain.com, i get a KeyError stating that session doesn't have a test.
is there any way to share the session data between two flask blueprints? thanks in advance!
please ping me if you have an answer
I suspect this ties more to the fact that the cookies aren't properly shared across subdomains (rather than Flask itself)
Hi, I am trying to learn flask-admin, and already having trouble. First thing in documentation in "Getting Started" section shows how to initialize empty admin interface and then open page http://localhost:5000/admin/, but when I open this page i get following error jinja2.exceptions.TemplateNotFound: admin/index.html. As I can understand this problem could be solved by copying templates from flask-admin package. But there is no word about it in documentation. Do I do something wrong?
@solar spire You still need to create a single admin/index.html file. Here's an example: https://github.com/Sumukh/Ignite/blob/master/appname/templates/admin/index.html
You might not need the same level of customization that I did there but the key bit is {% extends admin_base_template %}
it is strange that there is nothing about it in section documentation
And then there is {% extends 'admin/master.html' %} further down in documentation. So should I make that template too?
I don't think you need it. (In fact my understanding was that you didn't really even need a admin/index.html at all if you don't need an index page)
How are you initializing the Admin class? Here's how I do it: https://github.com/Sumukh/Ignite/blob/master/appname/admin.py#L46
I suspect this ties more to the fact that the cookies aren't properly shared across subdomains (rather than Flask itself)
@sleek hazel how do i share cookies across subdomains? sorry i'm kinda new to Flask
@kindred gate I haven't messed around with it much myself, but I think it's through the SESSION_COOKIE_DOMAIN config and setting it to .yourbasedomain.com to indicate you want the cookies to be shared across your subdomains. (you basically need to tell flask to change how it handles a HTTP header that tells browsers how to deal with cookies)
thank you!!
@quick cargo I like Fomantic UI a lot
Hey is there any guide to make ecommerce website using django paid or free both if available anywhere?
@elder wyvern you can create a web app with proper authentication which serves the playlist after checking the authentication. Should not be any problem.
I'm new to web development in django, what would be a beginner friendly approach to hosting django applications
@lilac root for me, learning flask helped understand what's happening in django. But again I am new to web dev in general.
@lilac root if you are a beginner, you can get a free tier AWS Ec2 and just run your Django app in a screen / pm2 session in there. Voila, your app is online. It won't scale well for multiple users but it's a start
Sorry if selenium doesn't fit the channel but I'm having a problem with my build erroring with selenium any help? Sorry for the image i took it fast.
You need to install selenium first using pip install selenium
Ah, pycharm probably created a venv for you, which is basically an alternate python install
You need to type the command into your system terminal, or run the script from pycharm
Well, you should try pip install wheelspip install wheeland then retry
Without an s at the end, sorry
Nice!
Hello, good people.
Can anyone comment. I need to create restAPI, I have a MySQL database and I want to make it available via api. I have never done anything like this, I have no experience. How to do it the easiest way in Python?
how do you make python exit the program?
exit(), or sys.exit()
@native tide if you want ultra light weight you can use flask
personally i normally use Django so i can run my normal site and then backend api with oauth2
but depends on your use case
My use case look like this: I mean the simplest solution so that I don't have to learn a lot and that I can finish it.@quick cargo
I note that I have no knowledge about creating API. I am an absolute rookie.
I need information which solution will be the simplest for me. I was thinking about the Django Rest API, I know there is such an add-on.
If I have not worked with any framework with is better for develop and deploy Flask or Diango if I want only API?
it depends
Flask is considerably more lightweight but doesnt have the orm
django's rest framework can be harder to understand
but then you also have the orm and serializers
I already have a database in MySQL. I am its administrator, I have to make an api to this DB. I only know Python.
That is my task 🙂
then probs best to go with flask
It will be easier?
yh
In recent years REST (REpresentational State Transfer) has emerged as the standard architectural design for web services and web APIs.In this article I'm going to show you how easy it is to create a…
pretty simple article for it
Do you guys have any open source projects that use DRF in mind? I wanna look into unit testing API and get some ideas
Appreciate it in advance :)
drf?
Any idea why safari just on my computer won't load my website? It has a standard SSL certificate and other browsers (even safari on other computers) will open it
I deleted all cache from safari manually as well
Django rest framework @quick cargo
ohh, I use DRF tho sadly not open source because of some endpoints a certain company doesnt want shown 
class ClusterData(generics.RetrieveAPIView):
""" Clusters call this to post and load data """
def get(self, request, **kwargs):
queryset = ClusterInfo.objects.all()
serializer = ClusterSerializer(queryset, many=True)
return Response(serializer.data)
def post(self, request):
payload = request.data
payload = payload['data']
payload = json.loads(payload)
cluster = ClusterInfo.objects.filter(cluster_id=payload['cluster_id'])
if len(cluster) != 0:
cluster = cluster[0]
cluster.guild_count = payload['guild_count']
cluster.user_count = payload['user_count']
cluster.shards = json.dumps(payload['shards'])
cluster.save()
else:
cluster = ClusterInfo(
cluster_name=payload['cluster_name'],
cluster_id=payload['cluster_id'],
guild_count=payload['guild_count'],
user_count=payload['user_count'],
shards=json.dumps(payload['shards']),
)
cluster.save()
return HttpResponse(status=200)```
i tend to use the generic api view in a class
then the serializers
you get alot of control over what fields you return overall
this is a pretty simple example from a quick and dirty system knockup
I'm pretty sure 'all' skips id
yh
it takes all the non-automatic columns
id is just an automatically generate unique value
tho you can replace it with a diffrent auto field depending on db size
which does then show up
Uh I guess gonna keep searching for unit tests
Huh, anyone experienced with flask?
I'm having unexpected issues I cannot fix using gunicorn and nginx to deploy a flask app
(which is just a static website, more or less)
I was following both miguel grinberg's and corey schaffer's tutorials
at some point I stopped and went straight for deployment, and did not mess with blueprints, and all
I'm trying to deploy using gunicorn -w 3 my_app:app
where my_app only has from app import app
this is enough to run on the local 127.0.0.1
app/__init__.py has, among more, the following
app = Flask(__name__)
from app import routes
Markdown(app)
if __name__ == "__main__":
app.run()```
does anyone have any idea on how to proceed now?
do you get an error
do ya'll have any links to any free web development courses?
@delicate vector I know about harvardx cs50
@quick cargo let me know if there's any file you'd like me to post
I see that miguel grinberg also made a manage.py script
you take it at your own pace
Does anybody have some experience in integrating Mailchimp in a Flask app? (https://github.com/VingtCinq/python-mailchimp). It's not quite clear to me if I can grab an API key without creating a Mailchimp app. When I try to authenticate via a simple API key (without creating a Mailchimp app) I get this response:
'You must provide an OAuth access token or API key'
seems pretty straight forward
you need API Key and username and you are good to go
@zealous siren No idea, but after couple refreshes it worked without touching anything, probably it was still picking up the previous config.py.
Another quick one: is it possible to add a celery task as a method in a class?
What I'd like to achieve is to subscribe a user to a mailchimp list (I was thinking to implement a task given that I don't want the app to hang while this is executed) but it'd be nice to implement this as:
# Create new user
new_user = User(id='id_string', ...)
new_user.subscribe_newsletter(frequency='weekly')
Instead of implementing a method in a tasks.py file:
@celery.task
def subscribe(user_email, frequency):
# Call mailchimp api to subscribe user to list
Hope it's clear enough
I'm not sure how to ask for help on this django issue I am having given that troubleshooting django requires the full file system I'd guess
I didn't change anything with my user settings nor my post actions and for some reason both are triggering errors, registering a new account triggers a bad input to save(), and trying to create a new post for some reason reads NULL as the post author
perhaps screenshots of the errors might help I don't know
that is what is triggered when trying to create a new post via the form, you can still create new posts successfully via admin panel
it was previously working
it shouldn't be getting null though
it is looking for the author attribute which is supposed to be assigned by the post
the post action requires a login verified with the loginrequiredmixin
so it should have a user to reference and define the author attribute
also, upon registration this issue is happening:
that one makes less sense to me
@fair agate What is your /register view code?
Could someone help me to implement Captcha with using Magick++, aka LynxChan C++ implementation?
I'm at a lost how does one accomplish the same while using Python and C++?
https://gitgud.io/LynxChan/LynxChan/-/tree/master/src/be/native
The best chan engine that you will ever shitpost with. Official board: https://balkanchan.ga/lynx/ IRC: #lynxchan @ rizon. Main front-end: https://gitgud.io/LynxChan/PenumbraLynx.
did you look at captcha
I did and don't want to use it as it's really really old and not maintained.
kryptonian because doing your own captcha is like doing your own encryption
Doesnt google have a captcha api you can use
I'm having a flask linux deployment issue. In a previous deployment I had to change img src to {{ url_for('static',filename='file1.jpg')}} how do I do this if I have the imgs nested in folders in static?
filename='path/in/static/file.jpg'
damnit url_for() didn't fix the issue anyway. Getting 404 on static files...templates is fine though...
Followed this https://www.digitalocean.com/community/tutorials/how-to-build-and-deploy-a-flask-application-using-docker-on-ubuntu-18-04
Dockerfile contains FROM tiangolo/uwsgi-nginx-flask:python3.6-alpine3.7 RUN apk --update add bash nano ENV STATIC_URL /static ENV STATIC_PATH /var/www/app/static COPY ./requirements.txt /var/www/requirements.txt RUN pip install -r /var/www/requirements.txt
I can't see how it's not finding the static folder, when static path is correct
if anyone has any ideas please shout. It's the final step in this web deployment and it's driving me nuts
do you know what specifically isn't finding the static folder?
e.g. the task running flask doesn't have access to it vs. the file doesn't actually exist where you think it might?
Docker I guess? It's the Dockerfile above that points to the static folder.
Could it be a permissions issue?
this is a rather random one but
any idea why a code with this bracket reversed works? If it correct it it does not work lol
I have some questions about the gmail smtp.
- When it says you get 100 a day does that mean it refreshes everyday at 12 orrr a day as in a 24 hour period.
- Does it all refill at the same time or does it refi based on the time it was used for example - I send an email at 11am, then one at 11:30. The next day will I get that credit back at the same time or will it all be available at one specific time
Found the answer in case someone also needs this information in the future
“They apply on a rolling 24 hour basis. That means that if you have a regular Gmail account and you send 500 emails at 2:00 p.m. on Wednesday, and it takes 10 minutes for the emails to send, you won’t be able to send any more emails until 2:10 p.m. on Thursday. Another example: if you send 100 emails from 2 p.m. to 3 p.m. on Wednesday, and 400 emails between 3 p.m. and 4 p.m. on Wednesday, then you won’t be able to send any emails until 2 p.m. on Thursday, at which time you’ll be able to send a max of 100 emails. After 4 p.m., you’ll be able to send more.”
do ya'll have any links to learn web development?
@delicate vector https://www.w3schools.com/ is a good first stop
Does anyone know what are the best tools for creating a simple coding website?
I have a university assignment where we have to implement some kind of 'quiz' web app (using Flask), with separate interfaces for admins to create quizzes, and people to take them.
I want to create a web app for teachers / lecturers of CompSci / SoftEng units to be able to create coding exams, and students to take them on the app (bc srsly taking coding exams in pen and paper is the worst).
How hard would it be to implement a simple version of this? I don't even know where to start in terms of having an interpreter IN the browser, and I'm aware that doing this blindly leaves huge security risks. Even if it was just one language (eg. Python) would be fine.
thanks, bud
Trying again because it's morning now haha. Is anyone familiar with Flask and Docker deployment? My webapp keeps 404 my static folder files and I have no idea why. I've followed this tutorial to the letter..https://www.digitalocean.com/community/tutorials/how-to-build-and-deploy-a-flask-application-using-docker-on-ubuntu-18-04
Hey, could someone explain me, please, how django apps work? F. E. I have a blog project, what apps I should add? Should I add an app for login/registration, for posts, for settings, profiles..?
@still depot You decide, it's about factorization and modularity
An app will tipically define models and views.
You have to decide what should go together
and put it in an app
If it's a small project, you could put everything in the same app.
Putting the authentication in another app makes sense though. That's what I'm doing.
Well, that's if you're handling authentication yourself, you could use a library such as allauth.
Or Django builtin.
Thanks. And what should you recommend to do in the blog site? Should I create one app for the blog, another for the login and stuff and another for an admin panel? Or should I split blog app into more apps?
That's a vast question. It depends on the complexity of your project. The purpose of structuring your project is mainly about maintainability. Is stuff easy to find ? Are you surprised to find stuff in some directories (you shouldn't) ? Is it easy to know if there is stuff or there is not ?
I'll make the hypothesis your project is rather small so, in your shoes, I'd use Django builtin admin and authentication system. So you don't have much to code.
And you could put everything in a single app.
I did that for a test project and I ended up with only 3 urls for profile and register. All the rest is handled by Django.
Oh, got it. Thank you very much.
Fixed my static files issue...just pointed STATIC_URL to the path instead
Does anyone know with digitalocean droplet and docker how I would point a custom domain to the ip:port?
hey guys, very newbie question, any quick explanation about <input type="file"> ?
how does it upload, how can i specify where it's stored? it stays inside a database? does a database stores images?
It can store images if they are converted to base64
and files? how does it work? like, .xls, .pdf, .doc
if it could create a folder with customer name as it's name and store files inside
would be perfect
i'm using flask
the folder creation i guess i already know how it works
but uploading it (in interface) and sending to customer folder
actually i found it
https://www.tutorialspoint.com/flask/flask_file_uploading.htm
Flask â File Uploading - Handling file upload in Flask is very easy. It needs an HTML form with its enctype attribute set to âmultipart/form-dataâ, posting the file to a URL.
sounds 'easy'
remember to use enctype attribute when working with files, it's easy to forget
hey guys I have a very quick question please
i have this to get the name from the form
and this
and I defined usr=user
but for some strange reason it gives me this error
usr=user should be an argument in your url_for function call, not the redirect function call
thank you so much that was a very silly mistake than you very much for the clarification 💙
hello everyone, I am having an issue with django
I hope you guys can help
I have two tables, CustomUser and Client
there are 3 types of CustomerUsers,
STAFF_LEVEL = (
('1', 'Associate'),
('2', 'Manager'),
('3', 'Partner'),
)
now when a user is creating a client, it needs to be assigned to a partner
the problem is, the form I created is listing ALL users, in the field I have as 'partner' and this is wrong
I have been trying to follow this: https://stackoverflow.com/questions/47182279/how-to-limit-choices-for-foreignkey-field-in-django-createview
I have a model structure along those lines:
models.py
class Foo(models.Model):
...
class Bar(models.Model):
foo = models.ForeignKey(Foo)
...
class Baz(models.Model):
bar = models.
but I failed
@native tide Not certain why, but can you add print(kwargs) and paste the output.
@native tide Not certain why, but can you add
print(kwargs)and paste the output.
@queen bough interesting, thanks for teaching me something here.
here is the output: {'initial': {}, 'prefix': None, 'instance': None}
Is __init__ in the view?
I am not sure... my django/python experience is limited to just completing Django for Beginners
I am going to say no..
I have edited it out
but partner is in that field so you can see the full section
Which class did you put the
__init__in?
@queen bough form
Can you print kwargs in get_form_kwargs?
it is blank {'initial': {}, 'prefix': None, 'instance': None}
which makes sense, the error I am getting says it cant find it
def init(self, *args, **kwargs):
partner = kwargs.pop('3')
super(ClientForm, self).init(*args, **kwargs)
self.fields['partner'].queryset = CustomUser.objects.filter(function=partner)
something is wrong with that
What's "it"?
def get_form_kwargs(self):
kwargs = super(ClientCreateView, self).get_form_kwargs()
print(kwargs)
kwargs.update({'3': self.request.user}) <------ this line gives an error
return kwargs
Ah right.
init() got an unexpected keyword argument '3'
Can you print(self.request)?
Can you print(
self.request)?
@queen bough <WSGIRequest: GET '/pms/new/'>
Which python version are you using?
3.7
OK, can you do print(dir(self.request), vars(self.request))
it print out all my directories
Try printing self.fields
Anyone can tell me if it's possible to use GitHub actions to auto commit a file in the repo?
Just to clarify - where do you expect partner to come from in the form?
@native tide
Doesnt google have a captcha api you can use
What part of no 3rd party services cannot people understand?
kryptonian because doing your own captcha is like doing your own encryption
@zealous siren Maybe so, but I don't want to give data to Google nor any 3rd party service.
Just to clarify - where do you expect
partnerto come from in the form?
@queen bough it should come from the CustomUser table
print(self.fields) is also blank @queen bough
what am I missing?
To access partner you'll need to get it from the Client model object.
Can you paste the Client model?
RISK_RATINGS = (
('1', 'Low'),
('2', 'Medium'),
('3', 'High'),
)
DEPARTMENTS = (
('A', 'Audit'),
('DA', 'Deal Advisory'),
('FRM', 'Financial Risk Management'),
('ITA', 'IT Advisory'),
('IRM', 'Information Risk Management'),
)
DESK = (
('0', 'Partner'),
('1', 'Risk Management'),
('2', 'Managing Partner'),
('3', 'Finance'),
)
class Client(models.Model):
client_onboarder = models.ForeignKey(
get_user_model(),
on_delete = models.SET_NULL,
null=True,
)
client_name = models.CharField(max_length=140)
is_individual = models.BooleanField()
address = models.CharField(max_length=140)
town = models.CharField(max_length=140)
country = models.CharField(max_length=140)
postal_code = models.CharField(max_length=140)
email = models.EmailField()
telephone = models.PositiveIntegerField()
client_evaluation_date = models.DateField()
next_year_end = models.DateField()
partner = models.ForeignKey(CustomUser, on_delete = models.PROTECT, related_name='client_partner')
client_type = models.CharField(max_length=140)
industry = models.CharField(max_length=140)
parent_company = models.CharField(max_length=140)
parent_reference = models.CharField(max_length=140)
duns_no = models.PositiveIntegerField()
is_sec = models.BooleanField()
is_global_client = models.BooleanField()
is_quoted_locally = models.BooleanField()
slp_approval = models.BooleanField()
tog_10 = models.BooleanField()
client_risk = models.CharField(max_length=1, choices=RISK_RATINGS, blank=False, null=False)
desk = models.CharField(max_length=1, choices=DESK, blank=False, null=False)
@native tide In the get_form_kwargs can you add:
object = self.get_object()
print(object)
It should be the client model object.
ClientCreateView is missing a QuerySet. Define ClientCreateView.model, ClientCreateView.queryset, or override ClientCreateView.get_queryset().
How about get_context_data?
Right the aim is to get the partner value from the view (after finding where it is).
And then use that partner to filter the CustomUsers.
wait a moment, here is the logic in my head, then you tell me if you are understanding correctly, the CustomerUser table has the list of users with the attributes
Yes.
class CustomUser(AbstractUser):
DEPARTMENTS = (
('A', 'Audit'),
('DA', 'Deal Advisory'),
('F', 'Finance Department'),
('RM', 'Risk Management'),
('FRM', 'Financial Risk Management'),
('ITA', 'IT Advisory'),
('IRM', 'Information Risk Management'),
('MPO', 'Managing Partner Office'),
)
STAFF_LEVEL = (
('1', 'Associate'),
('2', 'Manager'),
('3', 'Partner'),
)
area = models.CharField(max_length=3, choices=DEPARTMENTS, blank=False, null=False)
secondary_area = models.CharField(max_length=3, choices=DEPARTMENTS, blank=True)
function = models.CharField(max_length=1, choices=STAFF_LEVEL, blank=False, null=False)
so, CustomerUser how I defined has function
which has the three levels
Client has a foreign to CustomerUser
my thinking was to simply run a query set to filter out and do a standard function=3 run
Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.
To do this, use the following method:
```python
print('Hello world!')
```
Note:
• These are backticks, not quotes. Backticks can usually be found on the tilde key.
• You can also use py as the language instead of python
• The language must be on the first line next to the backticks with no space between them
This will result in the following:
print('Hello world!')
So that you can get all the CustomUsers with the
Partnerfunction?
@queen bough exactly
and that would be linked to the form
I see. So where should/does the partner value come from?
and that would be linked to the form
@native tide G2G, sorry I couldn't help. I'm not sure of the implementation details but if you can work out how to access theClientmodel object being controlled by the view then you should be able to access its.partnerfield. If you are creating aClientthen you'll have to work out how to access the passed parameters (self.request.POSTI think) and filter based on one of the parameters passed.
ok thanks for everything @queen bough
can anyone suggest me some course for Django
or flask
first tell me which one will be good. django or flask?
!code
Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.
To do this, use the following method:
```python
print('Hello world!')
```
Note:
• These are backticks, not quotes. Backticks can usually be found on the tilde key.
• You can also use py as the language instead of python
• The language must be on the first line next to the backticks with no space between them
This will result in the following:
print('Hello world!')
either is great to learn, both have tutorials as part of their documentation site
i want to make my carrier in web dev
then I'd suggest django, its tutorial covers a very wide range of its features
to get the same functionality in flask you have to configure libraries or make it yourself
hey, very new to this, started my first project today, trying to make a webscraper. Inside my container, I'm trying to pull out the info inside the SECOND div of a parent div, not the first. How can I do this? Thanks.
After defining the container and putting in
container.div
what goes next after that if I don't want to call the first div in that div inside that container by using
container.div.div
instead I want to call the second div inside the first div so
container.div.(what goes here)?
I could always call the whole container.div but I'd rather just get the individual piece of info out of it
Hei guys I needed a bit of help with Django
whats up
Good
Hi . everytime I run my webapplication locally it runs on a different port
http://localhost:50584/ 1st try
http://localhost:51117 2nd try
I would like to have it always fixed on some specific port
I need to redirect back a Oauthentication code back to a specific port that I should already know . and it is kinda impossible with the project choosing a random port everytime
WBU?
@viscid spoke you're flask right?
yes sir
@young grove im good, whats ur issue
@viscid spoke how are you starting the flask server
"""
The flask application package.
"""
from flask import Flask,request,render_template,redirect,session
client_id="705765391510798408"
client_secret=""
scope="identify"
redirect_url="http://127.0.0.1:50000/login"
discord_login_url="https://discord.com/api/oauth2/authorize?client_id={}&redirect_uri={}&response_type=code&scope={}".format(client_id,redirect_url,scope)
app = Flask(__name__)
@app.route("/",methods=["get"])
def index():
return redirect("discord_login_url")
@app.route("/loggin",methods=["get"])
def login():
return "logged in"
import FlaskWebProject1_oAuth.views
Idk if this will answer your question but I am literally using Visual studio flask project without editing anything
I'm facing a problem with the code Django, a bug to be more specific, that is when I'm adding an item to the cart for the first time(with variations let's say Red and Medium), it's being added nicely. Then when I'm adding another item(let's say Blue and Large), it's also working. But when, I'm increasing the item quantity from the order_summary.html, it's increasing the quantity of the other item not the one I clicked(if I clicked Red and Medium, Blue and Large's quantity is increased) and says : Please specify the required variations. Why is this happening? Can anyone please help me out? Thanks in advance!
@viscid spoke are you using vs to run the flask server?
yes
go into the setting for vs where you select what to run
should be a port option
@young grove i take it you're using templating right?
Yea
SHould I just add my port here ?
My models.py:
class Item(models.Model):
title = models.CharField(max_length=120)
price = models.FloatField()
class Variation(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
name = models.CharField(max_length=50) # size, color
class ItemVariation(models.Model):
variation = models.ForeignKey(Variation, on_delete=models.CASCADE)
value = models.CharField(max_length=50) # small, medium large etc
class OrderItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
item_variations = models.ManyToManyField(ItemVariation)
quantity = models.IntegerField(default=1)
ordered = models.BooleanField(default=False)
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
ref_code = models.CharField(max_length=20)
ordered = models.BooleanField(default=False)
items = models.ManyToManyField(OrderItem)
start_date = models.DateTimeField(auto_now_add= True)
ordered_date = models.DateTimeField()
can you send the snippet where you have the templating in the html aswell
and where you inject the template
np 👍
Hey @young grove!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
My urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('add_to_cart/<slug>/', orders_views.add_to_cart, name='add-to-cart'),
path('remove_from_cart/<slug>/', orders_views.remove_from_cart, name='remove-from-cart'),
]
My order_summary.html (where I can increase quantity):
<a href="{% url 'remove-single-item-from-cart' order_item.item.slug %}" class="btn mr-2"><i class="fa fa-minus"></i></a>
{{ order_item.quantity }}<a href="{% url 'add-to-cart' order_item.item.slug %}" class="btn ml-2"><i class="fa fa-plus"></i></a>
If you need anything more, please inform me....
Again, to sum it up, I'm facing a problem with the code, a bug to be more specific, that is when I'm adding an item to the cart for the first time(with variations let's say Red and Medium), it's being added nicely. Then when I'm adding another item(let's say Blue and Large), it's also working. But when, I'm increasing the item quantity from the order_summary.html, it's increasing the quantity of the other item not the one I clicked(if I clicked Red and Medium, Blue and Large's quantity is increased) and says : Please specify the required variations. Why is this happening? Can anyone please help me out? Thanks in advance!
thats weird
its good
tho for somone like me who's doing a site for their finals
cant rlly use it
cuz DBs are big marks and orms dont give ya points
Django is everything
No sql, no php
Fantastic 😍
And django-admin?
Legendary 😍
noice
And some NAT rules on my router
Of course a DMZ to protect all my personal devices in my lan
My router came setup with NAT out of the box which was both a nice thing and also a rather annoying thing when attempting to route somthing or other
hehe mine wasnt
if you want my advise
dont get an asus router
they cost an arm and a leg and last like 4 months
Ah
tho the warranty is reliable i dont enjoy going through 6 routers 2 years
Eheh
"My" router is Zixel lol
Sometimes my providers give Fritzbox that is really good
So I was praying to have it
But they gave me a Zixel
That isn't really famous
I'd say Cisco is best if you are running multi Gbps pipes
otherwise, all you are paying for is the na,e
hi i am learning django and i have a question
so i see this
to me it looks like I am mapping the same url twice
what am i not getting?
hey guys I need help I need to create a form where people fill it out and when they press send it gets inserted into a database
i have the UI finished, and the flask server running, the flask server is connected to the oracle database
but I dont know how to actually send the information to the flask server
idk if this is the write channel but can anybody tell me why this doesnt work?
from selenium.webdriver import Chrome
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from time import sleep
driver = Chrome()
driver.get("https://www.youtube.com")
WebDriverWait(driver, 600).until(expected_conditions.presence_of_element_located(("css selector", "#button"))).click()
sleep(30)
driver.quit()
it is supposed to open up youtube and click sign in
nvm, i figured it out!
@urban talon Do you have the HTML written out already? The form element on the HTML side essentially gets the browser to send data to the server via a POST.
hey guys I need help I need to create a form where people fill it out and when they press send it gets inserted into a database
i have the UI finished, and the flask server running, the flask server is connected to the oracle database
but I dont know how to actually send the information to the flask server
@urban talon ```
@app.route('/your_route', methods=['GET', 'POST'])
def your_view_function():
form = YourForm()
if form.validate_on_submit():
number = form.number.data
yourObject = YourClassModel(number=number)
db.session.add(your_object)
db.session.commit()
return redirect(url_for('somewhere'))
return render_template('somewhere.html', form=form)
this is an example, i supposed you have a form, and you have to fill a number
to me it looks like I am mapping the same url twice
@native tide So, see the directory, polls and mysite, two different things. mysite is the project folder (the main folder) and polls is an app of your website (remember concept of django modularity).
Bros any help for me?
@native tide mysite/urls.py basically says that there are 2 main apps, admin/ and polls/, and inside /polls notice that there is the method include('polls.urls'). So in your localhost for example, if you type 127.0.0.1:8000/polls/, first django goes into mysite/url.py and search for a match, it find polls/, then it goes into polls/urls.py and it search for another match
That help you for better mainteined code, its bad have all routes inside one files
which bug
I'm facing a problem with the code, a bug to be more specific, that is when I'm adding an item to the cart for the first time(with variations let's say Green and Medium), it's being added nicely. Then when I'm adding another item(let's say Blue and Small), it's also working. But when, I'm increasing the item quantity from the order_summary.html, it's increasing the quantity of the other item not the one I clicked(if I clicked Red and Medium, Blue and Large's quantity is increased) and says : Please specify the required variations. Why is this happening? It's also worth noting that when I'm adding the same item with same variations from my single product page, then it's working fine. I think this bug is occurring because of the way my views is written. I tried to solve it myself, but I'm getting lost
how do i get a ng-bind in selenium?
hey guys, can anyone help me please? i don't manage to upload images with flask
i've already explained my code into this stackoverflow topic https://stackoverflow.com/questions/61657361/the-upload-of-the-image-doesnt-work-in-flask-python
i'm trying runtime.getManifest() to get the complete manifest.json file for a web extension, serialized to a JSON object but it says runtime not defined ?
it looks like that function is only available in the context of a browser extension https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/getManifest
is that where you're running that code?
@amber moat have you specified the runtime?
You need to specify the browser that you want to run it on
The syntax is browser.runtime.getMainFest()
@cold anchor the extension is a bookmarks manager, and whenever i open a new tab it always shows up
@native tide now i get this error TypeError: browser.runtime.getManiFest is not a function
am i missing any step ?
@amber moat try to fetch some of the data from json say name
You can try this
var manifest = browser.runtime.getManifest(); console.log(manifest.name)
that works well and prints out the name key, but how do i list all the manifest keys ?
@amber moat you need to parse the JSON. As the function returns an object in our case manifest then you can just apply parsing to that object
Ok thanks rdbaker and DarkShadow i got it.
Hey so today I was spammed by someone who created group chats and added me. I'm sorta new to selenium and I plan on making it whereby I leave the group for which the user spammed me. I did contact discord regarding the incident in hopes of them helping me. However, it will some time for them to respond and I'm not sure how they will respond to my situation where it be removing me from the group the spammer decided to add me or not. So I'm asking assistance in regards to creating a simple script with selenium which leaves the groups that I'm in with the spammer.
discord on chrome for selenium to work
I'm sorry but automating discord goes against discord tos so isn't something we'll help with .
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious/inappropriate or be for graded coursework/exams.
Yes
Alright.
nicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 3220: ordinal not in range(128)
Facing this issue does anybody has any idea its on my docker
I am trying to use flask to build one of my first pages. I have built a table in HTML and I want to return the form data to python. I am not sure how to go about it. Here is my table:
{% extends "base.html" %}
{% block content %}
<!-- Entry form in bootstrap Book, Author, Rating -->
<form action="{{ url_for('table') }}" method="POST">
<div class="form-group row">
<label for="book" class="col-sm-2 col-form-label">Book Name:</label>
<input type="text" placeholder="Book Name" id="book" name="book">
</div>
<div class="form-group row">
<label for="author" class="col-sm-2 col-form-label">Author:</label>
<input type="text" placeholder="Author" id="author" name="author">
</div>
<div class="form-group row">
<label for="rating" class="col-sm-2 col-form-label">Rating (Out of 10):</label>
<input type="text" placeholder="Rating" id="rating" name="rating">
</div>
<div class="form-group row">
<button type="submit" class="btn">Submit</button>
</div>
</form>
<hr>
{% endblock %}
I have a view function set up in python as follows:
@app.route("/table")
def table():
@knotty seal tyically the route that renders the form will handle both the GET request (first render of the form) and POST request (when user presses submit)
you can have a branch in the route on the condition request.method == "POST" and handle the form data from there
you need to add @app.route("/table", methods=["GET", "POST"]) to allow both request types
Is there anyway of using selenium to find by text?
driver.find_elements_by_xpath("//*[contains(text(), 'My Button')]")
is this way?
@surreal tangle - Thanks. I have now written the display in python as:
@app.route("/entry", methods=["GET", "POST"])
def entry():
if request.method == "POST":
bookName = request.form["book"]
authorName = request.form["author"]
rating = request.form["rating"]
print(f"Book: {bookName} Author: {authorName} Rating: {rating}")
else:
return render_template("entry.html")
👍 works as expected?
@surreal tangle - I had to add a return in the POST conditional, but yes, it works 🙂 Thanks!
great 😄 and np
Anyone have thoughts / preferences on Flask & Jinja2 versus Flask as an API and then something like ReactJS on top leveraging the API? I just finished doing this (https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world) and applying it to a project I have been working on and trying to figure out where to go from here.
I don't @severe swan, but I have been doing that tutorial too. It's a bit too complicated for me at the moment, but has taught me a lot.
I usually make that decision based on what type of service/product it will be. Single app with minimal "external" functionality? -> flask app by itself. Enterprise or consumer app that has a lot of bells & whistles? -> flask as API with react on top
Does anyone know how to protect db from sql injection? (flask, sqlite)
@fickle fox Always use bound statements
validate your inputs
Treat user input as hostile
@cold anchor that's a good thought & partially the way I was thinking. Have me and my wife use it as is & then build an API for my front-end to interact with instead of using direct routes with direct DB calls. And then if I want to move it forward, just build React on top of the API I have built.
using declarative sqlalchemy will take care of 90% of that
Wait wait how to trwat it as hotstile or to use bound statement?
Hostile means, assume that every data you receive has potential attacks in them
So validate in JS, validate on the server
see if what you get makes sense
As in, run a regex or whatever to see if the email address contains an @, or if it's bullshit
As I always like to say: a plain bullshit filter
you store the hash in the db
psql for example has a good facility to salt and pepper passwords
but hash it in your programming language
this way you don't even need to take care of that
bcrypt is the standard for this https://flask-bcrypt.readthedocs.io/en/latest/
Here is an example from my code:
#------------------------------------------------------------------------
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
Speaking of that Flask mega tutorial - this section shows user / password hashing & storage. https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-v-user-logins
never heard of using the db as a crypto before https://stackoverflow.com/questions/2647158/how-can-i-hash-passwords-in-postgresql that's interesting
Not all db can do that, but if it can, I'd suggest using it
and kind of nice, but it raises a good point: the unhashed password is floating around your system a lot longer and it liable to be logged in things like queries
Sqlalchemy?
It's a orm system
Sqlite is now something i am using
Basically it abstracts the database interaction into OOP
you can exchange the backend at any point
Object-relational mapping (ORM, O/RM, and O/R mapping tool) in computer science is a programming technique for converting data between incompatible type systems using object-oriented programming languages. This creates, in effect, a "virtual object database" that can be used f...
Thanks i will try it :D
@severe swan that's very popular setup, miguel shows how to create static website
nothing wrong with it
I'm currently trying to make a simple wishlist using django and was currently trying to render something if the wishlist has no items, but it doesn't show up
<h1>Wish List Items</h1>
{% for item in item_list%} {% if item_list|length == 0 %}
<h3>No Wish Items Exist</h3>
<hr />
{%else %}
<h3>Hello</h3>
{% endif %} {% endfor %}
</body>```
I noticed that when I do Items.object.all() in the shell, it says Item has no attribute object, but not sure how to fix it
you're rendering your conditional that checks if the length is 0 inside the for loop, but since the length is 0, it doesn't enter the for loop
move the if/endif block to outside the for block
so i added some items to the wishlist using the adnin so i checked it using the shell, so it should display hello
>>> Item.objects.all()
<QuerySet [<Item: Laptop>]>```
on the webpage, it still says no wish items exist
alright i fixed it
Thanks for the help here. Made my first Flask App. It's a shitty app, but :)
https://themercantile.pythonanywhere.com
Hi. Does anyone have experience pulling reporting from DCM api?
Guys is there a way to populate flask_Wtf hiden form with jinja ?
you could render a field like {{ form.email(class_="hidden") }}
is that what you are asking?
class wtforms.fields.HiddenField
then {{ form.whatever ( value = {{ itemfromloop.id} } ) }}
does anyone know why i get error 'post' undefined
def edit(id):
if request.method == "POST":
post = BlogPost.query.all()
post.title = request.form['title']
post.content = request.form['content']
post.author = request.form['author']
db.session.commit()
return redirect('/posts')
else:
return render_template('edit.html')```
it's probably not coming from that code. Paste the stack trace. (And you might ask in a regular help channel)
Hi again! Im following this django tutorial, for a particular view function, the last line is return HttpResponseRedirect(reverse('learning_logs:index')), to be executed upon a valid form submission.
in the template for that page, the form ends with <input type="hidden" name="next" value="{% url 'learning_logs:index' %}" />
is this not redundant?
because the button redirects you but then so does the app once you submit
Should i use Vanilla JavaScript or Jquery when i am building a website's frontend?
which one is better?
if you have no prior knowledge of jquery and you just want to sprinkle some js in your html I think you're fine with vanilla
here's a nice little reference to do all the things jquery does yourself if you're looking to learn about it http://youmightnotneedjquery.com/
Examples of how to do common event, element, ajax and utility operations with plain javascript.
- Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead. - Debug mode: off
Usage: flask run [OPTIONS]
Error: Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory.
idk whats wrong
nvn
anyone familiar with Quart?
I'm having an ImportError that I'm having a difficult time solving
ImportError: cannot import name '_lookup_app_object' from 'quart.flask_patch.globals'
does anyone know where I can go to receive help with css?
what is your query? @native tide
guys, i'm having an strange error.
my flask app runs, i can see my pages, all imports are done, but the page seems to not interpret my User class.
'User' class is inside this
Is heroku hobby tier worth it
anyone know how to "un-init" a flask-sqlalchemy database?
learning sqlalchemy, made a bunch of mistakes and wanna wipe the whole thing and start from scratch
is there a way to get embed image from python code
python code with upload html and css and javascript and then run it and output gonna be embed immage
i don't get it why the css isn't loading in the existing html
i've tried changing to absolute path ./
this has happened earlier too
<link rel="stylesheet" href="./components.css"></link>```
and both all the css files are in the same directory
here's what i got from console
ReferenceError: chrome is not defined
Resource URL: file:///D:/Unfinished%20Projects/Visual%20bookmarks%20firefox/reference/vb@yandex.ru/layout/zen/loader.js
Source Map URL: loader.legacy.vb-bundle.js.map```
Run a server, then it will work
also, there is no </link>
python -m http.server on your directory
@amber moat
guys i'm trying to upload images through flask but when i do the upload, the image doesn't load onto the server but without returning errors
is something wrong?
def save_picture(form_picture):
random_hex = secrets.token_hex(8)
_, f_ext = os.path.splitext(form_picture.filename)
picture_fn = random_hex + f_ext
picture_path = os.path.join(app.root_path, 'static/profile_pics', picture_fn)
form_picture.save(picture_path)
return picture_fn
@app.route('/account', methods=['GET','POST'])
def account():
...
...
form = UpdateAccountForm()
if form.validate_on_submit():
if form.picture.data:
picture_file = save_picture(form.picture.data)
current_user.image_file = picture_file
current_user.email = form.email.data
db.session.commit()
return redirect(url_for('account'))
...
image_file = url_for('static', filename='profile_pics/' + current_user.image_file)
return render_template('account.html', form=form, user=us, notifications=notifications, image_file=image_file)
What would be a way to convert user input date to mysql column is there a way to format mysql column to accept just d m Y ?
or i guess i cna go with datetime.strptime
@tired root why do i need a server ?
@tired root now i'm left with only this error: ReferenceError: chrome is not defined
i don't use chrome
is there a way i change something
@amber moat Because webstuff is sandboxed and cannot access the filesystem, that is the gist of it
A webserver serves the files needed
it seems so i was just now reading about it on SO
I don't know where that error comes from, so cannot say anything about it
Probably some js library
No, there is nothing you need to do. python -m http.server is only for pure html/js/css files though
If you are doing django or flask, they have built-in debug servers
however, that wouldn't fix the js error
need to look into the docs there
like on SO an additional thing was mentioned Everything on there will be allowed to be got. Example: background: url('http://localhost:8080/waw.png');
This is going to suck when you go live
as you need to exchange the URI then
keep that in mind
i didn't even get it though
that's alright it's an example. i thought i had to do something like 'http://localhost:8080/new.html' everytime to make it go through the server set up...
i'm completely new to this
Yeah, I think you are mixing up a few things here
any1 here with django i needed some help
what if i use a chromium based browser for a dirty fix ?
@amber moat That won't solve the issue
The chrome variable is available on firefox as well
i'm using brave i think it's chromium based if im not wrong
chrome returns a callback, browser a promise
a promise ?
yes
need to look up terminology lol
What library is throwing that error?
I want help with submitting a image and then displaying it on a page dynamically (not using admin panel) in django
i'm digging inside an extension
django project ideas
Yeah thought it is an extension
wow
I don't think you can run this with a simple web server
I would need to look at extension programming to say more, can't really help there
@solar hatch r u saying to me?
??
can i attach the .xpi file ?
you need to debug the xpi file in the browser while sideloading it
it's not webdev as such, it's a whole different world
what exactly ?
my actual idea is to create a visual bookmarks extension
Look at the link I gave you, it's a howto on extension development
never done it, can't really help with it
ok i'll take a look
i have a similar issue with vivaldi too
vivaldi's files are all html and css (it's an electron app) and the html doesn't load css or js when opened in an external browser
and shows up errors
Not allowed to load local resource: chrome://vivaldi-data/css-mods/css
DevTools failed to load SourceMap: Could not load content for chrome-extension://odbfpeeihdkbihmopkbjmoonfanlbfcl/sourcemaps/contentscript.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME
i think it's trying to access an extension
In flask, how do I return a template to a specific container?
Like I would with an href? <a href="#property">
That is an anchor, it would scroll to the location where the anchor is defined
@harsh flare
so if I'm doing ```@app.route("/form", methods=["GET", "POST"])
def my_form():
some_stuff...
return render_template('contact_submitted.html')
How do I get the template I've returned to scroll to that anchor?
I don't understand the question. An anchor is something that is present in the html
It has nothing to do with flask
you need to explain what you want to achieve
Do you want to load dynamic content or what is the goal here?
So the function is meant to return a template where the contact section has been changed to "Thank for you submitting your enquiry" in place of the form. However the template returns to the top of the page, and I want it to load to the contact section
I think the answer is you can't. https://stackoverflow.com/questions/31863582/automatically-scroll-to-a-div-when-flask-returns-rendered-template
use a redirect, not render_template
then you can also use a simple anchor actually
So, whatever handles the contact form, needs to return redirect("/contact#submitted") for example
It's a bit confusing, I'd need to see how the routes are set up
You mean set up a route to the contact_submitted.html as @app.route("/contact") def contact(): return render_template('contact_submitted.html')
then for the form set up
def my_form():
some_stuff...
return redirect('/contact#contact') ```
yes, for example, then you just need to include the submitted thank you message with js or so
^ it worked
Many ways to do this kind of thing though
Probably not the most efficient eh! The contact_submitted.html is just the same as index.html but I turned the contact form into a <h3> that says "Thank you for your enquiry...."
I mean, you can also run the route with javascript via xhr and insert the message after it was completed successfully
then there is no visible reload
yeah thats what I'd prefer really...you got a link to a tutorial on that?
just look how a xhr request works and make a route that returns some json if it was successful or not
and make sure to POST the form content
hey i am trying to edit post but its not working for some reason
anyone knows why?
@app.route("/posts/edit/<int:id>", methods=["GET", "POST"])
def edit(id):
if request.method == "POST":
post = BlogPost.query.all()
post.title = request.form['title']
post.content = request.form['content']
post.author = request.form['author']
db.session.commit()
return redirect('/posts')
else:
return render_template('edit.html')```
"is not working" is not an error message and not a traceback
but look at your query
If that would work, you'd edit all rows of BlogPost
maybe you want to actually use that id to update the blog post that is being edited
and check if the user has actually permission to do so
i didnt yet add permissions so i will probably do it later
how would look my query?
i mean why should i change
If you cannot answer that question, then maybe you shouldn't be handling databases...
again, you are trying to edit all rows in that table
There is no where clause based on the id
so maybe you want to filter_by and use the id
BlogPost.query.filter(BlogPost.id==id).first()
id may or may not be right, however you've setup your tables
hmm its still not working
never mind i fixed it 😄
Anyone to help me out with Sqlalchemy query
can someone give me tutorials
how to make website
@native tide Yo' this guy have the best free course I have every seen online:
In this Python Flask Tutorial, we will be learning how to get started using the Flask framework. We will install the necessary packages and get a basic Hello World Application running in our browser. Let's get started...
The code for this series can be found at:
https://githu...
In this Python Django Tutorial, we will be learning how to get started using the Django framework. We will install the necessary packages and get a basic application running in our browser. Let's get started...
The code for this series can be found at:
https://github.com/Core...
flask and second django
I'm sorry I didn't understand what you mean, can you say again?
At this point I want to warn people from letting some random stranger on the web host their stuff
Scorcher, hey bro, I wanted to know if there are alternatives to WordPress as a headless CMS to manage the database for the web app
Flask to be specific
Where does this bullshit come from? Honest question. You are the second person this week to ask how to manage a database with Wordpress
Write an admin panel.period
Or, use a static site generator, it is more than enough for a blog
yeah
it doesnt take long to make a system todo that
django even has an inbuilt admin panel for managing db data
i dont even get why people like wordpress
My blog is updated by sending a markdown file into a git repo, which sits on my raspi in a cabinet in my living room. It then syncs the output to my webhost.
nice
You can have the same for free with github pages
I just implemented that myself @ home
is it just waiting for a commit then to the repo then get the file?
I am using Ruby Jekyll
fairs
The git has a post-receive hook, which starts a script building my web using Jekyll
then I connect via rsync to my webhoster and upload the differences
bundler exec jekyll build --verbose --trace
rsync -aP -e ssh /home/user/$PROJECT/_site/ $REMOTE:html --delete``` that is all the magic
No database to maintain, no attack vector and no bullshit. The last part is the most important for me.
No broken plugins, no hacking templates
pretty nice
Fuck Wordpress with an anchor
i dont see the use with wordpress
Hello guys.
CMS is so bad
I am getting circular import errors in flask and sqlalchemy
!imports
@somber wedge You are probably importing things from the main app in another file right?
But that is how the tutorial says and it worked last night too.
from flask_sqlalchemy import SQLAlchemy
# Create SQLAlchemy
my_db= SQLAlchemy()
``` put this into an extra file
the folder should be at the lowest hirarchy
#this is models.py file
db = SQLAlchemy()
#define classes here
#this is app.py
with app.app_context():
db.create_all()
from file_youve_put_this_in import my_db as database
# Initialize ORM
database.init_app(frontend)
with app.app_context():
database.create_all()```Put this in your app.py
I'm confused
Is there something I can read for details?
Like some articles or something
@somber wedge The documentation for flask-sqlalchemy
You create an SQLAlchemy instance and then you need to bind it before your app starts
Okay. Thanks. But most of the tutorials for sqlalchemy do it with circular imports.
because most tutorials suck and only copy the introduction code and act like they know stuff
It's just stupid clickbait
facts
There are very few websites out there that actually go into detail and teach how to really do it
That is true, docs are not even that bad tbfh
That is why it is important to understand shit and get away from Ctrl-C Ctrl-V
Lol it was actually me from before too scorcher, but look, okay I can make an admin portal, but they want to be able to edit the websites layout as well, that wouldn’t be possible with any other existing CMS right?
The whole point is to let a non-developer staffs manage the website after I am done building it for then
Them*
I prefer reading docs myself. But I was following a bigger tutorial where handling the db is a side task. So I thought there might be some quick stuff I could learn. But thanks for the help, I'll look into the docs.
@viral sphinx You can make an editor using a drag and drop library for js, but at this point they should just use wordpress then
Btw is there something I should learn before learning sqlalchemy? I only have knowledge of handling db from command line with manual sql or in sqldeveloper. But I've never created integrated apps with db. So I don't exactly understand the full concept of sqlalchemy. I understand something like it maps python objects to db tuples programmatically hence automating the db fillup and SQL. But that's all I know.
It also sanitizes input so your db cant get exploited
Btw any of you work with heroku
I have worked with it in the past
So how much time it takes for a sleeping dyno to wake up? Like if someone is loading the app for first time in a while?
Is it within like what you'd call normal load times for websites?
Yes I guess
I usually use AWS elastic beanstalk for that, simple and straightforward
I'm already running something on beanstalk.
So I was looking into the possibility of heroku
Is this a website or an API?
API
There is a dedicated API service on AWS
This is a backend that will be used with a front-end
It kinda works like an api, only sending json.
Everything else happens in the front-end.
There is a jinja addon, but it barely works
@rustic pebble This is pretty much how vue and others work
so...
I see
react, vue and angular are not python based though
So? They take a json string from a backend and construct the frontend
Of course
If you do the backend with flask, ruby, php or rust or C++ does not even matter
Well yes
But then Node makes it seems effortless especially if you are running on typescript
I take something else over node any day
Why is that?
That is not a real answer, it is just your personal opinion about the library
No one said you aren't
Does anyone have any suggestions for what sorts of things I should be testing when making a django app? I'm feeling like I don't know which things I should test, and which things don't need tests. For example, if I use the ListView generic and give it the model name/template, where the the template displays an alternate message if no items are found, I'm unsure what needs testing and what just amounts to testing the ListView class. I felt like the alternate message should get a test because it's sort of non-default behavior of my template I'm testing. A test that adds a record and sees that it's displayed doesn't seem necessary though, because that's built in behavior. Are these feelings in the right ball park for what to test in general?
XSS, SQL injections
Thanks, I'll keep those in mind. What about non-security portions?
well, if the output is what you expect
jsonify the data and check it with a unit test
Here is a small snippet:
import re
class Minify:
def __init__(self, text: bytes, remove_linebreak: bool):
self.text = text
self.regex = "[>]\\s{2,}[<]"
# First step: remove line breaks
if remove_linebreak:
self.text = text.replace(b'\n', b"").replace(b'\r', b"")
def run(self) -> bytearray:
new_html = bytearray()
matches = re.finditer(self.regex.encode(), self.text, re.MULTILINE)
pointer = 0
for each in matches:
new_html += self.text[pointer:each.start()+1]
pointer = each.end()-1
# Add the rest without matches
new_html += self.text[pointer:]
return new_html
It is minifying the html output
not perfect, but small and quick
maybe someone finds it useful
This is probably going to be over my head, but I'm curious so I figured I'd just ask...
If I rent a dedicated server, can I run a website off it after paying for the domain?
I'm not looking for the best performance, I'm just looking for something that I can use to host web apps when I start building a portfolio. I started learning Django a few days ago and from the little I know about DNS routing, as long as I have a server with an IP to route to then I should be set to run a web app off it.
Or am I missing a piece of the puzzle? Like I said, I'm very new to web development, but I'm curious what my path is going to look like.
definitely doable
I run https://teensy.info on an el-Cheapo EC2 instance
I don't think I installed anything on the box besides python itself, and some packages from pip ... and ... I think nginx
but I only installed nginx because I wanted to do TLS; before then I didn't use nginx
@molten quarry Generally, yes
If you buy a domain, you probably have DNS covered, make sure the provider has a dns panel where you can edit IPV4 (A) and IPV6 (AAAA) and that they provide reverse zones
DNS isn't routing though btw
The more challenging part is not getting it hacked
Also dedicated root may be a bit too much for that
a vps is more than enough
but you still have to administrate it and abide by various RFC, such as 1918, CGNAT and APIPA
If you want MX, make sure to have SPF records and DKIM dmarcs
Otherwise your mails are going nowhere
@quasi ridge Apache is perfectly fine for TLS, so I don't get it, Apache also comes with native Python support
If one wants to be extra fancy, I'd use haProxy as Layer 7 reverse proxy, then you can just run Apache and have haProxy handle the requests
well I suppose I could have chosen apache, too; I chose nginx instead
haproxy is a multitude faster than nginx and apache together, but as I said, it's a pure reverse proxy
something tells me that @molten quarry is more interested in ease of setup than speed
Well, ease of setup isn't a concern when you set up a root server facing the public
if you want easy, go Heroku paid
not a bad idea
Because people wanting easy is why I get paid a lot of dosh to weed out the ones that got hacked and make sure our part of the internet is safe
and the bad guys 😛
deploying sites youself isnt gonna be ease of use no matter what you do so you might aswell go the long way and do it properly
we're all just guessing what Fishy's priorities are
i gotta sort my ssl cert out tomorrow 😫
On heroku you have at least system security covered and don't get locked because your server is sending RFC1918 into the network or reflecting NTP growth attacks
@quick cargo I've been using letsencrypt with some "client" software called "acme"; I was surprised how easy it was
Contabo the host im running a vps off atm has zero details on setting up ssl with one of their machines
so gonna be a bit of a research task first lol
contabo VPS
no, which webserver software
oh
it's just a matter of that
im just using nginx and gunicorn atm
then nginx needs to supply the certificate
how can i set that up?
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com;
root /var/www/example.com/public;
ssl_certificate /path/to/your/certificate.crt;
ssl_certificate_key /path/to/your/private.key;
ssl_protocols TLSv1.2 TLSv1.3;
}```
apt install certbot or so should install the let's encrypt certbot
run certbot with either the acme challenge (webserver based) or a dns challenge
certify the challenge and certbot will create the certs
then add a cronjob to update the certs all 2 months
it's really simple if you know your way around Linux
also make sure to redirect all requests to http to https
yeah ofc
listen 80;
server_name linuxize.com www.linuxize.com;
return 301 https://linuxize.com$request_uri;
}```
I don't know what I want. At the moment, I'm not knowledgeable enough to know the difference. More than anything, I just wanted to confirm that an el-Cheapo server could run a website. I thought I might have to get something special aside from a server and a domain name.
Anyone knows a good way to autoreply by email to a person who just submited contact form on my flask website?
WTF have this?
I was just planning to get a $10 server from OneProvider and launch something revolutionary.
yh small sites arnt rlly load instensive
the databases are generally more intensive then website
I don't understand why this is happening with flask, I guess it's a bug or something http://www.lifeisyo.ga/uploads/wtflask.mp4
😍
autocomplete for flask templates?