#web-development
2 messages · Page 83 of 1
Use this
Post.objects.filter(user=request.user)
@woeful trellis
<p>Post Created: {{ Post.filter(user=request.user) }} </p> that is where i want to dispplay the result
error Could not parse the remainder: '(user=request.user)' from 'Post.filter(user=request.user)'
show your Post model
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
date_published = models.DateField(default=timezone.now)
Post.objects.filter(author=request.user).count()
Add it in views
still not working sur
The gn's code is right
def profile(request):
if request.method == 'POST':
user_form = UserUpdateForm(request.POST, instance=request.user)
profile_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(request, f'Profile have been update')
return redirect('profile')
else:
user_form = UserUpdateForm(instance=request.user)
profile_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'title': 'Profile',
'user_form': user_form,
'profile_form': profile_form,
'post': Post.objects.all()
}
return render(request, 'users_app/profile.html', context)
the view includes updating user data
'post': Post.objects.filter(author=request.user).count()
'post': Post.objects.filter(author=request.user).count()
@woeful trellis sir sir its working haha nice nice thank you @woeful trellis @vestal hound 😅 👍
btw why do i need to get the count on the view instead in the template? is it illegal?
or its the difference between model views and def view?
Hey, I have a lil problem in #help-kiwi about Django. I think it's easy to solve my problem, but idk, it may be a whole nother bucket of stuff.
hmm what's peoples experience with Bulma
I just discovered this and it looks super cool
@woeful trellis sir sir its working haha nice nice thank you @woeful trellis @vestal hound 😅 👍
@lapis spear
Your welcome
Anyone know how Sanic is failing to parse this requests body? I'm making the request /w aiohttp.
async with session.request(
method="POST",
url="http://XXX.XX.XXX.XXX/request/",
headers={
"Authorization": ("X+"
"X==")
},
data={
"method": "GET",
"url": "https://partybot.xmistt.repl.co"
}
) as r:
It seems perfectly fine to me.
This is the response I get exactly:
<!DOCTYPE html>
<meta charset=UTF-8>
<title>400 \xe2\x80\x94 Bad Request</title>
<style>html { font-family: sans-serif }</style>
\n
<h1>\xe2\x9a\xa0\xef\xb8\x8f 400 \xe2\x80\x94 Bad Request</h1>
<p>Failed when parsing body as json\n</p>
Sending the request from Postman for example works just fine.
hey guys, can anyone tell me about something in django ?
i would like to know what's the difference between installing an app in settings.py this way 'snippets'and this way 'snippets.apps.SnippetsConfig'
@past cipher This might be a dumb question, but I'm quite new to discord and i have no idea how to post a code snippet like that? Is that just a picture?
@zealous cloud type ` once for an inline comment and then add another at the end of your code
type ` three times follow by py and paste your code, then at the end of your code type it three times again
@past cipher Awesome. Thank you
Hello guys, I'm building a simple api with Flask with just few routes, I'm using flask-restful and I'm looking for "the best" architecture to build it, I'm currently looking to use Blueprint with flask restful and I wanted to know if it is a "good choice" or if there is something else I should check. The implementation is not a problem just want to know if there is other thing I should be aware of when thinking about architecture an api with flask. thx !
Dumb Q.... how much of Django is based on templates/jinja? I’m switching my pages from just HTML to Base.html/Jinja.
A good chunk of the Views.
But it is fully optional. I usually use Django only as an API
@lethal orbit is it annoying tho that when you have 5 pages... you might have to change the script if something gets updated?
What do you mean?
If your data is dynamic and you code the templates to handle it, you don't really need to update the scripts.
@lethal orbit I know, I thought you meant “optional” as in “no”, but ok! But tho.... how easy could my routes that I already have, get messed up when I switch to Jinja way?
I have a question. I want to make a http request to add a porduct to card. Every time if i send the request i get an error ACCES DENIED to the website. I try it on footloker.de
@lethal orbit I know, I thought you meant “optional” as in “no”, but ok! But tho.... how easy could my routes that I already have, get messed up when I switch to Jinja way?
@frozen python Are you switching from static HTML or from the Django Template Language? Either way, it shouldn't mess anything up...
Fun fact, Jinja was originally based on Django as a superset of Django's engine
I am using flask. I want to extract an access token from the redirect url from an implicit grant. Information is returned essentially as query strings, but rather than starting with a ?, it starts with a #. request.args.get("access_token") will not work because of that, and when doing request.url or request.full_path, it ignores the # and every after it. How can I get the information?
@ me when responding, please.
As an example:
http://127.0.0.1:5000/discord/#access_token=XXXXXXXXXXXXXXXX&token_type=Bearer
I would want to get the full url at the very least, because then I can extract the token with regex.
@lethal orbit I’m just trying to hook up “main.html” as my Django main page for everything to inherit from. I think I’ll do a “test.html” to then see if it hooks up right, then I’ll apply it to my pages I have working. I have the routes and view working, I don’t want to mess them up
hi guyz i want to update my profile form, but unfortunately it's not working
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
def register(request):
if request.method =='POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been created! you are now able to log in ')
return redirect('login')
else:
form = UserRegisterForm()
return render(request,'users/register.html', {'form': form})
@login_required
def profile(request):
if request.method =='POST':
u_form = UserUpdateForm(request.POST, instance= request.user)
p_form = ProfileUpdateForm(request.POST,
request.FILES,
instance= request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, f'Your account has been updated!')
return redirect('profile')
else:
u_form = UserUpdateForm(instance= request.user)
p_form = ProfileUpdateForm(instance= request.user.profile)
context = {
'u_form': u_form,
'p_form': p_form
}
return render(request, 'users/profile.html', context)
```
How to use flask with react?
Ping if you want to help me.
how can I make HTTPS requests during development?
https://url.com/here
there is also FastAPI for building pure RESTAPI SmilingDude
if you mean make the server itself SSL and HTTPS then you could use something like Cloudflare's flexible system to stick it behind or just slap the cert files to the server if it supports it
you'll need some sort of SA tho in general for HTTPS and SSL
yeah, I would have suggested that Rabbit, but he specifically asked for Flask+React lol ... i don't agree, but who am I to judge
Cant argue with a good old Flask api tho
well ... i CAN argue it lol
dead simple to setup tho maybe not as powerful as FastAPI
cant get away from just how awesome FastAPI is tho
that is why I liked Falcon for so long. Was flask-ish with none of the UI crap i would never use lol
Never used Falcon much only for 1 or two odd things
fastapi didn't exist when i was using python for these things lol
Sanic seems to be my main goto
tbf i imagine ASGI was either non existant or very new at the same time
when i write an API, I'm always in Go
Im just switching from Go back to Rust now 😩
yeah ... I remember when Asyncio his the scene ... and then aiohttp ... and all of that craziness ... needless to say, none of it was prod ready lol
came along way
it sure has lol
I still find writing APIs too cumbersome with Rust yet, so i've not done a lot there
Hyper or Warp are my main go to's but yeah i personally wouldnt ever go to it for API stuff
So much stuff todo even for a very simple system
equally its the reason why im going back to rust over go
I've considered writing an actual, good, api framework for rust, with a sane server default ... I just haven't yet
I think the thing which will make rust viable will be Rocket
tried Rocket yesterday for Rust, but started having problems
By fat the cleanest Library for Rust imo
with my WSL setup probably
lol @ by fat
tho i gotta say Warp is very clean aswell but a different style
Rocket will run on stable next release
think warp is alot lighter than Rocket aswell
and async
tho i think rocket was going to async again?
i cant remember
actix is a bloat machine tho overall
my problem with the current ecosystem is the focus on being a full web framework ... i have no interest in any of that lol
200+ deps by default when using the web build + Awkward for windows development + rather confusing middle wear system
@mellow tide Lack of good Database systems aswell
from what ive heard diesel is pretty poor and requires manual migrations
Haven’t tried rocket in a while, how many deps does it require?
eh, db's i don't have a problem with, i've no issue writing raw SQL statements
same here
My toy is probably over 300
Raw SQL you know exactly whats going on at any time
Dependencies
atty ^0.2
base64 ^0.12
log ^0.4
memchr ^2
num_cpus ^1.0
pear ^0.1
rocket_codegen ^0.4.5
rocket_http ^0.4.5
state ^0.4.1
time ^0.1
toml ^0.4.7
yansi ^0.5
tho writing a ORM is pretty good way of learning new things tbh
Rocket 
so i've mainly been a node/react/aws guy for the past 4 years and have been looking to get out of my comfort zone and add a portfolio project in a language/framework i've never really worked with and had settled on Python/Flask, but now you guys are making me reconsider Rust/Rocket or Go/whatever
@craggy trout Just Go, no framework needed 😄
you loose alot of development speed for the sake of performance
If you want full control, rust
saying that i found Rust is actually really fun to use
yeah, Rust is a lot of fun, but it's a lot slower than other languages in that space
yeah, rust in general kind of reminded me of more functional languages where the bulk of dev time is front-loaded
I love go for the runtime but i hate it for the runtime errors
development is slower i mean
so easy to slip up with Go's system but its a nice balance of performance and dev speed
rather than back-loaded with fixing bugs that pop up later
Strongly statically typed languages
I agree with rust's system of show all the errors at once at compile rather than at runtime
Go sits closer to Rust on the frontload/backload deal, but there are backload things if you use interfaces/reflection all over the place
by far the nicest thing about it is you can almost have no chance of runtime issues if it compile in rust
still possible for sure but if done right its rare
I've had issues with generics ... but mostly because i forgot how to use them from using Go for so long lol
another issue i had with Go is switching between it and python
how many lines ive go X := xyz by accident in python
hmm. maybe a Rust backend with Elm front-end ... that would take forever
that sounds no fun lol
i recon Rust's eco system for it will grow, id say its at the a similar stage as asyncio and Aiohttp was with Python a while ago
tho more production ready its certainly rough around the everywhere in places
yeah ... you have to be very careful with prod Rust right now
simply switching out shitty C libraries is a good use case, but there just isn't a lot of productivity outside of that in a prod system yet
I need to take a look at the windows binding though ... if microsoft actually keeps up with that ... it'll take the scene by storm
Im interested to see how Hyper is implementing HTTP3
there is some rough designs for it but that'll be interesting to see
lol ... i just want to see HTTP2 in browsers, i can't even fathom HTTP3 yet lol
yeah
did think that when i saw it, considering 90% of the web is still http/1.1 anyway
tho thats the way the internet is ig
anyone used Python/Go/Rust with DynamoDB?
when i've brought up dynamodb in other discords, i've had rocks thrown at me, so this was just a test
anyone use jinja with fastapi?
eh, dynamo isn't my favorite ... (given that they flat stole the IP from mongo lol), but it's usable. I tend to steer folks away from AWS if I can though
but that being said ... i've never had a massive data loss using Dynamo, and I have with Mongo ... sooooo
really wanted to use mongodb in my next proj, but i've gotten so used to dynamodb and the "single table" approach that i'm not looking forward to it
in what context @native tide
for some reason get_flashed_messages() works with flask but converting the exact code to fastapi seems to make it not like to work
not much about it online, wondering if anyones run into the same issue
oy, yeah IDK, again, I'm Go for web these days 😄
aha, wise choice, need to learn MUX at some point
why steer others away from AWS? vendor lock-in? price? piss poor documentation that'll drive you insane over and over again?
or is it that they're pretty much replacing the old guard of evil corporations, they're becoming the biggest evil megacorp
Scylla or postgre are my mains now
Mongo is great for beginners but pretty slow and holy fuck is so awkward to edit things with
Amazon is basically Shinra now
Sure, but benefit of cloud databases are hard to pass up
why steer others away from AWS? vendor lock-in? price? piss poor documentation that'll drive you insane over and over again?
@craggy trout yes ... yes to all of this ... lol
yeah, my last job was full blown serverless stack: appsync, s3, cloudfront, cognito, lambda, dynamodb, elasticsearch in ec2, transcribe, translate, etc, etc
in many ways, it was beautiful, especially once you got things working
yuck ... $$$$$$
but getting things working was quite difficult a lot of the time
We do alot of serverless on Azure at work, it has it's benefits as well
j4ng5y not really
rapid development can override the cloud run costs
it was actually cheaper than what they had before
yea, containers/VMs have set bottom cost where some of this stuff can be pure consumption cost
all in aws anyway in ec2
i suppose if your stack was designed for it, you can get away with it ... but i've seen time and time again that lambdas that spawn lambdas that spawn lambdas (etc...) end up costing far more than EC2
not sure why you would do that
idk ... architect there was an idiot lol
appsync fixes a lot of problems
but that's not cloud fault
if you use it correctly. i didn't consider AWS serverless viable when you had to rely on just API Gateway + Lambdas
oy ... yeah apigateway is ftl
partially because i just hated API Gateway and refused to learn it :p
only problem with AppSync is kind of a lot of boilerplate ... and the webui would slow down tremendously if you had a decently sized gql schema ... hence almost never using it except for the occasional instance where it was useful for debugging
the reason we had the step functions though ... was because instead of using an actual ETL pipeline, they were using lambdas because serverless ... and it was idiotic
and the runtime limit cased them to spawn lots of sub functions
but i've seen many a company while doing consulting that was trying to shoehorn serverless in places it didn't need to be
thus my beliefs
obviously, aws wasn't going to stop them from giving them a truckload of cash lol
i've seen a small business (less than 20 employees and less than 3m in yearly revenue) paying 5k/month to AWS
which might seem reasonable in certain cases, but in this one it was waaay too much. ms sql and large ec2 instances were the bulk of cost
for a web platform that currently doesn't escape free tier aws limits
well, in some casees
still a couple hundred a month for s3
i did a consulting gig with a startup that couldn't figure out why they were spending 20k/mo with aws (i guess they had never heard of the cost dashboard, but w/e) ... turns out they were running basic workloads on P3s
and also, because the CTO they fired was running crypto miners on all of them
haha
they tried to hire me as CTO afterwards, but i was negative interested lol
man, i should have tried that at last place .. they had a lot of production workstations for video editing with quadro cards that stayed on 24/7.
lolol
not sure if quadros are good for that, know very little about crypto mining
basically it depends on the coin algo lol, but even if it doesn't work that well for bitcoin, it's sure to work well for one of the altcoins
you see a lot of the malicious miners going for monero and stuff like that because it's CPU cycle based, less GPU
i heard kim jong un likes monero
wonder how someone would go about trying to steal all of it
i've heard he is dead/in a coma ... don't believe everything on the internet lol
eh, it was just the idea that monero is harder to trace so NK liked to steal it
yeah ... i like zcash for the non-traceability, but the value is very low lol
anyway ... i've steered this convo WAAAAAY off topic lol
so web development is fun
I feel like I have it down with creating a views and classes for Django. But now, it’s to be able to “add” objects “from the admin” to show on the front.
Scylla or postgre are my mains now
@quick cargo How would you recommend getting started with Scylla?
@delicate fable very useful video https://www.youtube.com/watch?v=hdI2bqOjy3c
In this crash course we will go over the fundamentals of JavaScript including more modern syntax like classes, arrow functions, etc. This is the starting point on my channel for learning JS.
Code including html/css:
https://embed.plnkr.co/plunk/8ujYdL1BxZftGoS4Cf14
21 Hour J...
What causes *args and **kwargs to be faded out?
What causes *args and **kwargs to be faded out?
@frozen python unused
@vestal hound I have them in the correct place in my page paths
@vestal hound I have them in the correct place in my page paths
@frozen python wait, what do you mean "faded out"
@vestal hound there grey
show pic
@vestal hound
yes, they're not used
that's what I said above
you don't do anything with them
e.g. add a print(args) there
it'll change colour
@vestal hound should I even use them?
I’m switching to a “templates” folder, and then having my routes like that. I added them to my urls.py as well and they worked.
He included those in the classes
Is initilizaing a flask app in a init.py file good?
@noble star doing anything in an __init__.py is generally an anti pattern or at least a code smell and should be avoided
instead of init.py, should I just create a helper.py file where common variables will be stored? @mellow tide
Common variables? Not sure what you mean for sure, but if you mean more like global app variables, those should probably be avoided too lol
like the app = Flask(name). where I import that in different files
For flask, I generally will have a whatever-i-am-calling-my-app.py to let both myself and others that may work on my code where to start
So if you had a blog.py (for example), you would do all initialization in that file (question 1) and import what you needed from other files? (question 2)
If you have seen Corey Scafer's Flask tutorial, it basically looks like that (Package Structure Video)
I've not seen that blog, I'm just letting you know how I write greenfield apps at work :)
But yeah, I put all entry point code in the file that looks like it is the root of everything
Cool, thanks for the heads up
Hey guys, lemme know if there's a better place for me to share this, but i've been working on a Web API to access university course information. I've only implemented my school UC Irvine, but I'm wondering if anyone wants to help or learn to Web-scrape (this is how we populate the database)
I made it at first using Flask, but switched over to FastAPI since the framework wasn't too hard to migrate to
github: https://github.com/nananananate/CourseCake
docs: https://docs.coursecake.tisuela.com/
Lemme know if u guys have feedback! Also if any of you are looking into making a web API for funsies, lemme know! I'd like to see if I can help and contribute
By making course data easier to responsibly access and more "edible" for programs, we hope CourseCake offers a smooth approach to build useful tools for students. - nananananate/CourseCake
By making course data easier to responsibly access and more “edible” for programs, we hope CourseCake offers a smooth approach to build useful tools for students.
ayy, uc irvine is a cool campus haha.
I am always making web apis for funsies as well haha
Is it good to use third party libraries for django?
Like libraries in djangolibraries website
Is it good to use third party libraries for django?
@limber tide wrong question.
if you need extra functionality and can find a well-maintained library that does what you want, then, sure.
but don't install libraries for the sake of having more libraries
How can I trust them
ah
you mean "how do I tell if a library is safe"?
i.e. won't steal my sensitive data
Yup
in general, anything used by a large number of users will be safe
(simplifying, but well)
because, if you think about it...how do you know Django itself is safe?
can someone guide me through permissions and users for s3 buckets
ive tried reading documentation but i cant wrap my head around it
im using an s3 bucket to store and retrieve files for my django website
yes
i am able to upload files to the bucket
but i get invalid request when running the deployment server
wdym
<Message>The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.</Message> i get this error when going to the image url
Ohh hmm
i tried googling this error but didnt find much
what?
i have set the permissions to not block public access
AWS_QUERYSTRING_AUTH
this
have u set this value in your project?
if not, set it to False
also have u specified the region
thats what i tried doing now and i got an error
AWS_S3_REGION_NAME = "eu-west-2.amazonaws.com"
wrong
it is a django error
Provided region_name 'eu-west-2.amazonaws.com' doesn't match a supported format.
set it to eu-west-2 only
yea
not sure which guide you followed
but
this is a good guide
:v:
Let's say I have a malicious user, and they submit two post requests at the exact same time. Will the server form a que and process these one by one, or will the server process them straight away?
Also lets say a user submits one form on one IP, and another form on another IP. will the server que the items
Depends on the server and protocols
How can I set it up to form a que do you know ?
What prod server r u using atm?
currently using development server on localhost
What information is the form collecting? What is it doing with it? If you're storing it in a DB, what DB?
Databases are pretty good at locking tables, and preventing duplicate entries at the same time.... you don't normally have to deal with queues.
token and email, but if the db is locked while it appends new information, then I shouldn't have anything to worry about
i didn't know tables lock, thanks for that
Well, they usually lock the table, but if you don't have "unique" constraints, it may enter duplicate entries.
And it depends on your actual system...
Django with postgres and a UniqueConstraint should be pretty solid.
ne1 out there?
well yeah the token is primary_key, so shouldn't be able to add dupes
Any resources to learn flask or a path with which should i learn?
Corey
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...
What is the easiest to make a flask API for react.js?
Dir tree??
@frozen spear
Pay attention to your dir tree maybe a spelling mistake and a prob like this
hello, does anybody know how I can style a rectangular image so that it only shows it's center as a square (I hope you know what I mean), so that I could put it in a grid of other square images?? in css
object-fit is what you want to look at
is there a way i can display current logged in user info in the textboxes
i tried a self function but didnt worked
users should probably be stored in DB
then query the DB
what is it you're doing
maybe use a session
session is giving me trouble
it keeps telling me to log in, even though I'm logged in
like my landing page has a @login_required decorator
and even when I'm logged in, it loops me into the login page
how can i display this class into the admin panel
I am trying to basically see the ip of someone who makes a request (Flask).
Is that what the following provide?:
request.remote_addr
request.access_route
And what exactly is access_route? It is hard for me to test much myself as I currently hosting it on my own computer, which is why I am asking here.
@ me when responding please, and thank you for your time.
When flask encourages circular imports 👀
I think the trick is to make your app more modular @noble star
but im new so idk
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin' or request.form['password'] != 'admin':
error = 'Invalid Credentials. Please try again.'
else:
session['logged in'] = True
flash('You were just logged in!')
return redirect(url_for('staffdashboard'))
return render_template('login.xhtml', error=error)```
I am pretty sure that what flask promotes
#app routes for webpages
@app.route("/")
@login_required
def staffdashboard():
return render_template("staffdashboard.xhtml")```
oh u using flask-login
this code is causing me to redirect to the login page after I log in
im actually not @native tide
I should be, but I want an MVP before I refactor
oh ok continue with ur work , gl
the function just happens to be called login_required
I don't know what the issue is, because as I said. there's a session active in my app when I inspect element
so shouldn't it track the cookie
#web-development message
Any responses yet?
Hey, I am messing around with a package called eel right now and was wondering if this is something that the package can do
So, this is my HTML page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Eel Tutorial</title>
<script type="text/javascript" src="/eel.js"></script>
<script type="text/javascript">
function log_py(n) {
console.log('Got this from Python: ' + n);
}
eel.python_function()(log_py); // Uses the Python function 'python_function' and will log the result to the console
</script>
</head>
<body>
Text Here
</body>
</html>
And this is my python file```py
eel.init('web')
@eel.expose
def python_function():
return random.randint(1, 10)
eel.start('main.html', options=options, suppress_error=True)
```HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Eel Tutorial</title>
<script type="text/javascript" src="/eel.js"></script>
</head>
<body>
eel.python_function()
</body>
</html>
```Like this kinda?
def delete(self, productID):
query = self.query.filter_by(productID=productID).first()
db.session.delete(query)
db.session.commit()
@seller_bp.route('/dashboard/delete/product/<productID>', methods=['GET'])
def delete_product(productID):
Products().delete(productID)
ProductDelivery().delete(productID)
When a user visits the delete link, it deletes it from the database, but instead of redirecting back to the product page, it returns an error of; sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.NoneType' is not mapped
Any idea why?
can someone help me, is there any way I can automatically delete data from postgres if it is X days old?
using Flask SQLAlchemy and postgres
so for example delete all data that was committed 7 days ago.
cron task
oh, isnt that for linux?
no
What is Crontab
Cron is a software utility that allows us to schedule tasks on Unix-like
systems. The name is derived from the Greek word "Chronos", which means "time".
The tasks in Cron [https://en.wikipedia.org/wiki/Cron] are defined in a
crontab, which is a text file cont...
Is this an okay spot to ask about a web scraping question? I'm trying to write a very "fragile" web scraper that breaks (intentionally) when changes are made, so that I can be confident it didn't "miss" anything. I am trying to avoid missing fields or boxes that may appear only occasionally, so I want to log any unexpected structures. I'm using lxml.html at the moment, but the API feels a bit ... clunky in places, for certain tasks. Like, it's great for finding things you know are there, but seems shakier for looking at things you don't expect.
I am realizing that if someone else were to get the information in the web cookie, that they could edit the dashboard as the user whom they took the information from. How can I secure this better?
My current idea is to store the data in a database instead, and the cookie/session would just store an custom encrypted session ID, and that session ID would be used to get the info. The database would also store the IP of the user that was logged, so that if the session ID was used in the cookie from a different IP, the application would force them to log in again. Is this a solid method, and are there any issues/improvements I should know of? I am using flask by the way, and would use request.remote_addr for the IP.
@ me when responding please.
Is this an okay spot to ask about a web scraping question? I'm trying to write a very "fragile" web scraper that breaks (intentionally) when changes are made, so that I can be confident it didn't "miss" anything. I am trying to avoid missing fields or boxes that may appear only occasionally, so I want to log any unexpected structures. I'm using lxml.html at the moment, but the API feels a bit ... clunky in places, for certain tasks. Like, it's great for finding things you know are there, but seems shakier for looking at things you don't expect.
@north perch not sure what your question is
if its about logging, create a txt and append errors to it
Yeah, I'll elaborate a bit, sorry -- Say I'm at some node in the element tree, and I want to make sure that the only further elements are ./ul/lia/a -- precisely only that tree, nothing else, no siblings at any level. The syntax for doing this with lxml.html seems very ... verbose, to say the least.
I am realizing that if someone else were to get the information in the web cookie, that they could edit the dashboard as the user whom they took the information from. How can I secure this better?
My current idea is to store the data in a database instead, and the cookie/session would just store an custom encrypted session ID, and that session ID would be used to get the info. The database would also store the IP of the user that was logged, so that if the session ID was used in the cookie from a different IP, the application would force them to log in again. Is this a solid method, and are there any issues/improvements I should know of? I am using flask by the way, and would use request.remote_addr for the IP.
@ me when responding please.
@topaz finch are you using flask-login ? if so use login_required and make current_user.get_id() matches
guys I've been trying to center text right in the middle of it's container, like both vertically and horizontally, but I've so far not been able to center it vertically... any ideas on how to do that?
guys I've been trying to center text right in the middle of it's container, like both vertically and horizontally, but I've so far not been able to center it vertically... any ideas on how to do that?
@crude heath lets see your code
I have to enumerate the children, ensure it's only one child, then pick that child, enumerate all of its children and so on -- it gets very verbose very quickly. So my question is "Is there a python library that you are aware of that might offer good syntax for writing assertions about the shape of the DOM?"
hold up, I mean I haven't been able to align it at all in it's container so it's hard to send you something I realized doesn't work
I'll send you anyways
i usually use flexbox for positioning, but tbh front-end isn't my strong point
<section id="welcome-section"> <div> <h1>Hey I am Great Fate</h1> <p>A self-taught programmer</p> </div> </section>
css
`body {
margin: 0px;
padding: 0px;
}
#navbar {
position: fixed;
top: 0px;
left: 0px;
background-color: #333;
width: 100%;
}
#navbar ul {
list-style: none;
}
#navbar li {
display: inline;
}
#navbar a {
text-decoration: none;
color: white;
}
[#welcome](/guild/267624335836053506/channel/267631170882240512/)-section {
width: 100%;
height: 100vh;
}
[#welcome](/guild/267624335836053506/channel/267631170882240512/)-section div {
margin: auto;
}`
I'm trying to center the div inside the section inside of it's container (the section)
I thought margin auto would do the job
It's a good idea to use libraries for login, or it's more safe to make from scratch?
@past cipher i am currently not using flask-login, do you recommend it over my proposed method?
Time is not a factor im considering, more security.
@crude heath
#welcome-section {
width: 100%;
height: 100vh;
display: flex;
}
@past cipher i am currently not using flask-login, do you recommend it over my proposed method?
Time is not a factor im considering, more security.
@topaz finch yeah I would use flask-login
its what I use for all my projects
you can create custom decorators to make sure user is logged in etc
alright
oddly enough that actually worked holy shit lol @past cipher
usually I didn't think I'd want to use flexbox if I didn't want to organize multiple containers at once
thanks though
Is there some sor of unique id in django_channels?
i am so frustrated, im stuck
@swift sky with what
My try at making an online compitetive coding platform. Frameworks used: Next Js, Django Res.
Languages: Python, Javascript
CodeStrike is an online community of coders.
Is there a way to create a background api with a post event in the main class? The event should get triggered when the server gets a post request
@modest scaffold im trying to figure out the user authentication portion of my app
and for some reason my code is prompting me to both log in, as well as displaying a flash message that I already logged in.
the landing page has a @login_required decorator, which redirects to the login page, which is then supposed to redirect to the landing page
so it just keeps looping to the landing page regardless
i have it set so that if the user uses a certain username and pword, it's supposed to change the session = True
i think the tutorial im watching is outdated
flask tutorial from 2014
Hi everyone, I have to improve my solution. I have an sudoku algorithm and I want to be able to type on website, run the algorithm a return it. Is there a way to somto create 81 inputs without typing them each by each or generating the entire html in another code (for loops to generate the table, th, td). How would you do it
I have a web app that connects to the Pet Finder API. It requires an OAUTH token for any requests. I have a Class that gets the token, as well as generates an instance that I can use to handle all requests. Right now I create the instance at the beginning of my Django views.py so that it’s globally available to all of my methods.
The only problem is my token expires after an hour, and the API doesn’t send a refresh token with the initial request. I need to find a way to create a new instance of the class every hour.
I’ve been reading up on threading and think maybe it can be used to solve my issue, but I’m not familiar enough with it to really figure out how. Maybe threading.Timer()?
I tried putting the thread.Timer under the init of my class to see if I could get it to run the init again and get another Token, but that didn’t work.
If I did something like:
def Token:
x = PetFinder(keys here)
threading.Timer(3550, Token())
return x
pf = Token()
Would that work? Or would the method wait for the timer wait to complete before it returned x?
why not just create token everything the function is called ?
Because in order for the whole app to function, I have to have a valid token. I guess I could remake a new instance of the class every under every method, but I have a feeling that would sort of abuse the API and I’d get my keys revoked.
Anyone know why my email would return the Username and Password not accepted. error with SMTP handler? I a using gmail and set the ports and mail server up properly.
I have less secure apps setting enabled
Is there a way to paginate results from a GET api call? Im making an api call and then taking those results and placing them into a jinja template and displaying them on my page. Do i need to run a for or while loop here? Im making this call to the propublica api and setting the offset to 100, but I'm still only getting the first 20 results. I tried setting the limit parameter, but no luck.
This is my jinja template for reference
Sorry this should be my flask route
@zealous cloud use dict.key instead of dict['key'] with templating
@zealous cloud use
dict.keyinstead ofdict['key']with templating
@quick cargo Is there a functionality difference? Quite new to Flask and went with what I knew basically. thanks for the tip
how can I avoid getting my uri overwrite the last parameter ? https://dpaste.org/xn7x
Im not sure I follow. All my other routes are working as intended.
anyone know a good website for the framework bottle?
how to delete a file on a s3 bucket with boto3
i tried getting the object like this s3 = boto3.resource("s3") obj = s3.Object("bucketname", "path") obj.delete()
the documentation for boto3 is really useful for learning how to use their functions
that is what there documenatation says
I am trying to do the following, but however I got an overwrite from the last part of my url similar to this. how can I improve the way I am using the slug from models to urls.py , and avoid getting overwrite my lesson module uri ?
<blackleitus> https://dpaste.org/uuYn
but does this mean that it only deletes the objects if it is null? Removes the null version (if there is one) of an object and inserts a delete marker, which becomes the latest version of the object. If there isn't a null version, Amazon S3 does not remove any objects.
@hallow jacinth
I don't think that is how you pull a file from s3. I only looked at the documentation for like 2 mins. I'll look again after classes
ah, I see it now
yeah ill look at it when im out of class
thats what i found on some stackoverflow article
i also tried this
client.delete_object(Bucket="bucketname", Key="path")```
this did not work either
uhm i have a quick question
mabye there is some django way to do it
can someone help me write something in python?
well
i need to write a house in python using the print command and have one line of script (im new to python and taking a class on it)
you need to "write a house"
can you elaborate
like make a picture out of punctuation ?
also this is #web-development
that also
im looking for someone who knows djangorestframework well
How do you guys learn TDD and stuff like that? Work experience?
try
client = boto3.client("s3")
obj = client.object(bucket="bucketname", filename="filename")
obj.delete()
if that doesn't work then try
client = boto3.client("s3")
obj = client.object(bucket="bucketname", filename="filename")
obj.delete(MFA='string', VersionId='string')
If that doesn't work, then I am not sure if this is the proper way to go about deleting a file. Usually when I have an issue with boto3 I just play around and read their documentation
@modest scaffold
also with boto3 you dont have to put things like bucket= or filename= just make sure things are in correct order, otherwise set the arguements
How do you guys learn TDD and stuff like that? Work experience?
@native tide projects! I do not often do test driven development, but I believe the principles behind it can be seen in a simple way from doing code challenges, i.e codewars. The best way to learn imo though is to just do it, think of a project, and develop it using TDD.
For example, I'm building a website, I just don't see how I can incorporate TDD. What can I write tests on? Maybe I just don't understand it
mmm, ive never much used TDD for a website.
For me test driven dev is is more like: I need to format this data this specific way, so I write tests that can compare the actual output of my code to the output I would expect that code to give me with those predetermined inputs.
I do not work professionally doing this, so someone else may be able to contribute more to this topic.
hmm, thanks! I'll definitely look into it to wider my understanding
For example, I'm building a website, I just don't see how I can incorporate TDD. What can I write tests on? Maybe I just don't understand it
@native tide how are you building it?
like what frameworks/libraries
Flask, sqlite, html css frontend
I guess I could incorporate some testing for APIs that I'll make
I guess I could incorporate some testing for APIs that I'll make
@native tide okay, so minimally you should test your endpoints
the key to testing is understanding the specification of your APIs
preconditions and postconditions, minimally
e.g. say you have a simple API that takes two numbers and divides the first by the second
your preconditions: both inputs must be convertible to int, the second input must not be 0, etc.
write one negative test (input is invalid) for each precondition
same for postconditions
got it, that's a good start, thank you
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Yo. After exporting FLASK_RUN, I try running flask run, but I get -bash: cd: too many arguments
BUT IF I DO python3 -m flask run, it works fine. Anyone know why?
Does anyone have experience using Recaptcha3 for serverside validation with Flask?
@noble star isn't it FLASK_APP for the environment variable to export and the command is flask run?
Hello,
I am using Flask for a ctf app and the login system I have should be working but everytime I "login" it gives me an error 400
from flask import Flask, request, render_template, redirect, url_for, Blueprint
import os
from dotenv import load_dotenv
import sqlite3
app = Flask(__name__)
load_dotenv()
connection = sqlite3.connect('database.db')
loggedIn = False
teamSizeLimit = 4
currentID = 0
userteam = ""
error = None
username = ""
@app.route('/ctf', methods=['GET', 'POST'])
def ctf():
global loggedIn
while loggedIn == True:
global userteam
if request.form['btn_logout'] == 'logout':
loggedIn = False
return render_template("ctf.html", username=username, userteam=userteam)
while loggedIn == False:
return redirect('/')
@app.route('/', methods=['GET', 'POST'])
def login():
global error
global currentID
global userteam
global loggedIn
if request.method == 'POST':
if request.form['userteam'] == '':
error = 'Did not provide a team'
else:
currentID += 1
userteam = request.form['userteam']
with sqlite3.connect('database.db') as con:
cursor = con.cursor()
cursor.execute(
"INSERT INTO Teams (TeamName) VALUES (?)", (userteam,))
error = ''
con.commit()
if error == '':
loggedIn = True
print(loggedIn)
print(userteam)
return redirect('/ctf')
return render_template('login.html', error=error)
# Launch the FlaskPy dev server
app.run(host="localhost", debug=True)
this is my main code and
this is what the page it is supposed to load is
<html>
<head>
<title>ScribeHacks CTF</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="container">
<h1>ScribeHacks CTF</h1>
<br>
</div>
</body>
</html>
<html>
<head>
<title>Login/Register</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="container">
<h1>Login</h1>
<br>
<form action="" method="POST">
<input type="text" name="userteam" value="{{ userteam }}" required="true">
<input class="btn" type="submit" value="Login">
</form>
{% if error %}
<p class="error"><strong>Error:</strong> {{ error }}
{% endif %}
</div>
</body>
</html>
this is the login page also
it should be going into localhost/ctf
400 means bad request.
is the server not logging an exception or something?
i guess it wouldn't be an exception for 400
how do i log the exception
i gave you all the code i had
reading up on it there might be something wrong with the way i am requesting the 'userteam' variable
why are these while loops instead of conditionals?
while loggedIn == True:
global userteam
if request.form['btn_logout'] == 'logout':
loggedIn = False
return render_template("ctf.html", username=username, userteam=userteam)
while loggedIn == False:
return redirect('/')
the both return always on the first loop though
and its still giving the same error
yeah, i didn't think that was the error, just thought it was odd
everything that i read about error 400 in flask says it has something to do with the request.form
but it doesnt seem like there is
<form action="" method="POST">
<input type="text" name="userteam" value="{{ userteam }}" required="true">
<input class="btn" type="submit" value="Login">
</form>
oh shoot i forgot about that
ok so i removed that part
@app.route('/ctf', methods=['GET', 'POST'])
def ctf():
global loggedIn
global userteam
if loggedIn == True:
# if request.form['btn_logout'] == 'logout':
# loggedIn = False
return render_template("ctf.html", username=username, userteam=userteam)
if loggedIn == False:
return redirect('/')
you shouldn't need global if you're just reading the globals
you also don't use them consistently
oh yeah good idea
because you don't have username despite it being a global
did it work now after removing that form check?
nope
silly question but you definitely have a ctf.html in the same directory as login.html?
hmm, how does it know to look in downloadables
so that's not the layout of the code you're running?
currently i am just loading ctf and login
yea but i'm saying you're showing those templates in a subdirectory called downloadable so i wouldn't expect render_template to find them by just the name login.html and ctf.html
oh never mind me
i missed the arrow
haha
lol
what happens if you just return "Logged In" instead of the template
something weird is going on
i did that
and it tries loading /ctf again
from flask import Flask, request, render_template, redirect, url_for, Blueprint
import os
from dotenv import load_dotenv
import sqlite3
app = Flask(__name__)
load_dotenv()
connection = sqlite3.connect('database.db')
loggedIn = False
teamSizeLimit = 4
currentID = 0
userteam = ""
error = None
username = ""
@app.route('/ctf', methods=['GET', 'POST'])
def ctf():
global loggedIn
if loggedIn == True:
return render_template("ctf.html")
if loggedIn == False:
return redirect('/')
@app.route('/', methods=['GET', 'POST'])
def login():
global error
global currentID
global userteam
global loggedIn
if request.method == 'POST':
if request.form.get['userteam'] == '':
error = 'Did not provide a team'
else:
currentID += 1
userteam = request.form.get['userteam']
with sqlite3.connect('database.db') as con:
cursor = con.cursor()
cursor.execute(
"INSERT INTO Teams (TeamName) VALUES (?)", (userteam,))
con.commit()
if error == '':
loggedIn = True
print(loggedIn)
print(userteam)
return "Logged In"
return render_template('login.html', error=error)
# Launch the FlaskPy dev server
app.run(host="localhost", debug=True)
<html>
<head>
<title>Login/Register</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="container">
<h1>Login</h1>
<br>
<form action="" method="POST" enctype="multipart/form-data">
<input type="text" name="userteam" value="{{ userteam }}" required="true">
<input type="submit" value="Login">
</form>
{% if error %}
<p class="error"><strong>Error:</strong> {{ error }}
{% endif %}
</div>
</body>
</html>
heh, sorry i meant return render_template("ctf.html")
😄
the 400 is happening on the /ctf route as far as i understand
same thing
im confused on why it tried going to /ctf when i never said for it to go there that one time
are you sure you're restarting your server
im just ctrl-c and flask run
and you don't have another old one running on a different port that you're going to 😄
what is the difference between flask-alchemy and the normal way of using sql query like c.execute(SELECT * FROM ...............) which one is better to use?
@sage thistle sqlalchemy is an orm. it gives you a way to work with databases via objects or query builders over writing strings
different people have different preferences
oooh! soo both are the same
i will go ahead and debug from here
they're just different ways to query the same thing
@real island so you were testing against a different server?
just wanna make sure i'm not crazy 🙂
there was an old one running
ooooh! ty @queen sinew
alright that explains it heh
how can I build a proper model for this structure? https://dpaste.org/Lg5F
hi guys
When I get paginated data from Google, it sends me a nextPageToken that I can use to get the next page. Does this token store the pagination state, or is it just a reference to some state Google stores? If it's just a reference, doesn't it violate REST's statelessness constraint?
@seller_bp.route('/dashboard/products/', methods=['GET'])
def product_page():
return render_template('/seller/products.html', message=get_flashed_messages(), products=Products().queryProducts('sellerID', current_user.get_id()))
@seller_bp.route('/dashboard/delete/product/<productID>', methods=['GET'])
def delete_product(productID):
Products().delete(productID)
ProductDelivery().delete(productID)
flash('Product Deleted')
return redirect(url_for('seller_bp.product_page'))
def delete(self, productID):
query = self.query.filter_by(productID=productID).all()
for item in query:
db.session.delete(query)
db.session.commit()
It deletes the product(s) from the database. However it returns an error of:
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.NoneType' is not mapped
Anyone know why?
Traceback: https://pastebin.com/WqivWWb5
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Seems to have been a problem with my tables, got it solved now
How should I pick the way I exchange data via REST? I mean I can put the data in path, as a parameter or in JSON. So far it seems that I should use more frequent things in path, dynamic things as parameters and sensitive or just big data in JSON
@native tide I like to pass parameters and filtering options throw the URL, everything else I prefer in the body.
Example from Flask Docs:
@app.route('/uploads/<path:filename>')
def download_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename, as_attachment=True)
i want this https://hastebin.com/uqixavoyer.pyto link to index.html in create-react that i made how?
Ping me if you want to help me.
anyone thata's used flask-mail before think they couold help me in #help-chocolate ?
Ewo, is anyone here have an experience in using the Tweepy package?
I wanna ask smth
ask away
Can I like stream the tweets by year while retaining the filter tags?
anyone thata's used
flask-mailbefore think they couold help me in #help-chocolate ?
@hallow jacinth whats your issue
I am getting this error smtplib.SMTPNotSupportedError: SMTP AUTH extension not supported by server.
but what is weird about it is that the system was working a few days ago
sent emails and everything
@past cipher
lets see your code
have you established the connection before sending email
make sure email/pass are valid too
i just got started with flask
and i need help so when i run my website it give me the link but in the website it says unable to connect
can i not use operators on flask sqlalachemy queries?
post = Post.query.filter_by(date_posted <= cutoff).delete()
Anyone know how to decode the text from this url? https://www.scorespro.com/livescore/ajax0.php
<= doesnt work but = works
with what
i need help so when i run my website it give me the link but in the website it says unable to connect
any alternatives to selenium when web scraping javascript based sites
@native tide requests-html? im not sure if thats what u need tho
Hey
How can I use django allauth to login to admin, without all of the templates packed in ?
oh
if it is same as mine you should have debug mode on, ur says off
also ur environment says production and not development
still not working agter i changed ports
yeah thats weird, try http://localhost:5000 maybe?
wait
https://i.imgur.com/3bsIYya.png this is what mine looks like
i might have to change prefrences in my firefox maybe
maybe
nope still not working
can u show us ur code
def home():
return "Hello! <h1>HELLO<h1>"
if __name__ == "__main__":
app.run(port=8080)```
i did still not working
did u add flask app? app = Flask(__name__)
yes
app = Flask(__name__)
@app.route("/")
def home():
return "Hello! <h1>HELLO<h1>"
if __name__ == "__main__":
app.run(debug=True,port=8080)```
hmm
try running it from command prompt
set FLASK_APP=app.py
and then doflask run
on cmd
nope didnt work
so weird, maybe try a different route. maybe add in /home on ur app.route?
nope
probably something wrong with ur ports then
thats all i know, hopefully someone else can help u
sorry i couldnt be of much help
all good man
Hey guys! I am new to web development in python and i was wondering if can go straight to django or flask? i know all the basics and my career path is web development?
Yeah, you can go straight there @native tide
@native tide start with flask
@native tide Django is a steeper learning curve, but generally more all inclusive, flask is easier, but you need to do a lot of things yourself that you get for free in Django
but if you start with flask, moving to django would be a breeze
That being said, I use neither lol
may as well start with Django if thats your long term goal IMO
and most django developers work in teams since django is for larger websites
@solar pecan I disagree, you would need to learn the Django isms regardless
@native tide start with flask
@solar pecan > @native tide Django is a steeper learning curve, but generally more all inclusive, flask is easier, but you need to do a lot of things yourself that you get for free in Django
@mellow tide I know basics of html and css so can I learn django or Flask?
I take it you know Python
@native tide ok, you need python basics first :)
@native tide okay you are familiar with database integration and python syntax?
if so then you could prolly go to django then
but flask is just simpler if you wanna be web developer, your choice though
Yes I know python basics and I have built many projects but not related to web development
Are django and Flask backend languages or frameworks like node or react?
@native tide frameworks, although Django is the only one that's a real framework, flask is a micro framework
if you have the willpower then go with django, it'll take some time to get use to but yeah
hi
i'm trying to set up flask_cors to only allow specific origins on a POST endpoint
app.py has
CORS(app, support_credentials=True)
...
route has
...
@cross_origin(origins='foo.com')
...
but i can still make requests with header Origin: bar.com. what am i doing wrong?
do i just not understand CORS? i thought that would mean only requests originating from foo.com would work
haha okay but is there a way to do what i want
or is what i did correct and the problem is elsewhere?
I know nothing of that library unfortunately
i'm losing my mind over this i thought i understood it
Hey, im trying to make a small function that will change a button color (like toggle it)
function changeColor(elem, color) {
if (document.getElementById(elem).style.backgroundColor === 'Grey'){
document.getElementById(elem).style.backgroundColor = color;
}
else if (document.getElementById(elem).style.backgroundColor === color) {
document.getElementById(elem).style.backgroundColor = 'Grey';
}
}
```Any reason in specific why this doesnt work? If I just do
`document.getElementById(elem).style.backgroundColor = color` it works fine but not with the `if` statements
@young crane change else if to elif or else:
@brave flare I was looking around and its because I need to do something like this
var button = document.getElementById(elem);
var style = getComputedStyle(button);
console.log(style['background-color'])
```But this will log the rgb (eg `rgb(255, 0, 0)`)
@native tide pyppeteer?
RelatedObjectDoesNotExist at /profile/
User has no profile.
I got this error
I don't know how a Profile is not being made
how to convert orderedDict to a regular dictionary ?
I want to fill out the data from What you'll learn and STUDENT REQUIREMENTS https://imgur.com/a/uzkOE5v from my database where it's a single table attached to courses, but however I want instead of a select be inputs https://dpaste.org/m4aa#L8,9,10,16,17 and interate them over the template , but however I am getting 'ManyRelatedManager' object is not iterable
im trying to deploy my django project to heroku and im getting this error
at=error code=H10 desc="App crashed" method=GET path="/"
the cause is this gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
i havent been able to find anything to fix this can someone help me
my procfile web: gunicorn amazakar.amazakar.wsgi
anyone have experience with hosting a flask site with nginx and gunicorn? I am trying to host on GCP and got it working with just gunicorn but seem to be running into permission errors between nginx and gunicorn.
damn fastapi looks amazing, I think I'll rewrite my flask project in it
wooo just deployed my website
do you guys recommend any libraries for a web-messaging system?
What do you mean by that?
with open("disboard.txt", "r+", encoding="utf-8") as f:
url = 'https://disboard.org/search?keyword=test'
req = Request(url, headers={'User-Agent': 'XYZ/3.0'})
response = urlopen(req, timeout=20).read()
f.write(response.decode("utf-8"))
why no css?
@native tide what are you trying to do?
there's no CSS because the resources are loaded by path name and not the full URL
If you want CSS, you can try prepending the disboard root url to all the resource paths
Then your browser will be able to load them
just found that out tysm
hi
can someone give me a hand with django?
i have some troubles with class based views and forms
i keep getting this error message
share the code plz
and you will need to go through the full traceback, as this error is not super helpful
to see where the error was actually invoked
It is a simple form to search for a product
Im just starting with django
and didn't do that yet
couldn't solve that part*
yeah, if you scroll down it should (hopefully) show you exactly where the error starts. Then you can go to that code and see what needs to be fixed
how can I show you?
well, for now just go to that debug error on your browser, then scroll down and see where in your code the error originates from. It should hopefully be bold. Then you can go to that code and
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
if you need to
I mean in the traceback leads me to the execution of the libreary itself
so it is not very useful
if you scroll below that there should be a full traceback
like this
the one on the bottom is highlighted and is what you are looking for
Thanks
@lucid vine Would be good to rewrite! I did it for one of my pet projects, wasn't too bad
Hi! I want to profile a flask web application but do not where to begin. Any suggestions or literature on profiling a crud app in general or profiling a flask apps is appreciated.
@tough cosmos this series is pretty helpful! https://www.youtube.com/playlist?list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH
Also, if you're looking to create a Web API, take a look at FastAPI! https://fastapi.tiangolo.com/
FastAPI framework, high performance, easy to learn, fast to code, ready for production
@worn rapids already have the API and web app ready. I am now looking to profile it find bottlenecks in performance.
OOOO MB
misread it
This is what I used: https://flask-monitoringdashboard.readthedocs.io/en/latest/
This monitors endpoints, and u can configure monitoring to find the lines of code causing congestion
From their Readme: "Profile requests and endpoints: The execution path of every request is tracked and stored into the database. This allows you to gain insight over which functions in your code take the most time to execute. Since all requests for an endpoint are also merged together, the Dashboard provides an overview of which functions are used in which endpoint."
@tough cosmos
@worn rapids thanks, will try it
Thinking about getting a vps for web development. It’s 30 bucks a month. Any ideas of what I could expect with this set up?
Not planning anything major, just some portfolio type websites for my friends.
I don't think 30$ is worth it for a simple portfolio website. If it is a static website, you can use github pages for free. If you really need a vps, vultr.com is a good option. And if you want something specific to django and flask, heroku.com is good (but it might get a bit costly if your website suddenly starts getting massive traffic)
Linode gives you a terabyte of traffic for $5/mo. I use their cheapest service to run an application deployed to the internet and it performs extremely well
yep these vps services are pretty cheap if you know where to look. the only downside is you have to configure stuff like ngnix and all yourself, which can be a headache for the first time. paas services like Heroku take care of them for you, but at an increased cost.
Okay thanks. I don’t expect a lot of traffic even when I redo my own website. Just trying to get experience and make it accessible to show off.
if your website is static (most portfolio websites are), you should just go with github pages
For my personal website I plan on having a form. My friends probably will be static though so yeah I probably should lol.
a simple heroku plan is free. look into that
Will do.
One point for Linode- corey schafer (popular python teacher on Youtube) has deployment tutorials for both Flask and Django for them. If you follow them word for word they will work perfectly
but yeah, if you don't want to bother with that, Heroku is good
he has one for heroku django too
ah did not know that. very solid guy to learn from
I haven't looked into him yet but planned on it. Currently doing a Django weather app from codemy skillshare account.
corey schafer is a python hero
amen
lol, full seriousness we should have like a corey schafer week on this server or something. That dude single handedly got me very into python
Hi, In Django I have this view: https://dpaste.org/t7Wp#L1 and I call it like this: http://localhost:8000/api/org/wellcoords/Some Company-TEST-test but I get error: "Authentication credentials were not provided.". Why do i get that when i have put @permission_classes([AllowAny]) on the view? I also tried setting permission_classes = (AllowAny,) to no avail
guys how I clear my sqlite database?
hey guys, im trying to make internet store with django, and got next problem: i want to render my queryset as table in template, but cant find propper way to do it, any ideas?
How do you save cookies to browser session inside fastapi?
@royal radish you can install SQLITE DB MANAGER and delete the data u want
or you can just delete the .db file
@lucid vine moz-extension://af4c12f6-7751-4792-bad5-2838abce2657/readerview.html?url=https%3A%2F%2Ffastapi.tiangolo.com%2Ftr%2Fadvanced%2Fresponse-cookies%2F&id=137438953500
FastAPI framework, high performance, easy to learn, fast to code, ready for production
😂Great synchronization 13:03
Hey is there a way do add aditional pk in a Django rest framework url ? I am interested in delete request. I need to send at least two pk's in the request, is there a way do to this ?
Hey is there a way do add aditional pk in a Django rest framework url ? I am interested in delete request. I need to send at least two pk's in the request, is there a way do to this ?
@native tide send as HTTP params?
so something like http://127.0.0.1:8000/products/23/?id=54/ ? How will i be able to reach this additional id in the destroy method?
@vestal hound here's the SO post i made with this topic https://stackoverflow.com/questions/63723520/use-2-pk-instead-of-1-in-django-rest-framework-delete-method?noredirect=1#comment112684385_63723520
Thinking about getting a vps for web development. It’s 30 bucks a month. Any ideas of what I could expect with this set up?
@gentle ingot Digital Oceon is probs better, only pay for what you use
TypeError: argument of type 'WindowsPath' is not iterable
Whats with this Django Error?
you put a single value where there was supposed to be list I would assume
yo i have a post model and i want to add another model post_comment contains(post_comment, user) so the foreign key would be post and user if i am right.
now i am displaying the comments together with posts via detailView how can i add the comments model to be listed also in my detailed view?
its django
Hello how can i make flask serve the backend of react?
here is my repository https://github.com/happyperson10/flaskreact.
if you want to help me ping me.
hello, I have created a webpage where I can upload images following this tutorial: https://www.roytuts.com/upload-and-display-image-using-python-flask/ How can I make it such that when I upload an image, a new sub-website gets created such that it doesn't overwrite the old one?
Hi, anycan help me? I am trying to call a remote .php script via a Python script. How do I pass the params correctly? Code is below
import requests
url = 'https://www.kvberlin.de/60arztsuche/suchep.php'
myobj = {
'fachgebietep': 'Psychologischer Psychotherapeut',
'Stadtteil':'Neukölln',
'Arztdataberechtigung':'Tiefen*'
}
x = requests.get(url, data = myobj)
print(x.text)
x = requests.get(url, data = json.dumps(myobj) )
The .php script tells me, that in order to return results, I need to at least pass some params. It don't seem to transfer the params. I checked the correct names of the values to submit in the url.
Maybe the format of myobs is wrong?
http params ?
the params in this form https://www.kvberlin.de/60arztsuche/suchep.php
try this
'https://www.kvberlin.de/60arztsuche/suchep.php/?param1=value1¶m2=value2'
requests.get only with url then?
https://www.kvberlin.de/60arztsuche/suchep.php/?fachgebietep=Psychologischer Psychotherapeut&Stadtteil=Neukölln
try this. GET doesn't take body of request, only headers
how to execute this in maybe a python script so I can have the result in a local file?
hey guys, is anyone at ease with django models ?
lil bit
great :), I would like to ask you something then
shoot, glad to help if I can
thanks 🙂 so i would like to make a model for users
it would look differently than django classic users so i want to make a model for it
i want to reproduce something like uber eats
so there would be 4 tables i guess
maybe you can tell me what you think about my schema
i'll show you i drew it
look for a video from jetbrains at yt
it helped me a lot in the 1st place
re: django user models
i'll look at it thank you 🙂
so as i said it's more to make like a copy of uber eats
and here's how i thought it would look like
it's far from being done it's just an alpha
you should def use UML to avoid multiplicities errors
is it worth learning it for this project ?
worth for any SE project
first, build your models neatly, then implement
saves you a loooot of time
do you know how to change the width of the <hr>?
do you have a resource i can learn UML from ?
it seems that there is UML 2 and people don't specify if they teach uml 1 or 2
and i suppose uml 2 is better
urghs sry I dont have any specific res except my university slides
i see, it's ok then
hey, how can i adapt this repo : https://github.com/discord/discord-oauth2-example to django ?
thanks !
or, just, how can i simply return a user's email ?
how can i do light grey background color on my website?
how can i do light grey background color on my website?
@native tide You have the css property for background color, as for get the color values, you can use a color picker https://www.google.com/search?q=color+picker
if anyone knows how to place a cookie in users browser inside of a function with fastapi I will love you forever
when using pandas to combine data frames, you think i should combine dataframes first then export to csv
when using pandas to combine data frames, you think i should combine dataframes first then export to csv
or convert each one to csv then combine csvs
is there any way or idea to add a system for the user to not be able to delete another user's uploaded asset
https://cdn.discordapp.com/attachments/267624335836053506/751163313815158818/unknown.png
Guys, just a question. I'm using objects.filter to select specific objects from a queryset in django. Is it possible to select these objects in a random sequence?
So the sequence is constantly changing
I would personally just change the sequence after you get the objects. with like, random.shuffle xD@formal shell
is there any way or idea to add a system for the user to not be able to delete another user's uploaded asset
@frozen spear you could use a check before it is allowed to be deleted and on the template. So only if like:
if image.user == user:
# run the code to delete here
and the same in the template, you could do like:
{% if this_image.user == user %}
<div class="delte">
<button>delete</delete>
</div>
{% endif %}
^pseudo code btw
@acoustic oyster I had no idea about this function, thanks a lot my friend!
haha, no problem, it is fun to play with
@acoustic oyster i will check that out
after 3 hours of trying I managed to integrate google oauth into my fastapi!
now I can finally go to sleep lol
It was a pain in the butt but a good learning experience 🙂
🙂
how can i add css to a html template..i searched online and all guides are for old django
you need to load static
and refer to those static files
% load static %}
<!DOCTYPE html>
<html>
<head>
<title>Wizard</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="{% static 'wizardslair/css/bootstrap.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'wizardslair/css/style.css' %}">
<!--disables navbar and footer for home.html-->
{% block extra_css %}{% endblock %}
<link rel="icon" type="image/png" href="{% static 'wizardslair/images/logos/favicon.png' %}">
</head>
@frozen spear
hmm, what is whitenoise xD
is this in production?
it sounds like your middleware is not configured properly
i love css
same man
yEAH
Not sure if this is the correct channel, but does anyone have experience using selenium (in python) to submit an ajax form?
this is the page I'm looking at: https://cmsweb.pscs.calpoly.edu/psc/CSLOPRD/EMPLOYEE/SA/c/COMMUNITY_ACCESS.CLASS_SEARCH.GBL?&
@woven pasture I use https://letsencrypt.org/
Yeah but how
and also I bought http://zovice.xyz using namecheap
how do I add a webpage
And they have a lot of documentation on how to do it, but to get you started, what type of application are you deploying (flask app, django app) and on what machine will you be hosting on (laptop, cloud service, etc.)? @woven pasture
And they have a lot of documentation on how to do it, but to get you started, what type of application are you deploying (flask app, django app) and on what machine will you be hosting on (laptop, cloud service, etc.)? @woven pasture
@worn rapids I host using heroku
and right now lmfao I just have basic html
not even basic html
are u making a personal website?
just text saying
yeah personal website
for adiscord server I have
that sells stuff
ahhhh kk. Well, if you're in it for the learning process, go ahead, but my personal recommendation for a static website (meaning, no scripts are behind it) is to use github pages to generate and host a website. here's my personal website: https://tisuela.com/
You could adjust things to make it appropriate for ur discord server's website
wdym by no scripts behind it
It wouldn't be dynamic -- things can't change too much (you would need scripts for things like commenting, uploading / downloading files, etc.)
I use heroku to host
and so far it only has html
(css will also be added)
so how do I get a
ssl certificate
I haven't used heroku, but here's a seemingly good tetorial https://medium.com/@franxyzxyz/setting-up-free-https-with-heroku-ssl-and-lets-encrypt-80cf6eac108e
Actually, try this one @woven pasture https://medium.com/@bantic/free-tls-with-letsencrypt-and-heroku-in-5-minutes-807361cca5d3
the difference is, the latter one has you make a static file to answer the acme challenge (to validate that this is your website). The former link uses a script to answer the acme challenge
💀 oh thats linux
can i create a delayed redirect in django since i made a simple loading screen
discord?
webpages
he's asking how to make another webpage on a heroku-hosted web application
oh
@woven pasture it sounds like you're building from scratch. Are you not using a web framework like flask to help you?
I
@woven pasture it sounds like you're building from scratch. Are you not using a web framework like flask to help you?
@worn rapids I've never used Flask.
I only know a tiny bit of html and css and to help me learn better (an excuse for me to buy a website) I bought a website
So, what exactly are you using the build your site? Does heroku have some sort of framework to help you, or is it just you writing files?
I was planning to upload what I make onto the site
So, what exactly are you using the build your site? Does heroku have some sort of framework to help you, or is it just you writing files?
@worn rapids I just write the files
vsc and then transfer it to github
You should use a web framework (I recommend Flask) to build it. I know it's a bit intimidating, but you have a helpful community here, and it will be rewarding. You need some sort of web framework to make handling requests to your website (like, how you would get from discord.com/register to discord.com/login after registering).
TL;DR: Want to easily add + create + maintain webpages? Use a web framework. Tho anyone out there who's reading this, if u have a easier solution for this guy that would be nice
From my head, an easier solution would be to use Github Pages. You wouldn't need heroku on this route, Github would host it for free (no worries about SSL certification or any of the hosting nitty-gritty). You can still write your own HTML, but Github uses an app called Jekyll to use the HTML templates you wrote and fill in the information dynamically.
You would need to learn how to use Jekyll tho. And my example is here: https://tisuela.com/
And if you don't want to learn HTML, I recommend Weebly as a pretty good website builder, without needing to know HTML or CSS
Hey everyone i need to make a website on a topic and i need some advice is any help will be greatly appreciated
so i have to make a website on topic: The new emerging perspectives post covid 19 and sub topics are a) The pandemics impact b)life after covid 19 and c)socio economic impact of covid 19 and i am out of ideas i know the basics but i have few things in my mind like sticky navbar but am not sure how to do that
well, we can certainly help you make your website come to life. I do not know how much we can help for a very vague issue like that.
As far as sticky navbar, that is just it! you can google things like that. w3 schools is an amazing resource for things like this https://www.w3schools.com/howto/howto_css_fixed_menu.asp
For a sticky navbar, you pretty much just need to use "position: fixed"
alright i have made a website in past using HTML and CSS in VS Code @acoustic oyster would you mind looking it i can PM you so you can have an idea about how much I know
if you do not have a clear picture of what to do, then I recommend just getting started. Add features you know you need/like. Such as the navbar, then things will hopefully come together. Think about the structure, since it is a very specific website, you could have a home/introduction page, a page with all the real data (like all the facts and in-depth descriptions). Or perhaps you would like to make a new page for each topic
feel free to pm me
Which framework is good for start?
I started with django personally. But I got discouraged the first time because it was very intimidating. After learning more about python I came back and loved it.
I cannot speak to Flask because I never used it. From what I understand flask is easier to get a simple website set up, so it is a more friendly start
Django have nice file structure
I found django a great learning experience because of the forced structure. It taught me a lot about how to structure a python project.
I recommend starting with django, but I am biased. You also need to know that you are getting yourself into a more complex framework and be prepared to learn anything you do not understand.
The first time I tried django I did not know what a dictionary was or how to use it, so I got very confused and was already overwhelmed haha.
Corey Schafer on youtube makes it incredibly easy to start with
I believe he also has flask tutorials though
Okay thx can I dm you if I have any problem? 😅
hi
hi can someone personally help me with html and css organization
i have this big unformatted working code that i need for someone to organize it
like making the code look neat?
@native tide [sry for ping]
yes
@native tide make the code in html css format
<head>
<script src="https://twemoji.maxcdn.com/v/latest/twemoji.min.js" crossorigin="anonymous"></script>
</head>
<link
href="https://fonts.googleapis.com/css2?family=Varela&display=swap"
rel="stylesheet"
/>
<title>Chatapp-shit</title>
<style>
img.emoji {
height: 1.1em;
width: 1.1em;
margin: 0 .05em 0 .1em;
vertical-align: -0.2em;
}
body, html {
font-family:Varela;
text-align:center;
color:black;
background: url("https://cdn.glitch.com/f5439616-0499-46af-88f4-47cd6c56f967%2Fb1fe7c55-6b04-4b0a-9ac3-9e7dc2f71c31.image.png?v=1599054597547") no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
</style>
<div id="box">
<h1>
Chatapp
</h1>
<h3>
Chat with friends in a comfortable way!
</h3>
</div>
<div id="messages">
Connecting...
</div>
<div id="inputs">
<br />
<input type="text" id="name" placeholder="Name" />
<br />
<input type="text" id="token" placeholder="Token" />
<br />
<button onclick="connect()">Connect</button>
</div>
<script src="client.js"></script>
Okay thx can I dm you if I have any problem? 😅
yeah, feel free, you can also post here and @ me if you want
yo is it possible to add 2 models in detailview (django framework)?
@acoustic oyster 😅
well hello hello
hmmm, I cannot think of a way off the top of my head. You may need to write a custom view for that, you could possibly inherit from detailview though
wait, a detail view refers to a single view of an object, so I would say no
you would probably need fully custom view for that
well i havent learned custom view yet
I mean, you would have to write your own. gimme one sec
yes yes sir😅
you would pretty much need to create your own view, im not sure if any of the existing ones would help here.
but a simple version could be
def my_view(request):
context = {
"model1" = model1.objects.all(),
"model2" = model2.objects.all(),
}
return render(request, template_path, context)
so i should just not use class base view for this one?
although for a detail view, you may wish to use slugs, or the PK to get the models, rather than getting all
you certainly could, in fact I would recommend it, this was just a simpler way to write out the logic
alright ill try it sir thank you
@lapis spear this could help? https://stackoverflow.com/questions/12187751/django-pass-multiple-models-to-one-template
thank you sir @acoustic oyster im slow so it may take sometime for me to absorb this 😅
no worries, there are tons of resources and help available
With sanic, would it be faster to load files at startup then return those variables instead of returning a html file on a request?
thank you @strange briar i was sleeping
Hello, anyone here have any thoughts about VOD API services? like mux, muvi, brightcove, or vimeo OTT?
thoughts like preferences, red flags, experience
I am considering these services for a simple learning system