#web-development

2 messages · Page 138 of 1

toxic forge
#

Hello, i have one question when i am doing python manage.py makemigrations but django doesn't create all the fields for the Todo Model, please help what's wrong here?

class Todo(models.Model): task = models.CharField(max_length=255) title = models.CharField(max_length=100), _date = models.CharField(max_length=100), categories = models.CharField(max_length=100), keywords = models.CharField(max_length=100), summary = models.TextField(), description = models.TextField()

Migration Model

`class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
    migrations.CreateModel(
        name='Todo',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('task', models.CharField(max_length=255)),
            ('description', models.TextField()),
        ],
    ),
]`
wicked elbow
#

id also suggest using a models.DateTimeField(auto_now_add=True) for the date. itll be standardized that way

toxic forge
#

@wicked elbow i did both but output is like below now

class Todo(models.Model): task = models.CharField(max_length=255), title = models.CharField(max_length=100), _date = models.DateTimeField(auto_now_add=True), categories = models.CharField(max_length=100), keywords = models.CharField(max_length=100), summary = models.TextField(), description = models.TextField()

`class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
    migrations.CreateModel(
        name='Todo',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('description', models.TextField()),
        ],
    ),
]`
wicked elbow
#

open the actual db file. migrations dont show every field

toxic forge
#

@wicked elbow 0001_initial.py?

#

db i am using djongo

wicked elbow
#

no. your db file that was created, migration files dont show everything

toxic forge
#

oh but in /admin it only shows description field

wicked elbow
#

i dont see anything else wrong with it though.

toxic forge
#

django version can be the issue?

wicked elbow
# toxic forge

im dumb, sorry still morning time. remove all the commas

toxic forge
#

@wicked elbow Thanks man small , issue it took me hours to figure it out 🙂

wicked elbow
#

lmao. my brain isnt working yet. i looked at your code and thought they were needed. not awake yet haha

leaden widget
#

how can I make 2 elements stand next to each other(horizontal) using css?

wicked elbow
wicked elbow
leaden widget
#

it worked, thank you !

wicked elbow
native tide
#

how do i make a custom error 404 page using django?

#

views .py

def handler404(request,exception):
   return render(request, 'rostats_app/error404.html', status=404)
#

urls .py

handler404 = 'rostats_app.views.handler404'
#

comes up with this

toxic flame
#

What does the debug=False say?

wicked elbow
native tide
native tide
wicked elbow
#

django doesnt serve static files when debug=False. that includes the 404 page. your apache/nginx server will handle the error pages

#

django isnt a server. its backend coding. you'll have to set up mod-WSGI or ASGI to deply a django app

native tide
#

dude i dont get what you mean

native tide
wicked elbow
#

in your settings.py file, you have debug=True which means django is running in developement. if you turn debug=False itll run in production. but you have to also set up, apache with mod-wsgi or a nginx server with daphne/uvicorn/gunciorn

dark hare
#

debug=True will give them the full stack trace

#

nothing to do with serving static files

native tide
#

why would that matter when the other pages load

native tide
dark hare
#

debug=true will return the stack trace in the browser

native tide
#

any ideas to help me

#

idk what im doing wrong

wicked elbow
#

yes, in developement django serves static. in production, django doesnt. thats how you switch from to developement to production.

native tide
#

is that for me?

dark hare
#

kendal, what do you mean serves static??

wicked elbow
native tide
#

can anyone help me???

native tide
#

just the error page doesnt work

#

which is probably because im doing something wrong

wicked elbow
native tide
#

what?

wicked elbow
#

your server will handle the 404. django isnt a server

native tide
#

dude you just confused me way more

wicked elbow
#

ive said the same thing multiple times

native tide
#

yea which is probably why you are confusing me since idk what you are on about

dark hare
native tide
dark hare
#

are you running your django app locally?

native tide
#

yea

dark hare
#

what is your debug setting value?

native tide
#

False

dark hare
#

why?

native tide
#

wdym why

dark hare
#

you need it to be true

native tide
#

no...

wicked elbow
#

then it needs to be running on a server.

dark hare
#

^

native tide
dark hare
#

did you not read what Kendal said?

wicked elbow
#

it wont serve anything when debug equals false without a server

dark hare
#

you cannot serve static files locally by default with debug=false

native tide
#

all the other views work tho...?

#

why would it be different from the 404 page

wicked elbow
#

throw it on stack exchange, or ask google. im not gonna beat a dead horse.

native tide
#

cool

dark hare
#

do you know your function is being called?

#

have you put a debugger in there and checked

wicked elbow
#
If you still need to server static locally (e.g. for testing without debug) you can run devserver in insecure mode:

manage.py runserver --insecure
#

but you really dont need to handle page errors in django. let the server do its job...

wicked elbow
# native tide cool

for learning purposes, use django for your views/html. in the real world though, youll use django as an api backend. and you'll use react, angular, or vue to run your pages in the front end. thats true almost everywhere these days

native tide
wicked elbow
#

but again, you dont want to bog python down with serving static even though theres ways to do it. thats the whole job of a server. IMO what they were built to do. python is slow, dont put to many tasks for it to do. handling 1000s of people accessing an api is more then enough.

toxic flame
#

He's not using static files anyways, he's using a template

#

Though they aren't very different, django does serve templates

toxic flame
static wind
#

hey everyone, i'm having a lot of trouble setting up my flask application with namehero & cpanel
i've followed at least 10 different methods of setting it up, none of which have worked. a common error i seem to be getting is just a 503 service unavailable page, on any routes on the page, regardless of if i include them in flask
i'm using the python app option, and i've added a requirements.txt that has every package i need, although right now i'm just using the most basic flask thing to display a hello world

i'm frustrated and confused, any help would be appreciated

wicked elbow
keen python
#

I think HTML is the easiest programming language to make a website because I've made 5 or websites and the ones i used HTML was the easiest who agrees?

noble spoke
#

html is the only way to make a website

#

its the only thing rendered in a browser

barren moth
#

👀

#

actually I beg to differ

#

firefox pretty prints api outputs

#

with json

toxic flame
wicked elbow
toxic flame
#

yea react is just an example

#

react as in a fronted framework

wicked elbow
noble spoke
#

a json output isnt exactly what you call a website

wicked elbow
noble spoke
#

and js creates html elements to place in the DOM, its not rendered

toxic flame
#

JSX IS THE NEW THING BOYS

wicked elbow
noble spoke
#

javascript isnt rendered dude, theres a reason i used that word and not anything else

wicked elbow
#

lmao you've never used a framework, obviously. it uses html, but the jsx is rendered in javascript. any dom modification is rendered.

toxic flame
#

yop

noble spoke
wicked elbow
#
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>safespace</title>
    {% load static %}
    <link rel="stylesheet" href="{% static "frontend/stylesheet-main2.css"%}" />
</head>
<body>
    <div id="app" style="height: 100%; width: 100%"></div>

    <script src="{% static "frontend/main.js"%}"></script>
</body>
</html>

thats all the html in my entire website. the rest is jsx, react-dom
to say javascript doesnt render is completely wrong.

toxic flame
static wind
#

yea

#

3.7.8

toxic flame
#

I only have setup django on cpanel.but they shouldn't be much difference

#

So the python uses a passenger_wsgi.py to do everything for u

#

just find ur wsgi file and import the "application" or whatever u have set it to onto the passenger_wsgi.py

static wind
#

yeah i've read things saying to get rid of that

#

yeah

#

thats what im doing

