#web-development
2 messages · Page 4 of 1
Someone your are so sensitive but insult other people and still expect them your sensitivity
That's not ok
@brittle copper
no u
@grand badge I personally used https://ultimatedjango.com/ https://www.codingforentrepreneurs.com/
I think Justin Mitchell, the coding for entrepreneurs guy is the most popular.. has Django videos are the most popular on udemy. But I usually go bunch of tutorials when I do frameworks and then build something myself. Good luck.
Yes i used Coding for Entrepreneurs before but i mainly just use treehouse cuz of the variety of topics
Any misago users here?
@jagged sedge Django has a very powerful CMS that is very easy to understand and use
Do I need any of that if I only run a blog without storing any information about my visitors?
If there is no identifiable data stored on any of your servers then no
If someone can grab some info from your blog and can trace it back to the user, and the user cannot remove it then I'm led to believe that's against GDPR
Oh it does?
So, under the section regarding a user being able to edit the information displayed, does that mean they are legally obliged to edit any information relating to them in the article?
i make programming posts xd
and the only user account is my own, in the django admin
i always think that regulations like this are great but not when i need to change my own stuff
Do you have comments?
As well as that, that article recommends to check your 3rd party companies are compliant with GDPR
I don't
That's fine then
Yeah I think you would be required to rectify, but like anything else, some common sense is required
Like if I told you I was the queen of England, you would be able to go "nah mate"
does the CSS log user ips though 
IPs are not considered identifying
They aren't identifying, so that's a good thing really
@jagged sedge I personally like Wagtail... I think it's less monolithic (customizable) than the others, slick UI.. I like the modularity it presents
And it's in Django ..so you would probably have to know django as well
inb4 80% of websites forced to delete their access logs because of IPs 
i don't plan on doing much web development with python, but should i look into it 'just in case'? if so, what should i use?
Flask is popular on this server, so is django
there's no end to python web frameworks tbh
django is the one I've heard of the most
web.py was my first. Django was my first real framework. Flask was the first I fell in love with.
I'm very much a believer in starting with Flask, though, and then moving to whichever one fits your style
Django is a fine framework but Flask keeps it simple. Much easier to start out with, hands down.
Flask allows you to clearly see what's going on without having to look through tons of files
yeah
I read the gdpr thing but what the hell does it mean. I find it confusing
people are in voice?
Not yet
goes to voice(get ready to feel the pain)
@grand badge
I had a look into Django's documentation about the User model from: django.contrib.auth.modelsI dont understand what the User model is meant for so can someone please explain it to me?
i mostly use User in views
to determine if the user is logged in, if they're an admin, etc.
auth also handles OOTB stuff like admin login
and you can generate modelforms for user logins
and account change forms, etc.
didn't know 2.0 is out :x
it has been for some time+
and it does soo much so much better
for example they finally allow flask style URLs
true
the flask like urls is one of the best features
no more regular expressions bois!!
Yeah Flask URLs are great
@app.route("/user/<int:id>")
def user(id):
return get_user_page(id), 200
hahaha
me lik dis meme
lmao
Now you REALLY have no reason not to use LE
woah
I just recall that they said it'd be very hard to implement or something
so I'm happy they managed to do it
anybody know if django automagically handles caching things like database query results?
thanks for the doc link
Can't tell if sarcasm
be positive, he is not sarcastic
no, it was what i needed to know
The saga continues. Figured this would be more appropriate in here. https://blog.github.com/2018-03-14-eu-proposal-upload-filters-code/
now thats bad
Yep
oooh mama that is approaching trump levels of bad
now brexit is seeming more appealing 
I want to move to the UK
Why do they do this to us..... They make the whole open source community their enemies with that....
@brave mantle does that mean when I upload a picture to discord i may not use copyright protected images?
And that discord has to filter them
That's what they propose yes
I don't like this...
Big Brother is Watching.
I mean first they are like uuuh protect data protect data and now they are doing this
@opal coral agreed, but still kinda deep for Nix
well it'll undoubtley effect more than just those in the EU, indirectly
Hey dudes, if I got a question specifically about web development, do I ask it here, or is that better suited for the help channels?
ask here
Great! Thanks. Well, I need some advice. I'm working on a role / permission system for my webapp, and I got an admin page where I want to be able to add roles and link specific permissions to them. I got this table setup https://i.imgur.com/YuqZyQ0.png and I can add roles and all that fine, but I was wondering if you guys had some advice on how I could update my database in the backend when I update a role with the checkboxes. My main roadblock is that the permissions (the titles at the top, such as read_members) are also just entries in my Permission table in my database
You would use ajax
bot.tags.get("ask")
If you have a question, please just ask it outright in the channel that it belongs. Don't ask for topic experts, don't ask if anyone has experience with what you're using, don't try to PM people, just pick a channel, and ask the question outright in that channel. If you're unsure where it should go, just ask in #python-discussion
If i have a website running on pythonanywhere, will it have SSL? I read something on pythonanywhere, it said that websites with the pythonanywhere domain name already has HTTPS. However, when i first deployed a side project to pythonanywhere, it didnt say HTTPS in the URL. Will that website have SSL despite having HTTP in the URL?
i took the website down later so i dont know, i will try deploying again to see if it works
You took the site down within a minute of asking the question?
no
within three minutes of asking the question?
im talking about a side project i deployed weeks ago
I was learning to deploy
And this question just pooped into my head
Don't you think it would make sense to ask the question when the site was up 🙃
yup, im stupid but i wasnt really bothered until i was 😛
Fair enough
:)
im trying to make a image that will take up most of the screen using this code : https://hastebin.com/imawunimay.xml
if i wanted to center align the image what would the code for that be
plez
bot.tags.get("ask")
Don't ask to ask - just go ahead and ask your question!
but he did 
@native tide If you can make it fixed width, then you can margin: auto it
probably better to use flex at this point
Ok ty
@sterile peak if you do use gunicorn (or at the very least set up logging for the flask server) you should be able to figure out why it dies.
that's basically the next step for you
without that information, nobody can help you
roger that, thanks
I mean, it's a python process, it'll leave a traceback
it could be load related i feel, server has 2gb of ram and at peak had 10 odd people accessing at once
if you're just listening
but it seems unlikely
because the discord bot running in parallel works fine all the time
yeah. my guess is there's just a simple error somewhere that logging would make clear
the code doesn't return any errors, have tried that way too much
but I mean you absolutely need logging either way.
yes, that's true
running any kind of webservice without it, it's just irresponsible.
so fix that first
and see what it says when it dies.
if it says nothing, we'll work with that
maybe it says nothing
who knows
okay for logging, should i run the logging module in python or use gunicorn for it?
but most likely there'll be a traceback
that's your call but it wouldn't hurt to use a real webserver instead of trying to use the flask thing even though flask expressly tells you not to
Use gunicorn for logging
i've spoken to someone who knows way more than i do last night and they think it has to do with API requests failing/timing out
It doesn't hurt to use the logging module in addition though
To just format your output
both is pretty common, yep.
I mean gunicorn will tell you if it stops serving the site for any reason
but your site itself should also log things
that's actually pretty damn useful
gunicorn won't tell you if that one api call is fucking up, for example
that's up to your site to log info about
see how there's a bit of separation there?
yeah that makes sense actually
just for a bit of extra context the site is up at the moment and it runs fine - it's when multiple people use it at the same time or in quick succession that it fails
Are you just not using gunicorn?
not yet
he's just using the flask debug server
yeah
I mean, if you only have one flask server then yeah that'll break
that'll be it then i think
You need to have a bunch of workers because there's no concurrency by default in flask
That's why we use stuff like gunicorn
it would explain the lack of errors or anything in the console too
Well it wouldn't crash but the requests will get backed up
i believe so too
This is about PHP, but.. Three thousand people line up on your apartment's welcome mat and demand to be shot in their feet. One by one, you oblige them, but halfway through, the http connection times out and the crowd lynches you.
haha, glad you appreciate the service we provide.
just ask if anything else comes up :)
i'm gonna look into setting up gunicorn today and hopefully that'll be it
thanks ever so much 
cheers!
it's pretty easy to set up, gunicorn
it's one of the easier ones.
but if you run into trouble with it just ask in #414737889352744971 and we'll help you out :)
yeah "multiple people accessing at once" and "request hangs" sounds like you want more workers or a different worker class if possibly
wait I missed that part, sorry
yeah web dev scrub over here 

