#web-development

2 messages · Page 71 of 1

tardy trellis
#

Though

coral raven
#

There are some things I do not understand like why don't they make seperate files for each part instead of refactoring

tardy trellis
#

@coral raven Because not all pages are the same

#

And it aint

#

Worth it

#

To repeat the same thing

#

Like the title

#

Of the page

#

The header

#

Is almost always the same

#

So why write it over and over again

coral raven
#

that only applies to templates right?

tardy trellis
#

Yes

#

Im talking about templates

coral raven
#

why don't they make separate files for models, views, routes etc and wait till the file becomes large enough to maintain

#

in Corey's guide he refactored the code 2 times

tardy trellis
#

I mean when you import libraries or modules in python you are refactoring too,cause you are not writting those libraries from scratch

#

@coral raven Just to be mote organized

coral raven
#

In django there are specific files to place specific parts, which is good but there is no freedom

tardy trellis
#

Yeah thats the point of django

#

Its a framework

#

After all

#

Its not a library

#

Like flask

#

More or less

#

Also templates are kinda like views

#

And from what i saw in coreys code

#

He uses

#

A model

#

But the project is pretty small

#

So you dont really need

#

A bunch of models

#

And also the controllers are separated

#

But that seems to be a personal choice

#

Not a standard

#

Cause flask gives you more flexibility

#

On the way you separate your models views and controllers

bleak bobcat
#

I think you're confusing the enter/return key with the space/dot key

fickle saffron
#

Hi everyone
Which aws service can be used to deploy django backend with android app?

inland stirrup
#

you could use lightsail but be careful as they charge you for the storage space used in lightsail services but not for the lightsail service itself
(one of the many alternatives)

nova storm
#

@fickle saffron go for amazon lightsale bcz it's free

inland stirrup
#

coupled with elastic beanstalk

#

but be carefull you will be charged regardless of the plan you use (personal experience)

tardy trellis
#

@bleak bobcat What do you mean

minor horizon
#

Hello. I'm new to security with flask. I have a restful api server. For a basic authentication, I want to give my customer an access token that I want to return a response only who has a valid access token.

I can just create a random key, deliver it to my customer and say "when doing a request, send me the access token in it" and check if the incoming requests includes a token and is valid.

I want to do this in the right way but I don't know which way is elegant and not amateurish. Thank you for your advices

native tide
#

Hello. I'm new to security with flask. I have a restful api server. For a basic authentication, I want to give my customer an access token that I want to return a response only who has a valid access token.

I can just create a random key, deliver it to my customer and say "when doing a request, send me the access token in it" and check if the incoming requests includes a token and is valid.

I want to do this in the right way but I don't know which way is elegant and not amateurish. Thank you for your advices
@minor horizon Take a look at json web tokens (JWT)

minor horizon
#

Looking for it, thanks

bleak bobcat
#

@tardy trellis I mean that you don't need to press return every 3 words

dawn elk
#

Hi, anyone that has experience with React and Python? I have an <input type='file'> that passes its data (type is JS's formData) via an http request to my Python app. And I can't read/parse it. It shows up empty.
What's the best way to pass a file from React/JS and read it in Python? Maybe I'm not using the right format, or most probably I'm not reading it correctly

elfin mountain
#

@dawn elk what are you using for the backend?

dawn elk
#

python

elfin mountain
#

@dawn elk a web framework?

dawn elk
#

+asyncio but nothing like django or so

elfin mountain
#

@dawn elk how are you sending an http request to a python standard library?

#

Do you have a simple HTTP server setup in python?

dawn elk
#

From React I'm doing an http request using fetch.
On the Python side I am using WAMP and Crossbar

elfin mountain
#

@dawn elk Okay, do you have the ReactJS proxy feature setup?

#

You need to setup a proxy redirection from React to the python server.

dawn elk
#

I believe the aiohttp_cors I'm using from aiohttp does this

#

In the same fetch request I'm sending other data (JSON). That data is read just fine.

#

So the problem I believe is with the formData I'm sending

#
        const files = Array.from(e.target.files);
        const formData = new FormData();

        files.forEach((file, i) => {
            formData.append(i, file);
        });
        setImages(formData)

    };
#

This is on the React side the handler for onChange

#

And then I take the formData and pass it as an argument on the fetch POST request

#

OOh I just noticed:

                    variableX: variableX,
                    photo: images,
                }),```
#

This is the body of the request and I am JSON-stringify-ing it

#

Maybe that messes things up

elfin mountain
#

stringify-ing the file?

dawn elk
#

yeah I am also sending other data

#

so I 'forgot' that I am also sending a file

#

and I'm passing it alongside the other stringify-ied data, bad right?

#

So, inevitably I'll have to do 2 requests, correct?
One for the JSON data (stringyfied) and a separate one for the file

elfin mountain
#

Yeah, I would look to sending it as binary data

dawn elk
#

Or can I send 2 types of data in 1 request?

elfin mountain
#

you can send two types of data in 1

dawn elk
#

ok thx, I'll check that later

limber laurel
#

I want to add a delete button in flask, I am wondering is there a way I coyld use def delete(self): and send a delete requsst somehow when the button is pressed?

#

Or shpuld I use a post request redirecting to a delete page

crimson yarrow
#

anyone know how i can

#

create a pyplot plot

#

and dynamically display it

#

using jquery

#

in flask

native tide
#

I want to add a delete button in flask, I am wondering is there a way I coyld use def delete(self): and send a delete requsst somehow when the button is pressed?
@limber laurel You can make a delete request using AJAX, I don't think HTML forms support delete requests.
But it also can't hurt to just as you said use a post to a delete endpoint

limber laurel
#

Alright, will look into it, could be a good learning experience as I havent worked with that or even JavaScript yet

#

Thank you

chrome scaffold
#

I am following Tech with Tim's flask tutorial, and he is doing this

#
@app.route('/admin')
def admin():
    return redirect(url_for("home"))```
#

But I found out that this works py @app.route('/admin') def admin(): return redirect('/')

elfin mountain
chrome scaffold
#

What's the difference between the two and why would I use one over the other?

elfin mountain
#

@chrome scaffold where do you want to direct the user?

#

those may possibly direct the user to two different locations

chrome scaffold
#

The home /

#

I am just asking about if there is a time in which I want to use one over the other

limber laurel
#

url_for seems more dynamic

elfin mountain
#

One creates the endpoint based on function name and the other expects an endpoint

limber laurel
#

If you end up changing uo the routes as you scale your project

elfin mountain
#

@limber laurel Is correct, url_for is more dynamic.

chrome scaffold
#

Oh so if I then change the route for the page I don't have to change it in more than 1 place

elfin mountain
#

Unless you change function name.

chrome scaffold
#

Yeah

#

thanks @elfin mountain @limber laurel

elfin mountain
#

👍

lapis stratus
#

Hi

#

I'm wandering if I can do Django even though I'm not good enough in JS

cold anchor
#

totally, JS isn't required to create a site with Django

modest scaffold
#

hi im using an old book to learn some basics of django

#