#

503

wicked elbow
#

what server?

static wind
#

cpanel

toxic flame
#

hMMMMMmMM

static wind
#

flask

toxic flame
#

maybe like django u have to set allowed host?

static wind
#

hm?

toxic flame
#

Did u pip install the stuff

static wind
#

yes

toxic flame
#

And errors on the log?

static wind
#

no log file

#

no clue how that works

toxic flame
#

u should have one, its created by default

static wind
#

where

toxic flame
#

its on /logs for me

static wind
#

directory is empty

#

lemme add a filepath there and then restart

#

yea no logs

#

set it to logs/passenger.log which is the default or whatever

toxic flame
#

Yea

static wind
#

no logs

wicked elbow
toxic flame
#

idk man, never set for production any flask apps

static wind
#

followed that

#

wait

#

if its running on localhost

wicked elbow
#

it probably has something to do with the wsgi set up though

static wind
#

yeah i have no clue though

#

ig rn its deployed on localhost or whatever

#

because i tried running thru terminal and it said it was running at 127.0.0.1:5000 which is localhost

wicked elbow
#

localhost is wrong on a shared server. cant run on 127.0.0.1/ should have a private ip for you to use

static wind
#

do you have any idea how to fix that

wicked elbow
#

im just guessing honestly, ive only set up in aws. and aws gives you a private ip to use

#

and only django

static wind
#

ok wait here's what i have setup for wsgi stuff if this helps at all

#main.py
from flask import Flask
app = Flask(__name__)


@app.route("/")
def hello():
    return "This is Hello World!\n", 200

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

#passenger_wsgi.py
from main import app as application
#

and then in the application manager:

wicked elbow
#

i dont know anything further to help with cPanel though, never used it

toxic flame
#

set startup file to passenger_wsgi.py @static wind

native tide
#

Django: Hello everyone, my question is about an update view but with multiple forms not one. So you would get through a filter call many objects that need to be put in the form?

static wind
#

ok will try that @toxic flame

toxic flame
#

lmk

static wind
#

503

toxic flame
#
  • restart right?
static wind
#

yup

toxic flame
#

Gomenasai brother i got no more jam

static wind
#

damn

native tide
#

Django: Hello everyone, my question is about an update view but with multiple forms not one. So you would get through a filter call many objects that need to be put in the form?

#

Please help

wooden ruin
native tide
#

I understand but they can all be updated at the same time

#

so need to be displayed on one page

wicked elbow
#

what your talking about would require JavaScript im pretty sure. im confused about why everything is seperate if it needs to be done together

glossy arrow
#

Say I have something like ```py
@app.route("/")
def index(request):
response = TextResponse("Hi")
session.init_session(response)
return response

@app.route("/get")
def get(request):
return TextResponse(session(request)["data"])
``` The session.init_session() method is setting a cookie, but its only available on the next request

#

How can I make it available on the same request?

toxic flame
#

run the function seperately i guess

#

or again twice

glossy arrow
#

Hm

#

I think I've figured it out

toxic flame
#

I am django user i have no idea lul

glossy arrow
#

Lol

#

