#web-development

2 messages ยท Page 1 of 1 (latest)

bleak olive
#

!warn 553258638441971742 I've deleted your post; this is not a job board.

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied warning to @plucky siren.

lusty shoal
#

@lavish prism

harsh stump
#

please star if you like

prisma dawn
#

hello

deep cave
#

hiya!

prisma dawn
#

umm.. I'm coming form DRF background.

#

Building API with flask, should I use the plugin?

deep cave
#

cool!

#

which plugin do you mean?

#

DRF?

prisma dawn
#

Flask restful

deep cave
#

well if you've never used flask perhaps you should familiarize yourself with it first

#

but yeah flask restful might be a good analogue to DRF

prisma dawn
#

I've used flask for side project

native tide
#
โœจ Level Up!! โœจ

Julian just got to Level 1 - Beginner

prisma dawn
#

I'm just thinking of going barebone flask for building API.

#

Just asking second opinion though

deep cave
#

I usually build my APIs in barebone flask,

#

I've never had any compelling reasons not to.

#

I guess my advice would be to see if you can come up with a compelling reason to use more than just barebones flask, and if you can't, why bother?

#

don't use an extension just to use it, use it because you need a feature.

prisma dawn
#

have u tried sanic

deep cave
#

no I don't know what it is :D

prisma dawn
deep cave
#

hahaha it's actually based on the sanic meme :D

#

gotta go fast!

prisma dawn
#

yea. it support async out of the box

deep cave
#

right. yeah if you need async you might wanna look into some other frameworks.

#

I know @brave mantle loooves aiohttp

#

might be worth a look

brave mantle
#

Well it's all I had experience with

#

I tried kyoukai but it requires asphalt up the butt and at that point it's no longer a small framework

#

Never seen sanic

#

But my routes use route classes, not decorators, and aiohttp supports that

deep cave
#

but the decorators are so pretty

brave mantle
#

Function is more important

deep cave
#

I'm a romantic when it comes to programming :D

brave mantle
#

Haha

kind steppe
#

@prisma dawn for api's I don't use any module

#

I find it a lot easier just to use @app.route

#

And then add custom caching methods using decorators

grand badge
#

Anyone use flask?

brave mantle
#

I've seen a few people using it

grand badge
#

Im a beginner, taking courses on treehouse

#

Flask is cool

brave mantle
#

Flask is neat

#

but you're wasting your money

grand badge
#

?

brave mantle
#

Treehouse

grand badge
#

Treehouse actually helped me

native tide
#
โœจ Level Up!! โœจ

Hasan Ahmad just got to Level 1 - Beginner

brave mantle
#

Treehouse is well known for being kinda bunk

grand badge
#

Bunk?

brave mantle
#

the best way I can put it is that their courses are broken

#

they're mostly fine but they all seem to have small problems that add up

grand badge
#

True

brave mantle
#