basic (but probably hard) question
what would be the most effective way for anyone that doesnt know about #aaa or anything related to it find out or learn about that?
for example,
- what it looks like
- what it does
- why it's 3 letter
- why it has a # before it
- why the letter are the same and repeating
- what exactly the saturation of that color is
- what exactly is the lightness or darkness of that color
- anything else about what in the world that means
aka: how would anyone in this universe that doesnt know about anything related to this get from that point to learning about #aaa ?
that is the question, and best answer/solution is needed
Well you aren't telling us what that is either
0123456789ABCDEF
| ^ |
0% Lightness 100%
#AAA
|||| Blue
||| Green
|| Red
| Indicates a hex value follows (not important tbh)
All three values are equal, so the colour is gray.
More specifically, a light grey.
A channel name? A hashtag? A hex colour?
If it's colour then I got you covered
@app.route('/index', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
email = request.form['email']
database = mongo.db.subscribed
if email is None:
render_template('request_denied', )
else:
cursor = database.find_one({"_id" : email})
if cursor is None:
database.insert({"_id" : email})
return render_template('request_success.html', email=email)
else:
return render_template('request_denied.html', email=email)
else:
return render_template('index.html')
it sends me tp request_success.html even if i don't enter an email
and it still stores it into the database with an id of ""
yeah yeah
but why does it render me to it?
woops
i know why
probably
no
my bad
it still does it
but i don't enter an email in the input form
yes...
but entering no value means
""
not none
it has a value, the value is just empty
you should check if its ""
with "" i mean
ik
oh ok
== '""'?
if email == ""
same for if email: - else:
dunno then.. it should return something
is it maybe because of
render_template('request_denied', )
not being in your template directory
yea in the code sample above you forgot to return inside that if-statement.
just request_denied.htmk
@app.route('/index', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
email = request.form['email']
database = mongo.db.subscribed
if email:
cursor = database.find_one({"_id" : email})
if cursor is None:
database.insert({"_id" : email})
return render_template('request_success.html', email=email)
else:
return render_template('request_denied.html', email=email)
else:
render_template('request_denied.html')
else:
return render_template('index.html')
ohh
right
it works
yeah
thanks guys!
else:
render_template('request_denied.html')
That's still a path without return.
well first of all you get all the documents
done ^^
and then you pass them to your html template
and then your html template generates a table or something
i tried as i do with discord.py
if you're not using a templating language
def ideas_review():
ideas_list = []
if request.method == 'POST':
database = mongo.db.ideas
cursor = database.find({})
for document in cursor:
ideas_list.insert(1, "ID: {}\nUsername: {}\nEmail: {}\nIdea: {}".format(document["_id"], document["username"], document["email"], document["idea"]))
return render_template('admin/ideas.html', ideas=ideas_list)
else:
return render_template('admin.html')
you've already lost
yeah, see, newlines don't work
because you're working with HTML
i should do <br>
but it would print <br>
i know how to do a table
but no idea on how to do it in this situation
I mean you can just pass the cursor to the template for a start
the actual table generation should be done in the template
which I'm assuming is a jinja template
<body>
<ul>
<li><a href="/index">Home</a></li>
<li><a href="/subscribe">Subscribe</a></li>
<li><a href="/ideas">Ideas</a></li>
<li style="float: right;"><a href="/admin">Admin</a></li>
</ul>
<br><br>
<form method="POST" action="/ideas_review">
<h3>Ideas Review</h3>
<br>
<p>{{ideas}}</p>
</form>
<form method="POST" action="/emails_lookup">
<h3>Lookup Emails</h3>
<br>
<input type="submit" value="Submit">
</form>
</body>
well that looks like jinja
jinja can do loops and all of that stuff
so you'd start with your table element, your first <tr> with your heafings
then loop over the documents, generating a <tr> for each
and then close your <table>
OK, so you sent a bad request
Check the logs
i've created 2 "def"'s
instead of only one
and it is probably going to check this stuff in the first one
and not in the second one (the right def)
@app.route('/admin', methods=['GET', 'POST'])
def admin():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
database = mongo.db.admin
if username:
if username == "cmstaffevents2k18":
if password:
if password == "cmstaffevents2k18pw":
return render_template('admin.html')
else:
return render_template('request_denied.html', type="Authenticate", error="ERROR: Invalid password.")
else:
return render_template('request_denied.html', type="Authenticate", error="ERROR: Password field empty.")
else:
return render_template('request_denied.html', type="Authenticate", error="ERROR: Invalid username.")
else:
return render_template('request_denied.html', type="Authenticate", error="ERROR: Username field empty.")
else:
return render_template('authenticate.html')
def ideas_review():
ideas_list = []
if request.method == 'POST':
database = mongo.db.ideas
cursor = database.find({})
for document in cursor:
ideas_list.insert(1, "ID: {}\nUsername: {}\nEmail: {}\nIdea: {}".format(document["_id"], document["username"], document["email"], document["idea"]))
return render_template('admin_ideas.html', ideas=ideas_list)
else:
return render_template('admin.html')
if username:
if username == "cmstaffevents2k18":
if password:
if password == "cmstaffevents2k18pw":
Come on now
:P
You shouldn't be providing errors that verbose
¯_(ツ)_/¯
but what about my problem?
i have 2 defs and it probably goes to the first one
thing that shouldn't happen
yes
Take a look at the whole MethodView thing
You might find that a bit easier to work with
i can have a class with many def's
MethodViews are one class per route
And each function in the class corresponds to an HTTP method
One class, yeah
so like, def get():
But not one "def"
You can't have more than one def per route
I'm pretty sure that's undefined behaviour
I did something better
I mean, i like it as well
Now i need to create the table
@brave mantle sorry for the tag
the page works
but it doesn't show the documents
well, are you inserting them into the page in the template?
Are there actually documents in the table?
you're progressing, I guess
i am 
how do i create newlines?
wait
i can do it with the table
but how?
for document in cursor:
ideas_list.insert(1, "ID: {}Username: {}Email: {}Idea: {}".format(document["_id"], document["username"], document["email"], document["idea"]))
return render_template('admin_ideas.html', ideas="<br>".join(ideas_list))
cause if i do that, it prints documents separated by commas
I dunno why you're trying to do formatting in your class
don't do that shit
do it in the template
ok but how?
I told you how
Generate a table using a loop
If you don't know how to do it, read the jinja docs
Thanks!
just out of curiosity, how much of the server website is flask, and how much of it is other stuff?
It's all flask
We do have a websocket framework as well, but we're not using it yet
oh okay nice
i do want to learn flask, but after i've made something.. then what? i can't get stuff hosted or anything due to being in a very low-income family.
I think heroku still has a free plan, but I don't know if it's 24/7 uptime
yeah, i know. i mean, it's not like i'm going to be using it for much, just a personal little space to do my own stuff.
That's probably your best bet, then
i mean, if i could i would host it on my own internet, but that's just thick.
google cloud is extremely cheap, and you get one year for free
define 'cheap'
you have your very own internet? :o
could buy a raspberry pi and host it on that on your own connection
people like to do that
Raspberry pi is a good long term small scale solution
gives you the illusion of having a server
you can ssh in and pretend
and it's pretty cheap. and fun.
it is a server though, is it not?
i've been saving up for a raspberry pi, but i don't know which model to get
straying away from #web-development now though, oops
All the standard models are fine
if you're not comfortable with giving away your ip to the public, you can also look into something like cloudflare
hey, is there a way to see if the request is from a specific page and manage it before redirecting?
with flask
whoops i think i accidentally deleted your message @mental chasm whilst cleaning a mark on my phone screen
sorry :P
it was "What do you mean?"
np
Hm
I do quite love Flask
although how would I best serve it?
cuz I'm pretty sure we can all agree on the fact that the built in dev server is absolute trash for production
if someone answers please ping me
gunicorn
can I use that with NGINX too?
Yep
how?
but I'd prefer to stay away from venvs
... why
I personally used uwsgi
====== any chrome users here or another day ? =====================
on chrome://settings/fonts , you can change the font 'type' (like how it looks)
- but i dont think it changes it on some sites
how does this chrome font thing work basically? (im guessing there's may not be any links that explains it) does it replace fonts on all sites?
or does the site decide what font to use?
Have you looked up info about this online yet?
@fiery kestrel No, it won't do that, it won't make sense
websites decide what fonts they will display
At least it doesn't seem like that's how it should work
It could change the font when a site has not declared a specific font
ahh this looks like it:
The font settings that you set in the options are used when the following is true:
The web page has not specified a font of its own.
The web page has properly declared the language of the content.
browsers have a default style sheet
that's the font that is used when the site doesn't define the font-family style
I am having the following issue from Flask Rest Plus:
Traceback (most recent call last):
File "C:\HOMEWARE\Anaconda3-Windows-x86_64\lib\site-packages\flask_restplus\api.py", line 207, in __getattr__
return getattr(self.default_namespace, name)
AttributeError: 'Namespace' object has no attribute 'refresolver'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\HOMEWARE\Anaconda3-Windows-x86_64\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "C:\HOMEWARE\Anaconda3-Windows-x86_64\lib\site-packages\flask\app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\HOMEWARE\Anaconda3-Windows-x86_64\lib\site-packages\flask_restplus\api.py", line 313, in wrapper
resp = resource(*args, **kwargs)
File "C:\HOMEWARE\Anaconda3-Windows-x86_64\lib\site-packages\flask\views.py", line 84, in view
return self.dispatch_request(*args, **kwargs)
File "C:\HOMEWARE\Anaconda3-Windows-x86_64\lib\site-packages\flask_restplus\resource.py", line 42, in dispatch_request
self.validate_payload(meth)
File "C:\HOMEWARE\Anaconda3-Windows-x86_64\lib\site-packages\flask_restplus\resource.py", line 88, in validate_payload
self.__validate_payload(expect, collection=False)
File "C:\HOMEWARE\Anaconda3-Windows-x86_64\lib\site-packages\flask_restplus\resource.py", line 73, in __validate_payload
expect.validate(data, self.api.refresolver, self.api.format_checker)
File "C:\HOMEWARE\Anaconda3-Windows-x86_64\lib\site-packages\flask_restplus\api.py", line 209, in __getattr__
raise AttributeError('Api does not have {0} attribute'.format(name))
AttributeError: Api does not have refresolver attribute
just because I write validate=True on an endpoint like:
@namespace.expect(report, validate=True)
@namespace.marshal_with(report_full, envelope='report')
def post(self):
without the validate=True, it works
any idea? 😶
I imagine validation just can't be applied to that object
why not?
report = namespace.model('Report', {
'id': fields.Integer,
'title': fields.String,
'description': fields.String,
})
Because it doesn't have a refresolver
seems pretty straight forward
I don't know what this is, seems to come from jsonschema
I'm not at a PC unfortunately
But the error message is clear enough
Namespace object has no refresolver
makes no sense to me and google apparently =x
Well, why not look at the restplus docs
See if they say anything about a refresolver
You might be able to pick up some clues from that
I did, whole day, everything points to the doc. Sorry the example of implementation which I am not suppose to touch.
which I do not touch
the thing is the trace doesn't come from my code, so obviously it's a wrapper they did of it
but I don't see any wrong usage I would do of it =x
Yeah, it sounds like a tricky one
Anyone used django with pythonanywhere? I "pip install django_markdown" it says requirement already statisfied but when I include "django-markdown" at INSTALLED APPS, error pops up
Any help is appreciated
TLS 1.3 has been approved by the IETF.
interesting
Moving my question from help to here to better be on topic:
Can someone take a look at this code, it's supposed to check a database for user creditdentials and return a fail or login and pass them to a new page. Instead when logging in with correct credits it only returns GET 200 request, no errors, and nothing happens.
Connecting to the DB
con = sqlite3.connect('databasepath.db', check_same_thread=False)
c = con.cursor()
Checking passwords and validate users
def check_password(hashed_password, user_password):
return hashed_password == hashlib.md5(user_password.encode()).hexdigest()
def validate(username, password):
con = sqlite3.connect('databasepath.db', check_same_thread=False)
completion = False
with con:
c = con.cursor()
c.execute("SELECT * FROM Users")
rows = c.fetchall()
for row in rows:
dbUser = row[0]
dbPass = row[1]
if dbUser==username:
completion=check_password(dbPass, password)
return completion
Login Form
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
completion = validate(username, password)
if completion ==False:
error = 'Invalid Credentials. Please try again.'
else:
return redirect(url_for('secret'))
return render_template('loginForm.html', error=error)
Send to new page
@app.route('/secret')
def secret():
return "You have successfully logged in"
EDIT: Almost have a fix for this, maybe. Will update.
plaintext passwords are good :^)
guys using 2 settings.py is nessiccary for django?
u only need one settings.py
you only need one, but I like to put mine into a package
i load prod config when running through wsgi and dev for anything else
Hello guys, I am having a little problem w/ GeoDjango on Windows (W10x64), I get this error when running any manage.py command (e.g. python manage.py test or python manage.py makemigrations):
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\Python36\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line
utility.execute()
...
File "C:\Python36\lib\site-packages\django\contrib\gis\geos\geometry.py", line 8, in <module>
from django.contrib.gis import gdal
...
File "C:\Python36\lib\site-packages\django\contrib\gis\gdal\prototypes\ds.py", line 9, in <module>
from django.contrib.gis.gdal.libgdal import GDAL_VERSION, lgdal
File "C:\Python36\lib\site-packages\django\contrib\gis\gdal\libgdal.py", line 47, in <module>
lgdal = CDLL(lib_path)
File "C:\Python36\lib\ctypes\__init__.py", line 344, in __init__
self._handle = _dlopen(self._name, mode)
OSError: [WinError 127] La procédure spécifiée est introuvable
(last line OSError says "specified procedure not found")
However, when I run the same import in Python console (same env), no problem (of course this is the same Python version as the one used to run manage.py commands like above):
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from django.contrib.gis import gdal
>>> gdal.libgdal.GDAL_VERSION
(2, 2, 4)
(actually sourced this to setup env, using bash for Windows)
#!/bin/sh
export OSGEO4W_ROOT=/c/OSGeo4W64
export GDAL_DATA=$OSGEO4W_ROOT/share/gdal
export PROJ_LIB=$OSGEO4W_ROOT/share/proj
export PATH=$PATH:$OSGEO4W_ROOT/bin
Also corresponding dll is indeed present
$ ls -lh /c/OSGeo4W64/bin/gdal*.dll
-rwxr-xr-x 1 Solon 197609 19M mars 22 23:48 /c/OSGeo4W64/bin/gdal202.dll*
Also note that I do not have this issue when working on my Archlinux machine (dev) or Debian (server)
Any idea? 😅
(please mention me if you answer)
Sup! I have a little problem with Flask. I use Azure Webapp + MySQL (free level with Dreamspark) for my app in Python. On local my app is working great but, on azure, when I login I have:
Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
I can see the login screen, but the app crash when I submit.
web.config
https://pastebin.com/jcwwETxD
views.py
https://pastebin.com/TqmHeqFy
login.html
https://pastebin.com/nCmfUTP9
hi! i was wondering what IDE's you guys recc for using Flask
ive been using visual studios and its been feeling pretty awkward..
I use V Stu too
atom is an editor
PyCharm is pretty much the IDE everybody uses
works really good, free, many plugins
None of them hold a candle to a fully-integrated IDE
that point that you always make is kind of pointless nix
👍
vim master race
neovim master race
word - worst possible choice race
^^
we should just follow lemon and write our code in the yt comment section tbh
nah i use wordpad
is that possible to comfy use some pythonic-like language that compiles to js, and utilize browser api, js libs, etc?
coffescript claims to be a python ish js derivate @neon prairie
yes
errr...
but still not so pythonish as I hoped
# Functions:
square = (x) -> x * x
# Splats:
race = (winner, runners...) ->
print winner, runners
# Existence:
alert "I knew it!" if elvis?
I guess there's always brython
Lamson used to look great until they abandoned it
in Django, is it possible to ignore a database from testing? i don't even use this one but django tries to create a test database regardless, which doesn't work because the Postgres user is read-only. here's the db setting:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'stats': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.getenv('PGSQL_DBNAME'),
'HOST': os.getenv('PGSQL_HOST'),
'USER': os.getenv('PGSQL_USER'),
'PASSWORD': os.getenv('PGSQL_PASSWORD')
}
}
and the exception:
$ python manage.py test
Creating test database for alias 'default'...
Creating test database for alias 'stats'...
/Users/Johannes/.local/share/virtualenvs/programming-site-WuXY6p7p/lib/python3.6/site-packages/django/db/backends/postgresql/base.py:259: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the default database instead.
RuntimeWarning
Got an error creating the test database: permission denied to create database
now this looks like it runs the tests, but it doesn't 🤔
oh I have an idea
You should be testing on a separate database dude
one that you have write access to
sorry, i should've mentioned, the database stats is not used in any tests, and django is not supposed to ever write to that database anyways. it's from another app
apparently there's no simple solution on the django end, gonna look into getting write access
@meager anchor are you writing an api for programmings stats database lol
Oh fairs
oh man django is SO GOOD
i initially used a generic View
so I had methods get, post, etc. instead of checking for the request type myself and handling all possible cases
now I read a little bit more, and essentially what my view does is render a form for creating something
.... voila
now the code is 90% sending the webhook
django ❤
django is really spcific
It has CRUD views
Im going to need to learn it for that ugly site im making
Show it
What kinda web dev?
As far as I'm aware that's not a thing.
What does you software do
Well
Could you provide some links?
You see its not a very popular field at the moment
What is it
server
I'm still in disbelief
Of course you are
There is an Assembly framework called Line Up
Code samples would be appreciated
^
sorry, code samples are tooooooo powerful
I don't see any framework called Line Up, care to provide a link?
There is no framework
Well it's a framework, somehow you found it, why can't I?
Ahh yes sorry
jk i never
ask the SOOWD
So, ImportError, tell me, what are the major differences between 16 bit and 64 bit assembly
Secret Organisation Of Web Development
Ahh yeah I'm a member
no
no
I lost interest in your comical joke around when you said "I did web development in assembly"
hahahhaa!
yes
So I'm gonna go
Okay yeah, well, jokes over, back to #ot0-fear-of-python
any ideas for a good symbol to use to represent "edit this"? currently using × to represent "delete this"
I found ✎, but I'm actually leaning towards 🖊, looks a lot better, thanks!
volcyy wat are u making?
website for our server
Dont we already have juan tho?
not this server
o
Link?
which site do you mean?
i sent that like a dozen time to you
Wat
ummm, not that juan
the progtamming juan
Volcyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
@kind steppe https://github.com/strinking/site
what
why not contrib to our site 😦
I think ImportError has more Django experience
hm
@meager anchor thanks!!!!!!!
since yesterday i dont trust django devs anymore....
i mean, i consider myself a beginner. But idk
import error i dont trust you anymore
but i like flask too
Its just that i prefer Django
hahano