BTW, is this a correct implementation of a Session? ```py
class SessionHandler:
def init(self, app, secret_key=None):
self.app = app
self.lifetime = self.app.to_seconds(1, "hour")

    self.secret_key = secrets.token_urlsafe()

    self._dict = {}

    self.initialized = False

def init_session(self, request, response):
    if not request.cookies.get("secret_key"):
        key = secrets.token_urlsafe(50)
        response.set_cookie("secret_key", key+self.secret_key,
                            httponly=True, max_age=self.lifetime)

        self._dict[key] = {}

        self.initialized = True

    self.initialized = True

def __call__(self, request):
    assert self.initialized, "Session Not Initialized"
    return self._dict[request.cookies.get("secret_key")]
wicked elbow
#

no idea, i just use basic setup

native tide
#

hey

#

im having an issue fitting an image to fit the whole screen

#

ive tried setting max-height and height to 100%

#

but cant figure anything out

hybrid bobcat
#

can Flask model store custom object in columns?
so like if i have db.Column(db.string(20)) can i replace string with a custom object?

desert parrot
#

Hey. I have a large amount of html code in an url. Is there any quick way of reading it all? requests and urllib.request are taking so long.

limber dew
#

i dont know if this is a right channel to post my problem.
My question is how can i pass the variable from Vue js to django?

<div v-for="post in posts" class="post-preview">
          <a href="{%url 'detail' [[post.id]]%}">

This is not working, any ideas to tell me a different approach ?

wicked elbow
marble spade
#
<form method="POST" action="">
        {% csrf_token %}
        {{form.username.label}}
        {{form.username}}

        {{form.email.label}}
        {{form.email}}

        {{form.password1.label}}
        {{form.password1}}

        {{form.password2.label}}
        {{form.password2}}

        <input class="submit" type="submit" name="UserCreate">
    </form>

I have the following form class in Django however I want to style it in CSS. I want to style the input boxes (The form bit as it is a built in input box). I have tried to create div classes to no avail!

Any help would be greatly appreciated.

wicked elbow
#

people need to get away from using django as a whole package distributor. its just not though. build html and connect it to your backend.

marble spade
#

what if your just trying to get into web dev

wicked elbow
#

dont start with django, start with html/css/js. then learn your backend and connect it to your front end.

#

you can't have a good back end without a quality front end template

#

but fyi you can do @marble spade

<style>
.something * {
  ...styles for the stuff inside something
}
or
.something input {
  ... styles for your input here
}
</style>
<div classname="something">
  {{form.email.label}}
  {{form.email}}
</div>
marble spade
#

is there any way for me to put text inside of the input class, like a placeholder I believe it is called/

wicked elbow
#

no idea how to do it from django, but in pure html <input type='text' placeholder='Text_goes_here' />

marble spade
#

yeah hm doesn't really work with django

limber dew
vestal hound
#

okay

#

so how it worked was

#

channels would provide a compatibility layer

#

to run your Django project as ASGI

#

but Django itself

#

was only WSGI compatible

#

now Django is natively ASGI compatible

wicked elbow
vestal hound
wicked elbow
#

im still pretty sure ASGI support has been around for a bit. channels v2 was had daphne which was an asgi server to run on

#

and channels v2 compared to v1 was a huge leap forward was what the video i watched said

#

so i would think for sure true asgi has been supported since then

wicked elbow
#

been around since dec 2019, so im taking it your more correct then i thought. makes more sense the stuff about the sync_to_async commands in channels

vestal hound
#

yes

vestal hound
#

but if Django supported ASGI natively

#

you wouldn’t even have needed daphne

wicked elbow
#

you still have to deploy on an asgi server. thats what daphne and uvicorn are. havent found asgi support for apache

vestal hound
#

ye but at that time

wicked elbow
#

i wanna know why channels isnt built into django. websockets are every day things

vestal hound
#

uvicorn did not exist

#

they HAD to make daphne to support ASGI at all

vestal hound
#

and it takes a lot of effort to make it async without breaking stuff

#

and to be fair many apps can run without websockets

#

or any sort of server to client communication, for that matter

wicked elbow
#

daphne is maintained by the same person who maintains channels, but hes said uvicorn is more advanced then daphne these days

vestal hound
#

precisely my point

#

daphne was made FOR channels because there was no ASGI server and one was necessary for Django integration

wicked elbow
#

a lot of modern apps use sockets, video calls, all the social media sites, any delivery service with real time tracking. and chat. web sockets arent exactly new. was supported in browsers in 2009

#

im just saying, i find it weird that theres no major documentation behind using it with a database behind it. most things i see use redis to pass the next message to all active users, but doesnt do anything with data that happened before you joined. it makes it difficult to program, no documentation with no user base to explain. just kinda trial and error until i figure it out

#

and even channels doesnt have true support with rest framework. have to use another 3rd party module to get it to work.

#

i bought a django book to help me understand the more advanced topics of all the different views/viewsets/generics and i feel like i wasted my money. just feels like maybe using django was a bad idea cause of the limited support. and when i talk web sockets it goes over everyones heads

#

i did finally find a couple different examples of channels with drf now. studying how they are done

vestal hound
#

in Django

#

that are LITERALLY

#

10 years old

#

many parts of Django are really outdated

#

lacking websocket support is defo one of them

#

when you get affected by the others you'll know

#

but yeah.

#

like I have legitimately considered

#

starting from the ground up

#

with FastAPI + Peewee

wicked elbow
# vestal hound there are bugs

yea, its just amazing to me though. django could be something. i like it way more then i did php. but theres some major hurdles in it. lot of people enjoy using it. but like a lot of other things python related, it has pitfalls. just like guis like tkinter

vestal hound
#

well

#

a lot of people use Django

#

therefore backward compatibility is very important

#

therefore lower agility

wicked elbow
#

yes i know, but still. gotta be modern to stay in use

still wedge
#

yo

#

ok

#

ok

#

is id selector

#

. is class selector

#

try with .Logo

#

noice

#

🙂

#

np

#

you can dm if youll need more help, we can google it together 🙂

toxic flame
#

@vestal hound what backend framework do u recommend at these modern days?

still wedge
#

how does django compare to CakePHP?

indigo kettle
#

django is not user friendly?

#

3x is a lot

#

I think django is pretty good

still wedge
#

to me only speed matters...

indigo kettle
#

so to say something is 3x more user friendly than django is pretty crazy

still wedge
#

speed as in speed of web app, not amphetamines

#

🙂

#

anyway... how is your css going? is this your first time doing front end? i can recommend you some resources i used to learn design

#

lol wtf

#

2 oranges

#

not again

#

its you... ok...

#

only on the web...

#

anyway...

#

about css

#

as i said, i could recommend you some yt channels i found most useful to kickstart learning css

#

css can be... finicky...

#

i know lol

indigo kettle
#

why is this happening

#

lmao

still wedge
#

im checking each message now

#

for sender id

#

XD

#

we have 2 oranges

#

whats with deleting messages?

wicked elbow
split steeple
wicked elbow
split steeple
#

Yes. They do.

#

Good lord.

toxic flame
#

just use vim and all your problems will be gone

#
  • productivity
#
  • no syntax warnings
#
  • no need for the mouse
buoyant shuttle
#

anyone here

#

i have a problem running a script in the same file as models.py meaning inside my app. but getting this error

#
 File "/home/samuel/dev/tools/stocks-scraping/reddit_stocks_scraper/reddit/reddit.py", line 12, in <module>
    from .models import ScrapedStocksStatisticDB
ImportError: attempted relative import with no known parent package
wicked elbow
toxic flame
#

idk about that

#

No mouse usage = 20% time save

noble spoke
#

Does your app have an __init__.py

native root
wicked elbow
native root
#

F

wicked elbow
# native root F

but i am still getting a call error, im just trying to find the issue, but thanks for seeing that

native root
#

Yeah, looking into it atm

#

This seems a problem line.. I'm tired but

#
  File "H:\Users\Kendal\Desktop\safespace\safespace\notification_api\consumers.py", line 77, in subscribe_to_list
    await self.notify_change_handler(list=True)
#

What's the code involved here?

wicked elbow
#

yea, its passing to the wrong notify_change_handler. i dont understand why theres 4 of them anyways
should pass to

    @notify_change_handler.groups_for_consumer
    def notify_change_handler(self, owner=None, list=False, **kwargs):
        # This is called when you subscribe/unsubscribe
        if owner is not None:
            yield f'-owner-#{owner}'
        if list:
            yield '-all'
``` but its passing to 
```py
    @model_observer(Notifications)
    async def notify_change_handler(self, message, observer=None, **kwargs):
        # called when a subscribed item changes
        await self.send_json(message)

as far as i can tell.

native root
#

Well, are they in different classes or have you defined two methods with the same name?

wicked elbow
#

they are all in the same class, the decorators have something to do with where they are supposed to go. the code i followed and anothers example does the exact same thing

native root
#

Ok.

#

well, don't do that

#

It's a bad example. Because you're using decorators I'd give it a shot giving them unique names and trying to call it specifically. In python the last one defined is the one that ends up with the name, so perhaps you've got the order different.

wicked elbow
#

actually, it was my error. i missed await self.notify_change_handler.subscribe(list=True)

dawn heath
#

machine learning via tittle or summary for rss?

wicked elbow
native root
#

Yeah, would imply you gave it stuff that wasn't just dict/list/str/int/float

#

It's a bit strange and boilerplatey but if you familiarize yourself with djangos save signals it actually kinda makes some sense

#

Basically I think send_json calls json.dumps() on what' it's givne, you're giving it message, and in the examples message is usally a dict/jsonlike structure, so you've probably given it an object somewhere

wicked elbow
cosmic panther
#

if youre writing a super simple landing page thats going to take a users information before directing them to a youtube video. Is it best to store that info in a databse or something more simple like a googel doc

wicked elbow
#

and i solved that as well, had to call the child of the foreignkey. thanks @native root and @manic frost. i have real time notifications now!

lavish prismBOT
native root
tough tartan
wicked elbow
#

looks like your passing the wrong client id, but i cant tell, i dont know flask even in the slightest

native root
#

^

tough tartan
#

@wicked elbow what would the correct token be?

wicked elbow
#

is that your client id?

#

you should probably not be making that public.

tough tartan
wicked elbow
#

are you sure its correct?

eternal blade
#

This is how I load it in the html

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'css\style.css' %}">```And when I enter the homepage this is what I see in the terminal
```powershell
[03/Mar/2021 09:40:14] "GET /static/css/style.css HTTP/1.1" 404 1766```I have set a static url and a static root in the settings.py, Thanks :)

Btw sorry for the late response I didn't see your message ping me next time when you reply
nocturne remnant
#

I'm trying to set up a socket.io function that emits a message every 10 seconds using Flask (or Django), I already got it semi-working with Threads but it was spawning multiple threads so there must be a better way, I already explored Celery (not good for this use case) and I'm looking at Eventlet or Gevent.

tough tartan
tough tartan
gritty sky
#

can anyone help me with some bs4 stuff lol

nocturne remnant
#

@gritty sky what are u scraping

gritty sky
#

chegg site

#

im not v familiar w bs4, so i found some open source for it

#

but it keeps retuning there is not text etc

tough tartan
nocturne remnant
#

paste the line of code

gritty sky
#

its there

#

unless its something wrong with my headers?

nocturne remnant
#

which line returns the error

gritty sky
#

sorry, i meant to say it doesnt return nothing

#

it sends back whats on line 40

wicked elbow
nocturne remnant
#

@gritty sky it could be anything. hard to say, you should add print statements to debug

gritty sky
#

hmm alright i will, ty

nocturne remnant
#

@gritty sky i mean since you wrapped the whole function in a try: statement

spare iris
#

@gritty sky is scraping against their TOS?