and in one example we try to get a digit of the url using this code path('time/plus/(\d{1,2})/'

#

the book is a bit old so it looks like this url(r'^time/plus/(d{1,2})/$'

#

do i still need the caret or dollar sign and im assuming i dont need to say its a raw string

vernal finch
#

@native tide would appreciate if you added me

native tide
#

@modest scaffold is this for a class? If the book isn't required for something else, I'd honestly recommend the docs/tutorial. If you have to use the book, check the beginning for which version is used and them look up urls.py in the docs, hover the bottom right-hand corner, and change the docs to your version

#

The Django docs are so good you can pretty much get away without a book for a while, then pick up two scoops of Django for the latest version

faint abyss
#

Hi! Can you help me in Django?
So I'm creating a DetailView, but what if I'd like to use a username instead of pk?
Is it OK, if I just simply use <username> in my url
and pass these two attributes to my UserDetaulView class?

    slug_url_kwarg = 'username'```
quasi hawk
#

Can you use html templating in a github page?

modest scaffold
#

@native tide k thanks

native tide
#

is sqlite3 your database backend?

limber hemlock
#

Hoy, is there a library for using google forms? To simplify Form creation etc...

modest scaffold
#

Doesn't sound likely mabye you can make it!

lapis stratus
#

totally, JS isn't required to create a site with Django
@cold anchor Only HTML and CSS?

viral sphinx
#

Hey guys what is docker, and is it useful for all applications???

cold anchor
#

even css isn't really required, but html is definitely required

#

you'll need css if you want it to look nice

terse surge
#

in forms

#

u dont need html

#

tbh

#

u just do {{ form }}

#

and ur done

#

but

#

html is required

#

ur not writing it

#

but django is

quick cargo
#

idek why people dislike writing forms tbh

#

Like i dont find them that bad to write out manually and it makes it easier in places for stuff like css

solar crag
#

sup guys, any1 available for questions?

quick cargo
#

!ask

lavish prismBOT
#

Asking good questions will yield a much higher chance of a quick response:

• Don't ask to ask your question, just go ahead and tell us your problem.
• Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving.
• Be patient while we're helping you.

You can find a much more detailed explanation on our website.

solar crag
#

i want to build a website for myself, but dont want to pay like 20$ a month to one of those sites like wix or whatever

#

if i build it myself, will it be cheaper in the end ?

quick cargo
#

oh yeah

#

massively cheaper in the long run

#

and short tbh

#

and you learn a new skill

solar crag
#

do I only have to pay for the domain?

quick cargo
#

and hosting

#

but hosting is dirty cheap for small websites

solar crag
#

what are hosting prices like?

cold anchor
#

it also depends on how you want to spend your time, if you want to build a site that's a pretty www.mysite.com page, then yeah do it yourself

solar crag
#

i saw domains for like 1$ a year ? lol

quick cargo
#

yeah domains are pretty cheap

#

tho they depend but normally cheap

cold anchor
#

$12/yr usually

quick cargo
#

hosting can easily be < 5$ a month

solar crag
#

I see

quick cargo
#

i dont think it would be that bad

#

other than oof that site is http

solar crag
#

well i always bought my domains at godaddy, i think they were like 0.99$ for first year

cold anchor
#

very simple, I saw something like that for a site I wanted and just copied it

quick cargo
#

go daddy say theyre 0.99 for the first year

solar crag
#

very simple, I saw something like that for a site I wanted and just copied it
@cold anchor you can just copy ? lol

quick cargo
#

but they're very expensive on domains

#

and hosting tho idk their exact amounts

cold anchor
#

yeah, right click > view page source

solar crag
#

i wonder if i can just buy it for a year, cancel the subscription, and after i dont have it anymore, buy it again for 0.99 after the 12 months

cold anchor
#

lol I don't think so

solar crag
cold anchor
#

they keep a record of the domains you bought and won't offer it for the same price again

solar crag
#

new acc :p

cold anchor
#

most domain sellers put a parking page on the domain for a while after it expires so they can hold it in case somebody wants to buy it and they can sell it at a higher rate

quick cargo
#

its not hard to pickup tho overall

solar crag
#

the duck

#

looks so good

#

you did all by urself?

quick cargo
#

mhmm

#

css and html isnt that bad once you find a system which you like

solar crag
#

do i only have to learn css to be able to do that?

quick cargo
#

I did that entire site without writing any css lol

solar crag
#

i literally just know a bit of python

#

thats all i know about programming

quick cargo
#

html isnt that bad to learn and you can pick it up quickly

solar crag
#

idk what a framework even is

quick cargo
#

a css framework (I personally prefer Tailwind but things like bulma also exist) makes it so you dont need to write any css really

#

its all done with the class names

#

so rather than some massive css block to make a flex box the moves everything center

#

in the html's class

#

you can just do something like flex justify-center

solar crag
#

may I ask what the total cost of that website of yours is /month ?

quick cargo
#

That site costs me maybe 2$ a month or lesss

solar crag
#

nani

quick cargo
#

but the domain is free and its ran on the side of a bigger site

cold anchor
#

I feel like css is easy enough to not have to use a framework even

solar crag
#

teach me the magic pls

#

O:

quick cargo
#

The actual cost of hosting on my servers is > 150$ a month

#

but thats because they're much bigger systems

solar crag
#

i dont really know much about this tbh

#

all this hosting stuff and so on

#

but

#

can you tell me where i should start now?

cold anchor
#

heroku free tier

solar crag
#

like, I know that things like ( domains , framework, hosting, css, html ) exist now, but dont really know what to do with that knowledge

quick cargo
#

Id say have a look at flask for the backend (if you need the site to be dynamic not static)
as for css look at some css frameworks it might make your life easier
and yeah as for host, heroku do a free tier but its not 24/7

cold anchor
#

very easy to set up, and cheap to scale to something worthwhile

solar crag
#

how should I start now?

quick cargo
#

have you worked with a backend framework like flask before?

solar crag
#

i literally just know a bit of python
@solar crag 😄

#

i was serious when writing that lol

quick cargo
#

then let me introduce you to the main man Corey!

#

He does an amazing series on using python to create a dynamic website and goes through everything like deployment etc...

solar crag
#

thanks! i will start there

terse surge
#

idek why people dislike writing forms tbh
I love making them but i cant really design anything good... i have css and html knowledge but the idea doesnt come

cold anchor
#

sign up for a bunch of products and see how they do forms

terse surge
#

but now im a backend dev and i have a frontend dev so no need to..

cold anchor
#

look especially at their use of spacing, color (to highlight), font changes (between labels, helptext, titles, etc.) and animations

#

just a suggestion ¯_(ツ)_/¯

terse surge
#

ty tho

#

for the suggestion

cold anchor
proper hinge
#

I relate to that intro

solar crag
#

how long did it take you to learn css and html?

pulsar ivy
#

How can i know if site is secure enough??

#

Oh and yes hoe can i create table in flask???

#

many to many relationship

native tide
#

can anyone explain url_for? ping if you know

oblique jungle
#

@native tide i been writing a shit ton of flask so I could help

native tide
#

what does url_for do exactly?

oblique jungle
#

anyone got any thoughts on celery vs rq vs flask_executor for job management?

#

you can read it there

#

but the gist of it is that it takes the __name__ of your function, looks it up in a look-up table that gets created when you annotate with @app.route, and returns the URL for it

#

anyone got any thoughts on celery vs rq vs flask_executor for job management?
anyway though, i really am stuck at a crossroads

#

in rails I'd just be using whenever

pulsar ivy
#

U should do it with js @native tide

native tide
#

can't you just do?
<a href="github.com" class="github">See code? </a>

oblique jungle
#

you can!

#

but @native tide if you do something like <a href="/path_on_my_site"> then you change the endpoint for /path_on_my_site, you'd want your links to update

#

and that's where url_for comes in

pulsar ivy
#

Well flaks is backend, if you want real time clock u should do it in js

native tide
#

ok thanks

pulsar ivy
#

Yeah, but its not that hard, basically typing in yt how to make clock in js eill drop you tutorial for that

cold anchor
#

@oblique jungle I researched them all a few years back and liked the community and flexibility of celery best

#

and I have a personal preference of using SQS as the message broker, but if you use redis you get a nice admin console

solar crag
#

does anyone here know about google sites for creating websites?

native tide
#

Hi i had a question. Where can I learn basic Web development

proper hinge
#

We have some resources on web development recommended on our website

#

!resources

lavish prismBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

open tinsel
#

Why are figures normally rendered as indented?

Test this sample with image.png in same folder:

<p>Normal paragraph</p>
<figure>
<img src="image.png" title="Captioned figure" />
<figcaption>Captioned figure</figcaption>
</figure>
dawn elk
#

Continuing from my question about how to receive/handle formData sent from a React/JS app into Python. I still can't figure out how to parse the data (it's a file).

#

I'm sending the data from React like so:

  const formData = new FormData();

        files.forEach((file, i) => {
            formData.append(i, file);
        });

        setImages(files);
fetch(url, {
                method: "POST",
                mode: "cors",
                cache: "no-cache",
                body: images,```
#

On the Python side, I'm logging the payload to my console and the output looks like this:
<Request POST /url >

#

I can't find a way to parse/get the actual data.

#

Anyone?

celest lynx
dawn elk
#

@celest lynx is this about my question?

celest lynx
#

no sorry

dawn elk
#

I'm not using Django or any other framework

bleak bobcat
#

Then without more information about your python code we can't do anything

dawn elk
#

Tell me what info you need

bleak bobcat
#

How do you handle the http requests ?

dawn elk
#

Here's the part that handles the request:

    async def handle_method(cls, payload):
    logger.info(payload) # logs <Request POST /url >
        ```
#

And I want to access the actual file somehow

bleak bobcat
#

What's your webserver ?

dawn elk
#

WAMP & Crossbar router

bleak bobcat
gentle oracle
#

Hi All, just a quick question - does db.session.commit() | db.session.flush() |db.session.rollback() closes the session ?
or do we need to explicitly write db.session.close() to close the session ?

sullen roost
#

So I'm writing some inventory management but I've hit a bit of a roadblock.
I'm using Django and I have my shelving units defined, but the problem is that I have similar items that exist in multiple locations in varying quantities so I'm trying to figure out the best way to represent this.

#

Ideally something akin to

location = {
  binA: 3,
  binB: 2,
  binC: 5
}
#

Hrm. I guess I can have the master item model, then physical item models that point to that master item model and a bin.

open tinsel
bleak bobcat
#

Browser default styling

#

Example for chrome :

figure {
    display: block;
    margin-block-start: 1em;
    margin-block-end: 1em;
    margin-inline-start: 40px;
    margin-inline-end: 40px;
}
open tinsel
#

Where is that css?

#

Is it possible to define a figure css block that just ignores the default figure block and formats the code like it had never been defined?

bleak bobcat
#

Where is that css?
@open tinsel As I said, browser default styling. It's defined by your browser.

open tinsel
#

Just wondering how I find it.

#

for any browser
https://github.com/flywire/caption/issues/3#issuecomment-660056171

bleak bobcat
#

I have no idea and it doesn't matter. it's different for every browser, and even if you change it inside your browser it will not change inside the browser of other people

open tinsel
#

so it seems I need to define it if I'm not happy with it for others to use

bleak bobcat
#

yes

open tinsel
#

thanks

bleak bobcat
#

Just like you need to define the font-size of h1, h2 etc... if you're not happy with their default size

#

Same thing

open tinsel
#

I'm trying to do minimal but I can't live with indented figures - I'm using them for other things

misty creek
#

Hello Everyone,
Can any one guide me regarding Django. I want to know the repositories to follow on github to understand the application structure of django and how its flow in larger code base

sonic ferry
late stone
#

hi, anyone familiar with selenium web driver ?

#
  File "/Users/user/Desktop/employee_env/lib/python3.7/site-packages/selenium/webdriver/common/service.py", line 76, in start
    stdin=PIPE)
  File "/Users/user/opt/anaconda3/lib/python3.7/subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "/Users/user/opt/anaconda3/lib/python3.7/subprocess.py", line 1522, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'chromedriver.exe': 'chromedriver.exe'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "supreme.py", line 35, in <module>
    go = SupremeCheckOut(keys)
  File "supreme.py", line 11, in __init__
    self.driver = webdriver.Chrome("chromedriver.exe")
  File "/Users/angelmoreta/Desktop/employee_env/lib/python3.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 73, in __init__
    self.service.start()
  File "/Users/angelmoreta/Desktop/employee_env/lib/python3.7/site-packages/selenium/webdriver/common/service.py", line 83, in start
    os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'chromedriver.exe' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home```
#

i am getting this error, but thats weird because i have the chromedriver in the same directory, please help

dapper tusk
#

It needs to be in path, not in the same directory. You could programmatically add the directory of the file to path with

from pathlib import Path
import sys
sys.path.append(Path(__file__).parent)```
late stone
#

i was able to get around this issue by installing a webdriver manager

#

thank you for gettin back to me, appreciate it

native tide
#

i can't seem to change something in visual code studio i'm trying to make a website
if you want to help ping me

twilit zenith
#

what is that thing you want to change

mint tangle
#

Hi.
Is this the right place for a stackoverflow link related to a Django issue?

bitter patrol
green flume
#

Hey guys! I have a problem where I got this error NameError: name 'person' is not defined , my code is basically this ```js

if minha == 0:
person = 'PEDRA'
print(person)```

normal sigil
#

minha is probably not equal to 0

sullen roost
#

@green flume You need to define person right above that conditional. I'd suggest None and some additional logic to handle if minha is not equal to 0

green flume
#

ah, i forgot the int

#

It was really that

mint tangle
#

If it's long and advanced, maybe #❓|how-to-get-help is more appropriate
@bitter patrol It's definitely advanced. Zero code, basically a theoretical question you can say.

dapper tusk
#

Do not define person above the if, just make sure you give it a value in all cases

mint tangle
dapper tusk
#

Maybe a separate DB for users and a separate one for django stuff. Though you don't get the orm then

quick cargo
#

actually i believe you do

#

django is able to support multiple databases at once

mint tangle
#

That's a nice idea but I'll still need to restart the server after making migrations

quick cargo
#

thats because of how django works with its ORM as a fundamental in that case

#

so lakmatiol would be right in saying no orm

dapper tusk
#

Well, my idea was to not use django at all for the second db and just manage it separately. There may be a way using django though

quick cargo
#

sadly not hot reloading for django

mint tangle
#

But in the end, I'll use the forms via Django. So even if I use something else for updating the DB, I'll still need Django to recognize the changes.

Basically, (I know it's sketchy) I'll modify the models.py and makemigrations from there.

#

Actually, is there a way to have Django as the backend and another framework or something as the front end.

#

So even if Django is reloading, the frontend still serves the webpage

twilit zenith
#

yes

#

kind of

mint tangle
#

Or maybe there's no point in using Django at all. Just switching to another framework

dapper tusk
#

Well, you could just serve static files from a non-django route and.load all django data through JS, so when django would be restating, there would just be loading. But you lose templates then.for.quite a few things

mint tangle
#

Oh?

twilit zenith
#

look into django rest framework

#

but you can't serve forms

mint tangle
#

look into django rest framework
@twilit zenith Already using them.

twilit zenith
#

which FE framework are you using?

mint tangle
#

But then it would be twice as much workload. Basically managing two servers at this point. This was the first idea that came to mind

#

which FE framework are you using?
@twilit zenith Not using one yet. I was hoping you guys could suggest one.

twilit zenith
#

yeah, its very time consuming

#

i use Vue.js and Django rest

#

its kind of hard switching between 2 languages

mint tangle
#

i use Vue.js and Django rest
@twilit zenith oh? Doesn't Vue run separately than Django?

twilit zenith
#

you can use CDN to run it within django templates

#

or CLI (which runs seperately

#

i use CLI

mint tangle
#

Oh.

twilit zenith
#

cuz i want to make single page app

mint tangle
#

I think using the CLI actually is the way to go.

#

Since you're using CLI, I'm guessing the Vue FE is a standalone and not dependant on Django. Which means even if Django reloads, you still have Vue front end running

#

Or am I getting this wrong?

twilit zenith
#

i think you are

#

Vue depends on Django API to send and receive data

mint tangle
#

Oh.

twilit zenith
#

vue can serve frontend, but no data will be displayed without API

mint tangle
#

I got an idea but I don't know if it will work.

Basically, host a separate server in using Node.js and Vue as front end and sends and recieves data through Django Channels.

#

This way, even if Django reloads, the we socket connection will be broken until Django is back online.

#

And while the socket connection is broken, I can just display like a waiting message using Vue

twilit zenith
#

ah idk

mint tangle
#

And everything works normal when Django is back online and Vue starts reccieving and sending data

twilit zenith
#

i don't get what you mean

native tide
#

what does it mean method not allowed?

quick cargo
#

you have diffrent http methods

#

like GET, POST, PUT, DELETE

#

if a method isnt allowed

#

it means youre trying to use a Method (GET, POST, etc...) that the endpoint has specified that you're not allowed todo

solar crag
#

can anyone recommend a good web dev udemy course?

native tide
#

ok thanks

regal timber
#

Thats kinda offtopic I guess but I don't know where to ask for this
I tried to install phantomjs and when I add the file to my %PATH% and echo it
It shows a "?" that I didn't type (checked 3 times)

unborn dawn
#

hello

#

please

#

can someone explain briefly what class Meta is in django?

#

I've been looked through so many resources but cant get it

late stone
#

@unborn dawn

ionic brook
#

Does anyone know how to run a python script from JS? I want to pass form inputs to a python script when the form is submitted.

bleak bobcat
#

Look into flask

tight rivet
#

I'm using Flask and I want to steam a numpy array and display it as a image in the browser (at 5 fps). I managed to achieve this using PIL to save the array into a buffer in PNG format, sending it to the client using a generator inside a direct Response (as a stream). However the method PIL.save is taking too long to save in the buffer. Is there a better method to stream a 2d numpy array as an image?

tight summit
dense slate
#

I ran a websocket server on my DO droplet and then was timed out of the terminal. I need to terminate the server but I can't find it in the ps or top lists to do so.

#

Is there another way?

cold anchor
#

are you sure it's running? how do you know it's running?

dense slate
#

It still allows me to connect to it in the client.

#

And if I try to run it again, the client acts as though it is interacting with older code.

#

As if it was the previous version.

#

Well, let me ask this: if I run "python server.py" am I looking for "server" in the list?

cold anchor
#

lsof -i:$PORT

#

will show you the processes listening on that port

#

you can get the pids from that

#

then you can kill $PID from there

static wind
#

anyone know if it's possible to use Jinja2 syntax inside a .css file

cold anchor
#

yup, totally possible

static wind
#

it's the same as you use it in normal html, right

#

might as well try it and see

cold anchor
#

you can do:

>>> from jinja2 import Template
>>> template = Template(open(cssfile, 'r+').read())
>>> template.render(name='John Doe')
static wind
#

yeah, i know, just wasn't sure if you could use it in css

#

oh

#

well i'm using flask as well

cold anchor
#

yup, it's very general

static wind
#

but i assume it's basically the same but with flask

cold anchor
#

eh, if you're using flask's static file serving, I don't think you can do it through that

#

you'll have to be serving the assets yourself

static wind
#

i'll give it a go

cold anchor
modest hazel
#

Hi guys, i'm just wondering how it's possible to do fingerprinting server side? I'm looking through fingerprintjs pro site: https://docs.fingerprintjs.com/pro/pro-vs-free and they say the fingerprint is never exposed in the browser. How is that possible? Doesn't a script need to be run locally to get a fingerprint?

Also, I guess in the same vein, how does stuff like google analytics/adwords and Facebook Pixel work? It's just a script tag on your website, how are they able to access user session data?

#

I'm just a noob btw, working on bot detection.

terse trail
#

Hello, I need some help, I was following a flask tutorial because im trying to learn, but i ran into a problem even though i copied the tutorial's code line for line and couldn't find a working solution anywhere

This is the python/flask code:

from flask import Flask render_template

app = Flask(__name__)

@app.route("/")
def home():
    return render_template("index.html")

if __name__ == "__main__":
    app.run(debug = True)

And this is the html file:

<!DOCTYPE html>
<html>
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        Hello World!
    </body>
</html>

This is the exact error code: "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."

rustic pebble
#

@terse trail you should be looking at the error in the python console and not the browser

terse trail
#

It doesn't output anything? @rustic pebble

minor topaz
#

@terse trail what they mean is that wherever you are running flask from (the console for example) should spit out the error

terse trail
#

it doesn't

minor topaz
#

I can see a missing comma here
from flask import Flask, render_template

terse trail
#

idk whats the problem

#

ty for pointing that out and i fixed it, but it still gives the same error and no errors in the console

vernal yacht
#

Hello everyone - does anyone know how to change your website's embed and how that appears across the internet? I am a beginner at web development and have no formal education so I'm not even sure if I'm asking the right question here. But I'd like to make my site's embed look a little nicer:

#

(also if this is the wrong place lmk)

frozen python
#

I’m been using React and Vue for a while and want to narrow down “need”, is learning Flask a good way to get familiar and learn Python?

frank nebula
#

Does anyone know how to deploy a django + celery app with just 2 docker containers? (heroku limit for free service)

native tide
#

@frozen python I can't say, I've been using django and it's primarly OOP / functions

frozen python
#

@native tide is Python narrowed down a bit compared to JS? JS, it’s integrated at time with HTML and CSS that can be “anything”, so I’m wanting to be more dedicated as a need

#

I like oop/functions in React/ JS

native tide
#

I learned HTML, CSS, and bootstrap to healp with design. I learned some JS as well and was unsure about what the pcross/difference woulb be like switching to python. With python and something like flash/django you still need HTML, CSS. You just use some logic in order to ulpload the pages and send people going to a url to a function that returns that html

#

It's way better to be honest, I got pretty burnt out making mock websites all the time. Also there isn't a lot of hard coding or anything. It's more using simple code for functional use to deliver webpages etc

#

and with something liek django it's just all made for you

frozen python
#

@native tide ok, but is it a little bit narrowed down to what your doing? HTML/css.... ok here’s a box, ohhhh I don’t like the size or color..:: the font isn’t what I want..... haha.
Ok 👍 I’m going to start with flask, or should I start with Django?

#

@native tide I like JS with creating objects in React/Vue. It’s kinda gets weird here and there with useState. But I like the interaction and functionality of things

native tide
#

Yeah it's not as wide of a skill set that you need to worry about. It's from start to finish the same sort of process with each project. It's primary URL to returning HTML. If you are full stack or solo then you would need to concern yourself with the design otherwise you don't. Also you make things called MODELS that represent THINGS on your website. It's like a class. You'll use those models to render it into your HTML pages. aside from that everything else is extra

#

with js and front end there's so many frameworks and things to learn man..

frozen python
#

@native tide is a model like a “component”?

#

@native tide so far, it seems like Py goes back to “vanilla” HTML, css.... your back to creating a HTML page for a template?, and other things

native tide
#

It's like a class. It represents something like a person etc

frozen python
#

@native tide like a def? Int?

native tide
#

I mean you don't have to create your html page with just html, css. you can use bootstrap or another framework with it

#

def?

frozen python
#

@native tide ok, I like React and Vue... are the objects similar to how you create things in them?

native tide
#

correct

frozen python
#

Ok, but how do you place things in python/flask? In React/Vue it’s “<Navbar />” “<Box />”

#

And it connects to the component page you made

native tide
#

I think you're talking about components you've made showing up on your html page? If so it's some code like this {{ some_code }} that you can write right into your html page

#

sry if that's not what you meant I've never used react/vue

#

language barrier

frozen python
#

Yes, components. But it’s not just HTML written on one page. React and vue, make it so there’s not a long list of code on a single page, it’s components that are brought in “represented “ to be placed on your page

native tide
#

Oh i see. I looked up a photo. Yeah It looks like there's some hard code in there or something. In django all that code is on a seperate file in your project. You integrate it by using variables that represent larger pieces of code in another file. you might write a for loop or something with a single variable or even multiple variables

frozen python
#

@native tide yes 👍 I looked up models and yes that’s what it looks like what I’m referencing to. So far
Person = {
‘Name’ : ‘Bob’
},

Is similar to a object in react/vue, then you have

<h1>{ this.name }</h1>

To use it

#

But also, in React/vue, with components there’s class/functional components, you can also define height, width, color.

@native tide

native tide
#

Oh I see. Yeah it's probably more design oriented

#

Come over to the dark side

frozen python
#

Hahaha

frozen python
#

@native tide “dictionaries” is what reminds me of objects in React, but models seem more like it

frozen python
#

@native tide should I even be thinking of Django like a front end/design? Or is that strictly made by a framework like bootstrap, vue, React?

frozen python
#

Jinja kinda seems redundant in python.... you can add things like that with React/vue, why use it from python?

cold anchor
#

server side rendering vs client side rendering

#

they present different solutions to the same problem, and end up giving you different sets of problems to worry about

frozen python
#

Ok 👍, Django and Flask, seem as if it’s a style framework in a way.

frozen python
#

HTML/CSS, it’s the structure and style.... then JS is the functionality....

What should I think of python/flask/Django as?

dark hare
#

@frozen python python is a language, flask is a micro web framework built using python, django is a web framework built in python, which has a lot more builtins and libraries available you to out of the box

frozen python
#

@dark hare ok, so when you create routes in flask, as in a navbar, what’s different than a front end to do that? Also, between objects/classes.... what’s the difference between flasks & React? Thank you!!

dark hare
#

I think you are trying to learn and take in too much stuff at once. I would reccomend understanding one thing at a time.

#

react and flask are frameworks for a certain purpose, react which is built using javascript, flask is python

frozen python
#

@dark hare so basically web vs desktop?? But that is, with info/data for a website to work?

dark hare
#

I would reccomend learning how the web works first, I dont know what you mean by web/desktop, there is client/server, browser/server, and I dont know what you mean by info/data

#

theres a part 2 as well i believe

native tide
#

I'm so lonely

#

I'll venmo anyone willing to talk to me

native tide
#

Hold on

#

Let me check

#

I don't know how that thing works @open tinsel sry

open tinsel
#

Don't worry about the python code, I'm only querying if the html/css is reasonable

tough star
heady bear
#

Hi, I'm starting to program with python for web, I ask for your guidance

blissful dome
#

guys what conecpts of web development are very important to know?

fair light
#

hello
i am beginner to flask and i get this error. i have installed everything correctly i guess but i get this error. anyone knows help. Ping me

heady bear
#

Tanks.

native tide
#

@fair light ```py
from flask import Flask

fair light
#

i did

#

oh wait

#

thanks

#

i used lower case

limber laurel
#

If I use the FormView mixin in Django, how can I pass in paranaters and a context?

quick cargo
#

@tough star if your just starting quart is good because it's basically async flask

#

Viboa is pretty dead

#

Hasn't been maintained for 2 years

#

Sanic is pretty good but lower level that quart and you'll find yourself doing custom middlewear more often but it's a framework I use that I enjoy a lot

#

Fast api is good for API type stuff but Ive never used so couldn't say

iron cliff
#

in a django project should I put settings.py file in gitignore?

bleak bobcat
#

no

rigid laurel
#

You should store any secrets somewhere else though. Environment variables for example

iron cliff
#

thank you

fair light
#

this is my login using oauth

#

and when it reaches login

#

it says

#

cannot GET /login

#

how to fix this

#

ping me

formal shell
#

Hey guys, I'm new here and a completely begginner with Django and Firebase. I have a real time chat application, created with js and Firebase. You need to be authenticated to use this chat, but I wanted to use the specific auth of my django project. I was thinking to make an OAuth from my django project to the chat, but I have no idea how to do it. If anyone could help me to sort this out or know a better alternative, it would help a lot!

eternal frigate
#

@fair light run flask in debug mode with app.run(debug=True) and check if there are errors logged to the console

fair light
#

@eternal frigate i did run like that and it showed no error in the console

eternal frigate
#

/ redirects to /login?

fair light
#

yes

#

it should be a html file or something?

eternal frigate
#

You tried to GET /login directly?

#

domain/login

fair light
#

like this

#

@eternal frigate

eternal frigate
#

Well I don't know flask, but if there is an error while accessing the url it should be logged by flask. Also it does not returns 404, right? It seems to be an error in the url routing

fair light
#

nop it does not return 404

eternal frigate
#

Create a new endpoint like /hello and return hello world to see if other urls works

fair light
#

when i change that 127.0.0.1:5500/login to 127.0.0.1:5500/botlist.html (one of my webpage) it redirects sucessfully

#

but as it returns , i cant see if does function proper or no

eternal frigate
#

Flask does not prints anything to the console?

fair light
#

just this

#

while running

eternal frigate
#

Try to get /login, it should log the http request

fair light
#

it says cannot GET /login and that was the error.... how do i get /login now

eternal frigate
#

That error message does not tells anything really, it should tell why

#

I have doubt if you are really running in debug mode

fair light
#

am i?

eternal frigate
fair light
#

..

eternal frigate
#
export FLASK_ENV=development
flask run

You did it?

fair light
#

no

#

if py is above 3.6 its not required to do i guess.. idk i found something like that somewhere

snow sierra
#

hello guys 🙂

i need this php code to python syntax .
<?php

$fname = array(1 => "scot", 2 => "john");
$lname = array("scot" => "smith", "john" => "doe");

echo $lname[$fname[1]];

?>

and want to publish frontend by jinja2(django3).. help me please

native tide
#

@snow sierra ```py
first_names = ['scot', 'john']
last_names = {'scot': 'smith', 'john': 'doe'}

print(last_names[first_names[1]])

#

Dictionaries are pretty much the equivalent to associative arrays

snow sierra
jade kelp
#

How can I add the appropriate escape sequences to a link? (i.e. hello world => hello%20world)

quick cargo
#

pretty sure urlib has a feature inbuilt todo that

jade kelp
#

@quick cargo Ok, thanks. I'll check it out.

fickle fox
#

guys do you know how to create table in flask???

glass sandal
#

wdym by "table"

#

You mean model?

native tide
fickle fox
#

@glass sandal i want to build table for many to many relationships but i am strugling a little with it xD

glass sandal
#

Can't u use HTML?

#

It works I guess

late stone
#

hi friend, so i found this template powered by boostrap 4 on the internet. Is it legal if i just go ahead and add it to my project ? sorry if my question sounded stupid but i am very new to web development and i am a terrible at the front end

#

i just want to know if its good programming practice to take others ppl work and add it to your project

velvet vale
#

0

I want change css. when i change continer height for oncklick function, after 1 second returns the same size, and when i have error console refresh in 1 second and i can't see. how fix? i turn off livereload plugin.It refreshes everything in 1 second.

#

please help me

native tide
#

does anyone know why i get an import error when i try to import setup_test_enviornment in a shell?

glass sandal
#

Circular import error?

native tide
#

ima check

#

the thing is i just started my shell tho

#

lol

#

im so dumb

#

i cant spell

glass sandal
#

Oof

native tide
#

imagine not being able to spel lol

sly vessel
#

Hello everyone. Can anyone tell me how to highlight the current tab using Dash/Plotly Bootstrap? I'm finding tutorials on how to do this in CSS, but not quite sure how to implement it in Dash

formal shell
#

Does anyone know if it's possible to authenticate in Firebase through django authentication? Thanks in advance

#

I would be kind of integrating both databases

faint abyss
#

Hi, I need some help in Django!
https://github.com/CoreyMSchafer/code_snippets/blob/master/Django_Blog/11-Pagination/django_project/blog/templates/blog/home.html

        {% if page_obj.number == num %}
          <a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a>
        {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
          <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a>
        {% endif %}
      {% endfor %}```
Can you, explain me the add -3, and 3 part?
I'm totally lost 😄
native tide
#

@faint abyss I guess it adds -3 to the current page number as well as adds 3 to create a range of page numbers for display, that are also clickable and will reroute you to that page by number

sly vessel
#

Anyone know how to manually resize a button/toggle switch/checkbox in dash/plotly?

#

This what I'm trying to do, but it doesn't change the size of the actual checkbox, it instead increases the size of the box that the widget is in

sly vessel
#

How about linking a custom CSS to individual components in dash?

hearty tendon
#

I am trying to build a News Feed Web-App. I have made a scrapper and set it on cron job. I am thinking about to use API to send the data to the APP so that it can use the data and display it. What should I use? DRF or Flask?

native tide
#

DRF?

proper hinge
#

Django Rest Framework

#

It's difficult to suggest one or the other without more info on the requirements your app has.

#

I tend to favour the simpler things if possible. In this case, that'd be Flask.

#

If you need to leverage some of Django's batteries-included features (like forms, ORM, etc) then use Django

#

If you wanted to write purely an API (so no rendering of web pages), then I'd suggest a "micro-framework" like Falcon @hearty tendon

native tide
#

hllo

hearty tendon
#

@proper hinge Thanks! Since this NewsFeed Web-App is simple. The Web-App starts with login page and once you are logged in then it displays the news title, description, etc. (It also has page numbers in the bottom to allow browsing through pages).

#

I have made the scrapper to yield JSON file so my next task is to use Flask API.

pliant moat
#

hi

lavish tundra
#

hello

remote ruin
#

hey is here anyone who uses the Django crash course book by greenfeld and can help me out for a sec? I'm traing to set up my cookie cutter project and then my anconda cmd said that i havent git installed, but i didnt skip any part so i'm confused and stuck

native tide
#

@remote ruin We can deff help you out with that.

#

Mr kimchi man

#

git --version if you're on mac

#

git --version

#

Oh wait

remote ruin
#

alright so do i do that in my normal windows 10 cmd?

#

no it's not installed

#

@native tide would you mind joining a vc with me?

native tide
#

my wifes laying next to me at the moment. I'm not too sure how it would be downloaded other than that though anyways

#

in terminal

#

I can tomorrow but I'd have to look into it. You use mac or windows?

remote ruin
#

i'm using windows 10

#

but hey thx, i will just look up a video

#

i appreciate your help

native tide
#

yeah shouldn't be too long. I'm on mac so it's slightly different commands

remote ruin
#

alright

remote ruin
#

i got it now ^^

limber laurel
#

In django, I want to add more items to my context in a DetailView, any ideas how I can do that?

limber laurel
#

Found it in a stackoverflow post, but thanks anyways. 🙂

native tide
#

Realtime updates of a value on a Django site.

#

Ideas?

formal shell
#

Does anyone know where I can find a good tutorial for a real time chat application, using django?

sinful stone
#

yo !

icy sparrow
#

or styling in general?

#

Looking it up gave me a result called crispy forms

#

pip install django-crispy-forms

remote ruin
#

can someone hop over to me in vc, i'm struggling a little bit with connecting postgreSQL with my django project

midnight needle
#

does vibora have a own discord server?

native tide
#

can someone hop over to me in vc, i'm struggling a little bit with connecting postgreSQL with my django project
@remote ruin do you have psycopg2 installed?

#
users = People.query.all()

for user in users:
    print user.name

@sinful stone That's because sqlalchemy is an ORM, you could communicate using sql directly without using sqlalchemy but the communication protocol of your database vendor

#

You can change the attributes of the form's html elements through widgets

minor horizon
#

Hey guys. In request.authorization from flask, is it possible to except from request headers include a "organization" and"password" pair instead of "username" "password"? So I can get the organization name with

auth = request.authorization
print(auth.organization)
midnight needle
#

how can i set my stylesheet with flask?

sly vessel
#

I actually have a smiliar question, except with Dash (which is based off Flask I believe)

lavish prismBOT
#

Hey @sly vessel!

It looks like you tried to attach file type(s) that we do not allow (.css). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .m4v, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg.

Feel free to ask in #community-meta if you think this is a mistake.

sly vessel
#

How would I reference this in my Dash app for a bootstrap toggle switch component?

midnight needle
#

how do you load css file?

#

i dont know how to

sly vessel
#

I've tried setting "className" to every one of those classes in the dash app, but it's not picking up the style correctly

limber laurel
#

Where can you learn to optimize queries

#

Maybe there is some youtuve cpurse or some documentation someone can link

#

Or personal advice?

#

Maybe I shpuld be puttibg this in databases, but it is in relation to developing web application

stray sorrel
#

Hello, each time I am trying to do something related to manage.py file (like running the server or doing a help command) I get an error, I am trying to develop a website in Django.

green flume
#

Hey guys, how can I get the "nome" ? I tried this aluno1 = { "nome": "Cauã", "nota1": 8, "nota2": 6 } print(f"Alunos: {aluno1.nome} ")

thorny geyser
#

aluno1["nome"] @green flume

green flume
#

@thorny geyser Thanks

thorny geyser
#

np

native tide
#

Hello, each time I am trying to do something related to manage.py file (like running the server or doing a help command) I get an error, I am trying to develop a website in Django.
@stray sorrel You can run it from the command line, no need to start python's shell

stray sorrel
#

It is pretty similar when I try to do python manage.py runserver

#

Do you think that the issue is caused because I am in the virtual environment? Or it doesn't matter?

native tide
#

Could you paste your installed apps?

#

from settings file

stray sorrel
#

How do I do that? I am still learning django 😄

#

Oh, found it 😉

native tide
#

you are missing a ,

#

after PagesConfig

stray sorrel
#

Ohh, thank you so much for your help 🙂 !

native tide
#

np

sly vessel
#

Hello. I'm trying to figure out what I'm doing wrong here. I created a custom CSS toggle switch in an online generator and I'm trying to implement it in my Dash app.

Here's the CSS file:

#

What exactly am I supposed to change to get the CSS to show up in my code correctly? Right now the server runs, but the page is all jacked up and doesn't show anything close to what I'm trying to achieve

#

Here's the cleaned up code...

green flume
#

Hey guys, how can i get all fruits I tried a lot of ways, but i can't get the expected result. EDIT: I want get the result using for ```python
foods = {
"fruits": {
"fruit1": "Apple",
"fruit2": "Banana",
"fruit3": "Watermelon",
},

"vegetables": {
"veg1": "Broccoli",
"veg2": "Lettuce",
"veg3": "Tomato"
}
}

for fruit in foods:
print(fruit)```

native tide
#
for fruit in foods['fruits'].values():
  print(fruit)
green flume
#

thanks

opal robin
#

hello can someone explain me what is the need of forms.py file when working with user models

#

on django

willow iron
#

hey how do I compare two uploaded text files in Django?

remote ruin
#

@native tide hey i'm going to bed soon. i read your solution for my postgreSql problem, so i will have a deeper look at it tomorrow and maybe turn back to you. i appreciate your help

native tide
#
            <div class="form-element checkbox">
                <input id="tnc_optin" type="checkbox" name="tnc_optin" class="css-checkbox" onclick="refresh(this)">
                <label for="tnc_optin" class="css-label ">

What's the value of a checked box for this HTML element? Not sure at all

#

@native tide If the value attribute was omitted, the default value for the checkbox is on, so the submitted data in that case would be tnc_optin=on
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox

quasi hawk
#

Does anyone know if you can render json serverside in a github page?

native tide
#

thanks! @native tide

quick cargo
#

@quasi hawk github pages are static sites so no

quasi hawk
#

Can you use jinja2?

#

Nvm its dynamic too i think

#

What do you think would be best way to do a onetime rendering?

native tide
#

@native tide Sorry, one more question.

            <div class="button-container">
                <input type="hidden" name="recaptcha" id="recaptcha">
                <button type="submit" class="button red large">ENTER NOW</button>

for a button like that, what is the value for a clicked button?

quasi hawk
#

Like im using json for cleanliness but then render it when I want to deploy it to my static page

static moss
#

I'm struggling to extract post data in Sanic. I have a simple html-form that posts data to the same site (right now it's just returning the data as a json, but the goal is simplpy to extract the POST data). The html looks like this:

    Test <input type="text" name="test_text">
</form>```
And the Sanic code looks like this.

```@app.route('/test2')
def index(request, methods=['POST', 'GET']):
    if request.method == 'POST':
        return response.text('POST request - {}'.format(request.json))
    elif request.method == 'GET':
        return response.html(q_html)

app.run(host="0.0.0.0", port=8000)```

But I just get an error because the request ends up being empty. I've tried a bunch of permutations  and looked where I could find info, but clearly there's something fundamental here that I don't get. the only thing I can think of is if I'm supposed to do something specific with the "action" part in the html, but I can't find any info on it. Any ideas?
#

(oh and the q_html is just the html string above

native tide
#

I'm struggling to extract post data in Sanic. I have a simple html-form that posts data to the same site (right now it's just returning the data as a json, but the goal is simplpy to extract the POST data). The html looks like this:

    Test <input type="text" name="test_text">
</form>```
And the Sanic code looks like this.

```@app.route('/test2')
def index(request, methods=['POST', 'GET']):
    if request.method == 'POST':
        return response.text('POST request - {}'.format(request.json))
    elif request.method == 'GET':
        return response.html(q_html)

app.run(host="0.0.0.0", port=8000)```

But I just get an error because the request ends up being empty. I've tried a bunch of permutations  and looked where I could find info, but clearly there's something fundamental here that I don't get. the only thing I can think of is if I'm supposed to do something specific with the "action" part in the html, but I can't find any info on it. Any ideas?

@static moss @app.route('/post', methods=['POST']) in the decorator

#

Not in the function defenition

static moss
#

@native tide Oh I see. That fixes the issue of not allowed POST, but I'm getting the same error I had on a different permutation (see below) where it fails to parse the body as a json (as far as I can tell the request is empty)

def index(request):
    return response.html(q_html)

@app.post('/test2')
def return_post(request):
    return response.text('POST request - {}'.format(request.json))```
native tide
#

anyway I can do someshit like this in django ?

quasi hawk
#

Anyone know how to change default page of a github page? i.e. change it from index.html to somethin else

open tinsel
#

in mkdocs.yml

native tide
#

@native tide Oh I see. That fixes the issue of not allowed POST, but I'm getting the same error I had on a different permutation (see below) where it fails to parse the body as a json (as far as I can tell the request is empty)

def index(request):
    return response.html(q_html)

@app.post('/test2')
def return_post(request):
    return response.text('POST request - {}'.format(request.json))```

@static moss I think form data is being posted and not json data? So try request.form

quasi hawk
#

@open tinsel What does mkdocs.yml do?

open tinsel
quasi hawk
#

dope ty

static moss
#

@static moss I think form data is being posted and not json data?
@native tide I (probably wrongly) assumed it just came out formatted as json data. If I do return response.text(request) I get <Request: POST /test2> but not the input data, how would I extract that?

native tide
#

I think request.form.get(input_name)

quasi hawk
#

any recommendations on static html page generators in python?

open tinsel
#

Will MkDocs do what you need? How complicated is your site? RST is more powerful but more work.

static moss
#

I think request.form.get(input_name)
@native tide Will you look at that. Thanks a lot dude!

native tide
#

Np

quasi hawk
#

I just need something that will render json into html files

#

what is rst?

open tinsel
#

Can you show me an example of rendering json to html?

quasi hawk
#

yeah gimme a sec

#
<div class="text-center">
  <ul id="filters" class="filters mb-5 mx-auto pl-0">
    {% item in items %}
      <li class="type active" data-filter=item.filter>item.content</li>
    {% endfor %}
  </ul>
</div>

<div class="text-center">
  <ul id="filters" class="filters mb-5 mx-auto pl-0">
    <li class="type active" data-filter="*">All</li>
    <li class="type" data-filter=".python">Python</li>
    <li class="type" data-filter=".placeholder">placeholder</li>
  </ul>
</div>
open tinsel
#

where does the json come from?

quasi hawk
#

a local json file

open tinsel
#

why is it in that file?

#

what is your application trying to do?

quasi hawk
#

its just for organization's sake

#

Im building a portfolio website using github pages

#

and want to keep project information in a json file to render

#

so I would just be rendering the html locally any time i add projects

native tide
#
            <div class="button-container">
                <input type="hidden" name="recaptcha" id="recaptcha">
                <button type="submit" class="button red large">ENTER NOW</button>

What's the value for this button that will send the POST to the server? Thanks

open tinsel
quasi hawk
#

Not sure how to incorporate this into my problem

#

Does it do the rendering?

open tinsel
#

I'm not sure there is an extension that will process json - I didn't check the third part list

quasi hawk
#

ah i see, thanks for the help!

open tinsel
#

I've just had a look and I can't see anything that will process json. If you process it you can still get MkDocs to process the document.

quasi hawk
#

Yeah im thinkin thats the route im gonna take

#

lookin at it now

open tinsel
#

There is a tutorial in their wiki for extensions

rustic pebble
#

@native tide you need to add a form

#
<form action="/some-route" method="post">
  <button type=submit></button>
</form>
open tinsel
willow iron
#

hey how do I compare two uploaded text files in Django?

sly vessel
#

Can anyone tell me what it is I'm doing wrong here? I'm trying to use a custom generated CSS toggle switch in Dash and I'm assuming it has to do with how I'm implementing the class name from the CSS file, but I'm not sure...
Here's the code and CSS file:

subtle hollow
#

👍

native tide
#

Guys just come over to django

#

We can go to disneyland together with django tshirts and ride the t cups

keen lily
#

what do people pair django with

#

often

proud frigate
#

how to learn django as a beginner in python

native tide
#

@keen lily Python? If that's what you mean

#

@proud frigate You go to youtube and watch everything and then again. It's the hustle baby

#

And udemy

keen lily
#

React, Angular, Vue or what

proud frigate
#

suggest some channels @native tide

native tide
#

And this guys playlist is pretty good but a very few things are outdated but overall its still good.

proud frigate
#

ok brother

native tide
#

@proud frigate Just pound em out like hotcakes

proud frigate
#

Just pound em out like hotcakes@native tide not a native english guy brother" so pls make it simple

native tide
#

What's your native language?

proud frigate
#

malayalam

#

from india

#

where are u from

native tide
#

USA, California

proud frigate
#

hooo nice

#

student or not

safe glen
#

this are my tables

     class Project(db.Model):
      __tablename__ = 'project'
      id = db.Column(db.Integer, primary_key=True)
      project_name = db.Column(db.String(120), nullable=False)
      project_tickets =db.relationship('Ticket', backref='project_ticket', lazy='dynamic')


    class Ticket(db.Model):
      __tablename__ = 'ticket'
      id = db.Column(db.Integer, primary_key=True)
      title = db.Column(db.String(120), nullable=False)
      project_id = db.Column(db.Integer, db.ForeignKey('project.id'))
      comments = db.relationship('Comment', backref='ticket_comments', lazy='dynamic')
      history = db.relationship('Ticket_history', backref='ticket_history', lazy='dynamic')

    class Ticket_history(db.Model):
      id = db.Column(db.Integer, primary_key=True)
      details = db.Column(db.String(500))
      ticket_id = db.Column(db.Integer, db.ForeignKey('ticket.id'))

   class Comment(db.Model):
      id = db.Column(db.Integer, primary_key=True)
      details = db.Column(db.String(400))
      ticket_id = db.Column(db.Integer, db.ForeignKey('ticket.id'))

i am trying to figure out how to delete all data related to a project from the database for example:

project name = Item
and i want to delete Item with all Tickets related to Item, all Ticket_history related to Tickets in Item and all Comment related to Tickets in Item

i have tried alot of sqlalchemy query codes and i cant yet figure it out.

bleak bobcat
safe glen
#

@bleak bobcat thanks man

#

@bleak bobcat im new into sqlalchemy i didnt know it had cascades🤦🏽‍♂️

bleak bobcat
#

That's fine, now you know 🙂 pls don't ping me every 5min

brittle iris
#

hey guys

#

im trying to reverse proxy using nginx

#

on my docker django application

#

which serves static files on port 8000

#

i want port 80 to redirect to port 8000

#

ive tried what i could

#

but its not allowing me so

#
upstream apex {
  ip_hash;
  server apex:8000;
}
        server {
                listen 80;
                server_name _;

                location /static {
                  autoindex on;
                   # static files
                   alias /app/static/; # ending slash is required
                }

                location /media/ {
                        # media files, uploaded by users
                        alias /app/media/; # ending slash is required

                }

                location / {
                      proxy_pass http://apex/;
                }

        }```
#

this is my nginx.conf

hearty tendon
#

In this Python Flask Tutorial, we will be learning how to deploy our application to a Linux Server from scratch using Linode.

If you would like $20 of free credit towards a Linode account, then you can use my link here to sign up:
https://linode.com/coreyschafer

We will be ...

▶ Play video
#

Corey deploys it on lineode, but I am unable to afford an account over there. I have got student account from Github which allows me to use Heroku.

#

Is it possible to deploy this on Heroku?

#

I have used sqlite as well.

bleak bobcat
#

Why not try and see where that gets you ?

hearty tendon
#

@bleak bobcat I do agree with you, but I was trying to save time since I don't get much time after the job to do the project.

bleak bobcat
#

Yes you can host it on Heroku but don't ask me how I've never used it

hearty tendon
#

Okay, thank you!

fair light
#

hey

#

anyone can help me on flask?

#

i want to display something on my pre build webpage. i am using oauth to take user's name . i can return it . but i dont know how to display it on a specific webpage (like: index.html)

#

i tried render_template

#

it dont work

#

maybe because i dont know

#

can someone guide me?

sturdy pike
#

@fair light I wish I could help you :/

sage thistle
#

@sturdy pike u know how to work with oauth2? and display some details about user?

sturdy pike
#

@sage thistle No I'm sorry. I shouldn't have opened my mouth. yert

sage thistle
#

aaaaa okay

#

can someone help me with backend for my website? please ping me

merry geode
#

Not sure where this question fits exactly, I am putting here since the whole project is a web application.
We are building a stock screener. It's basically a page where you can select certain criteria and filter out stocks meeting those criteria. We have some 200 criteria and over a 1000 stocks across 20 years.

#

And some of the criteria can span multiple years, like, give me stocks whose annual profit growth has been > 5% every year over the last 10 years

#

The data is stored in Mongo db

#

Overall, running this kind of criteria takes a very long time. So We have loaded the entire data (~12 GB) into a Pandas dataframe and keep it loaded into the memory at all times

#

But this doesn't seem like a feasible approach for the long run

#

Can anyone suggest some ways as to how operations on such datasets are handled in other projects?

#

So that it doesn't take 10 minutes to run a complex query

quick cargo
#

seems like something SQL would be more suited to if the data is tublar

#

@merry geode thats for u^^

#

@fair light Use render_template(some_kwarg=user_name)
in the template html you can do {{ some_kwarg }} and jinja will replace that with the kwarg name with the value you give it

merry geode
#

I know. It's just that a lot of processes are tied up with how the data is stored. So changing to SQL now would basically mean a complete overhaul of the project. That's not possible, unfortunately

native tide
#

Just throwing something out since i have no real input but could you chunk the data set by combining it with python generators in some way?

quick cargo
#

if you can rework the db you're probably gonna need to work with a compiled lang and chunk the data ig

#

tho you're probably still gonna have to cache it

cold anchor
#

Make some workers that will calculate these “rollup” metrics and store them in a separate collection so that you have these metrics easily in your database but only need to calculate them once and then in the webapp you just query the rolled up metrics

fair light
quick cargo
#

are you doing {username}

fair light
#

yes

#

oh wait

#

lemme check

#

i get like this now :/

#

@quick cargo

quick cargo
#

do you render it as a template?

fair light
quick cargo
#

and do you do something like username="some thing" in the render_template() bit

fair light
#

yes i guess

quick cargo
#

hmmm

fair light
#

..

quick cargo
#

1 sec

#

i need to double check something

#

are you just in debug mode using the dev server?

fair light
#

and wait i think i forgot something

#

yes

#

debug mode

quick cargo
#

change username to a btw

#

cuz i think thats what you mean todo

fair light
#

i named it the html folder templates at first

#

i changed to template

#

but still

#

same

quick cargo
#

i should be tempalates

#

so you're going to the server -> what ever endpoint

#

and its serving that

fair light
#

render_template or templates?

quick cargo
#

should be templates by default

fair light
#

i changed it

#

now

#

lol

quick cargo
#

i really dont know why thats going what its doing

#

whats your html code and full endpoint code?

fair light
#

html code

#

just for testing

#

so

quick cargo
#

you're missing a html close tag btw

bleak bobcat
#

Do you have a template engine ? ...

quick cargo
#

and body really should be outside head

#

i would imagine he has the engine considering Flask has one by default

fair light
#

aah i was just doing it in a hurry

bleak bobcat
#

Ah alright, I thought flask came without one

fair light
#

ok now?

bleak bobcat
#

Not as streamlined as it says then

quick cargo
#

I mean pallets who made flask are the people who made Jinja which is pretty much the only decent templater

fair light
#

are we going out of topic?xdd

quick cargo
#

not really lol

fair light
#

okay lol so what should i fix now?

quick cargo
#

send your full python code

#

!paste

lavish prismBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

fair light
#

ok

quick cargo
#
from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def hello_world():
    return render_template("login.html", username="bob")


if __name__ == '__main__':
    app.run()```
#

this works for me

#
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{{ username }}
</body>
</html>```
fair light
quick cargo
#

maybe try the html i sent above

#

i cant see anything blatantly wrong

fair light
#

ok lemme try

#

still no change for me :/

quick cargo
#

🤔

#

this is very weird

#

right

fair light
#

yes

quick cargo
#

lets just test something rq

#

remove the render_template import

fair light
#

ok done

quick cargo
#

and add:

from jinja2 import FileSystemLoader
from jinja2 import Environment

template_env = Environment(loader=FileSystemLoader(searchpath="./templates"))

def render_template(name, **context):
    template = template_env.get_template(name)
    return template.render(**context)```
#

then try go to the template with the dev server

fair light
#

name means web name right?

quick cargo
#

it just means the template name

#

dw about the param name

#

it will just mean when you do render_template('some.html, **kwargs) it will call that function

fair light
quick cargo
#

make sure the above code is just after where you define app

fair light
quick cargo
#

no

fair light
#

lol

quick cargo
#

litterally stick it just bellow app = Flask(__name__)

fair light
#

what should i do now lol

#

nothing to run

#

this is confusing tbh

quick cargo
#

huh?

#

you should leave all your original code

#

except just remove the import render_template

#

and just put that code bellow app = Flask(__name__) but before your endpoints

fair light
#

ok

#

i got the same thing ouf

quick cargo
#

are you just doubling clicking the html files by any chance?

fair light
#

no

#

after authorization

#

it redirects

#

to that page

#

wait let me try ur code

quick cargo
#

whats your code now

fair light
#

OMG

#

i tried that same code and not working

quick cargo
#

🤔 you must be doing something seriously jank

fair light
#

:/

quick cargo
#

what python version are you on?

fair light
#

3.6.8i think anyway its 3.6+

#

should i define or show the dir or something?

quick cargo
#

idek tbh

fair light
#

no one knows lol

#

why is this like this idk

quick cargo
#

and its not raising any errors either?

fair light
#

nop

#

O_O

quick cargo
#

🤔 that is fucking weird man

fair light
#

actually tired lol 3 days trying for this shit

bleak bobcat
#

What's the url in your browser ?

edgy raft
#

Hi I need help from Django rest framework expert,
Does anyone know what's the difference between APIviews and ViewSets?

I started using APIviews and I can acomplish everything I need with them
(Sending requests to serialize/deserialize models)

But what I'm missing is having routers for APIviews(so that I can see the whole structure on RestFramework 'dashboard') as well as a nice way to send requests from the webpage

So my question is can I use APIviews and ViewSets interchangebly and gain routers that way or am I gonna lose something by using them?

low blade
#

is a websocket basically a port that a user can connect to?

dapper tusk
#

websocket allows bidirectional communication, so a server can also send data to client. websocket runs on 80/443 server-side and on a browser-dependent port client-side (a different one for each connection)

low blade
#

that makes more sense now, thanks

dapper tusk
#

other option is event stream, which is one direction from server to client and pure HTTP

low blade
#

guess i'll need to look into other types of connections because - like you just said right now - there def exist one way connections

hearty tendon
#

Hello! I am trying to deploy my app on Heroku. I was using SQLite but moving to postgresql on Heroku.

#

I am getting this error in activity log while registering on the deployed website : sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "user" does not exist

#

This is my create_app in __init__.py:

#
    app = Flask(__name__)
    app.config.from_object(Config)

    db.init_app(app)
    with app.app_context():
        db.create_all()
    bcrypt.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)
    from NewsFeed.users.routes import users
    from NewsFeed.posts.routes import posts
    from NewsFeed.main.routes import main
    from NewsFeed.errors.handlers import errors

    app.register_blueprint(users)
    app.register_blueprint(posts)
    app.register_blueprint(main)
    app.register_blueprint(errors)

    return app```
#

I am unable to point out the reason. Adding __tablename__ = 'users' to the User class works but then it gives error in ForeignKey.

cold anchor
#

what is your table named in postgres?

errant garnet
#

hi frnds

#

i want ask a question , pls answer 🙂

#

Laravel or Django ?

ornate creek
#

Django

nova storm
#

Django @errant garnet

steady kettle
#

Laravel's good too. It's personal preference.

quick cargo
#

i mean theyre two diffrent language frameworks lol

#

also Laravel really isnt very performant

zealous siren
#

I mean, neither is django compared to SPA.....

plain laurel
#

Django vs Flask is a better question. 🤔

#

Laravel isnt even a python framework.

#

🙃

midnight needle
#

Sanic or Django ?

topaz widget
#

Django question: I have some built-in Django authentication views that call database objects (background images stored in the database). When I change the images in the admin panel, it requires me to restart the server before the database changes apply to the views. Is there a way to easily get around this without sub-classing since having to restart a working web server in production will not really be a viable option?

quick cargo
#

@midnight needle that depends they're two very different frameworks

#

And oriented at two very different styles aswell

native tide
#

hello there
i am working with discord on my bot dashboard
and i need to make sure the user has the appropriate permissions to do so
you can view some information about it here: https://discord.com/developers/docs/topics/permissions
i am using flask, but jinja doesnt support operators in it such as & so im going to have to do it in the python application
i have:

for guild in guilds:
            if (guild['permissions'] & 0x20) == 0x20:

so far
but i need to pass a var in my html to only display the servers with that permission
please help

Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

native tide
#

For anyone asking, learn django

jaunty quiver
#

how can I specify an HTML input field that looks for a duration with HH:MM:SS ?
tried it with <input type='time'> but that is seems to a) ignore seconds and b) include am and pm when the system is using am and pm. I dont need or want either for a duration.

