#web-development
2 messages ยท Page 5 of 1
when i did self.model.slug i had no idea what i was doing xd
are you sure that that's the actual slug of the current object and not the field of the model?
alright
I imagine this might be useful for some of you https://github.com/newsapps/beeswithmachineguns
Could someone at least point me in the right direction?
What do you mean @gleaming drift ?
I can copy paste see 2:43 (that's PST time) so roughly 6 hours ago
right before your and gdude's convo I believe
tbh I didn't know where to ask, figured since my program is in python this be a starting point
lol were they giving me shit cause my question was bad? I just noticed that
umm
i dont think many people use nodejs in this server. I mean its a server dedicated to python
right, i'll use python if possible
problem is idk what exactly im lookginf for
just dont want to sign into game, join match every time I wanna work on prog
U can stick to your node.js thing, but you have to find the right place to ask the question
Do u know the Programming server?
can i use python to just send the json to myself at set intervals
what you mean prog server?
actually, im sure i can, just thought of that
Is there a way to render templates with place holders. In example I have 50 pages for every state but don't want to write 50 routes. Just one where the url is index/[state]. Below is the code I wrote thinking it would work but got a template not found error.
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route("/index/<state>")
def state_page(state):
return render_template('state.html', state=state)
if __name__ == "__main__":
app.run(debug=True)
did u put the html template in templates directory? @indigo holly
@indigo holly maybe it'd be better to have state passed as a GET parameter and then passing it to the template as context?
It is in the template directory! And one second Volcyy. Let me see if I can translate that to code with what you suggested.
So @meager anchor I'm not sure how to make this code into a placeholder that can be dynamic. I understand how routes work statically though.
app = Flask(__name__)
@app.route("/state", methods=['GET'])
def state_page(state):
return render_template('state.html', state=state)
if __name__ == "__main__":
app.run(debug=True)
one sec
ok, so you want to access the GET parameters from the request
a quick glance over the docs tells me you can access the request using from flask import request, and then get arguments from it using request.args.get('key', '')
so in your case it would be
from flask import request # and your other stuff
@app.route("/state", methods=['GET'])
def state_page():
state = request.args.get('state', default) # set default to whatever the default state should be
return render_template('state.html', state=state)
# ...
then you can use state in your template
You'd want to change your @app.route to just be a catchall in this case, no?
wdym?
I think I misunderstood NotSam 's intent, you'd be accessing this though "example.com/state?state=VA", right? I first read it as wanting to access through "example.com/VA"
oh, yeah
Richy, you're correct about the example.com/VA my original example just included an additional slash for ... not sure
The goal is to be able to go to example.com/VA, example.com/PA ..etc with a single route
Sorry about the confusion here
I think your original code might have been correct,.
Can you try creating a static route that you know works, then retry using the template on that route. That'd help you diagnose the "template not found error".
Sure. Be back soon with results
@indigo holly Try enabling flask debug mode
That'll help you figure out errors like that
As for your first block of code, that approach was fine
The error was just that it couldn't find the template
Hm. Okay. So it's a pathing issue?
Because when I type example.com/FL I want it to open my FL.html but so I was trying to make the code replace 'state' with the string of the url entered.
Let me try the directory stuff again
If you have it stored in FL.html, that's the issue, it's looking for a file called state.html.
You'd need to a string replacement,
either
'{}.html'.format(state) or f"{state}.html"
But with templating, you should be able to create that state.html file, which takes the name of the state, and any of the information, and renders out the html from there.
@indigo holly , incase you're busy working, not reading Discord ๐ ^
๐ฌ
I think the string formatting method could work, but isn't it dangerous as a user could try to access example.com/../../someotherfile and break the app?
They could, yes, so you'd want to check the state is in a collection of supported states, and send them a 404 otherwise
No they couldn't
Not unless the param uses the path type
Which I don't think it does
Without the path type set it will ignore anything after the slash
Including the slash actually
Oh, I see, you were using .., I read that as ...
Alright, I think I have a better grasp of what to do here. Thank you for the helpful assistance everyone
If you have a seperate, manually created page for each state, the render template is probably not what you want, but hopefully you'll crack this nut
The HTML guys and supervisor change what they want everyday, so we'll see haha
Getting Postgres to work with Django tests is insanely frustrating
Yesterday I first had an issue with Django apparently truncating (pgsql) passwords longer than 70 characters, now when setting it up locally, I keep getting "relation does not exist" when trying to create a test database
Then, it keeps trying to delete and recreate the test database, which makes permission management very weird
If I tell it to not delete it, it will just not run any tests. If I tell it to (and I even made the pgsql user that django uses superuser for testing), I get ```py
psycopg2.ProgrammingError: relation "audit_log" does not exist
LINE 1: ..."audit_log"."reason", "audit_log"."category" FROM "audit_log..."
^
...
During handling of the above exception, another exception occurred:
...
cursor.close()
psycopg2.OperationalError: cursor "_django_curs_140735985812352_1" does not exist
which I don't understand. We had the same issue on the actual database yesterday but I don't know what fixed it
Did anyone run into similar issues?
I mean, I can just test against the actual remote PGSQL database (on a test database, of course), but that's a lot slower than running it locally and also kinda besides the point
For the record, I'd like to stay away from Docker for running this.
Maybe should've put it in #databases 
OK, I think I figured it out. I don't know what caused the above issue, but one of the migrations was wrong and didn't create a column properly. No, it was not audit_log.
I am trying to find a way to style a generic form in Django, I have looked online and have not found anything useful to help me style the generic forms.
# views.py
class TutorialCreate(CreateView):
model = Tutorial
fields = ['name', 'subject', 'description', 'content']
<div class="">
<form method="POST">
{{ form.as_p }}
<input type="submit" value="Create Tutorial" class="btn btn-primary">
{% csrf_token %}
</form>
</div>
i think i have to add custom css
fixed it
i just had to add some CSS
label{
display: block;
}
is it possible to use dash (https://plot.ly/products/dash/) with django? how can i use dash for just 1 page on my site, if it starts its own webserver?
django is like a "batteries included framework"
flask is a "batteries not included, buy them" framework
django makes u do stuff the "django" way
flask lets u do stuff your way
that's a decent analogy
but u can build the same stuff with both frameworks
django users are weird people to me
ok, i think im getting this
and what do you reccomend to deploy my site? it says that the flask built in server isnt suitable for production
easy to use would be gunicorn
that is what i found
with ngnix?
no no
You shouldn't, but yes
yeah but i might be seeing a lot of load on my server
you should have nginx serve your static files directly, and then proxy everything else to one of your gunicorn workers
iirc you proxy it to the master and that one handles routing to the workers
nah unlikely you see that much load
probably not but it might go big who knows XD
I think gunicorn recommends cpu_count * 2 + 1 workers?
Yeah
yeah thats what i saw volcyy
what does gevent do
its like asyncio
It makes a bunch of things asynchronous under the hood
It's pretty much transparent though
ahh
gunicorn has explicit support for it
and in case that isnt enough
you can still split your stuff up to multiple machines/vms/containers and put for example ngnix as a load balancer infront
haha dont think ill ever get that much load
but yeah, good to see expansion options
scaling is so important these days
also i saw a lot about running things in isolated python containers? what is all that about?
Docker
docker
yeah, you can do that, it does make automatic deployment easier
well there are others
We also do that
well I mean you'll be using docker or LXC
and docker is basically just an API on top of LXC, if you're on linux, so
what does docker do?
It's a very light virtualisation layer
You're basically running your application in a very small VM
All it does is keep its networking and resources separate from the rest of your machine
basically it runs another system which still uses the same kernel as the real system but everything else is virtualized
ok
think of it as a cool version of virtual machines
which bits would you put in a docker instance then?
Gunicorn and your webapp itself
u can use virtualenv in place of docker
no
i do that only
No you cannot
thats bullshit
they are completely different things
how?
they r different
not even close to
what does virtualenv do then
They do different jobs, you can't replace one with the other
that's a silly assertion
yeah, that's basically it
yeah
but everything still runs on the main system
why would isolating them be good?
When you have more than one python application on a single machine, their dependencies can overlap and conflict
its like virtualenv + pip
virtualenvs solve this problem
ohh
docker goes one step further and isolates the entire running environment basically
its no related to virtualenv
would you run a virtualenv inside docker then?
yes but due to most docker containers only being used for one thing it wouldnt make sense
it only makes sense if you have multiple things running on the system
like for example
2 flask apps which need different flask versions cause one cant use a higher one
in this case the one which cant use the higher version would break
yeah, mostly
good good
:P
thanks for the help guys
why would you want to use docker? to run multiple websites behind an ngnix server, on one (or more) servers?
lets say 1 instance of your web app cant handle the load
you just run 2 put them behind a load balancer and bam it can handle the load
and docker is used for running those two
and what would be docker's job there?
with docker you can run 2 seperated environments on the same machine
but why 2 seperated and not 1 big one?
assuming compatability of deps is not an issue
paralelism
look at for example super computers, why dont we just build one mega CPU and instead have dozens of computers running at the same time
so they can handle a LOT different tasks at the same time
right
while one big one may handle a small amount faster 2 normal ones can handle more at the same time
(at least thats my understanding)
so an open connection might block a webserver so your second instance can take another connection smoothly? am i kinda close here?
yes
and what the load balancer does is just counting who has who many connections to handle and splits them up according to that
and yes thats exactly what i was meaning with the super computer example
right
and the "tree" for everything would be in this order? ngnix -> docker -> gunicorn + flask
yes you can do it like that
is there a better way?
you could split it up to several physical machines too and run docker containers on all of them
but on the software level apart from maybe using some container orchestration software this is a very good way to scale the app
eh
what Nix says isn't very clear
Docker has this thing called swarming
so you set up a bunch of machines in your docker swarm
and then you can use - for example - saltstack or docker itself to deploy containers to the machines in the swarm
Not sure if this is the right channel but how would I go about using HTML to open a python script and run it?
Like if I were to click a button and it would launch a python script on my computer
(without flask or any similar programs)
well he could use electron and some js.....
@strange thorn How would I do it then
yeah thats true
Would it be possible to use PHP and exec the py script?
oh how so
well
python is pretty popular in doing the job php usually does
you can use a python webframe work like flask or django (django seems a bit overkill for this) to do what php usually does
and then just use normal html and js at the frontend
oh flask
Not sure if this is the right channel but how would I go about using HTML to open a python script and run it?
That would be a huge violation of your security lol
No one would ever visit your site if you can achieve it which you never will
Hi all, I just read posts. @twin shoal Web GUIs have these pillars: HTML, JavaScript and CSS and you cannot run python in your browser. Browser simply does not understand python.
But you can serve points to call from your web gui to accomplish what you want
thank you, but I ended up just using django ๐
Cool. I would had recommend flask ๐
haha at first I didn't really want to try django cause I had no clue what I was doing but spent some time on the internet and now it's all good
nice!
awesome, you've gotten further than i have and i've actually tried :D
I am trying to make a search bar in django using Class Based Views. However, the code i wrote always raises a KeyError when i type something into the search bar. I have looked online and couldn't find anything useful
class TutorialSearch(ListView):
model = Tutorial
template_name = 'tutorials/tutorial_search.html'
def get_queryset(self):
term = self.kwargs['term']
if not term:
return self.model.objects.none()
else:
return self.model.objects.filter(name__icontains=term)
the error that is raised from this is:
'term'
nvm i switched that view back to FBV
@grand badge is it because there's not 'term' key in whatever kwargs you've got?
fair enough
i just took the view back from CBV to FBV
Ok, so I'm working on user profiles for my site (Django). Currently profile URLs are profile/{user-id}, which works, but the URL is pretty ugly. I want to give users the ability to set "nicks" on their profile so they can access their profile using a simpler URL, e.g. profile/~volcyy. What's the best way to accomplish this without a redirect?
The redirect was my initial idea. Have an extra view handling profiles/~<str:nick>, if exists, redirect, else 404
But that would just change the URL back again and kinda ruin the point IMHO
well
nobody cares about what a URL looks like
it's more about accessibility
i think a redirect would work fine
hmm
I wrote incredibly shity code just to have my pages ?page instad of /page
show
Hold on
page = request.GET.get('page')
if page is None:
prev_opt0 = [1]
prev_opt = prev_opt0[:-1]
next_opt = [x + 1 for x in range(1, int(paginator.num_pages))]
page = 1
nexty = int(page) + 1
prev = int(page) - 1
else:
try:
if int(page) > paginator.num_pages:
page = paginator.num_pages
except ValueError:
pass
try:
prev_opt0 = [x + 1 for x in range(int(page))]
prev_opt = prev_opt0[:-1]
next_opt = [x + 1 for x in range(int(page), int(paginator.num_pages))]
nexty = int(page) + 1
prev = int(page) - 1
except ValueError:
prev_opt0 = [1]
prev_opt = prev_opt0[:-1]
next_opt = [x + 1 for x in range(1, int(paginator.num_pages))]
page = 1
nexty = int(page) + 1
prev = int(page) - 1
try:
mtitles = paginator.page(page)
except PageNotAnInteger:
mtitles = paginator.page(1)
except EmptyPage:
mtitles = paginator.page(paginator.num_pages)```
Yeah I do realize how bad this is
But it was my very first project ever
I directly jumped into django without even knowing what even a class was
Also half of these should be javascript instead of python, lol
what
i'm very sure that Paginator handles all of this by itself
literally all I had to do to add Paginator to my generic.ListView was adding ```py
paginate_by = 10
and some simple html
```django
{% if is_paginated %}
<nav class="pagination align-center">
<ul>
{% if page_obj.has_previous %}
<li><a href="?page={{ page_obj.previous_page_number }}"><</a></li>
{% endif %}
<li>
<a href="#">Page <strong>{{ page_obj.number }}</strong> of <strong>{{ page_obj.paginator.num_pages }}</strong></a>
</li>
{% if page_obj.has_next %}
<li><a href="?page={{ page_obj.next_page_number }}">></a></li>
{% endif %}
</ul>
</nav>
{% endif %}```
you mean in the HTML?
Hold on lemme show it
I made this whole thing work with python instead of using couple of lines of javascript
And I do realize the python code is also disgusting
But hey, I didn't know python at all when I started it sooo /shrug
this looks like you could accomplish it in the template with a for loop easily
I mean there are a lot of eaiser, better, cleaner ways to do it
But I used to suck
uhhh
a lot of image tags?
maybe one image tag
no
prolly no image tags
and just a background in css
too much bad pics
no that looks like seperate images
I'd say that is image tags
with css to say don't wrap to a newline after every image
it was ap
they are saparate html element each image is hyberlink
they are dynamic each time you load the page u get different images in different position and sizes
it's a flexbox layout
Doing my first web app deployment and using python anywhere. Anyone famliar with why I'm getting an error
"RoundBallmain.app as application imported but unused" Here is the relevant code:
import sys
# add your project directory to the sys.path
project_home = u'/home/my-path/RoundBallAnalytics/project/'
if project_home not in sys.path:
sys.path = [project_home] + sys.path
# import flask app but need to call it "application" for WSGI to work
from RoundBallmain import app as application # noqa
I followed the tutorial through their documentation and pulled everything from my Git files.
Locally, everything works fine however right now the site has some pages that show and others that give errors.
So I think my git clone downloaded all my files but older versions of them. This may be the issue. Not sure why github did that
Sup everyone, got a Flask question here.
I'm working on an OAuth workflow via a website for my Discord bot, and it just makes sense to make all the API calls after the authentication from within the website script instead of having the Discord bot do it for avoiding issues later on. Now, these API calls in total can take roughly 5-10 seconds, and I'd like to render an HTML basically saying "Hold up, this can take a few seconds", then rendering another saying it succeeded at the end. Using render_template at the top of the app route doesn't work though (I'm very new to web development). Anyone have any ideas on how to do it?
Ok, so you have a long-running task
there's a couple ways to do this
- Set up a task runner (eg, Celery), farm out your tasks to that, and use AJAX to query the status of the task (securely)
- Set up a task runner and use websockets to communicate task status between the server and the browser
either way, you can't just render and render again, you'll need some logic on the page to make the client reload or move to another page
that means javascript.
Gotcha. There's no way to render and after the render run more scripts, right?
No, the reason for that is just how the lifecycle of a request works
No data is returned to the client until the request function has finished executing
Ahh, that makes sense. I know literally 0 JS, so this is gonna be fun. ๐
Well, thanks man, appreciate it!
No worries
don't listen to the haters. JS is nice.
DAX Master Race ๐
Completely useless for coding but it's how I learned the basic stuff (in Excel, lol)
i've heard that it's possible to host a website on a raspberry pi, but i don't know how possible or advisable that is, especially for someone like me with very limited knowledge in this field. thoughts?
reasons to do it:
(1) very good learning experience
(2) you don't have to pay for anything you're not already paying for (except possibly a domain)
things to be taken into account:
(1) you need to obtain a static IP address
(2) you are more actively exposing your private network to you internet when asking people to come take a look at a website hosted on it. this shouldn't be a strong determent but be very security conscious
(3) you're probably not going to be able to field terribly heavy traffic
the learning experience is my main focus, by far.
Raspberry pi i guess is okay for hosting
and as i only plan to make a simple personal blog sorta thing, i don't think resources would be an issue
Have u heard of pythonanywhere?
oh, i really dislike that.
Its gud for beginners
but as a beginner, i want to learn all that i can
ah
also, i prefer to have everything where i can see it. yes, i'm that sort of person.
i get paranoid when i don't do stuff myself
(also the reason why i don't trust UUID haha)
hav u heard of heroku, linode or digitalocean before?
Ah k
and stuff like that
don't know much about linode, but your experience with digiocean is bound to be almost identical to your raspberry pi experience, just remote
So u gnna use raspberry pi to host?
oh wait actually I guess some people in the world use guis
nah i don't have a GUI on my pi
all the server work would be very similar, then, digiocean would just handle the whole "having a network" bit
but you see, i don't know what the fuck goes on with "having a network"
fair point
is digiocean an abbreviation?
yes that's what I call it
o lmao
because the tal is so hard to type
Why u do dis?
every curve of my swipe counts
Why u say digimon?
if you wanna battle me on swipe keyboards too we can throw down in #ot0-fear-of-python
k
i'm in.
i also thought about hosting my website on my rpi, but as lucy said that would mean exposing my private network and I'm not a big fan of that
it's great for other projects though, right now i have pihole running on it and, uh, well that's about it 
but yeah basically, you should look into a digitalocean VPS, if you're a student you can get a $50 starting credit
to me there's like no difference between using the VPS and the raspberry pi, both are debian derivatives ๐ so yeah, i'd recommend that. it's also a good learning experience
My pi runs arch :>
@brave mantle same
arch works well on rpi, also because I refuse to use any other os other then arch ๐
I used to have a pi-hole but they're kinda slow
Might set it up again if I end up with an actual machine for a server
They rewrote parts of it in C recently, IIRC
Anyone familiar with dynamic routes in flask?
If I have a bunch of HTML files for separate pages is there a better way to route to them with less code than an IF statement for each one, like this:
@app.route('/<page>')
def index(page):
if page=='example1':
return render_template('example1.html')
if page=='example2':
return render_template('example2.html')
That's what I was thinking actually
{
"example1": "example1.html",
...
}
will the html page always have the same name as the page variable?
e.g. index(x) would return x.html?
No its based off US states. so the URL preferably be
url.com/fl returns florida.html
Alright that makes sense! Just wanted some reassurance before I started. Thanks all
I'm getting an error that I haven't been able to troubleshoot with the internet so far.
Error: render_template() argument after ** must be a mapping, not str
I understand what its saying that the render_template can only take one parameter but unsure what to pass then
state_page = {
'fls':'florida_senate.html', 'vas':'virginia_senate.html', 'national':'national_congress.html'
}
@app.route('/<state_page>')
def index(state_page):
return render_template(state_page, **state_page)
i believe you should make your index argument named state_name then do render_template(state_page[state_name])?
@app.route('/<state_name>')
def index(state_name):
return render_template(state_page[state_name])
This worked! Thank you.
:D no problem
So for some reason my Django doesn't purge the database properly after each test case, and I get some incredibly weird behaviour because of that. Shouldn't TransactionTestCase isolate the test? I'm using it because the others don't support fixtures...
"A TransactionTestCase resets the database after the test runs by truncating all tables. A TransactionTestCase may call commit and rollback and observe the effects of these calls on the database.
A TestCase, on the other hand, does not truncate tables after a test. Instead, it encloses the test code in a database transaction that is rolled back at the end of the test. This guarantees that the rollback at the end of the test restores the database to its initial state."
what..
Ah. Yes, I'm quite the idiot.
can anyone help with django rest api
yes, but don't ask to ask
ok
so im doing node.js and im developing an api backend
im generating "random" images
so
this is my json output:
{
"gay": "http://isabaseurl.com/gay/gay1,gay2.png",
"lesbians": "http://isabaseurl.com/lesbians/lesbian1,lesbian2.png",
"boobs": "http://isabaseurl.com/boobs/boob1,boob2.png",
"ass": "http://isabaseurl.com/ass/ass1,ass2.png",
"pussy": "http://isabaseurl.com/pussy/pussy1,pussy2.png",
"dick": "http://isabaseurl.com/dick/dick1,dick2.png",
"men": "http://isabaseurl.com/men/men1,men2.png",
"random": "http://isabaseurl.com/random/gay1,gay2,lesbian1,lesbian2,boob1,boob2,ass1,ass2,pussy1,pussy2,dick1,dick2,women1,women2,men1,men2.png"
}```
This shouldn't be happening. It should be only picking one element from a constant array of elements. Any idea why?
const gay = [`gay1`, `gay2`];
const lesbians = [`lesbian1`, `lesbian2`];
const boobs = [`boob1`,`boob2`];
const ass = [`ass1`,`ass2`];
const pussy = [`pussy1`,`pussy2`];
const dick = [`dick1`,`dick2`];
const women = [`women1`,`women2`];
const men = [`men1`, `men2`];
const random = [gay, lesbians, boobs, ass, pussy, dick, women, men];```
This is my constant arrays
its grabbing all of the elemets and inserting them

sh
its just a practice thign
im just practicing lmao
i couldnt think of anything
so
like
it serves the json alright
but
im just stuck on how to actually "choose" one subject
I mean, there isn't enough code here to really
help you
you've got some json and some arrays
and.. nothing in-between
const app = express();
const base_url = `http://isabaseurl.com`;
const gay = [`gay1`, `gay2`];
const lesbians = [`lesbian1`, `lesbian2`];
const boobs = [`boob1`,`boob2`];
const ass = [`ass1`,`ass2`];
const pussy = [`pussy1`,`pussy2`];
const dick = [`dick1`,`dick2`];
const women = [`women1`,`women2`];
const men = [`men1`, `men2`];
const random = [gay, lesbians, boobs, ass, pussy, dick, women, men];
app.use((request, response, next) => {
console.log(request.headers)
next()
})
app.use((request, response, next) => {
request.gay = `${base_url}/gay/${gay}.png`;
request.lesbians = `${base_url}/lesbians/${lesbians}.png`;
request.boobs = `${base_url}/boobs/${boobs}.png`;
request.ass = `${base_url}/ass/${ass}.png`;
request.pussy = `${base_url}/pussy/${pussy}.png`;
request.dick = `${base_url}/dick/${dick}.png`;
request.women = `${base_url}/women/${women}.png`;
request.men = `${base_url}/men/${men}.png`;
request.random = `${base_url}/random/${random}.png`;
next()
})
app.get('/', (request, response) => {
response.json({
gay: request.gay,
lesbians: request.lesbians,
boobs: request.boobs,
ass: request.ass,
pussy: request.pussy,
dick: request.dick,
men: request.men,
random: request.random
})
})
app.listen(80)```
it's like a nothing sandwich
yeah that's a really odd way to do that
Why add them to the request object?
Just put them right into the json call
so what do you suggest then
because you assign to a different variable in each of your routes
putting it all into the same route
just basically fuck it in the same place?
response.json({
gay: `template literal?`
})```
no
you need to do a node tutorial
yeah

but
but this is a Python server, so I don't really have one for you
Not really
I see what you are trying to do, but the request in the app.use is a different request to the one in the / route
the standard library is different
tbh i dont really care about the efficiency
just want to try to solve the goddarn picking out
random
It works for me. .-.
that makes very little sense
which i thought i defined.
no you didn't
var rand = myarray[Math.floor(Math.random() * myarray.length)];
when you think javascript already chose random ones for you from your previous code snippets
bc it literally did that for me
yes but putting random commas into a string doesn't tell javascript "hey i wanna get a random value lol"
no
you are going to add an array with the 8 values in.
and then add it to the base url meme
base url meme lmao
niiice to knwo im a meme
hmmmmm
for it to work, id' have to redefine a new one for each variable?
im not fully understanding

fml
var BLAH = ARRAYNAME[Math.floor(Math.random() * ARRAYNAME.length)];
yes but the variable is a BLAH?
@mild bridge I'm getting flashbacks of bamboozle with aperture
yEET
yet what
lmao
@kind steppe that code solution fixed it but broke it as well
it does get a random element but it sticks with it all the time now
;ole
like
no matter how many times i reload it
its always the same
show the code
```const gay1 = [gay1, gay2];
var gay = gay1[Math.floor(Math.random() * gay1.length)];
const leb1 = [lesbian1, lesbian2];
var lesbians = leb1[Math.floor(Math.random() * leb1.length)];
const boobs1 = [boob1,boob2];
var boobs = boobs1[Math.floor(Math.random() * boobs1.length)];
const ass1 = [ass1,ass2];
var ass = ass1[Math.floor(Math.random() * ass1.length)];
const pussy1 = [pussy1,pussy2];
var pussy = pussy1[Math.floor(Math.random() * pussy1.length)];
const dick1 = [dick1,dick2];
var dick = dick1[Math.floor(Math.random() * dick1.length)]
const women1 = [women1,women2];
var women = women1[Math.floor(Math.random() * women1.length)]
const men1 = [men1, men2];
var men = men1[Math.floor(Math.random() * men1.length)]
const random1 = [gay, lesbians, boobs, ass, pussy, dick, women, men];
var random = random1[Math.floor(Math.random() * random1.length)];```
"gay": "http://isabaseurl.com/gay/gay2.png",
"lesbians": "http://isabaseurl.com/lesbians/lesbian1.png",
"boobs": "http://isabaseurl.com/boobs/boob2.png",
"ass": "http://isabaseurl.com/ass/ass2.png",
"pussy": "http://isabaseurl.com/pussy/pussy1.png",
"dick": "http://isabaseurl.com/dick/dick2.png",
"men": "http://isabaseurl.com/men/men1.png",
"random": "http://isabaseurl.com/random/women2.png"
}```
this never changes
maybe its just grabbing like a value higher than 2
well that is why
you've made the variables
but you've not actually sent them back
my dude I seriously recommend a Node.js tutorial

what even is node.js?
oh okay
Oohh I get it
@kind steppe It does update with random values; but I have to keep restarting the node.js script for it to take effect
so now i have to work out how to make it update with every request
make it generate every request
yeah you have to
When I scroll, the h1 content like jumps straight to the top. I want it to be continuous if that is understandable
https://jsfiddle.net/ZuhoR9R/tjsfpp6r/1/
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
Hello, I've installed Django onto my PC
I created an app
All of this is really complicated-sih
*ish
Is Flask easier than this?
no
it's not really easier, installing everything and making the webserver work is kinda complicated :/
especially for development
hmm... deployment you have a point on, but in terms of the bare minimum requirements for having a functional application, most people would tend to lean towards Flask for simplicity
in lemon's words, Flask is "less opinionated" about how you do things
if you want to build it into a robust application in the manner of django you can do so, if you want to serve a barebones API for an existing project you're also free to do that
so... I'm hesitant to say it's "easier", it depends on the sense, but it's not going to demand as much from you to get going. whether that's good or bad depends on your needs and convictions
I think flask is a lot easier to learn, but very often when I'm looking for something in Django - for example, "create a view to edit this objects", "create a view to list all objects" - it's already there. Django comes with this batteries-included approach, and that's really nice
flask is easier to start with
I really enjoy flask. Django gave me nightmares
Also,
Can anyone help me troubleshoot this View function did not return a response error?
Everything I've found suggests its an error when the return function isn't used or present. But I can't see what I'm doing wrong with this code:
@app.route('/data', methods=['GET', 'POST'])
def data():
if request.method == 'POST':
if request.method == 'POST':
admin = request.form.getlist('admin')
if admin == 'root':
return admin()
else:
return render_template('AdminPass.html')
relevant HTML
<form method="POST" action="/data">
<input type="text" name="admin" placeholder="admin">
What's admin()?
It's another function, directly below my data() function
But a line above, you check if it equals a string
So it looks like
@app.route('/data', methods=['GET', 'POST'])
def data():
....
return admin()
def admin()
hm
I don't know that much about Flask, but I don't think that this is some special thing that you can call after comparing it to a string
Hmm. I actually do this in the other function and it works though, lets me show you
Can you explain shadowing in laymans?
Also, ```py
if request.method == 'POST':
if request.method == 'POST':
seems a bit redundant
@indigo holly your function will not respond in all cases
thats what flask doesnt like
def add(a, b):
return a + b
if __name__ == '__main__':
add = 5
add(3, 5) # huh?
it wont respond to a request which is a post but hasnt admin == "root"
gives TypeError: 'int' object is not callable
because you shadowed the add function from outer scope
and you have to respond to that case
just always respond tbh
if you dont have like a default return value at the bottom
every if which returns must have an else that returns
otherwise it will crash at some point
I see..
def data():
if request.method == 'POST':
admin = request.form.getlist('admin')
if admin == 'root':
return admin()
else:
return render_template('AdminPass.html')
else:
return render_template('AdminPass.html')
yup
Isn't this redundant though ๐ฆ
I know it's right now. I just don't like it haha ๐
def data():
if request.method == 'POST':
admin = request.form.getlist('admin')
if admin == 'root':
return admin()
return render_template("AdminPass.html")
Thank you for the help! This worked.
no problem
How did that work if it's calling a string?
Good question 
"If x is equal to a string which is obviously not callable, call it"
When did I call a string??????
admin = request.form.getlist('admin')
if admin == 'root':
return admin()
admin = request.form.getlist('admin')
if admin == 'root':
return 'root'()```
You maybe thinking that it is working because it actually never runs and admin never equals to 'root'
def data():
if request.method == 'POST':
if request.form.getlist('admin') == 'root':
return admin()
return render_template("AdminPass.html")```
This simply eliminates the shadowing admin variable so should work
I'd've maybe guessed that you had an Admin object named admin that you wrote the __eq__ and __call__ but it is not the case apparently
Soo
def context_manager(template, context = None):
def actual_decorator(f):
def wrapper(request, *args, **kwargs):
_context = f(request, *args, **kwargs).get_context_magically()
if context is not None:
_context.update(context)
_template = loader.get_template(template)
return HttpResponse(_template.render(_context, request))
return wrapper
return actual_decorator
@deep cave
I'm trying to update the context with a decorator
Because in the website almost every function I write has at least 10 common item in the context
: /