nocturne remnant
#

@gritty sky it fails somewhere inside the try:

gritty sky
gritty sky
spare iris
#

@gritty sky uhhhh I would check that out you can get in serious trouble

nocturne remnant
#

@gritty sky like make sure line 18 works

nocturne remnant
#

@spare iris serious trouble? Lol how

#

They're gonna call the feds because he screen scraped their public website? lmfao

gritty sky
spare iris
#

@nocturne remnant get sued lmao

#

do whatever you want lmao I said what I normally say about webscraping

gritty sky
nocturne remnant
#

@gritty sky remove the try/except statement and run it

#

@spare iris what do you think about using cookies to mine cryptocurrency in the user's browser?

spare iris
#

@nocturne remnant Idk dude I’m just trying to sleep

nocturne remnant
#

maybe turn off your computer then

gritty sky
#

@nocturne remnant

nocturne remnant
#

@gritty sky then the problem is on line 20

#

@gritty sky put print(type(answerDiv))

#

@gritty sky try changing getText() to get_text()

gritty sky
#

bet, i gotta head to sleep but i’ll try tmro fs

#

ty bro :)

nocturne remnant
#

@gritty sky you're using bs3 methods

gritty sky
#

ohhh

#

damn

#

welp

nocturne remnant
#

yeah try changing that tomorrow

gritty sky
#

will do, ty

loud elbow
#

hey

#

so um how do I change the symbol of this when working on a local file

eternal blade
#

Hi, I have a css file linked to a html file, when I look at the console I can see a request been sent to the css file but the response status is 404.
This is how I connect the css file to the html```py
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'css\style.css' %}">

This is what I see in the terminal```cmd
[03/Mar/2021 11:46:20] "GET / HTTP/1.1" 200 3985
[03/Mar/2021 11:46:20] "GET /static/css/style.css HTTP/1.1" 404 1766```
This is my settings.py```py
STATIC_URL = '/static/'
STATIC_ROOT = "static"

Thanks :)

inland copper
inland copper
#

and add an img src

inland copper
#

hmmm

#

can u give a screenshot of your css file?

#

also this is not needed for css

#

just do {% include 'path' %}

eternal blade
#

This is what I see in the terminal

[03/Mar/2021 11:56:35] "GET / HTTP/1.1" 200 3985
[03/Mar/2021 11:56:35] "GET /static/css/style.css HTTP/1.1" 404 1766
[03/Mar/2021 11:56:35] "GET / HTTP/1.1" 200 3985
[03/Mar/2021 11:56:36] "GET /static/css/style.css HTTP/1.1" 404 1766```
inland copper
#

then the styling will work

eternal blade
inland copper
#

do {% include 'static/css/style.css' %}

eternal blade
#

Ok, thanks I'll try that

inland copper
#

no

#

sorry

#

u don't do it in the link rel

#

do it in the body

#

tag

#

@eternal blade

eternal blade
#

I know that I shouldn't do it but the css still needs to load right?.

inland copper
#

yes

#

that's the point

#

show me your css file

eternal blade
#

Ya, I'll change it cuz what i am doing now is a bad practice

inland copper
#

u just have font-family, alignment etc?

inland copper
#

but it'll wor

eternal blade
inland copper
#

k

#

try and say if it is working

eternal blade
#

Ok

inland copper
#

is it working? @eternal blade

eternal blade
#

Now it is not sending any request

#

[03/Mar/2021 12:02:25] "GET / HTTP/1.1" 200 3964

inland copper
#

what?

#

but is the styling working?

#

in the cmd/terminal

#

that might be one reason the static isn't working

eternal blade
#

Now I can see this

[03/Mar/2021 12:04:47] "GET / HTTP/1.1" 200 3985
Not Found: /h1{    color: red;}
[03/Mar/2021 12:04:47] "GET /h1%7B%20%20%20%20color:%20red;%7D HTTP/1.1" 404 2991```
inland copper
#

u have an an error in the css file

#

but it is successfuly loading the css alright

eternal blade
#

I just added ```css
h1{
color: red;
}

inland copper
#

?

#

that is important

eternal blade
#

I did it, wait ill do it again

inland copper
#

and also show me the output

#

type yes if it asks a question

eternal blade
#
Type 'yes' to continue, or 'no' to cancel: yes 

0 static files copied to 'D:\projects\app\static', 132 unmodified.```
#

it didnt copy anything

#

I ran this command before also

inland copper
#

hmmm

#

i made a website on these static files

#

but i can't figure the prob

eternal blade
#

But when I go it the admin panel I can see this

[03/Mar/2021 12:09:26] "GET /admin/ HTTP/1.1" 200 4478
[03/Mar/2021 12:09:26] "GET /static/admin/css/responsive.css HTTP/1.1" 200 18344
[03/Mar/2021 12:09:26] "GET /static/admin/js/nav_sidebar.js HTTP/1.1" 200 1360
[03/Mar/2021 12:09:26] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423
[03/Mar/2021 12:09:26] "GET /static/admin/img/icon-changelink.svg HTTP/1.1" 200 380
[03/Mar/2021 12:09:26] "GET /static/admin/img/icon-deletelink.svg HTTP/1.1" 200 392
[03/Mar/2021 12:09:26] "GET /static/admin/img/icon-addlink.svg HTTP/1.1" 200 331
[03/Mar/2021 12:09:26] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692
[03/Mar/2021 12:09:26] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876
[03/Mar/2021 12:09:26] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 86184```
inland copper
#

that was the wrong url sorry

#

this is the correct one

#

i learnt from this guy

eternal blade
inland copper
#

hope it helps

#

u can catch a step u missed maybe

inland copper
#

STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)

#

if u didn't already @eternal blade

eternal blade
#

Ok, ill put it thanks

#

after that do i need to run the collectstatic command?

inland copper
#

yes

#

i am not sure if it will work

#

but it was recomended in a website

eternal blade
#
?: (staticfiles.E002) The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting.```
inland copper
#

why is your static_root and static url the same? @eternal blade

eternal blade
#

Looks like I cannot have the same setting for those two

inland copper
#

both are same

#

u shld create a new folder called static_cdn and that shld be your root

eternal blade
inland copper
#

STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn')

oblique kite
#

hello guys ..
I want to send js object from AJAX to django .. and i want exact representation of js object in dictionary form .. how can i achieve it ?

inland copper
#

.json()

#

in python

#

it will be read as a dictionary

inland copper
oblique kite
inland copper
#

can us send github link @eternal blade

eternal blade
inland copper
eternal blade
#

Thank you very much it works now lemon_pleased
[03/Mar/2021 12:24:46] "GET /static/css/style.css HTTP/1.1" 200 30

inland copper
#

sure

#

can u send me a screenshot of the webpage

#

pls

#

@eternal blade

eternal blade
#

Ok

#

Here?

inland copper
#

ya

#

it is working right?

#

the static?

eternal blade
#

Yes, wait a second ill send it

inland copper
#

sure

eternal blade
inland copper
#

okay all right

#

it is working

#

that is good

#

happy to help!

half narwhal
oblique kite
# inland copper .json()

in python when i called "request.POST" then i got <QueryDict: {'filters[status][]': ['1']}> ..

eternal blade
inland copper
#

okay

uneven cedar
#

what should i use to build a website

#

app?

tribal tapir
#

anyone here

unborn vault
#

I'm here... off and on...

inland copper
oblique kite
native tide
#

Hey

#

can anyone give me some feedback on a website

inland copper
#