jaunty quiver
#

fixed it by slapping a few fields together

olive egret
#

is it a good idea to learn HTML, CSS, and Javascript if I want to go further on with Django web Development?
or is it not necessary?

wind walrus
#

I completed Corey Schafer’s flask tutorials, but how can I support Markdown for my posts?

zealous siren
#

if you want to do any frontend or full stack, beyond required Orbit

wind walrus
#

Also if I were to create a normal website with articles instead of blogs, would I still store the articles in a database like we stored the posts?

#

We don’t just use separate html files for each page?

#

Sorry these are extremely beginner questions but

wooden path
#

I just wanted to say that I commend you guys for being able to learn web-dev without destroying half the universe alongside your brain cells

hearty tendon
#

@cold anchor I am very new to this. Do I need to create it over there? I have added the procfile, wsgyi, and changed SQLite db to postgres using the environment variable DATABASE_URL which is linked with postgres on Heroku.

cold anchor
#

did you make tables on your heroku database?

hearty tendon
#

Nope.

cold anchor
#

that's something you need to do

hearty tendon
#

with app.app_context db.create_all()
It won't create table?

cold anchor
#

ah just read that, I guess it will

#

it looks like you're running into naming issues though

#

you're calling a table both user and users

#

sounds like your Post table should reference users.id and not user.id as a foreign key