(they're also really expensive)

grand badge
#

Its cheap (for me at least)

kind steppe
#

I use flask

#

Flask is f u n

#

all aboard the flask train

brave mantle
#

I prefer more modern stuff, but that's me

grand badge
#

Hey wats up, and yes, flask all the way!

kind steppe
#

I agree with Hasan flask ftw

#

What's your modern stuff

brave mantle
#

aiohttp and friends

grand badge
#

Btw, is flask a framework that employers look for?

brave mantle
#

python is very much moving towards asyncio

#

frameworks that refuse to support it will be left in the dust eventually

#

but I'm sure flask will at some point

grand badge
#

I wanna learn django later on

brave mantle
#

also, couldn't tell you

#

it's a popular one but not as popular as django

grand badge
#

True

brave mantle
#

it's worth noting that django is completely different and really requires you to do things "the django way"

grand badge
#

Very true

brave mantle
#

if you're doing django properly then you even have it generate the project structure for you

grand badge
#

I think i heard that from sentdex

#

...

kind steppe
#

Discord use Flask

grand badge
#

Nice

kind steppe
#

Discord API is mainly Python

grand badge
#

Ik

brave mantle
#

that could prove to be a bad move on Discord's part

kind steppe
#

You can even see Andrei using it in a dumb tweet lmao

grand badge
#

I semi agree with gdude

kind steppe
#

I do in some respect I do agree Async is becoming more and more popular

#

but

brave mantle
#

Nah, that's not what I mean

kind steppe
#

i like flask so I'll stay with flask

brave mantle
#

flask isn't designed for high availability

#

not like, say, tornado

grand badge
#

Yeah

kind steppe
#

you keep making me feel stupid mister gdude :<

grand badge
#

Dont worry joseph, gdude has a profile pic of a pony ๐Ÿ˜‰

brave mantle
#

not the first time I've heard either of those things

grand badge
#

Snd i have nothing

kind steppe
#

py!debug discord.utils.get(guild.members, name="Hasan Ahmad").avatar_url

grand badge
#

Sorry gdude if i offend i, need to keep joseph motivated

kind steppe
#

oh javascrip

#

with

#

htm el

brave mantle
#

it's the source code of google's swiffy tool

#

which doesn't exist anymore

#

it used to convert flash SWFs to HTML5

kind steppe
#

oh that sounds useful

grand badge
#

I really need to learn js

brave mantle
#

flash has been deprecated for years now

kind steppe
#

flash is F U N

brave mantle
#

don't use it for web

#

even adobe wants people to use html5

#

lol

grand badge
#

If you guys give me ยฃ100, i will attempt to make Crysis 3 in HTML

#

...

brave mantle
#

well to be fair

#

you won't be making it in flash either

#

:P

grand badge
#

Theres this guy who says html is a programming lang

brave mantle
#

it literally has "markup language" in the name

grand badge
#

Ikr

#

Sql is not a programming lang right?

#

Query lang

#

Im kinda new need to ask some questions

brave mantle
#

structured query language

grand badge
#

Yep

brave mantle
#

I feel like I answer that question every two days

#

lol

grand badge
#

Okay, ik its query lang

kind steppe
#

happy 21st october

grand badge
#

U too

#

Has anyone used discords api in their website?

brave mantle
#

I've worked with oauth

kind steppe
#

https://discord.report/ uses discord oauth2 for login

brave mantle
#

for a map, of all things

kind steppe
#

o

brave mantle
#

deliberately cropped

#

I bet you'd like to know what this is, huh?

#

WELL TOO BAD

grand badge
#

Theres this html code u can use to implement a disc server in a website

kind steppe
#

what if I don't want to know what it is mister gdude2002

brave mantle
#

then I'm still not telling you

#

since I'd be breaking the license that I wrote and added an exception for myself to

kind steppe
#

okay fair enough

brave mantle
#

xD

#

anyway the main thing you need to know is that discord oauth works and is also a pain in the ass to handle in a window

kind steppe
#

i might write a bot in Disco

#

because i like to dance

brave mantle
#

why not use Dithcord

kind steppe
#

because evie.codes wrote it and I have an aversion to her

#

plus the latest commit was in february

brave mantle
#

oh right, I forgot about her

kind steppe
#

Andrei's was 4 days ago kek

brave mantle
#

isn't she some super crazy feminist person?

#

I haven't interacted much but she was pretty hostile to me on the testers server for being a dude

kind steppe
#

she's crazy and minimods every discord server ever

brave mantle
#

borderline SJW, then..

kind steppe
#

even better

#

she makes youtube tutorials on discord bots

brave mantle
#

yeah, I knew that

#

anyway, this doesn't belong in here

kind steppe
#

true

grand badge
#

Im gnna change to django, guys, i think its time i grow up

kind steppe
#

no pls

#

@grand badge use Flask or Sanic

brave mantle
#

I generally recommend aiohttp

#

but you all know that

kind steppe
#

yes we all know that

#

kek

brave mantle
#

:P

kind steppe
#

or we could just abandon Python completely and use Elixir Phoenix

brave mantle
#

It amuses me how many language specific servers I've been to where the staff prefer other languages

kind steppe
#

Lmfao

brave mantle
#

Like #C++ on esper is full of staff that hate C++ and use C instead

#

Lol

kind steppe
#

I hate C++

#

C# or C is best

#

In order

#
  1. Elixir
  2. Python and Node
  3. C#
  4. C
native tide
#

see

kind steppe
#

wait erlang should be after Python and Node

#

erlang is fun

dawn vessel
#

Rustlang?

#

Golang?

grand badge
#

Can someone explain to me what the ```python
models.ForeignKey()

brave mantle
#

It's a foreign key relationship

#

Essentially it exists to refer to the primary key of a row in another table

#

thus associating this row with that one

#

I believe django generates a primary key for each model automatically, so that's what you'd be referring to

grand badge
#

@brave mantle thanks!

brave mantle
#

No problem

grand badge
#

@brave mantle do u use django mostly?

brave mantle
#

I use aiohttp mostly

grand badge
#

okay

#

im a django pony with flask for a hat

brave mantle
#

I could never get my head around django

#

It's far too opinionated for me

grand badge
#

oh yes i see wat u mean

deep cave
#

I used to be a django guy

#

but then I wrote one system in flask and never felt compelled to ever use django again

grand badge
#

i used to use flask but i think im gnna stick with django despite being more complex than flask

deep cave
#

I used to think flask was great for smaller projects and django was great for bigger ones but now I just think people should use the microframeworks for any project and write whatever complexion they need from scratch, or piece it in by integrating optional modules.

grand badge
#

true

#

for me, writing django is more fun than flask

#

and i feel that its easier for me in some ways

deep cave
#

not trying to talk you out of django. it's a great system.

kind steppe
#

I used to use flak for most things

deep cave
#

if you like it, you should do it!

grand badge
#

flask is great

kind steppe
#

I use Phoenix more now but that's not Python ยฏ_(ใƒ„)_/ยฏ

grand badge
#

but after comparing ima go play with the pony

deep cave
#

and the book Two Scoops of Django was very helpful, if you're into reading.

grand badge
#

okay

#

is there free samples online?

native tide
#
โœจ Level Up!! โœจ

Hasan just got to Level 2 - Memer Rank 1

grand badge
#

wat

deep cave
#

I don\t think so.

grand badge
#

okay

deep cave
#

it's also not a super cheap book

#

so.. there are probably good free sources you can use instead.

#

I just really liked it for its writing style

#

was very lightweight and fun and easy to read.

#

it's not a django learning book though, it's best practices

#

so it's for people who know django and wanna write better django

grand badge
#

65 DOLLARS!!!????

#

wowowowwww

deep cave
#

haha

grand badge
#

when u said expensive i thoght u meant 25 dollars or something

deep cave
#

nope, it's expensive

#

you can probably get one for an older version of django and learn almost all the same lessons for a third of the price

#

but still

#

just something to consider for later

#

if you stick with it

grand badge
#

its less in the uk but wow...

deep cave
#

that's for django 1.5, a very old version indeed.

grand badge
#

okay, gtg, was nice talking to ya

deep cave
#

and also probably piracy?

grand badge
#

and thanks korex for the link

deep cave
#

seeya hasan

grand badge
#

cya!

spare pelican
#

Whats the newest version?

deep cave
#

like 1.11 or something

spare pelican
#

ok

grand badge
#

yeeeeeeee i foound it for ยฃ31 on amazon

#

still really expensive

deep cave
#

I wouldnt buy it if I didnt have a steady income. tons of good free sources out there.

grand badge
#

yeh true

compact pelican
#

Hey guys quick question, when trying to get this function to work where it takes a policy ID to pull information to render a template i get that the attribute has no get function.
https://pastebin.com/jteJViZM there is the paste with my code, i cannot figure out what is wrong its usually something really simple i cannot see or am overlooking as pointed out by devoid . any help would be greatly appreciated. the get function is supposed to grab the data from an ORM database with foreign keys.

torpid linden
#

hi

brave mantle
grand badge
#

how do i get static files to work in Django?

deep cave
#

the official django tutorial covers it, and it's a reaaally good tutorial

#

have you run through it?

grand badge
#

i found it confusing

steep bane
#

hi, not sure if this is the best place to ask, but i was wondering if anyone here has experience working bs4?

#

nvm, got it (:

grand badge
#

i have some experience

#

nut its very little experience

#

but*

grand badge
#

Does anyone know any open source django projects that are good to learn from for a beginner?

celest zinc
#

got task was destroyed but pending
my idcheck function is taking long time to oerate but i have added await on it still it shuts the bot down
chrs=str(await idcheck(msg,0,message,client))

    
    for file in repo.get_dir_contents('/'):
        if file.name[-4:]=='.txt':
            msg=urllib.request.urlopen(durl+file.name).read()
            len1=len('{}'.format(msg).split('\\n')[0])
            len2=len('{}'.format(msg).split('\\r\\n')[0])
            if '{}.txt'.format(hwid)== file.path:
            #print('{}.txt'.format(hwid)+'<==>'+file.path)
                flag=1
                return flag
            elif len1<4:
                msg1='{}'.format(msg).split('\\n')[1]
                print(msg1)
                if msg1==message.author.name:
                    flag=1
                    return flag
            elif len2<7:
                msg2='{}'.format(msg).split('\\r\\n')[1]
                print(msg2)
                if msg2==message.author.name:
                    flag=1
                    return flag
            if flag==1:
                break
            #print('{}.txt'.format(hwid)+'<==>'+file.path)
    return flag```
#

<@&391349088387334147>

brave mantle
#

Coroutines are not magic

#

You're using urllib to grab a url, that's your problem

#

You should be using aiohttp

celest zinc
#

okey wrkin on dat

native tide
#
โœจ Level Up!! โœจ

killswitc_h just got to Level 1 - Beginner

kind steppe
#

@celest zinc please verify yourself

brave mantle
#

tbh that problem is less of a user problem and more of an implementation problem, I'm starting to realise

kind steppe
#

Elaborate on that

#

The first message they see tells them to read the rules and type the verified command

brave mantle
#

your bot isn't smart enough, basically

kind steppe
#

Also your at everyone only made 3 people verify lmao

brave mantle
#
  1. It requires case-sensitivity
kind steppe
#

oh ty ty

brave mantle
#
  1. It doesn't prevent people from assigning other roles when not verified
kind steppe
#

That's only a small issue

#

That might be an issue

brave mantle
#
  1. It makes us clean up incorrectly-formed messages (and chat) manually
kind steppe
#

I might just make a custom bot for all this

brave mantle
#

I dunno why you didn't tbh

#

lol

kind steppe
#

instead of editing PyButt every time lmao

brave mantle
#

I mean an alternativel solution would be tableflip

#

but

#

let's not do that yet

kind steppe
#

lol what

brave mantle
#

tableflip verification

#

but that might not work either

kind steppe
#

o

#

well we'd need a bot to assign the verified role

brave mantle
#

nope

#

well, not automatically

kind steppe
#

I couldn't be bothered to change channel permissions though

#

!server

jolly hollyBOT
#

โฏ Server Information
Created: 11 months ago (2017-01-08T12:03:33)
Members: 1218
Features: none

โฏ Counts
Roles: 26
Text: 37
Voice: 4

โฏ Members
status_online - 83
status_offline - 999
status_away - 102
status_dnd - 34

mild bridge
#

Not sure if this should go here, but when I'm using selenium webdriver with the --headless flag, I still get a console log window open. Is there any way to hide this?

deep cave
#

save it as a .pyw file and see if that does the trick. on windows anyway

#

headless only prevents the browser window

mild bridge
#

Tried it, but it seems that this window's the selenium log or smth. Looks like the python window is seperate

deep cave
#

hm. right

#

have you tried with firefox instead of chrome as the driver? might be the same, iunno.

mild bridge
#

I'll have a look when I get home, thanks

deep cave
#

the far more complicated solution in windows would be to somehow get chromedriver to run as a service

#

but I have no idea how to make that play nice with selenium

#

there seems to be some github packages intended to make chromedriver a service for use with the java version of selenium and with seleniumgrid

#

but nothing for use with python

#

that I can find, anyway

#

interesting problem, though

grand badge
#

how do i send emails in django???

brave mantle
grand badge
#

i went through it, and i got smtp auth error

brave mantle
#

so your password is wrong

grand badge
#

it was right

brave mantle
#

nope

grand badge
#

u sure??

brave mantle
#

yep

#

that's what the error means, after all

#

although knowing most people around here, you're probably using a mail service with 2-factor

grand badge
#

yep

brave mantle
#

yeah so you can't use your normal password

grand badge
#

gmail.................................

#

wdym

brave mantle
#

you have to generate an app password because 2-factor only works in the browser and gmail apps

grand badge
#

sooooooo how do i do that?????????

brave mantle
#

well, you'll have to do that with your mail provider

grand badge
#

oooookkkkkaaay

#

im using a filebased backend rn

brave mantle
#

that has nothing to do with anything

grand badge
#

ik..

grand badge
#

for gmail u have to turn on less secure apps

#

WOOOOHHOHOOOOO IT WORKED!

kind steppe
#

Gmail has an api doesn't it?

#

But if it worked then nevermind lol

signal karma
#

Does anyone use Flask here? =x

mild bridge
#

A couple

#

You should probably just ask the question

signal karma
#

Okok, good to know. I will definitely have questions tomorrow ๐Ÿ˜

#

home now

signal karma
#

I'm struggling in Flask-RestPlus with the following marshalling:

#
'articles': fields.List(fields.Nested(article, attribute=lambda x: x.articles)),
#

My Request table has articles = relationship("RequestArticle", cascade="all, delete-orphan"),
And RequestArticles has article_id = db.Column(db.Integer, db.ForeignKey("article.id"), primary_key=True)
I want to get in 'articles' the full detail of article.

signal karma
#

Finally having something working

#
'articles': fields.List(fields.Nested(article), attribute=lambda x: x.articles[0].article)
#

but it only gets the first then

#

How can it not only be the first? should be obvious I guess since it's a list, but can't find a way

#

This is not working:

'articles': fields.List(fields.Nested(article, attribute=lambda x: x.article), attribute=lambda x: x.articles)
native tide
#
โœจ Level Up!! โœจ

Elfayer just got to Level 1 - Beginner

signal karma
#

I get: TypeError: hasattr(): attribute name must be string

signal karma
#

Anyone doing flask here? ๐Ÿ˜•

signal karma
iron acorn
#

You are asking in a channel that has 16 people online.....

signal karma
#

right

signal karma
#

@iron acorn So is everybody using Django?

iron acorn
#

I think more so than people using flask

#

AFAIK more django resources on web than flask

brave mantle
#

Most people use flask or aiohttp here

#

I don't use flask, @kind steppe is always recommending it though so he might have an idea

signal karma
#

@brave mantle Ah good to hear ๐Ÿ˜ƒ

brave mantle
#

No, he is, owns the server

kind steppe
#

hello yes

#

I have used flask but I've never used what you are talking ahout

#

Also I don't really like flask anymore lol

signal karma
#

@kind steppe Ah why is that? ๐Ÿ˜

#

What do you use now?

kind steppe
#

I use something non Python lol, but Flask is your best Python webserver

signal karma
#

@kind steppe Really? ๐Ÿ˜ฎ

#

Django seems a lot more popular

#

And Flask is confusing to me.. Note I have never been very involved in back end development, I'm a front end dev.

brave mantle
#

Flask makes you write more boilerplate than django

#

The companies love django because it's standardized and can be documented easily

#

but it's a bit of a behemoth

#

flask, on the other hand, isn't really that opinionated about how you do things

signal karma
#

My company chose Flask ๐Ÿ˜ฌ

#

The problem is that I'm front end oriented, and in my company, no one knows really Flask โค

brave mantle
#

Then your company is one of the better ones lol

#

yeah, that's the problem

#

there's a lot of backend to write

#

flask won't do your database stuff for you for example, you'll have to do that yourself

#

django comes with an ORM

signal karma
#

I asked a question on the github of restplus(because that's what we use), I don't get why we have to write most twice marshalling and parsing...

#

I use sqlAlchemy

brave mantle
#

SQLAlchemy is pretty great

signal karma
#

not too bad

#

so far

brave mantle
#

Pair it with alembic and, hey, there's your migrations

signal karma
#

I also use alembic

brave mantle
#

Love me some alembic

#

I'm not sure what the marshalling/parsing is referring to

signal karma
#

tbh, they chose all the stack, I am unexperienced on back end stuff and no one knows around me how it should be used (international company)

brave mantle
#

I mean I know what the words mean, but not the context

signal karma
#

reffering to?

brave mantle
#

you're marshalling/parsing something

#

what's that something?

#

if you say "data" I'mma slap you

#

:P

signal karma
#

they call it a schema

#

marshalling s to define a schema, parsing is to fill a dict

brave mantle
#

right okay, so you have a schema and that's used to fill a dict, given some data

signal karma
#

So you'd say it is different then. But on my end points I can write @expect(some_schema), so I define already what I want in entry, why do I have redefine aaaall the keys again? (because on the parsing step, you have to specify each key you want)

brave mantle
#

system not smart enough?

#

That's not a flask thing anyway

#

at least, not that I know of

signal karma
#

right

#

maybe it is flask-restplus/flask-restful that are wrong then? ๐Ÿค”

brave mantle
#

I'm confused as to why you need those

signal karma
#

Even flask-restplus suggest to use marshmallow for marshalling

#

Is marshalling a common word for back end python?

brave mantle
#

Not really

signal karma
#

ok

brave mantle
#

OK, so let me get this straight

signal karma
#

so if should come from rest*

brave mantle
#

you're defining a schema

#

and that schema is used to validate incoming data via the rest api

#

to ensure it has the correct params

#

right?

signal karma
#

in and out

brave mantle
#

Ok, so the returned data as well

#

it sounds like it would be trivial to write a middleware and decorator for that

signal karma
#

I use @expect() and @marshall_with(), which defines the model out

brave mantle
#

Like, let's say you have a middleware

#

You have it inspect incoming requests, and also inspect returned data

#

Actually no, the decorator can do all of that

#

so you have your decorator defined like, I dunno

#
def validate(func, **kwargs):
#

I'm not sure how complicated your schema are, but assuming you're just looking at keys and values in the request, it should be easy

#
@validate(key=int)
def get():
    return ...
signal karma
#

looks like that. I think it already takes care of the validation (you can specify many things: require, type, min-max, etc)

#

but I just don't get why I define a schema and set it as input AND have to rewrite all the keys inside. What's the point to 'expect' something in then? Oo

brave mantle
#

It just sounds like your schema library isn't smart enough honestly

signal karma
#

I mean either I misuderstand something, or the design is wrong. I guess it is the first assumption, but still can't find anyone explaining this to me.

brave mantle
#

You'd probably have to ask whoever wrote the library

#

..and then we're back where we started I guess

signal karma
#

So what do people use above Flask usually?

brave mantle
#

Above?

signal karma
#

like nodejs would come with express. Are there any popular usage of libraries above Flask?

brave mantle
#

Flask has tons of extensions

#

Might be worth having a browse around

signal karma
#

I bet, same for node ^^

#

what about rest libraries?

#

the biggest thing I don't like about Flask is that the community is very slim...

#

compare to Django

brave mantle
#

well I dunno why you even need a REST library in the first place honestly

#

flask is minimal enough that making your endpoints is already easy

signal karma
#

okok

#

I didn't choose ;P

brave mantle
#

ah, :P

native tide
#

I added my self

deep cave
#

good

native tide
#

So are you saying i cant make a script in the models.py to add json data to the database?

deep cave
#

uh. sure you can.

#

but

#

basically inside models.py you're defining the generic model, so you have to do it in a generic way.

#

let's say you have a json file that has the age of all the users

#

you could set an age property inside models.py that goes into that json file and looks up the age based on the users name or something.

#

the key is to do it in such a way that it will work for every instance of that model

native tide
#

The data comes from an api of another site

deep cave
#

yeah. well you could have a property in your model that looks up some information in an api.

native tide
#

I made a def function that does

#

Im just not sure how to take the return data and put it into each field of the model

deep cave
#

okay. so you have a function inside the model that does what you want it to do?

native tide
#

It gets the json data ges

deep cave
#

basically you can just treat that function as a normal attribute then.

native tide
#

Yes*

deep cave
#

for example

#

if you have

class User(models.model):
    def age(self):
        # call some API and get the age
        age = api.get_age()
        return age
#

say you have this

#

now all your users will basically have an age property that you can just access like any other field.

#

so in your template you can simply do {{user.age}}

brave mantle
#

huh, didn't know django could do that without a @property

deep cave
#

all functions inside of models.Model objects are essentially treated as a @property

#

at least.. if I recall correctly. it's been forever since I wrote actual django but I'm looking at some old code now and I don't have a @property decorator on any of my functions.

brave mantle
#

Nice frontticks there

#

lol

deep cave
#

: (

#

SORRY SOME GUY CALLED PROP

brave mantle
#

haha

deep cave
#

but @native tide , to be clear, this doesn't actually store the return value of age() in the database. the database will only ever really have a reference to that function.

native tide
#

Thanks man

deep cave
#

did you get it working?

#

or at least manage to wrap your head around it a bit?

brittle copper
#

So you have a secret channel here

#

Nice

brave mantle
#

Not exactly secret when it's documented in #welcome :P

brittle copper
#

I never read those :(

kind steppe
#

lol rip

opal coral
#

youre verified so you agreed to them rules tho

brittle copper
#

The verify me command wasn't there IIRC

kind steppe
#

!info @brittle copper

jolly hollyBOT
#
Someone#1720

โฏ User Information
ID: 361708843425726474
Profile: @brittle copper
Created: 3 months ago (2017-09-25T03:01:48)

โฏ Member Information
Joined: 2 days ago (2017-12-28T12:18:35.671478)
Roles: Verified, Web Development

โฏ Activity
Last Message: 2 minutes ago (2017-12-30T14:41:48.457000)
First Message: 2 days ago (2017-12-28T12:20:02.137000)

kind steppe
#

Yeah we might not have had it 3 months ago

#

idk

brittle copper
#

"Joined: 2 days ago (2017-12-28T12:18:35.671478)"

#

2 days ago

kind steppe
#

Oh

#

I looked at created date lol

#

well we did have it 2 days ago

#

lol

opal coral
#

wait then howd you get verified

#

whut

brittle copper
#

And I still can't see the verify me command there

#

Joined: 2 days ago (2017-12-28T12:18:35.671478)

native tide
#
โœจ Level Up!! โœจ

Someone just got to Level 1 - Beginner

brittle copper
#

Oh

#

Where is it

kind steppe
#

yeah when you verify you get removed from the checkpoint channel

opal coral
kind steppe
opal coral
#

are you a hackerman

brittle copper
#

Yeah that is the problem

#

I just copied the command without doing anything you ask me to do

kind steppe
#

understandable

opal coral
#

lmao

brittle copper
#

I didn't even read the text after the command xD

kind steppe
#

understandable

brittle copper
brittle copper
#

Wouldn't it be awesome if django had the ajax ability with it

#

So we could write our ajax too with python :(

kind steppe
#

@brave mantle what was that python for web thing you were showing?

brave mantle
#

They've been working on webassembly compiling for python, but webassembly isn't ready for that kind of use yet

#

You can't really interact with the DOM with it yet

kind steppe
#

no there was the other thing

brave mantle
#

There are a few JS transpilers around or JS-implemented VMs

#

I can't remember off the top of my head

#

easy to find though

kind steppe
#

Brython

#

that was it

#
from browser import document, ajax

url = "http://api.open-notify.org/iss-now.json"
msg = "Position of the International Space Station at {}: {}"

def complete(request):
    import json
    import datetime
    data = json.loads(request.responseText)
    position = data['iss_position']
    ts = data['timestamp']
    now = datetime.datetime.fromtimestamp(ts)
    document["zone10"].text = msg.format(now, position)

@document['button10'].bind('click')
def click(event):
    req = ajax.ajax()
    req.open('GET', url, True)
    req.bind('complete', complete)
    document["zone10"].text = "waiting..."
    req.send()
brittle copper
#

This looks promising

kind steppe
#

It's pretty nice from what I've seen

brittle copper
#

Yeah, before trying to learn js I'll deeply look into this, thanks alot

native tide
#

@deep cave no i didnt get it working bro

#

I did figure out from further reading the documentation that i need to use a costume django-admin command but i keep getting a error when i run the script

brittle copper
#
class Title(models.Model):

    title_text = models.CharField(max_length=50, null=True)
    title_url = models.CharField(max_length=100, null=True)

    def __str__(self):
        return self.title_text


class Entry(models.Model):

    entry_title = models.ForeignKey(Title, on_delete=models.CASCADE)
    entry_text = models.CharField(max_length=2500, null=True, blank=True)
    entry_author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    entry_date = models.CharField(max_length=20, null=True, blank=True)
    entry_points = models.IntegerField(null=True, blank=True)
    entry_id = models.CharField(max_length=10, null=True, blank=True)
    entry_readability = models.BooleanField(default=True)

    def __str__(self):
        return self.entry_text```
#

How do I get all the Entrys' titles?

#

Not all the titles, I need them in an order so I need to get all the Entrys' titles and use them like that

brittle copper
#

Nevermind, done it

#

It was easier than I thought

#

Thank you all ๐Ÿ˜š

native tide
#

Im making a script to set up the data base when the site is first deployed

#

Would it be slow to request the json data one at a time then save

deep cave
#

I guess that depends on how much data it is.

#

but it certainly doesn't sound optimal

native tide
#

Would it be better to req tell the needed amount is met then save them?

#

Also when i first deploy the site it will be a lot

deep cave
#

no, that sounds like it would be the same. can't you request all the data in one request instead of lots of little ones?

native tide
#

Sadly no zzz

#

Maybe i need to find a better api

#

That serves the same purpose

deep cave
#

it's the network traffic you wanna watch out for, that's the real killer. doing 10000 webrequests is bad. doing 1 webrequest for 10000 things is ideal. likewise, you don't wanna do 10000 insert statements to the database, you wanna insert 10000 things in one go.

#

all the stuff you do in python is usually very fast

#

but making network requests is sloooow.

#

and if you absolutely have to make thousands of requests, you probably wanna look into threading or something so you can do multiple near-simultaneous ones instead of waiting for each one before starting the next.

native tide
#

Yes i see

#

I will just look for a better way to get wha i need

#

What*

#

A single req per item just wont work but there service only allows it that way

deep cave
#

but with all that said - don't optimize before you test.

#

if it's fast enough already, all of this is pointless.

#

first make sure it's actually slow, then fix it.

#

premature optimization is the bane of many talented programmers.

#

maybe the API is extraordinarily fast, maybe you don't have to fetch as much data as you think, etc. learn to profile it.

native tide
#

@deep cave i found a much better service that allows multiple items to be called with one req thanks so much for your advice bro

deep cave
#

good!

#

hey, no problem. that's what we're here for.

#

try to do the same when you spit the data into the database, too

native tide
#

This is my first site that im putting up for commercial purposes

deep cave
#

when inserting tons of data, there are techniques. you may wanna read up on it a bit.

#

common mistakes people make are to connect to the database more than once, to insert the items one line at a time, or to try to insert everything in one huge chunk.

#

what you want to do is connect one time, then insert batches of data at a time, verify it's working, and then commit.

#

you might want to do a bit of reading to find the best approach

native tide
#

Do you have any example code you have a link to so that i may see?

deep cave
#

the approach differs from database to database.

native tide
#

Or where to find it in the docs

deep cave
#

just google "inserting large amounts of data into postgresql" or whatever db you're using.

#

what db are you using? just out of curiosity?

native tide
#

MySQL cuss dreamhost offers ulimited space for it

deep cave
native tide
#

Is there a way to save data in the way your talking about using a model or will i have to use raw sql?

deep cave
#

some approaches here

#

I've never really worked with mysql but building a multi-row insert is usually a good approach

native tide
#

Django doc said to avoid raw sql as much as possible

deep cave
#

oh you're working with django. I see.

#

no, I think you have to use raw SQL for this kind of thing.

#

the django ORM is not suitable for bulk operations afaik

#

although it's possible if you go ask #django on freenode or something they will have a suggestion

#

there is this bulk_create() method

#

but.. iunno man

#

again it depends on the amount of data

#

I would have just written some SQL for this

#

it looks like if you absolutely must, you could probably use a list comprehension with that bulk_create() method

#

to insert your data

native tide
#

I just have never delt with it

deep cave
#

Entry.objects.bulk_create([Entry(headline=x) for x in headlines]) would presumably work if you had a ton of headlines in a list

#

but I don't know how performant it will be

#

so you might wanna test it if you wanna keep it in the family - and then do some profiling to see how long it takes.

#

but if it's super slow, pure SQL will probably be the way to go.

native tide
#

I will test and see thanks

deep cave
#

I'm assuming you understand listcomps

#

feel free to say if you don't, I'm happy to explain them

native tide
#

Tbh no bro

#

I was going to google it

deep cave
#

it's like a shorthand for building a list. it's very powerful and you probably should google and read a bit

#

but basically

#
nums = [1, 2, 3]

# this code
strings = [str(x) for x in nums]
print(strings) # => ["1", "2", "3"]

# is the same as this
strings = []
for x in nums:
    strings.append(str(x))
print(strings) # => ["1", "2", "3"]
native tide
#

Whats diffrence does it make one way over the other then?

deep cave
#

python considers them the same - but basically the former method can be very succinct and elegant if wielded responsibly

#

you can use the second approach if you prefer it

#
Entry.objects.bulk_create([Entry(headline=x) for x in headlines])

this is a good example. the second approach would have looked like this:

entries = []
for x in headlines:
    entries.append(Entry(headline=x))
Entry.objects.bulk_create(entries)
#

I prefer the first

#

or you can strike a nice balance between them and go for

entries = [Entry(headline=x) for x in headlines]
Entry.objects.bulk_create(entries)
#

anyway it's all style

native tide
#

The first way it good

#

Is*

deep cave
#

obviously in your case you'd replace the Entry constructor with whatever model you wanna create, but it should be easy enough to adapt.

native tide
#

Ik bro thanks man

#

Trying to figure out some thing atm zzz

#

Never ends lol

deep cave
#

good luck

native tide
#

Thanks mate

#

Just really not sure ive looked and looked zzz

signal karma
#

Hey guys

#

I am having difficulties to find my way around something or the right way to do it.

#

I am using Flask-RestPlus (same as RestFul)

#

I would like a marshalling such as follow:

'articles': fields.List(fields.Nested(article), attribute=lambda x: x.articles[0].article),
#

The problem is this [0], it is a list , I should not have to precise any index

#

But I can't figure out how to say I want the current object articles list and inside this relashionship I want the article relashionship.

#

I can provide more information if required, I just don't wanna spam of information๐Ÿค

native tide
#
โœจ Level Up!! โœจ

Elfayer just got to Level 2 - Memer Rank 1

signal karma
#

Still on it ๐Ÿ™‚

mild bridge
#

:\

#

You might have better luck posting in #help-falafel? Afaik you don't need any self-roles to see questions

signal karma
#

@mild bridge But Flask is really web dev, I'm afraid they won't like that.

brittle copper
deep cave
#

@signal karma

signal karma
#

๐Ÿ˜ฎ

deep cave
#

first of all let me just say that I don't really see the point in Flask-RestPlus at all. just write the whole thing from scratch, this just overcomplicates it. :/

#

secondly, I think the key to solving your problem is to use a real function instead of a lambda

signal karma
#

I think it is because it carries swagger

deep cave
#

but in order to help you with that, I need you to clarify what you mean by "the current object"

#

current how?

#

can I maybe see some more code?

signal karma
#

hm, in an end point, I return an object. This is the 'current object'.

#

Sure

#
article_full = namespace.model('ArticleFull', {
    'id': fields.Integer(required=True),
    'title': fields.String(required=True),
    'description': fields.String(required=True),
    'image': fields.String(required=True),
    'brand': fields.String(required=True),
    # TODO: Fix index location to user making the req
    'price': fields.Float(required=True, attribute=lambda x: list(filter(lambda y: y.location_id == 1, x.prices))[0].price),
    'category_id': fields.Integer(required=True),
})

@namespace.route('/')
class ArticleListAPI(SecuredResource):
    """Articles REST end points"""

    @staticmethod
        @namespace.marshal_list_with(article_full, envelope='articles')
        def get():
            return Article.query.all()
#

I have 2 lambdas

#

this is one of them

#

Does that make more sens? =x

deep cave
#

sure, you always use a lambda with filter

#

or. well, almost always.,

#

I can't speak to whether or not it's correct without seeing the rest of the code, but I take it this one works for you then?

signal karma
#

it does, just it should be dynamic on the user's location

deep cave
#

okay

signal karma
#

instead of y.location_id == 1

#

but I guess I can write whatever inside, since it seems it is only evaluated on return

#

When called

deep cave
#

so, would you know how to write a real function that returns the correct price?

#

taking in some sort of user location identifier as an argument?

#

it seems like a much simpler way to go about this

signal karma
#

That one thing I need to figure out, how to know who is making the request for thiskind of cases

#

and also to restrict API to users rights

deep cave
#

and attribute takes any callable that returns a value

#

so you can just put a regular function call in there

#

instead of this gross lambda stuff

signal karma
#

I could do that for the location. I'll probably do that, but not for the rights

deep cave
#

no, that's true, you'd probably want to restrict users at a higher level and never execute this if they don't auth

signal karma
#

okok good to know, I'll avoid lambdas^^

deep cave
#

you don't have to avoid lambdas -- but it's a good place to start if you're not sure why this doesn't work.

signal karma
#

i thought to build a decorator for that, but I still need user info

deep cave
#

yeah, a decorator is a good way to handle auth

#

but

#

if you need user info

signal karma
#

right

deep cave
#

just require it!

#

when people call or whatever

signal karma
#

I thought of using JWT or redis cache

deep cave
#

I mean I don't see how you're gonna do any of this without knowing who the user is

signal karma
#

exactly ^^

deep cave
#

yeah JWT is one approach I guess

#

but I guess you should start with that. figure out who the user is. then auth the user. and then write functions to use that userdata to fetch the right price or article or whatever it is you wanna fetch

#

then stick those functions in the marshalling attributes

#

problem solved

#

that make sense?

signal karma
#

ok

#

yes it does, it's more clear to hear it^^

#

Actually the problem I am trying to solve right now is how to get a SQLAlchemy relashionship many-many with the extra data inside the linked table.

#

I guess it should come from the table definition...

deep cave
#

what's the database

#

sqlalchemy is just how you access the database, and generally speaking the relationships are defined in the database itself.

signal karma
#
class Request(db.Model):
    """Model for Request."""
    __tablename__ = 'request'

    id = db.Column(db.Integer, primary_key=True)
    # [...]
    articles = relationship("Article", secondary="request_articles")
deep cave
#

so you're asking the wrong question.

#

I mean, don't get me wrong, SQLAlchemy does have mechanisms for many-to-many

#

but first you need to look at your actual database

#

and see if it even supports it

signal karma
#

You mean the db type?

#

mysql?

deep cave
#

sure. okay. mysql.

#

which of course has all kinds of relationships

#

an example here

#

this should work fine in SQLA -> MySQL

#

or at least something like it

#

also some good examples here

signal karma
deep cave
#

that's another approach

#

and then what, is it not working?

signal karma
#

I just get the Article information, not the extra data from the middle table

#

request <- request_article(extra data) -> article

#

but my relationship is

articles = relationship("Article", secondary="request_articles")
deep cave
#

that doesn't seem to match how they've done it in the documentation you linked.

#

let's see some more of your code for how you make that relationship

signal karma
#
class Request(db.Model):
    """Model for Request."""
    __tablename__ = 'request'

    id = db.Column(db.Integer, primary_key=True)
    # [...]
    location_id = db.Column(db.Integer, db.ForeignKey("location.id"), nullable=False)
    articles = relationship("Article", secondary="request_articles")

class RequestArticle(db.Model):
    """Model for Request Article."""
    __tablename__ = 'request_articles'

    id = db.Column(db.Integer, primary_key=True)
    request_id = db.Column(db.Integer, db.ForeignKey("request.id"))
    article_id = db.Column(db.Integer, db.ForeignKey("article.id"))
    state_id = db.Column(db.Integer, db.ForeignKey("state.id"), nullable=False)
    quantity = db.Column(db.Integer, nullable=False)
    article = relationship('Article')

class Article(db.Model):
    """Model for Article."""
    __tablename__ = 'article'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(255), nullable=False)
    description = db.Column(db.Text)
    image = db.Column(db.String(255))
    brand = db.Column(db.String(255), nullable=False)
    category_id = db.Column(db.Integer, db.ForeignKey("category.id"), nullable=False)
    prices = relationship("ArticlePrice", cascade="all, delete-orphan")
#

You have it all here guess

#

Does that clear it up ? =x

deep cave
#

yes, gimme a minute to read.

#

right. but you wanted bidirectional relationships, right?

#

so in the documentation you linked, they show an example using back_populates

#

did you try that?

#

there's also no use of secondary

signal karma
#

not really. I have a table of articles to show it in the store. I have a list a requests to which are attached articles, and here I need the article details.

deep cave
#

and I'm not sure, but something tells me that perhaps the variable names child, children and parents are not arbitrary but may infact be required to tell the classes about the relationships

signal karma
#

But articles themselves do not need to know which request they are attached to, that's why I didn't write a backref

deep cave
#

aha

#

okay

signal karma
#

I use the secondary to avoid returning the request_article table(when I request all Requests), I want the article full information, on the first level. But this way, I miss the extra data =/

deep cave
#

yeah

#

but

signal karma
#

That's why I had a lambda in the first place, I wanted the article info not just its id(from request_articles).

deep cave
#

I mean in the docs, they basically handle all that stuff after the def, but you sound like you want to just map the property of the one class to the other.

#

I mean, the value of this association stuff is in this code example

#
# iterate through child objects via association, including association
# attributes
for assoc in p.children:
    print(assoc.extra_data)
    print(assoc.child)
signal karma
#

And I would like to have these two merged

#

on return

#

Maybe it is not possible =x

#

But I am a front-end dev originally, and I'd ask to my backend dev to return it as such.

deep cave
#

it's probably possible - but I'm not sure I understand why

#

if you have these relationships intact, you have access to everything

#

why do you need to merge everything

signal karma
#

Because I want to treat it as one thing, not as extra and original data

deep cave
#

I get that but you can still merge those two things before you return them to the API caller

signal karma
#

this is back end logic, the client should not have to be aware of what is extra

deep cave
#

the problem is that you're trying to do that in the ORM class definitions.

#

that's not necessary

signal karma
#

Maybe I should...

#

I was worried of treating all the records before return the values, but I should use paging anyways...

#

I wanted it to be automated from there ๐Ÿ˜

deep cave
#

again - you can just make a function, feed it both of the datas, merge them in the function and return the merged dataset, and then feed that function to attribute

#

just to keep it simple.

signal karma
#

feed that function to attribute?

#

you mean using the lambda?

deep cave
#

yeah, like you're doing with the lambdas

signal karma
#

okok

#

sounds fine

deep cave
#
def merge_data(data1, data2):
    return data1 + data2  # it's probably not this easy but I'll let you figure this part out

# ...
'price': fields.Float(required=True, attribute=merge_data(data, extra_data)),
#

something like that

#

not quite like that, probably, but you get the idea.

signal karma
#

I do. Okok

#

I'll try that, thanks a ton ! ๐Ÿ˜‰

deep cave
#

I've never really worked with flask-restful, and I almost never use sqlalchemy either so this may not be the optimal or intended solution

#

but I think it'll work, and really, that's the important part.

signal karma
#

seems close to what I had, I got lost over trying I guess

deep cave
#

I usually just handle the SQL and the RESTfulness manually

#

maybe I'm old school

signal karma
#

haha

deep cave
#

@brittle copper I guess it looks healthy, but it desperately needs blocks and comments for readability.

#

it looks cramped, currently.

brittle copper
#

Nice, I was worried about the length because I read something like don't write too long view function; if the only problem is that it lacks comment, I can always add some :D

deep cave
#

blank lines and comments. yeah. it'll be longer, but it will be split into chunks which will make it far more readable.

#

right now it does look long

#

but only because the whole thing is just one big chunk

#

it's kinda like writing a normal english article or something, you need paragraphs, headlines, subheaders. nobody wants to read a wall of text.

brittle copper
#

I tried to follow pep8

native tide
#
โœจ Level Up!! โœจ

Someone just got to Level 2 - Memer Rank 1

deep cave
#

PEP8 says something like "use blank lines (sparingly) to indicate logical sections inside functions"

brittle copper
#

Hmm, PyCharm didn't warn me, damn :D

deep cave
#

it also has a section on block comments

#
# this is where the fudge gets made
go_around_corner()
for step in factory.road:
    take_step(step)
fudge = make_fudge()

# reformat and return
refudgify(fudge)
return fudge
#

this kind of thing is great for readability

#

although just make sure your block comments aren't too obvious

#

I probably wouldn't have written that last one

#

the point of the comments is to let the reader skim your code

#

and see what a section of code does without having to read any code

brittle copper
#

Yeah should add comments, some does look like as if it doesn't make sense without any context

deep cave
#

and lastly - pycharm is great for helping you maintain your PEP8 compatability

#

but

#

PEP8 is short

#

read it

#

at some point, at least, in your python career

brittle copper
#

My 30 days of python carrier xD

deep cave
#

you don't have to read it today, but it's quite pleasant reading

#

it's not too bogged down in technicalities

#

gives plenty of examples

#

and a lot of the stuff in there is just really smart stuff you can apply to any language

#

python is, after all, quite famous for its emphasis on readability and ease of use

#

and PEP8 is one of the reasons it has earned that reputation

#

it's a honking good document

brittle copper
#

Alright I'm on a train rn so I have nothing better to read :D

deep cave
#

cool

brittle copper
#

And thanks again

deep cave
#

no problem.

signal karma
#

I receive this error : TypeError: int() argument must be a string, a bytes-like object or a number, not 'Integer'
sending this:

{
  "id": 2,
  "articles": [{ "id": 1, "quantity": 2, "state_id": 2 }, { "id": 1, "quantity": 1, "state_id": 3 }]
}

with this python:

request = namespace.model('Request', {
    'id': fields.Integer(required=True),
    'by_user_id': fields.Integer(required=True),
    'for_user_id': fields.Integer(required=True),
    'reason': fields.String(required=True),
    'location_id': fields.Integer(required=True),
    'articles': fields.List(fields.Nested(cart_article)),
})

@namespace.route('/')
class RequestsListAPI(SecuredResource):
    """Requests REST end points"""

    @namespace.expect(request)
    @namespace.marshal_with(request_full)
    def put(self):
        parser = reqparse.RequestParser()
        parser.add_argument('id', required=True, type=int)
        parser.add_argument('articles', required=True, type=cart_article, action='append')
        args = parser.parse_args()

I have no idea where is comes from, I send only ints and it says it should be a string... my model only takes integers too... Note I get this error even commenting the whole function. I guess it must come from the @expect.

brave mantle
#

It should give you the exact line with the problem.

#

...

signal karma
#

too long ๐Ÿ˜›

#

wait

brave mantle
#

Well, look at the traceback yourself then

#

You should see the file you wrote code in somewhere

signal karma
#

it is the lib --

brave mantle
#

It'll give you the exact line

signal karma
#
File "C:\HOMEWARE\Anaconda3-Windows-x86_64\lib\site-packages\flask_restplus\fields.py", line 394, in format
    return int(value)
#

last log

brave mantle
#

No, it's probably not the lib

#

Read more of the traceback

signal karma
#

I did

#

obviously

#

since I am asking

brave mantle
#

Most people don't know how to read a traceback here :P

signal karma
#

it doesn't make sense since as I said my model takes int and I send ints.

brave mantle
#

I think I can easily wager what the problem is

signal karma
#

I guess it makes one more

brave mantle
#

But I don't have the full traceback

signal karma
#

but if the error was clear in the first place...

brave mantle
#

No, I think it's pretty clear

deep cave
#

just post the full traceback already

#

:P

brave mantle
#

You're doing type=int in one of your calls to add_argument

signal karma
brave mantle
#

That's my first guess

signal karma
#

there

#

ok

#

I'm not

#

just on the id, right

brave mantle
#

OK, you have a decorator of your own there, are you sure that decorator is correct?

signal karma
#

nop, comes from Flask-Restplus

#

similar to Flask-Restful actually

brave mantle
#

No, app/core/decorators.py

signal karma
#

uh

brave mantle
#

It's in the traceback

signal karma
#

๐Ÿ˜ฌ

brave mantle
deep cave
#

nice

#

I like that one

#

almost worth getting nitro over

brave mantle
#

So yeah that's your first stop, check that decorator

#

@deep cave ablobaww

signal karma
#

Actually it's not my code, worked well so far, I don't even know what it does exactly =/

brave mantle
#

You're using it though

signal karma
#

yep

brave mantle
#

Read the code, that might help you figure out what it does :P

signal karma
#

yep will do thanks ;P

#

It is supposed to check authorization, that's all I know

#

it should not touch the data

#

and it doesn't

#

even all the operations inside the function works fine, I just get an "Internal Server Error" on the client side

brittle copper
#

Try deleting the last bits of codes that gave the error and try another approach for the same thing you are trying to do maybe? @signal karma

deep cave
#

there's always an error associated with one of those internal server errors

#

set up logging for flask and check the log file, you'll see something

signal karma
#

my bad, it came from the returned value kms

#

feeling stupid

brittle copper
#

Guys, how do we change BooleanField in django?

#

Class.objects.get(pk=165).bool_fiel = False doesn't seem to work

#

And yes I do save it afterwards

#

I've tried ^= False and = not Class.objects.get(pk=165).bool_fiel too

deep cave
#

why are you trying to do that

#

it's a field, you're supposed to spit it out into a form. it represents the field. like.. a checkbox. it's not a boolean.

#

it doesn't really have a value. it can have a default value. the form is what has the value, after the user submits it.

brittle copper
#

I can change every other field without needing a form, why can't I do it with this?

deep cave
#

but why would you want to

#

I feel like you're using form fields in a weird way if you're changing them

brittle copper
#
def togglevis(request, entry_pk):
    referer = request.META.get('HTTP_REFERER')
    if User.objects.get(username=request.user.get_username()) == Entry.objects.get(pk=entry_pk).entry_author:
        Entry.objects.get(pk=entry_pk).entry_readability ^= False
        Entry.objects.get(pk=entry_pk).save()
        return HttpResponseRedirect(referer)
    else:
        raise Http404```
#

Form fields? I'm talking about model fields

#

class Entry(models.Model):

    entry_title = models.ForeignKey(Title, on_delete=models.CASCADE)
    entry_text = models.CharField(max_length=2500, null=True, blank=True)
    entry_author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    entry_date = models.CharField(max_length=20, null=True, blank=True)
    entry_points = models.IntegerField(default=0, null=True, blank=True)
    entry_readability = models.BooleanField(default=True)

    def __str__(self):
        return self.entry_text```
deep cave
#

right, that makes more sense.

brittle copper
#

:D

deep cave
#

(they're both called BooleanField, fucking django)

brittle copper
#

Damn

deep cave
#

btw I hate django

#

right so you're really trying to change entry_readability in this case?

brittle copper
#

After python @register.filter(name="replacer") def messagetolink(text): split = text.split('`') even, odd = split[0::2], split[1::2] return format_html_join('', '{}<a href="' + site_name + '{}">{}</a>', ((a, ("_".join(b.split())), b) for a, b in itertools.zip_longest(even, odd, fillvalue=''))) I hate it too

#

Exactly

deep cave
#

oh god, that's hideous.

brittle copper
#

There is no way to make a string permanently safe apparently

#

Soo, @deep cave how can I toggle the readability?

mild bridge
#

my eyes!

deep cave
#

I'm not really sure. what you were doing (the =, not the ^=) should have worked.

brittle copper
#

Do it better if you can @mild bridge xD

#

Damn

deep cave
#

that's how I would have done it, anyway

#

but.. uh.. you can specify the optional arguments in the .save() method maybe

#

iunno if it will help but it's a thing to try

brittle copper
#

wdym

deep cave
#

you can do like

Entry.objects.get(pk=entry_pk).entry_readability = False
Entry.objects.get(pk=entry_pk).save(['entry_readability'])
#

and see if it likes that better

brittle copper
#

Lemme try

deep cave
#

it shouldn't matter, but

#

I think it does an UPDATE instead of an INSERT when you specify

#

there's a force_update keyword argument you can do, too

#

it's possible your save is doing INSERTs instead and creating new rows

#

but you want to update existing rows

brittle copper
deep cave
#

lol, I guess it inserted a duplicate

brave mantle
#

so much for that ORM

#

lol

deep cave
#

naw, just remove the duplicate manually

brave mantle
#

The DB should have rejected it

deep cave
#

and try again but this time with the force_update keyword argument

#

and yeah the DB should have rejected it. :/

#

again - did I mention I hated django?

brave mantle
#

I thought you liked django

#

lol

deep cave
#

no. I like flask.

brave mantle
#

Fair do's

deep cave
#

I used django as my first ever webframework

#

so I kinda know it a little bit

#

but it was a pain in the ass

#

discovering flask was like a religious experience after having worked with django

brave mantle
#

You had to tithe a third of your wealth to get it working?

#

:P

deep cave
#

sadly I still have to maintain a few django apps

brittle copper
#

Still does exactly nothing

#

I mean it doesn't even give an error

#

Just nothing

deep cave
#

you removed the duplicate and tried with force_update?

brittle copper
#

Yeah

deep cave
#

hm.

#

well

brittle copper
#

When I toggle it from admin panel it works as expected, the posts doesn't show up in their link but I can't do it from a damn view

deep cave
#

have you made sure that your Entry.objects.get(pk=entry_pk) actually gets an object that you can use?

brittle copper
#

I have another view with url www.webpage.com/entry/entry_pk which shows the related entry

deep cave
#

right.

#

try this thing again but this time specify the argument name

#
Entry.objects.get(pk=entry_pk).entry_readability = False
Entry.objects.get(pk=entry_pk).save(update_fields=['entry_readability'])
#

cause.. I can't find the .save documentation so I'm not really sure about the order, can't confirm if update_fields is actually the first positional

brittle copper
#

Yeah this doesn't work either

#

I'm just gonna use CharField as BooleanField by giving it either 1 or 0

#

Thank you for your help anyway :D

deep cave
#

I mean, if it works from the admin panel I suppose you could just try to figure out how it's done there

#

the admin panel is after all just code in your project

#

but.. yeah I guess a charfield will do the job

#

I've done worse hacks in my own django projects :(

#

and to be clear - I'm sure if you go on freenode #django and ask, they'll tell you that there's a perfectly reasonable justification for this behavior

#

and that if you only do this and this and this and this it will work fine

#

because that's django in a nutshell

#

but I'm afraid I'm too shit at django to tell you what it is.

brittle copper
#
def togglevis(request, entry_pk):
    referer = request.META.get('HTTP_REFERER')
    entry =  Entry.objects.get(pk=entry_pk)
    if User.objects.get(username=request.user.get_username()) == Entry.objects.get(pk=entry_pk).entry_author:
        entry.entry_readability = False
        entry.save()
        return HttpResponseRedirect(referer)
    else:
        raise Http404```
deep cave
#

django to me is just chock full of these "why the fuck is it doing this" situations and then if you ask the django guys they're like "oh yeah that's a feature not a bug"

brittle copper
#

Apparently this works

deep cave
#

wait, how is that different

#

oh.. maybe because it's just one get

#

instead of two!

#

maybe by getting it twice you're undoing your previous changes

brave mantle
#

Thread-local object cache

#

ooh boy

brittle copper
#

Apparently my former try was getting the object second time before saving it

brave mantle
#

that's pretty common, though

deep cave
#

yeah, I guess it makes sense

brittle copper
#

Yeah, I can't believe I wasted 30 mins for this

deep cave
#

sure you can

brittle copper
#

I just didn't want to assign the object to a variable since I wasn't gonna use it again and again

deep cave
#

30 minutes isn't even that bad

brittle copper
#

Oh god I don't want to end up being a programmer xD

deep cave
#

you're already a programmer

brittle copper
#

Damn

deep cave
#

cause it's friday night and you just spent half an hour on a django problem.

brittle copper
#

But the hardest thing I've ever done so far was python @register.filter(name="replacer") def messagetolink(text): split = text.split('`') even, odd = split[0::2], split[1::2] return format_html_join('', '{}<a href="' + site_name + '{}">{}</a>', ((a, ("_".join(b.split())), b) for a, b in itertools.zip_longest(even, odd, fillvalue='')))

#

This

deep cave
#

non programmers don't do that

brittle copper
#

And I didn't even do that, couldn't, someone else did it for me

deep cave
#

well, that's almost ugly on purpose

brittle copper
#

How else can you do that?

deep cave
#

just do it with more lines of code, it'll immediately be cleaner and more readable.

#

but I have no idea what the hell it's doing

#

that return line is a clusterfuck though

brittle copper
#

Unless you return it in format_html_join() django automatically turns everything into escaped characters

deep cave
#

I wouldn't use that return line if I was writing code for my worst enemy

brittle copper
#

xD

#

I can tell you what I'm trying to do if you wanna give it a shot

deep cave
#

you can still return it in format_html_join(), just don't do everything on the same line

brittle copper
#

I mean I can't it just impossible for me