there are just js hrefs

native tide
#

thats all there should be right now

#

im just looking for feedback before i build it fully

inland copper
#

okay i like the UI a lot

native tide
#

thanks

inland copper
#

u use react?

native tide
#

No its just html and css

inland copper
#

i am kinda bad at frontend

#

i never learnt much css

native tide
#

Ive only known html for about 4 months, im self taught from w3 schools. I only ever built like 6 pages lol

inland copper
#

i use bootstrap to make it look dent

#

decent*

native tide
#

boostrap looks coold

#

cool*

inland copper
#

all are my websites

#

django

native tide
#

damn

#

look good

inland copper
#

thanks

#

this is my fav

#

how did u deploy with a custom domain

#

u paid?

#

@native tide

native tide
#

yea

inland copper
#

?

native tide
#

i bought with name cheap

inland copper
#

aws?

#

server

native tide
#

and proxied it through cloudflare

#

no, its my own vps

inland copper
#

okay

native tide
#

super cheap, €6 / m for 8gb ram and 4 cores

inland copper
#

nice

native tide
#

and i just installed ptero panel on it

manic frost
#

Does aiohttp not create an OPTIONS route for each POST route? That seems quite silly to me

opaque rivet
manic frost
#

yeah, that's why I'm asking 😄

opaque rivet
#

hmm, been trying to read about it and came across this:

#

you could try to set a custom header, or change your Content-Type header to something other than listed, maybe this will help

manic frost
#

well, that's quite a hack

#

maybe I should open an issue on aiohttp

#

because I don't really want to add an OPTION for every post

opaque rivet
manic frost
#

Maybe I should just give up and use starlette/fastapi

opaque rivet
#

does your CORS block every request which doesn't have a preflight?

opaque rivet
manic frost
#

No, 'simple' requests work fine (i.e. without preflights). A request with preflight (basically, every POST with a JSON body...) fails

opaque rivet
#

i see, could it be that your POST is still seen as a "simple request" by the docs, so isn't triggering a preflight?
so I guess you're looking for other libs that auto send a preflight for POSTs

manic frost
#

I don't really need CORS (because the frontend will be statically served from the same host), it's just for local testing, so that I can restart the frontend and the backend independently

opaque rivet
#

i see, something new learnt every day 🙂

ornate burrow
#

what is your guys opinions on optimal resolution/filesize for images on a website?

#

i have some pretty large files (all are approx 5-10mb each) and my cms wont even allow that size to be uploaded

desert parrot
#

okay I have a webpage. On the webpage, there is a clickable. If I click it, it downloads a file. Is there a way to download that file using a python script?

ornate burrow
#

wouldnt a get request work?

#
import requests

print('Beginning file download with requests')

url = 'http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg'
r = requests.get(url)

with open('/Users/scott/Downloads/cat3.jpg', 'wb') as f:
    f.write(r.content)

# Retrieve HTTP meta-data
print(r.status_code)
print(r.headers['content-type'])
print(r.encoding)
native tide
#

hey, can someone give me some feedback on the website im making?

#
import time
import random

while True:
    sites = random.choice(['google.com', 'youtube.com', 'weather.gov'])
    visit = "http://{}".format(sites)
    webbrowser.open(visit)
    seconds = random.randrange(1, 5)
    time.sleep(seconds)
``` It gives me error:  File "c:\Users\burka\OneDrive\Dokumenti\python coding\coding\webbrowser.py", line 7, in <module>       
    webbrowser.open(visit)
AttributeError: partially initialized module 'webbrowser' has no attribute 'open' (most likely due to a circular import)
#

webbrowser

#

is that the name of your file?

#

thats running from?

#

so your trying to import webbrowser from a file called webbrowser, See the issue there?

#

@native tide

#

ohhhh

#

I see

desert parrot
#

Hey.

how can I get the value of a driver.find_element?

native tide
#

Yeh thanks

desert parrot
#

Like I want that

native tide
#

you need to find class

#

your using selenium or bs4? @desert parrot

desert parrot
#

selenium

native tide
#

driver.find_element_by_class

#

I think it should be like that

desert parrot
#

I figured it pog
Its driver.find_element().text

native tide
#

ooo

#

POG

tropic mason
native tide
#

yea

#

@tropic mason

#

its not got much rn

#

but looking for feedback before i finish it

tropic mason
#

so far so good 🙂 i think you can reduce the indentation by 50%

#

still looking good imo

#

do you want feedback on the code as well or just the visuals?

manic frost
#

@native tide Not much content, I suppose, but you should increase the font size. It's a bit hard to see, and certainly hard to click on the links.

#

Also, the website doesn't look well on mobile

#

The colors are good.

native tide
#

Hello

#

I need some advice about React and Django Rest Framework

native tide
#

Hey guys, can I ask a javascript question?

#

There is something confusing me

#

Iwas working with the javascript onedrive sdk, and felt curious to check out the library and see how something works https://js.live.net/v7.2/OneDrive.js
I beautified a bit and this is how it starts:

#

none of this makes any sense to me, is this some kind of boilerplate or something, cause I can't understand any of it and its purpose. However my main question wan't about this, but I was curious of how this stuff works.

My main question, and the reason I was trying to read the library was to see how its executing code after clicking a button in the popup in the main browser window

#

thats how they suggested we use the library, this will open a onedrive popup. If I select a file and click Open the function given to success is executed in the main window. I was wondering how this "sorcery" happens, same goes for cancel and I guess if an error occurs, the error function is executed

rotund harness
#

In javascript you can use a function as an object's attribute so when you pass the options object to the OneDrive.open() function your function is passed with it. The .open function can then call this function so this is how OneDrive executes your function

native tide
#

but how does it do it from a button in a popup window

tropic mason
#
const OneDrive = {
    open: function (options) {
        // do things
        files = [] // get the files or idk
        options.success(files)
    }
}
#

does it help a little to understand what's going on behind the scences?

#

you pass your defined functions as options and then they will call those functions whenever it is needed

rotund harness
#

Somewhere in the OneDrive code it may be called like this:

#

'options.success()'

tropic mason
#

e.g. they will attach to their cancel button an event listener on click 🙂

tropic mason
native tide
#

right,

#

when I click this

#

which is that function above

#

this opens

#

if I select it and click open

#

so thats where you are saying its calling options.success(files)

tropic mason
#

exactly

native tide
#

but how is it getting the files

rotund harness
#

Pretty much yeah

native tide
#

from the popup

tropic mason
#

probably via onedrive api

#

none of our business that's why you are using their code, i guess

native tide
#

yeah I know

tropic mason
#

if you open up the developer tools and check the network requests it should send a few GET requests to the OneDrive API 🙂

native tide
#

ehh, forget onedrive, lets say I want to open a popup

tropic mason
#

which then sends back file files

native tide
#

lets say there is a textbox and a button in the popup

#

if I wanted to get that text from the textbox in the popup when I click that button to my main window

#

how would I do it

rotund harness
#

What do you mean by popup?

#

The file selector?

native tide
#

yeah

rotund harness
#

What kind of text are you getting from there?

native tide
#

just an input type text

#

lets say

rotund harness
#

You can usually get text from an input through its id or class like this:

native tide
#

even if its in a different window?

rotund harness
#

I'm not sure tbh

#
text = document.getElementById("input-text").value;
#

This would work if it's in the same window

native tide
#

like lets say I have a window.open somewhere and instead of google.com I had a a page of my own that has an input field and button

rotund harness
#

I can't think of any easy ways to do that

#

I'm sure they exist though

native tide
#

ahh

rotund harness
#

Actually nvm

#

I think there might be a way

#

You do: new_window = window.open("https://google.com","test","height=400,width=400")And then in the windowwindow.returnValue = document.getElementById("input-text").value;Then do ```
text = new_window.returnValue;