hearty tendon
cold anchor
#

It’s not your route it’s your table name in postgres

hearty tendon
#

Making the foreign key users.id
sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship User.posts - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.

#

I think I need to modify posts in Users and add foreign key posts = db.relationship('Post', db.ForeignKey('post.id'), backref='author', lazy=True)

#

And it didn't work

native tide
#

Django django

coral raven
#

Hello

#

How do I check what data is stored in my database

#

Using a sqlite db

foggy geyser
#

Hey

#

any one uses Django with google storage for media and static files ?

merry burrow
#

@coral raven if you use django, you can see your data in django admin

foggy geyser
#

I need HELP !

coral raven
#

Using flask rn

topaz widget
#

I've never used flask before, but there should be some way to access the database objects. Does Flask have a shell? @coral raven

fickle basin
#

@coral raven

#

Either you u use cli and import your models then you check

#

Or you download SQLite browser

#

Remember that with flask you can’t migrate the dB easily, so I guess you have to delete the SQLite.db into your project folder if you make any change to your models

coral raven
#

There's a module to migrate

fickle basin
#

@coral raven support you have a user model in the cli you do from flask import models the from models import user

coral raven
#

Flask_migrate, which gives django like commands

fickle basin
#

I never used it ^^’

coral raven
#

That I know, I wanted like a table representation of the table