I'm not sure this is a problem that should be occurring. perhaps it evidences poor site design.
but tbh you're in too deep for me to help
:3
I have no idea how you'd do that. if I found myself wanting to do that I'd probably go seek out #django on freenode and have them tell me where I went wrong.
seems like an antipattern to me
that's a great channel btw for really hairy django stuff
most of the maintainers are there
I wonder if aera/andrewgodwin is there
and a ton of exceptionally talented django devs.
Hmm, thanks
He's a django maintainer, and the origin of my old MC network
And this is for uhm, the context as in the user name, the index list etc.
They are mostly same in all the pages
isn't there some sort of global context in django like in flask?
Like the index list exist in every singe sub page
Is there? That is what I'm trying to do
lol
God damn it SO
in flask this is trivial, cause a global context variable comes with flask itself.
custom context processor, huh?
Wow, something built-in in Flask and not in Django :D
hmm
A context processor has a very simple interface: Itโs a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context.
that seems pretty straight forward, no?
All Django cares about is that your custom context processors are pointed to by the 'context_processors' option in your TEMPLATES setting
and then it's just handled automatically
Hmm
So they don't make me extract the context from the returned object but
All I need to do is to return a dictionary? ๐ค


That was uhm
Way easier than what I was trying to do
I'll take it :D
Thanks :D
I'd like to create a webapp/flask that has a form users will fill out. Upon submisison they will be routed to a printable page of their data. I'd like them to be able to save a version to edit or re-upload and populate the form. What type of file would you suggest?
I don't want to store the data for the user. I was thinking of maybe giving them the option to save a JSON file or something similiar.
This is something can be done with js
Technically speaking, you don't need to store the data, but it depends what you're doing
yeah, client-side JS is one option
Just looking for ideas, i'm new to python.
The goal being to replace a hand filled out form that they are currently using. I figured a webapp would be the way to go since future upgrades would be easier to distribute. There are many features that would be nice to implement including electronic submission way down the line.
I mean you really wouldn't want to use your server machine for simple stuff like that
You can use flask for backend
And make a js that handles the form thing
@brittle copper ?
A question mark isn't a question
@brittle copper What do you mean you wouldn't use a server for simple stuff like that?
If what user is doing doesn't concern you, if you don't log it, if you don't add new information to it
You wouldn't do it on the back end
Rather you'd use js
And do it in client side
Is there a way to interact with a FlaskForm object from flask_wtf in the REPL?
disregard found the working with the shell flask page
@quartz maple Are you familiar with Beautiful Soup and Requests?
I know of them
I recommend using BS4 for getting info from websites that don't have an API
Could a django expert check my models.py and verify if my ForeignKey logic is in order?
first_name = models.CharField(max_length = 50)
last_name = models.CharField(max_length = 50)
def __str__(self):
return "{} {}".format(self.first_name, self.last_name)
class ClassNumber(models.Model):
classNum = models.IntegerField()
def __str__(self):
return self.classNum
class SchoolDay(models.Model):
DAY_CHOICES = (('Monday', 'Mon'),
('Tuesday', 'Tue'),
('Wednesday', 'Wed'),
('Thursday', 'Thu'),
('Friday', 'Fri'),)
schoolDay = models.CharField(max_length=3, choices=DAY_CHOICES)
classNumber = models.ForeignKey('ClassNumber', on_delete=models.CASCADE)
def __str__(self):
return self.schoolDay
class Schedule(models.Model):
teacher = models.ForeignKey('Teacher', on_delete=models.CASCADE)
day = models.ForeignKey('SchoolDay', on_delete=models.CASCADE)
```
I've honestly tried everything i know for my ModelForms to render in html but it won't show what I'd like
bot.tags['ask']
Asking good questions will yield a much higher chance of a quick response:
โข Don't ask to ask your question, just go ahead and tell us your problem.
โข Try to solve the problem on your own first, we're not going to write code for you.
โข Show us the code you've tried and any errors or unexpected results it's giving
โข Keep your patience while we're helping you.
You can find a much more detailed explanation on our website.
we can't really help you much from that question
does anyone know of any web scanner for NGINX specifically?
Or mebe making a scanner focus mainly on nginx vulns
i am configuring an nginx server with a web app on top. I am simply practicing. I want to see if there any specific scanner for nginx servers. My server was detected by other scanners as vulnerable (it is), just want to make sure that there are no specific nginx ones
why not, the server is mine ๐
Hahaha
I'll make sure to email them
Should I include any special requests other than breaking the web server?
wait .. um, you lost me over there
the site
Did i miss a joke or something 
for metasploit?
goddem
omg are you telling me what i need to work on metasploit? 
imma kms for not understanding you
i hope i did this time
oh dear
hahaha i know of it. I didn't grasp if gdude was messing with me or nut (in the end i did)
I am not a newbie in security, therefore I thought he was messing with me somewhere in there
there was no ambiguity
I can't figure out where the resources page on the discordpython site gets its icons from json "Automate the Boring Stuff with Python": { "description": "One of the best books out there for Python beginners. You can buy a copy, but there's also a free online version.", "urls": [ { "title": "Website", "url": "https://automatetheboringstuff.com/", "icon": "regular/link" }, { "title": "Amazon", "url": "http://www.amazon.com/gp/product/1593275994/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1593275994&linkCode=as2&tag=playwithpyth-20&linkId=HDM7V3T6RHC5VVN4", "icon": "branding/amazon" } ], "payment": "optional", "payment_description": "A free version is available online, with the option to buy a physical copy" },
see "icon": "branding/amazon"
it's not in the CSS and I can't find it in a fulltext search of the whole site repo
It's in the branding repository
argh
I've never heard of this before
I'm browsing the branding repository and I have two questions... one, how does this get included into the site and CSS, I can't find any references to it in the site project. Two, there aren't any youtube or amazon icons in here but they are in the resources JSON and they work, where are they coming from?
@mild bridge
The icons are fontawesome icons
they're not in the branding repo
ICON_STYLES = {
"branding": "fab",
"regular": "far",
"solid": "fas",
"light": "fal"
}
for name, resource in items["resources"].items():
for url_obj in resource["urls"]:
icon = url_obj["icon"].lower()
if "/" not in icon:
to_remove.append(name)
logger.error(
f"Resource {name} in category {category} has an invalid icon. Icons should be of the"
f"form `style/name`."
)
continue
style, icon_name = icon.split("/")
if style not in ICON_STYLES:
to_remove.append(name)
logger.error(
f"Resource {name} in category {category} has an invalid icon style. Icon style must "
f"be one of {', '.join(ICON_STYLES.keys())}."
)
continue
url_obj["classes"] = f"{ICON_STYLES[style]} fa-{icon_name}"
thank!
๐
roons, your bot is hooked up to a database, right?
hey guys im wanting to have my bot configurable through a web interface, whats the best way of starting that?
database and yaml as settings
ah, you're using yaml currently
okay
but
the bot, will it be on the same server as the web interface?
urmmm not too sure really dude
okies, mysql is fine right?
then have the bot pull them in from the db when it boots up
sqllite sorry
any database is fine
and then
your web interface
just goes to the same table, same database
fetches all those settings
and lets you fuck with them, and saves them again.
if you want things to change live, you'd need to somehow tell the bot to reload those settings.
oh yeah...
that actually had slipped my mind
is there any reading material you recommend to starting something like this?
i basically know NOTHING about webdev
hm. well, flask would be good for this.
okays ๐
and it has plenty of useful reading material easily available.
we use it for our website
flask could do this and still basically be a single file.
django could do this too, of course. but it would be a big project with many many files.
for that reason alone I'd recommend flask for this.
gotcha
perhaps you should start by just doing a flask hello world
their official quick start guide isn't bad
and feel free to lean on us. we got lots of flaskers in here
wouldnโt using flask as a web interface for a bot be blocking though?
or would you run them separately?
yeah of course, seperately.
ah
@midnight spoke
but the basic idea is - you'll make a jinja template file (kind of like a normal html page but with certain special tags that allow you to write some python-esque code on the page). in this file you'll loop through some a dictionary with all the config settings and display a field for each configurable, pre-filled with its current value. At the bottom there'll be a submit button.
Then you'll have the flask file itself, which when you load the page in your browser, will contact the database, get all the configurables, and then pack them into a dictionary which it will spit out together with that template.
lastly the flask file will also respond when you do a POST request (so when you hit the submit button on that page), and then it will take all the changed configs and spit them back into the database.
it's as simple as that
then once you have that working, you can figure out how to have it restart the bot automatically and fancy stuff like that
it'll probably involve websockets.
but don't worry about that yet.
Does the bot need restarting tho
probably not, you could just update the relevant variables on the fly instead if the configurables are hot-seatable.
Yeah that sounds better tbh
depends on whether he's configuring stuff like, uh, the bot token
but yeah for most config you probably wouldn't need a restart.
knowing you, you'll have it figured out in a week
lol probably not, but i'll give it a good go!
us beginnners are not that fast ๐
this guide looks relatively inoffensive
but please put style in a .css file, not in <style> tags
or I will hunt you down
๐ yessir!!
I mean for something simple like this I'd use a prewritten template :3
Of course you would. -Lemon
lol :D

i like to learn though
writing a template and styling it is a great opportunity to learn some jinja and css
Learn html and css?
and web pages confuse me ๐
and those are wonderful tools
css is one of my favorite things, and I'll be only too glad to help you with it if you get stuck.
thanks buddy
i need to make the bot write everything to sql instead of yaml and write some nice wrapper functions
i think courier is on about 13 servers now
cool!
i do have a database i store quotes and league and battlenet data in there
yes. what kind is that again?
sqllite
oh
you know
when I said "I thought you had a database"
I meant that I thought you had a real database
mkay
yeah well for something like this sqllite is fine
even the yaml file would have been okay, tbh
I mean - you could just load that into your flask as well
true dat
I assume you already have pyyaml so that might be the easiest solution - and then you maintain the local configurability
i do have pyyaml yup
no extra dependencies either then if they're in the same environment
fuck sqllite then, just keep it in yaml and rewrite the yaml file
that's not nothing
but yeah I would just do that then
and then
this is the cool bit
you could just update the yaml if you need a new setting
and the website would just dynamically change
Sexah
do you run your bot with a supervisor?
i sure do my friend
then a super easy solution would be
have the website restart the service
you don't even need to communicate between the two
the flask script can just do supervisorctl restart bot
yeah you can probably do better
it just might be a lot more code for no real benefit
the real benefit is, no bot restart, and no downtime
I guess ยฏ_(ใ)_/ยฏ
and the bot is in charge of a discord server which it assigns roles
which they have to agree to welcome text
it has about 800 members so far?
well then you might do something like making the bot watch the yaml for changes and reload its config when the file updates. or you might send the bot a message via something like rabbitmq to let it know what to update.
and besides, reloading the config is sexier!
How is SQLite not a real database
wat
can we not
it is a real database
I'd be happier if you just didn't ask me. fine it's a real database, debate over.
Lol
lemon was just having a bit of fun with me, we do that a lot
Don't say questionable things, and questions won't get asked :)
sqlite is very gud
you're disregarding the context to make a thing out of something that wasn't a thing
He could have explained that, context is a wonderful thing
sqllite is fine. I'm a fan of sqllite
One L
someone fell outta the grouchy tree today
I just thought runewolf had a fully fledged database. I thought he had cairosdb or rethinkdb or something already and was wondering why he wouldn't be using that. I guess my memory failed me.
It's one of those really pedantic points I know, but it's kinda one of those things that really annoy you when they shouldn't lol
basically I wasn't saying "not a real database" as in "sqlite sucks", I was saying it as in "as opposed to something huge like postgre"
its no wonder you cant keep up with what ive h ad in there
I still think not a real database is wrong choice of words
probably
And leaves you open to this exact debate
yes, sqlite is shit compared to postgres
it's not shit
Why would you compare them anyways
compared to postgres
it's just a different tool for a different problem
^
??????????
?
You just said it's shit, and then agreed with lemon who was arguing against your point ๐ค
But the point is, you don't compare them
but it has its uses, for small projects
are you guys a comedy duo
They have different purposes
anyway, --> #databases for this discussion please.




sorry mum
Jason_000 - Today at 5:57 PM
How is SQLite not a real database```
Who said it isn't?
I demand an answer, who said it isn't a real database
SCROLL.
22 chills pills a day...
40***
so i have an EXTREMELY basic flask app running, however the stylesheet doesnt seem to be working?
so this is test.html
{% extends "layout.html" %}
{% block body %}
<div class="block1">
<h1>Hello {{name}}!</h1>
<h2>Here is an interesting quote for you: </h2>
<p>
{{quote}}
</p>
<img src="http://www.naturalprogramming.com/images/smilingpython.gif">
</div>
{% endblock %}
This is layout.html
<html>
<head>
<title>Website</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
{% block body %}{% endblock %}
</body>
</html>
and this is the stylesheet
@import url(http://fonts.googleapis.com/css?family=Amatic+SC:700);
body{
text-align: center;
}
h1{
font-family: 'Amatic SC', cursive;
font-weight: normal;
color: #8ac640;
font-size: 2.5em;
}
flask wants you to import static files with some special url_for jinja syntax.
including the stylesheet
so put the stylesheet in a folder called static
and see how they import it here
okies ๐
\o/
Okies, thats great!
thankyou lemon!
and now.....
time for bed!!
im trying to get the second box on the right to be on the same level next to the box on the right. I have looked online and couldnt find anything helpful
if fixed it
finally found something useful about css positioning
hey guys, nice to meet you all! I'm in the process of learning django to build a recipe website for fun
I wanted to double check whether my current thought process towards the website was correct:
-
Since my edit recipe page requires some jquery/ajax my logic was that I would build a rest api for the jquery
-
At that point I figured it may be good practice to decouple the front end as well.
-
Since i'd be using that instead of MVC, I wouldn't be using ModelForms and instead would just be using HTML forms
if you don't use the built-in forms, you'll need to handle validation yourself
If you want to customize the form's styling, you can always use something such as https://github.com/jazzband/django-widget-tweaks
that looks a bit funky and also a bit fresh.
@grand badge I hope you fixed it with flexbox.
So ive had a thought, if i people to change the settings on the bot, then they have to log into the website with discord so they only change their details. How would i even go about doing that?
uhm, wats flexbox @deep cave ?
it's the solution to that problem in 2018
but I'm guessing you used floats instead
@midnight spoke we support discord OAuth on our site
so. it's not uncomplicated, but if you're curious you could check out https://github.com/discord-python/site/blob/master/pysite/oauth.py
and a few other ones
you can see this PR
that's our OAuth PR
there's 12 files changed in total, so look through the changes and you should get a rough idea.