#

I gtg

#

Good luck

oblique kite
#

hello guys ..
jQuery function is not woking after appending checkbox

umbral bobcat
#

Hey everyone, I've been working through Corey Schafer's flask tutorial on youtube recently. Amazing series of tutorials. Got to the video on Blueprints, and i feel like io have no idea what is going on now. Is it common practice to develop an application, then split all the different parts of once it is finished? All the finding unused modules and making sure each file has the correct modules imported has just totally knocked my confidence after thinking i was getting on quite well with the course. I just tried to create a small app from scratch, I have no idea where to start after watching this video

native tide
tough tartan
cosmic panther
#

I need to set up about 30 static web pages using django. All with seperate Domain names. All they are doing is hosting an embedded youtube video and a database that will collect infomation such as name and phone number. Whats the cheapest way for me to host all these sites together? Its for my sales team

toxic flame
#

use one vps or dedi and install cpanel with django

#

or nginx setup multiple ports for different django instances

#

but since it's static I don't see the need of using django, since django is practically a backend

#

Unless you can have 1 backend / main domain that rotates the video url per request and have all your web pages point to that

native tide
#

ok um

#

i need help with php on nginx

#

instead of loading the php it just ignores it and downloads it

#

any ideas?

dark hare
# umbral bobcat Hey everyone, I've been working through Corey Schafer's flask tutorial on youtub...

Thats great you're building an app from scratch! However dont be afraid to make mistakes, even though you might be building something you want to complete dont be afraid to rewrite or throw away bits you aren't happy with, this is learning and practicing, any other vocation requires practice and this is how you can practice. There is no right or wrong way of how to build an app, there are only techniques, but right now get stuck in and focus on what you want to build.

burnt charm
#

which should i learn?

#

Flask/dijango?

#

which is better/easier

#

?

spare iris
#

I used Flask

#

but whatever you want to do

copper juniper
#

Django is the the worst thing on earth, flask is cool to play with but it has very limited potential

dapper tusk
#

django isn't bad

copper juniper
#

Deploying both is a nightmare when compared to other frameworks

dapper tusk
#

that is true

copper juniper
#

Django is terrible

dapper tusk
#

instagram does quite fine using it

#

can't be too horrible

copper juniper
#

I mean unintuitive

burnt charm
#

guys!

spare iris
#

there will always be an opinion that will disagree w what you think

dapper tusk
#

ye, it does have a learning curve

burnt charm
#

im getting mixed signals here

dapper tusk
#

learn django, it is easy to get things done in and requires less setup than flask

copper juniper
#

Every time i need to do something with Django I know I will forget that and will have to read the docs again

burnt charm
#

flask or django?

#

ok listen

#

which is easier to learn and use?

dapper tusk
#

flask, but it is not as powerful

#

well, by default

copper juniper
#

Try both

burnt charm
#

which has more potential

dapper tusk
#

once you do actually set it up to do everything django comes with, its even worse than django since you have 4 different docs instead of 1 set of docs

#

Django I would say

#

a modern website would probably just use fastAPI with react.js though

burnt charm
#

brainmon which do i use then?

dapper tusk
#

honestly, for 99% of websites

burnt charm
#

im not looking to make a massive website

dapper tusk
#

either will work fine

#

toss a coin

burnt charm
#

do you guys know any websites made from flask?

dapper tusk
#

I think some of discords APIs are/were in flask

burnt charm
#

so that i can see what is truly possible to achieve with flask

copper juniper
#

Tbh if you are seroius about webdev you should just learn react/nodejs, all the hype and bling is there currently

burnt charm
#

nah python is my choice

copper juniper
#

Flask is minimalistic and you have to write your own plugins and modules, any react dev will do in an hour the things that you will do on your own in flask for long long days, hard to compete with that

dapper tusk
#

react doesn't really do backend

#

which is where flask shines

copper juniper
#

True

dapper tusk
#

I do agree react > jinja templates

burnt charm
#

so django?

#

0=0

copper juniper
#

Maybe react / flask woudl be a cool thing, but didn't tried that

burnt charm
#

;-;

copper juniper
#

I mean react flask combo

dapper tusk
#

essentially, there are 2 parts to webdev