fickle basin
#

So try sqlie browser for viewing your dB

#

Sqlite that’s what I used to check my dB I suggest you to give it a try

coral raven
#

Will do

#

Thanks

fickle basin
glacial loom
#

So I have a issue with flask socketio, i looked up on the web how to do it and found an example, i was going to test the example then change it up for my needs, it worked perfectly fine for the person that made the example but i cant seem to get it to work

#
import sys, os, time
from threading import Thread
from flask import Flask, request, render_template, redirect, url_for
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = """"""
socketio = SocketIO(app)
thread = None

def background_thread():
    """Here is where you'll perform your installation"""
    count = 0
    # Call Install function 1 using time.sleep(10) to simulate installation
    time.sleep(1)
    print(1)
    count += 1
    socketio.emit('my response',
                      {'data': '1 installed', 'count': count},
                      namespace='/test')

    # Call Install function 2 using time.sleep(10) to simulate installation
    time.sleep(1)
    print(2)
    count += 1
    socketio.emit('my response',
                      {'data': '2 installed', 'count': count},
                      namespace='/test')

    # Call Install function 3 using time.sleep(10) to simulate installation
    time.sleep(1)
    print(3)
    count += 1
    socketio.emit('my response',
                      {'data': '3 installed', 'count': count},
                      namespace='/test')