@meager anchor im getting this error when i try to create a superuser on the Programming server site:
django.db.utils.IntegrityError: NOT NULL constraint failed: home_user.discriminator
right
i‘m an idiot
and modified the user model
i think you can circumvent this by manually creating the social application for discord through the database, but that‘s a really great example as to why that was not a good idea
i need to figure out a better way to attach a discord user to django
sooooo, umm i cant create superuser??
i did migrate
also, when i run the server, it says 'Illegal instruction: 4' and doesnt run
no it's not a "simple not migrated app error"
i modified the user model to add a couple of discord-related things
you don't have to create superuser
sqlite3 db.sqlite3, insert the social app and modify the domain of the site with ID 1, then oauth should be set up and you can log in through the site
what?
you can't create a superuser because i have a custom user model that django doesnt support natively
so you need to insert the relevant values without the admin
I just said it looks like that dude, chill; integrity errors are usually because there is no field in database; at least the ones I had when I was doing my website
what values are you talking about and where should i add those values?
just use sqlite3 db.sqlite3, ```sql
INSERT INTO socialaccount_socialapp VALUES ("discord", "Discord OAuth", your-discord-app-id, your-discord-app-token);
also make sure you set the domain for django_sites correct
if you run SELECT * FROM django_sites; it will most likely start with 1|example.com|example.com
you wanna set that to localhost or whatever you're entering into the address bar to view your local django dev server
UPDATE TABLE django_site SET domain = "127.0.0.1:8000";
is mine
what does it mean by the discord app id?
you need to create an application on the discord my apps thing
and then grab the id / token from that
okay
so i make a new app right?
ye
i made a bot and put the token in but it doesnt work
no it's not a bot
did u mean app-secret?
just the Client ID and Client Secret at the top of the page
oh okay
the catch is, being the smart guy i am, i hardcoded our guild ID for pretty much every permission check
so you won‘t be able to do anything on the site unless you set your superuser status in the database
smart move my lad
i tried putting the client id and client secret in, but it this is what happened: Error: no such column: <client_secret>
how did you insert
INSERT INTO socialaccount_socialapp VALUES ("discord", "Discord OAuth", your-discord-app-id, your-discord-app-secret);
anything wrong with that?
i did
in quotes?
oh shit
🤨
Error: table socialaccount_socialapp has 6 columns but 4 values were supplied
Seeningly, I probably forgot something
the first value is ID
run .schema and check the cols
maybe the site ID (1)?
CREATE TABLE IF NOT EXISTS "socialaccount_socialapp" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "provider" varchar(30) NOT NULL, "name" varchar(40) NOT NULL, "client_id" varchar(191) NOT NULL, "key" varchar(191) NOT NULL, "secret" varchar(191) NOT NULL);
i think im missing id and key
@meager anchor what is "key" meant to be?
empty
i forgot that column
I believe it‘s supposed to be empty, i can‘t check right now
nice, i think it works
okay, im going to create superuser
you cant
because i use a custom user model that it doesnt support
oOoO
yeah its a bit dumb 😛
but it works on its own, without some other bot or something lul
when i run the server, this happens:
System check identified some issues:
WARNINGS:
stats.AuditLogChanges.audit_entry: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.
HINT: ForeignKey(unique=True) is usually better served by a OneToOneField.
System check identified 1 issue (0 silenced).
April 03, 2018 - 17:28:39
Django version 2.0.3, using settings 'website.settings.debug'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Illegal instruction: 4
and then the server doesnt run
what the fuck
wait
i'm pretty sure you need to checkout a commit without the pgsql database
i thought it used sqlite
not only
try git checkout 8f8c56f95da8a1dc993eb177722b926eb17b26fd
that was the last commit before pgsql db integration
👍
no module named stats? apparently
where do you get that error?
this seems to be absolute hell to set up
i should fix that
the urls for guides, line 13
i will try fix it
sorry not urls.py
it works!!
fixed it
where is the login page?
see the $(YOUR_USER) in the top left?
yep
click
DoesNotExist at /accounts/discord/login/
SocialApp matching query does not exist.
got that error
alright, go into the database, and query SELECT * FROM django_site;
does the right column specify example.com?
do u mean http://127.0.0.1:8000/ ?
then:
UPDATE django_site SET domain="127.0.0.1:8000";
updated
no
then you need to insert that
for me it was sql INSERT INTO socialaccount_socialapp_sites VALUES (1, 1, 1);
and you have the socialapp set in socialaccount_socialapp?
?
the one i gave you at the start, with the app id and app token
i think so
query it to be sure
im not too familiar with SQL
SELECT * FROM socialaccount_socialapp;
yes i have the things i entered earlier on
ah, yes
my favourite error code
the one that was 100% clear about what didn't work and helped me save countless hours debugging
okay so its fine??
just to be sure: SELECT * FROM socialaccount_socialapp returns something along the lines of
1|discord|Discord OAuth|some id||<token>```
i wish (it isnt)
yes, it gives me the token and id stuff
the || before the token
yep
are you sure these are app credentials and not for a bot?
did you convert the app to a bot ?
no
did you specify a redirect URL, namely this one, in my apps?
http://127.0.0.1:8000/accounts/discord/login/callback/ here it is again, for copypasta convenience
yes
You must specify at least one URI for authentication to work. If you pass a URI in an OAuth request, it must exactly match one of the URIs you enter here.
ah yes
save changes, retry
click authorize, and you will realize the sad truth: that nothing really works, because i hardcoded the server ID, and the permissions setup i use is absolute cancer
but yeah
why did you set this up, anyways? 🤔
set the website stuff to work on my machine?
oh okay
like why am i contrib ing?
idk, im just bored and want to work on a collaborative project
oh cool!
i should, uh, hm, how do I make this usable by other people
the statbot integration kinda makes it hard
which?
at the start when i was trying to run the server, i module that does not exist got in the way
you removed the stats app
i think that was because you checked out an old commit
but I'm not sure
if its a specific commit thats broken i can look into it and rebase
should i push to the repo i forked?
i commented out from stats.models import Users as DiscordUser
which commit hash was that?
idk
are you in detached head?
i think so
if you run git status, I think it should show you which commit you're at
if you have a detached head
guides/views.py
lets hope I didn't just break the entire git history
looks ok
i think I fixed it, thanks
yeah, but you need an instance of statbot running
so theres no need for me to push?
nah
mkay
I'd have to rebase that commit either way
okay
say i come up with an idea for the site, how will i work on it without having a superuser?
that's a good question that i didn't have to ask myself yet
right now the superuser thing is integrated with discord: if you're an admin on our guild, you're a superuser
which is bad
hmm
i'm currently fixing up the user model so I check that stuff via statbot instead of messing with the model
awwww
gimme a sec
if you really really really want to contribute, you'll need an instance of https://github.com/strinking/statbot
what does it do?
it's the thing that drives our server statistics
oh
we plan to add this to the django site
the inspectdb command, I think that was it, is amazing
i had to write very little code because django automagically generated almost all models
you need to run that somewhere so that the django app can talk to it
okay
Can't he just get an account to the database
i doubt that
What's the point in it then
in what
In storing the data
for using it in statistics like on ddd or other things, such as the permission system i'm now using
But I meant what's the point if it's locked down for like 3 people to use
Handing out a read only user would be fine
whats the point of a bank vault if it's locked down for like 3 people to use
That's a very, very, very bad comparison
Like what lol
anyways, i don't maintain the pgsql instance, striking does. and striking knows what he's doing.
That is showing me the table, not an example of "sensitive data"
And actually if I remember correctly he was the one saying to hand out read only users the last time I asked about an API
i don't know the exact reasons.
...?
here's an example of sensitive data
what's the point of discussing this, anyways?
striking and ais set this up and they're well-respected people, they know what they're doing
I'm not saying they are wrong
And if you read what I said above, you'll realise that lol
would anyone know anything about setting up a json server to brodcast some json in a loop? (1 MESSAGE AFTER ANOTHER)
[
{
"id": 32,
"msg": "CL,u idiot?",
"sender": "BeTePaH_CATaHuCT",
"enemy": true,
"mode": "All"
},
{
"id": 33,
"msg": "на сейбре интересно хотябы летать?",
"sender": "legenda123678",
"enemy": false,
"mode": "All"
},
{
"id": 34,
"msg": "kk",
"sender": "diVineProportion",
"enemy": false,
"mode": "Team"
}
]
I can use like npm http-server to create simple server and access this json by localhost:8080/gamechat.json
but my program works using data[-1]... and it sees no "last message" when I tried it this way..
Am I looking for a JSON server? Or should I be reading the JS docs on how to print some lines of text, mimicing json to have a faux type json server?
Is REST API what I want?
actually that's just a local web
Im trying to get the detail view of an object to show in a template, but when im in the ListView, i get this error:
NoReverseMatch at /tutorials/
Reverse for 'detail' with no arguments not found. 1 pattern(s) tried: ['tutorials\\/(?P<slug>[^/]+)\\/$']
I am new to Django CBV's and tried improvising ways to get it to work.
# views.py
from django.views.generic import ListView
from django.views.generic import DetailView
from django.shortcuts import get_object_or_404
from .models import Tutorial
class TutorialList(ListView):
model = Tutorial
context_object_name = "tutorials"
tutorials = Tutorial.objects.all()
class TutorialDetail(DetailView):
model = Tutorial
context_object_name = 'tutorial'
def get_context_data(self, slug, **kwargs):
context = super().get_context_data(**kwargs)
tutorial = get_object_or_404(Tutorial, slug=slug)
context['slug'] = tutorial.slug
return context
# urls.py
from django.urls import path
from . import views
app_name = 'tutorials'
urlpatterns = [
path('', views.TutorialList.as_view(), name='list'),
path('<str:slug>/', views.TutorialDetail.as_view(), name='detail'),
]
<--tutorial_list.html--!>
{% extends "layout.html" %}
{% block title %}Tutorials{% endblock %}
{% block content %}
{% for tutorial in tutorials %}
<h2><a href="{% url 'tutorials:detail' %}">{{ tutorial.name }}</a></h2>
<h3>{{ tutorial.subject }}</h3>
<p>{{ tutorial.description|truncatewords:5 }}</p>
<hr>
{% endfor %}
{% endblock %}
TutorialDetail expects the slug as its argument
see the path: path('<str:slug>/', views.TutorialDetail.as_view(), name='detail')
yes
you may be looking for {% url 'tutorials:detail' tutorial.slug %} instead
that's how I use it at least
np
seeing as you dont use it in the template you can probably also remove py def get_context_data(self, slug, **kwargs): context = super().get_context_data(**kwargs) tutorial = get_object_or_404(Tutorial, slug=slug) context['slug'] = tutorial.slug return context
then
Im getting this error when i click on one of the links:
TypeError at /tutorials/test-tutorial-creation/
get_context_data() missing 1 required positional argument: 'slug'
then how will i get slug in get_object_or_404()?
no
although, if you pass the slug of the tutorial named as slug, you need to specify pk_url_kwarg = 'slug' in DetailView
because it expects pk normally
or you change path('<str:slug>/'... to path('<str:pk>/'... in urls.py
in views.py, should it be like this?:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['slug'] = self.model.slug
return context
well, if you can access the slug as tutorial.slug anyways, why pass it to the context like that in the first place?