burnt charm
#

)-(

dapper tusk
#

making the frontend, and the backend

#

the frontend is much easier in JS than in anything else right now

burnt charm
#

ok

dapper tusk
#

be it with vue.js, react or the "new cool framework"

burnt charm
#

and backend?

dapper tusk
#

the backend can be flask or django

#

and both will do about the same job

burnt charm
#

The questions is..... which one

dapper tusk
#

I suggest django since its less effort to setup

#

don't have to install a separate ORM and such

burnt charm
#

@dapper tusk @copper juniper have you both tried both django and flask?

dapper tusk
#

yes

copper juniper
#

Yupp

burnt charm
#

ok that means then both your opinoins are valid

#

@copper juniper what do you suggest?

copper juniper
#

My question is what do you want to do because python is not the strongest webdev language, not the best to learn as first

dapper tusk
#

python is perfectly fine for backend

#

node isn't that excellent

copper juniper
#

You can simply learn js, do react apps with simple backend on nodejs and be fine with that

dapper tusk
#

and honestly, node is a lot more effort to setup than django

burnt charm
copper juniper
#

Yeah, but node can ie execute code in browser while python has to send it through some v8 interpreter I guess

#

And thats why its much slower this way

dapper tusk
#

we are talking about backend

#

you aren't running your logic in the browser

#

thats just stupid

copper juniper
#

Depends

dapper tusk
#

you are running it on the server

#

which you buy

copper juniper
#

I do appreciate the puppeteer framework on node

#

To do any webscraping is much better than anything in python afaik

burnt charm
#

OK. Django is the way to go for backend?

#

and frontend?

dapper tusk
#

lets just say yes for simplicity

#

for frontend you want react or vue.js, or just html+css+templates

#

pyppeteer does exist and is afaik very similar

copper juniper
#

@burnt charm How good are you with sql/nosql?

dapper tusk
#

the django ORM works with sql, and you don't really need to know sql for it

copper juniper
#

On flask you will have to do all hard db work from scratch

dapper tusk
#

you can use sqlalchemy to also get an ORM

burnt charm
copper juniper
#

I think sqlalchemy is prettybad tbh, it is like learnng something completely different than sql and overloading your brain with this garbage methods

burnt charm
#

Guys, my main goal is to make a website with front end and backend by learning s least languages as possible.

copper juniper
#

Than go js, react frontend + nodejs backend, one language to do all

#

Won't be powerful but still can be decent

#

This is why js thrives right now

#

Not ideal, but fast to learn and make things

quick cargo
#

id probably recommend using TS over JS tbf

#

stops alot of easy and hard to debug errors at times

copper juniper
#

TS is compiled to the plain JS in the end anyway, transistion from one to another is pretty nice

#

Pretty ez to learn both

quick cargo
#

its just having those enforcements make TS nicer to work with as you're not running into underdefined all the time mmLol

copper juniper
#

Static typing alone removes half of security bugs on the planet so I guess TS will be the new standard someday

#

But to start today you can do both and will be fine

polar nova
#

is there anyone who use google app engine?

#

i am stuck with the sql database

#

it says attempted to write readonly database

#

is there anyone who faced with same problem?

native tide
#

can someone explain to me what reverse() does in django

umbral bobcat
hard umbra
hard umbra
hard umbra
#

Or it could just be the URL of a view without referencing a database object.

#

Sorry, fixed the above comment. URL gets translated to a view (either with or without parameters)

native tide
#

why is it called reverse()

hard umbra
#

If you pass the view to the reverse function, yes.

#

because it is the reverse of the URL resolver process, I guess.

#

I think if you use the %url% in templates, it also triggers reverse.

native tide
#

ohhh I see

#

That makes sense thanks

hard umbra
#

You are welcome

shadow gate
#

Hi. Does anyone know how a celery task can continue after reboot? Or link to any resources/diagrams to help understand how it works?

sudden grail
#

hey, do you have any clue about the future/career options in django?

#

it's on a massive decline? or?

#

nodejs seems to be taking over on it

hard umbra
#

django is a web framework for python.

#

nodejs is a runtime environment for javascript.

#

like cpython is a runtime environment for python

sudden grail
#

i know

#

i know how to code etc i know quite well ts, react, node, typeorm, django

#

graphql

#

just don't know which way could be a better bet in long terms

hard umbra
#

django is a pretty stable web framework that doesn't change much these days.

#

both python and js are popular languages.

#

it depends on what you want to build.

cosmic panther
mint folio
#

And depends on what the jobs are like or their demand is for django in your area

sudden grail
mint folio
#

I rarely see a job advertising django for where I live, but that’s my case.

sudden grail
#

not businsess

#

oh

#

got it

hard umbra
#

node has the big advantage that you can use the same language on both frontend and backend, since you are stuck with js in the browser. Python and django in the backend has the advantage that you don't have to change much about the backend each day because fashion changes.

sudden grail
#

I think I'm gonna apply for js and django jobs as well, and let see what my destiny wants to me 😄

hard umbra
#

I guess you will have to learn in any job.

spare iris
#

you always do

weak lynx
#

Hello there! Does someone know a boostrap template ofa single service? Like th products individual page with the description but with a service?

mint folio
weak lynx
#

not a physical object

mint folio
#

Sure you can probably find them online, but maybe not as specific

weak lynx
#

im searching but im not able to find it

mint folio
#

Are you after a static site?

vestal hound
#

in the context of web development

mint folio
#

Because generally things like plumbers would just have static few page sites, or are you wanting something more dynamic data driven

weak lynx
#

static yeah, im searching for it, but im not able to find a template

native tide
#

hey

#

can i get some help with a issue regarding html?

vestal hound
#

don't ask to ask

mint folio
weak lynx
#

thank you

native tide
#

so im making this project website to get some web dev down. And yk how you can press a button to go to a certain part of a page? like /#id, How would you do it so it stays on the same page but still goes to that part of the page?

vestal hound
#

that's called

#

a URL fragment

#

and it works using the id HTML attribute

#

e.g.

#

<div id="to-me"></div>

#

can be accessed with #to-me

native tide
#

doesnt that fresh the page tho?

#

i tried that but

#

when i press on the one

#

thats suppose to bring me to #test it doesnt

#

and instead refreshes the page

#

and goes back to the defualt page

vestal hound
#

nope

#

it shouldn't do that

#

it's probably

#

something to do with your href

#

okay just check Wiki for an example

#

Hypertext Markup Language (HTML) is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaScript.
Web browsers receive HTML documents from a web server or from local storage and render the documents into mul...

#

inspect one of the links in the table of contents

#

<a href="#Naming_conventions"><span class="tocnumber">4.3</span> <span class="toctext">Naming conventions</span></a>

native tide
#

oh yea it seems to be working now

#

i never implemented it before asking

vestal hound
#

🥴

native tide
#

i thought it redirected to a new page

#

and thats how it loaded

#

by going to /#a

#

thanks

vestal hound
#

yw

tough tartan
surreal horizon
#

I want to use my flask app as a web app and rest api and I want to receive data from the api with JS, so this is what my JS code looks like ```js
const fetch = require('node-fetch');

const apiURL = 'http://127.0.0.1:5000/api/myapi/';

async function getISS() {
const response = await fetch(encodeURI(apiURL));
const data = await response.json();
console.log(data);
}

getISS();
For some reason it works when I run it with node, but i also linked my JS with to my HTML template and it gives me this error
Uncaught ReferenceError: require is not defined
at app.js:13

opaque edge
#

it possible to make a web page with python ?

uncut spire
#

does a good strategy for implementing a db connector with sqlalchemy change when going from gunicorn/flask to uvicorn/fastapi? like do i need to do scoped sessions and make an async connector for my app to take full advantage?

umbral mulch
#

Hey!!
I am working on a project where I want to 'watch' for a button on the webstie to see if it is clicked. i am using python and the website is dynamic including the button. Any way I can easily do this?
thank you very much for your help!!

umbral mulch
pliant bane
#

thats what i do with a project of similar nature

wooden ruin
inland copper
#

yes

#

event listener and onclicked

dense wigeon
#

Anyone here with socket.io experience? I'm trying to run multiple tasks on my server while emit data. I used start_background_task to run a function which reads from serial port and emit data every time new data received. Now i want to do some calculation on that data, typically every time unit which will require me to have new independent task. But i failed to start multiple start_background_task. Any idea how i can solve this ?

from flask import Flask, request
from flask_socketio import SocketIO, emit
from flask_cors import CORS
from threading import Lock
from datetime import datetime
import json, time, serial, threading


app = Flask(__name__)
CORS(app)
socketio = SocketIO(app, cors_allowed_origins='*')
thread = None
thread_lock = Lock()


@socketio.on('connect')
def start_get_data_thread():
    global thread
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(target=emitSolarData)


def emitSolarData():
    while True:
        try:
            data = serial.Serial('/dev/ttyUSB0',115200).readline().decode('utf-8')
            if data != None:
                socketio.emit('solarDataStream', data, broadcast=True)
                socketio.sleep(0.1)
        except:
            print("Failed to receive or send data")


if __name__ == '__main__':
    socketio.run(app, host="0.0.0.0", port=5000, debug=True)
native tide
#

Can anybody advice me on the package you would use to adapt Django Rest framework schemas. I would like to autobuild my form on basis of a schema so they match with https://vueformulate.com/guide/forms/generating-forms/

Vue Formulate ⚡️ The easiest way to build forms with Vue.js

Built-in validation, error handling, grouped & repeatable fields, form generation, and more — make complex form creation a breeze.

tender crater
#

I am using a simple class for all my tests in a Flask app. Is there anything wrong in the snippet below that might prevent the db from dropping all tables in between tests?
I don't get why the migration is actually being executed but tables don't get dropped at before it.

import unittest

from flask_sqlalchemy import SQLAlchemy
from flask_migrate import upgrade

from backend import create_app

db = SQLAlchemy()

class BaseTestCase(unittest.TestCase):
    def setUp(self):
        app = create_app("backend.config.TestEnvironmentConfig")
        self.context = app.test_request_context()
        self.context.push()
        self.client = app.test_client()
        self.runner = app.test_cli_runner()
        db.drop_all()
        with app.app_context():
            upgrade()
        db.create_all()

    def tearDown(self):
        self.context.pop()

Obviously in the postgres db logs I can see the db gets queried correctly

quiet ridge
#

hey @native tide

#

so where did you get the javascript cdn

#

okay lemme check

#

well can you please tell me things in more detail

#

this contain library for version upto 3.1.2

#

which one do you use

#

so which one have you used with the flask-socket 5.0.0

wanton ridge
#

how can i use SHA256 in Flask for hashing password?

quiet ridge
#

just type this while storing the password

wanton ridge
#

it says SHA256 doesnt exists

quiet ridge
#
import from werkzeug.security import generate_password_hash, check_password_hash
#

and then use ```py
password = generate_password_hash(password , method = 'sha256')

quiet ridge
#

do this when you are storing the data on the database

wanton ridge
#

yeah will try later on, i am at work right now

quiet ridge
#

okay fine

rotund patio
#

I am considering creating a personal/ portfolio website. I was just wondering if anyone had any advice on what hosting service to use (hostinger?) and what libraries/ languages to use (node, react, angular, html/css)? Thanks

candid yew
#

I need help with my html code

#

does anyone here know html?

#

I want all the lists to not be indented like that

quiet ridge
#

well hey guys I m having some problem with the flask-socketio

#

lemme show you

eternal blade
#

Hi, I have some videos in my django site but it is taking pretty long to load.

quiet ridge
#

please help me

#

please check this too

candid yew
#

I need help

nimble epoch
#

not sure just an advice

eternal blade
glossy osprey
#

Hi all, first timer to Python Discord, so apologies if this is not the place. I am starting fresh in Django (though not new to python in general), and am wondering if there are any recommendations or best practices for implementing back-end recurring tasks (in unix land, "cron jobs") that can be managed throught he Django site. I've seen a lot of people jumping onto Redis and Celery, but those seem like overkill for a cron job that just needs to be Django context aware to update some models. Anyways, apologies again and hope this is the right place to ask!

toxic flame
#

Try float:left on all the "li"'s

opaque rivet
minor ether
#

hey guys im trying to coummicate with asp.net code and python code in same server or computer how can i do that most effectively?
asp will receive the request and forward it to python and vice versa

elfin gorge
#

can I somehow preset email field in views.py ?
class Online(models.Model): file = models.FileField(upload_to='online/') email = models.EmailField(max_length=254)

My intention is to set email field to email of authenticated user email.
I have tried: form = UploadForm(request.POST, request.FILES['file']) form['email'] = request.user.email

I'm using django

formal gull
#

i am making a flask app that can send a function through a selenium app that i have made. i need 5 people to be able to use it at once. is it possible to kind of assign a session to a new instance of it?

#

so that each person using it has their own browser and gets back their own information.

hybrid bobcat
#

hello guys, so like im currently using Flask for a stuff, and I wanna have a view function that have dynamic path. now i wanna each dynamic path to have its unique instance, so say if a user is on that path and then if a post request is made, only the instance on that specific path is changed, how is that done?

#

cuz i tried using a variable to represent the instance but once its chnaged on one of the path, all of the instances on the oher paths all changed

#

I don't wanna use databse btw

#

so like if a user can hold that instance as the session variable and the chnage (once the post is made), it will use websocket to emit to other connections on that path

#

so only the one on that path is changed

spark swan
#

hey guys. I am currently planning to make a selenium autocheckout bot which can be managed by a django website . I will also be using celery. Could anyone tell me where and how to host it? If there is a tutorial on it even better. So far i couldn't find a tutorial for it. Also I have to store some private info that is too sensitive but the bot needs to access it for checking out, etc where can I store it?

autumn solstice
#

which is better, django or flask? I am going to be designing a html frontend with bootstrap and need parts of it to work with python

maiden tulip
heady drum
#

@hybrid bobcat

autumn solstice
hybrid bobcat
#

Yea but but like if I change the variable all of the variables on all the paths changed for some reason

sonic stratus
#

Hello everyone,
I wrote a list of more than 200 cheat sheets that every dev should know about. It took me 8 hours to complete and I decided to post the full list on an online blogging platform. The article received more than 500 likes in less than two days. I invite you to go check it out and dm me if you have cheat sheets to have. I'm sure you will found it helpful. Don't hesitate to bookmark the article (it's on dev.to, if you have an account, or you can create one) and to leave a like if you appreciate it.
The link:
https://dev.to/devlorenzo/the-ultimate-compilation-of-cheat-sheets-100-268g
Thanks for reading!

DEV Community

Hello World Today I wanted to share with you my Cheatsheet Compilation that every dev should know abo...

fathom belfry
#

I'm learning Django. can someone explain this syntax pls

#

def update(self, instance, validated_data):
"""
Update and return an existing Snippet instance, given the validated data.
"""
instance.title = validated_data.get('title', instance.title)
instance.code = validated_data.get('code', instance.code)
instance.linenos = validated_data.get('linenos', instance.linenos)
instance.language = validated_data.get('language', instance.language)
instance.style = validated_data.get('style', instance.style)
instance.save()
return instance

#

on validated_data.get why are there 2 values being passed?

autumn solstice
#

i have used bootstrap to make html, css and some javascript. However, i need to deploy it with some python functionality. In which of the following frameworks can i use the js functionality and use python backend for some functions? django or flask?

shadow gate
fathom belfry
#

@shadow gate ahh that makes sense. thanks!

plain dust
#

I have

$('form#joinmeeting').submit(function(event) {
            socket.emit('joinmeeting1', {data: 'red'});
            return false;
        });

and in the form

<form id="joinmeeting" method="POST" action='#'>
    <input type="submit" value="I am in a meeting.">
</form>

but it doesnt cause the socketio function (first bit of code) to execute it just takes me to /currentpage#

native tide
#

(not exactly python webdev but still) How exactly does web based discord know when a message sent to a channel (not sent by you)

#

i.e. how does the server tell the client to update itself

plain dust
native tide
#

not giving answer

plain dust
#

oh

#

right

#

theres no question mark

#

its confusing

#

also this channel isnt strictly for python web dev

native tide
#

si si

#

but it's a primarly python based discord server

#

so

#

¯_(ツ)_/¯

desert parrot
#

driver.get(url) Always returns "access denied, you donot have permission to view this site" :(

I tried googling it, I found a lot but its just not working. Any ideas?

solemn flare
#

How do you create serializers with these data structures in DRF? ```
class AllPostsSerializer output:
{
"post_count": 2,
"posts": [
{ <data handled by another serializer> },
{ <data handled by another serializer> }
]
}

fluid fable
#

I'm not sure if this is the right spot to ask this question, direct me if there's a better spot:

Im using django and in designing my models, I have an interesting use-case for the User model (the model used for authentication). In my application, a User can either be a customer, or an employee. They both log in and have different permissions. The catch is that sometimes an employee needs to create a User as a customer (as one of their customers), and that new User cannot log in. It is just to be able to track that particular employee's customers. So to clarify, there are essentially two types of customers, those that can log in, and those who cannot. Other than authentication, they are stored with the same data. Is there a good way to implement this, potentially with class inheritance, to allow that separation between customers? or is the correct implementation to just create a User with no permissions to anything?

manic frost
fluid fable
#

@manic frost Thanks for your help. Having a UserData parent may be the best way to go. The reason I would prefer them to be attached to the same table is because in the system they are treated the same. For example, if there is Project that an Employee is doing for a Customer, that project needs to be tied to the Customer, regardless of which type of customer they are. If I stored the two types in two different tables, how would the relationship table be able to tell which Customer table to go to? (the Foreign key from the Project to the Customer table needs to to be an id from one table)