@app.route('/')
def home():
    return render_template("home.html")



@app.route('/result',methods = ['POST', 'GET'])
def result():
    if request.method == 'POST':
        thread = Thread(target=background_thread)
        thread.start()
        return render_template("result.html")
    elif request.method == 'GET':
        return redirect(url_for('home'))
        

socketio.run(app)```
#
<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>...</title>
    </head>

    <body>
        <h1>...</h1>
        <div id="log1"></div>
        <div id="log2"></div>
        <script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>
        <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>
        <script type="text/javascript" charset="utf-8">
            $(document).ready(function(){
                namespace = '/test';
                var socket = io.connect('http://' + document.domain + ':' + location.port + namespace);
                $('#log1').html('<br>Installing Software');
                $('#log2').html('<br> > ...');
                socket.on('my response', function(msg) {
                    $('#log2').html('<br> > Received #' + msg.count + ': ' + msg.data);
                });
            });
        </script>
    </body>
</html>```
#

all i simply need is to be able to change text without refreshing the webpage and this is the best way i found'

frosty veldt
#

Hmm, so what seems to be the problem?

glacial loom
#

just fixed the issue

#

turns out the tutorial version of ajax was out dated

#

i changed this

#

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>

#

to this

#

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.6/socket.io.js">

native tide
#

hey all, I have been struggling with this for a while now and cant find a fix
Can someone take a look at it and help me find the fix please

Basically, I am making a web-based visualization for a simulation tool used in energy supply optimization for communities

flint breach
#

anyone that has experience with django-filters and more specifically django-property-fields, is it possible to make an OrderingFilter, based on properties?

#

without hacking around too much

sleek stag
#

Hey, how can I use a open-source python project as an API to serve my Flutter application?