#web-development

2 messages · Page 228 of 1

dusk portal
#

it provides default image (works fine /as expected)

#

but when i add it from a form connected to the API (backend)

#

it doesn't sends

#

default value

#

idk whyy

#

man idk why

native tide
#

Like constraints of a variable would conventionally be set with a method

rigid laurel
#

the way it works is called type hinting - it's just a feature that's supported by Python. In general when you type hint something, it is only a hint and you it could technically be any type

#

but pydantic does some introspection and checks the types and it will then change it's behaviour based on those

#

!e

a_variable : int = "not an integer"
print(a_variable)
lavish prismBOT
#

@rigid laurel :white_check_mark: Your eval job has completed with return code 0.

not an integer
real root
#

Anyone know how to start a production server for flask?

native tide
rigid laurel
#

I'm honestly not entirely sure, but in my experience I've never had to manually set __annotations__ for anything

stiff plume
#

hey i am getting this error from this code

from selenium import webdriver
driver = webdriver.Chrome(r'C:\Users\ahmad\OneDrive\Desktop\Apps\html\chromedriver')
driver.get('https://www.wolframalpha.com/problem-generator/quiz/?category=Calculus&topic=BasicIntegrate')

wd = webdriver.Chrome(executable_path=driver)
players = driver.find_elements_by_xpath('//td[@class="problemImage ng-isolate-scope ng-scope"]')
C:\Users\ahmad\PycharmProjects\pythonProject3\main.py:2: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  driver = webdriver.Chrome(r'C:\Users\ahmad\OneDrive\Desktop\Apps\html\chromedriver')
C:\Users\ahmad\PycharmProjects\pythonProject3\main.py:5: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  wd = webdriver.Chrome(executable_path=driver)
Traceback (most recent call last):
  File "C:\Users\ahmad\PycharmProjects\pythonProject3\main.py", line 5, in <module>
    wd = webdriver.Chrome(executable_path=driver)
  File "C:\Users\ahmad\PycharmProjects\pythonProject3\venv\lib\site-packages\selenium\webdriver\chrome\webdriver.py", 
line 71, in start
    self.process = subprocess.Popen(cmd, env=self.env,
  File "C:\Users\ahmad\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 966, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\ahmad\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 1375, in _execute_child
    args = list2cmdline(args)
  File "C:\Users\ahmad\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 561, in list2cmdline
    for arg in map(os.fsdecode, seq):
  File "C:\Users\ahmad\AppData\Local\Programs\Python\Python310\lib\os.py", line 822, in fsdecode
    filename = fspath(filename)  # Does type-checking of `filename`.
TypeError: expected str, bytes or os.PathLike object, not WebDriver
#

anyone know what this is? if the error doesnt make sense i had to remove a bit of it in order to fit it in

thorny lake
stiff plume
#

yeah i fixed that

#

but now it is saying this

#

TypeError: expected str, bytes or os.PathLike object, not WebDriver

#

idk how to fix that

#

oh wait

#
from selenium import webdriver

import pandas as pd
driver = webdriver.Chrome(r'C:\Users\ahmad\OneDrive\Desktop\Apps\html\chromedriver')
driver.get('https://www.wolframalpha.com/problem-generator/quiz/?category=Calculus&topic=BasicIntegrate')

wd = webdriver.Chrome(executable_path=driver)
players = driver.find_elements(by=By.XPATH, value='//td[@class="problemImage ng-isolate-scope ng-scope"]')
#

new code

#

idk if i fixed it

thorny lake
#

1 sec, I have something like it

stiff plume
#

ok

#

do i remove

wd = webdriver.Chrome(executable_path=driver)
thorny lake
stiff plume
#

yeah i saw that do you just add .service() to that line i was trying to delete

stiff plume
#

yeah ok i added it

thorny lake
#

Yeah try -

wd= webdriver.Chrome(service=Service(ChromeDriverManager().install()))
stiff plume
#

it still gives me that error

#

do I even need this line?

#

can i just delete it when i do i dont get any errors

thorny lake
#

Make sure you have the imports

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
stiff plume
#

ok

#

well now I got

#

ModuleNotFoundError: No module named 'webdriver_manager'

#

ok

#

im putting pip install webdriver-manager

#

ok no more errors

thorny lake
#

nice

stiff plume
#

thx

#

yeah im just trying to webscrape a page for a specific image

#

i just need to find the image rn

thorny lake
#

are you using bs4

stiff plume
#

no selenium the website has javascript so i need to use selenium

#

and for some reason i cannot find the image

#
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager



driver = webdriver.Chrome(r'C:\Users\ahmad\OneDrive\Desktop\Apps\html\chromedriver')
driver.get('https://www.wolframalpha.com/problem-generator/quiz/?category=Calculus&topic=BasicIntegrate')

wd= webdriver.Chrome(service=Service(ChromeDriverManager().install()))
players = driver.find_elements(by=By.XPATH, value='//td[@class="problemImage ng-isolate-scope ng-scope"]')
#

try running this

stiff plume
#

im trying to get this

topaz widget
#

Hey does anyone know how to get a static file imported from JavaScript using a fetch request (with Django)?
I have some images I want to load as textures for this WebGL project I'm working on, and I'm trying to figure out the best way to get those images loaded.
I currently put a script tag/element in one of my HTML templates and then load the textures there so I can use the Django template syntax to dynamically load the static files, but I would like to get away from putting JavaScript directly into the HTML. I'm not sure how I can properly reference static files from another static file (JS file in this case) while having the path dynamically generated by Django on the back end.

thorny lake
topaz widget
#

If it were JSON data, I was downloading, I would know how to do this, but an image seems like it would be a bit different.

stiff plume
#

Ok thx I'll take a look at it

hollow dragon
#

guys what is this? should i worry about it?

#

im just trying to upload my flask app to github

#

i read somewhere that i should ignore this but im not sure

#

or maybe i should use: git config core.autocrlf true

hollow dragon
#

im having issues with venv

#

should i convert it to 'requirements' or what?

#

so all I have to do is just put the requirements.txt in my github and stop worrying about the venv folder?

inland oak
#

it is big and will be broken once its absolute path is changed

#

plus it is silly to commit such bit depepdencies

#

have you checked its size? it takes hundreds of megabytes!

hollow dragon
#

👍

dense cedar
#

My STATIC_ROOT = 'static/'
so I would use it: src="static/path/to/other-static-file.js"

twin prawn
twin prawn
#
# solution
  def calculate_total_cost(self):
        return self.annotate(
            total_cost=Sum(
                F('products__quantity') * F('products__price')
            )
        )
iron magnet
#

I'm new to using FastAPI and I'm quite impressed so far. I have a basic JWT authentication scheme kind of working. However, I have a Depends for a route where I would like it to fail if the dependency returns None.

@app.post("/highscores", tags=["highscores"])
async def add_high_score(score: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    ...

The function get_current_user checks the JWT token for validity, extracts a user id and loads the user from the database. However if the user has been deleted then the token is valid but there is no such user, so the function returns None. Is there a way to force the dependency to fail in that case?

#

Or should get_current_user raise an exception if no user could be found?

frank shoal
#

Use a different dependency called require_user which raises a HTTPException

#

i.e. ```py
def require_user(current_user: User | None = Depends(get_current_user)):
if current_user is None:
raise HTTPException(401)
return current_user

frank shoal
#

@iron magnet ?

iron magnet
#

@frank shoal Ah, that’s a great idea!

hard whale
#

Probably not quite python question but... I have a big table from sqlite bd on a home page and i want to add sorting and filtering. What is the best way to implement it provided I have no JS experience?

#

I use fastapi to interact with the db and a little jQuery

frank shoal
#

I suggest using datatables.

hard whale
#

Tell me more please

frank shoal
hard whale
#

I used Semantic UI to add tables to the page, but there is no pre-added sorting

frank shoal
#

If you have a lot of data, you could use ajax and the pip library sqlalchemy-datatables to handle it.

#

!pip sqlalchemy-datatables

lavish prismBOT
hard whale
#

Hm ok, so its not in vanilla sqlalchemy?

frank shoal
#

It's not a plugin, just a layer on top.

hard whale
#

I.e. I have full sqlalchemy installed

frank shoal
#

You just give it a list of columns, your url search params, and your initial database query, and it handles the rest.

lilac grotto
#

When I have a input field for example and when the field get changed I want to make a popup to save the Changes. How could I detect the change of the input field?

frank shoal
#

Oh, you want a live view of the data that you can change?

#

like a spreadsheet?

lilac grotto
#

Yea

#

If any data in given fields gets changed then a action should be performed

whole drift
# stiff plume

for images <img> use get_attirbute("src")
this will give you the link, for a href use "href"

lilac grotto
#

Is there maybe any way to do it with Flask?

#

You can take Discord Roles as a example. If any Text/Permissions gets changed you get a prompt to save it

#

Thats what I need

abstract birch
#

that would probably be a javascript thing and not python

frank shoal
#

Well it wouldn't be too hard to make a CRUD endpoint in flask.

#

It would just be detecting when a input is changed and setting a flag.

#

It's a bit simpler in a framework like vue

abstract birch
#

I got a small question, I got a db on mongo and using flask.
Do you guys know anyway I can show the database on the website in interactive way? so the users can filter through stuff, search and export the results ?

frank shoal
#

datatables!

abstract birch
#

hmm looks pretty neat but I can't see export feature

lilac grotto
frank shoal
abstract birch
frank shoal
#

put is replace. patch is edit

inland oak
lilac grotto
abstract birch
frank shoal
#

You would need to use the onchange event and mark a variable named something like dirty

lilac grotto
winter sinew
#

Hello ladies and gentlemen! Got a quick question regarding managing classes. I finally worked out a working webshop with a "Item" class. The "Item" class has many functions on it and is referenced in other classes to make the cart and checkout process running. Now i want to specify the products by creating new classes like "Shoe" or "Tshirt" which each has own attributes additional to the "Item" class attributes. What are my options to do that or what is recommended to do? I came around Abstract Base Model but i can not reference to abstract models. I read about PolymorphicModel, but is it really the way to go?

frank shoal
#

with sqlalchemy or django?

abstract birch
#

The table isn't loading at all, tried with hard coded data and its good

frank shoal
#

use serverSide: true, ajax: "/some-url"

#

You do need a <table> tag somewhere too

abstract birch
#

yea I got <table>

#

never worked with ajax 🥲

frank shoal
#

ajax is just a old version of fetch

#

make an endpoint in flask, and you should be fine.

abstract birch
#

like it should be a GET that returns the array ?

frank shoal
#

<table id="table">
    <thead>
    <tr>
        <th>Field 1</th>
        <th>Field 2</th>
        <th>Field 3</th>
    </tr>
    </thead>
</table>

<script>
    $(document).ready(function() {
        $("#table").DataTable({
            processing: true,
            serverSide: true,
            ajax: "{{ url_for('datatable_ajax') }}",
        });
    });
</script>
wicked comet
#

Guys have you heared about pyscript ??

frank shoal
#
from datatables import ColumnDT, DataTables
from flask import Flask, request

from .models import db, Table

app = Flask(__name__)

@app.route("/datatable_ajax.json")
def datatable_ajax():
    columns = [
        ColumnDT(Table.field_1),
        ColumnDT(Table.field_2),
        ColumnDT(Table.field_3),
    ]

    query = db.session.query().select_from(Table)
    params = request.args.to_dict()
    row_table = DataTables(params, query, columns)

    return jsonify(row_table.output_result())
#

libraries: flask, sqlalchemy, sqlalchemy-datatables

abstract birch
#

the Table and db is sqlite?

frank shoal
#

it's your sqlalchemy models

abstract birch
#

i'm using mongodb, i'll change that part

frank shoal
#

!pip mongo-datatables

lavish prismBOT
abstract birch
#

thank you sir

abstract birch
frank shoal
#

nope.

abstract birch
#

im not getting any error but its not working lol

abstract birch
#

Im getting this weird long request

127.0.0.1 - - [11/May/2022 22:12:32] "GET /datatable_ajax?draw=1&columns%5B0%5D%5Bdata%5D=symbol&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=0&order%5B0%5D%5Bdir%5D=asc&start=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&_=1652296289001 HTTP/1.1" 200 -
abstract birch
covert yew
#

how would you suggest I can add real time chat into my flask web app?

covert yew
abstract birch
#

you meant stock charts ?

covert yew
#

I meant chat 😂

abstract birch
#

oh sorry I read "charts" 😅

covert yew
#

lol

novel swift
#

How can I turn this into a flask app?

import requests

API="http://api.brainshop.ai/get?bid=166402&key=Plje0nBq6IAuFf0S&uid=[uid]&msg="
question = input("Question> ")
response = requests.get(f'{API}{question}')
print(response.json()['cnt'])```
midnight tundra
#

Hey trying to run a flask app in docker container, I keep getting the error "FLASK_APP has no env variables"

#

anyone has idea how to setup enviroment variables in windows?

frank shoal
#

How are you running it? Compose, docker run, or dockerfile?

lunar laurel
#

ok so im trying to make a login/form thing, but I'm confused on how to submit it. I would like for it to be put into a json file if thats possible
heres my form code incase you need it: https://hastebin.skyra.pw/idusicovih.htm

worn crystal
#

i'm using selenium to add items into a cart and I just wanna know if that is a safe thing to do? I want users to be able to use the window i opened to buy whatever is in their cart

lethal junco
#

please help

serene prawn
hard whale
#

Hi guys! Could you help me with modals? I have 2 modals on the same page but contents of both appear on the same popup window one under another
https://semantic-ui.com/modules/modal.html
How can I devide 2 modals?

native tide
#

can u be a little more clear/.

#

@hard whale

#

post ur output

#

and what u expected it to be

hard whale
#

I mean is there any id for modal to open some content in separate pipups?

#

Not in the same one

short flax
serene prawn
short flax
serene prawn
#

Oh, right, sorry 😅

#

Didn't see the render call

short flax
#

the render call was on else: statement

#

and i was getting that error

#

i removed the else and reverted the indentation on render and i dont get error nor income value is adding

#

a_form still working

#

no idea what is wrong :/

serene prawn
#

I'm not sure what's wrong there too, all i can suggest is debug it and see what you actually return from the function 🤔

native tide
#

Won't the post request get resent to the same view if u use redirect

#

@short flax

#

Won't it become infinite post loop

#

🤔

short flax
native tide
#

if u have primary keys

#

then it will throw an error while saving

native tide
#

or form validator

short flax
#

`class BudgetData(models.Model):
SPOZYWCZE = "Spożywcze"
CHEMIA = "Chemia"
RACHUNKI = "Rachunki"
ALKOHOL = "Alkohol"
GRY = "Gry"

CATEGORY_CHOICES = [
    (SPOZYWCZE, "Spożywcze"),
    (CHEMIA, "Chemia"),
    (RACHUNKI, "Rachunki"),
    (ALKOHOL, "Alkohol"),
    (GRY, "Gry"),
]
category = models.TextField(choices=CATEGORY_CHOICES, default=SPOZYWCZE)
cost = models.FloatField(default=0)
date_added = models.DateTimeField(default=timezone.now)
user_expense = models.ForeignKey(User, on_delete=models.CASCADE, default="")
income = models.FloatField(default=0)`
#

its the model

#

b_form use just the income at the bottom

#

class AddIncome(ModelForm): class Meta: model = BudgetData fields = ["income"] help_texts = { "income": ("Add your income."), }

#

and the form

vapid jay
#
def require_appkey(view_function):
    @wraps(view_function)
    # the new, post-decoration function. Note *args and **kwargs here.
    def decorated_function(*args, **kwargs):
        if request.args.get('key') and request.args.get('key') == APPKEY_HERE:
            return view_function(*args, **kwargs)
        else:
            abort(401)
    return decorated_function ```
#

can anyone tell what this code snippet actual does under the hood?

digital magnet
#

guys, i cant understand this: if i create templates in django, am i doing some kind of frontend development? so if i create just an api in django, can i then make the frontend in, for example, react and take the information from the django api i made? or am i confusing a lot of concepts?

dense slate
#

Templates are for FE dev for those that don't want a full FE framework like React/Vue

#

You'll look into Django REST or Graphene / GraphQL for that.

dusk sonnet
#

Hey, im planning to build a Chat Room Web App using Django and for the past day or two iv just been researching and watching videos on it because its a whole new realm for me. But one thing i havent been able to understand is how Redis is used? so to my understanding Redis makes queries to the database way faster because everything is stored in "memory". And you cant use "inMemory" for your CHANNEL_LAYERS unless its for testing purposes, which is to my understanding why Redis needs to be used for production and deployment. However i dont actually know how the process works. Like once you write channel_redis.core.RedisChannelLayer in settings.py to like initiate it, is that it? or do you have to start configuring and managing your code to suit it or something? I havent found any material that has helped me understand this part of it. Mostly i just see people use 1 line and thats it or something.

#

if anyone knows any good material that helps understand Redis i would really appreciate it.

dense slate
#

It would be better suited for something where you don't want to have to hit the server a lot, so maybe some queries that won't change often.

dusk sonnet
inland oak
#

plus the record has a time to expire property (which can be inifinity), once it is expired, it becomes not valid

#

so you can tinker with how long is valid the record there

inland oak
#

your record 123 will be valid for 5 minutes

#

after that something happens

dusk sonnet
#

ohh i see

inland oak
#

redis.get("abc") to get the value of 123

dusk sonnet
#

so sort of like Snapchatish

#

for example sending a message and then you can set a time until that message is removed?

dusk sonnet
inland oak
#

anyway. The point of Redis is that it is just the same dictionary, but its data is shared across instances of your application

#

accross multiple backend instances (we usually ran several django app instances in parallel to handle traffic of multiple users at once)

#

or even across several different backend apps

#

but it is basically still same dictionary with a bit different functionality, which just ensures having dictionary with shared memory across app instances

dusk sonnet
inland oak
#

If u a pervert, you could reinvent the wheel and make the same with multithreading stuff btw 😉 but it will be complex and not needed of course

inland oak
#

at maximum it can give you saving and getting objects in bulks in addition

#

the rest is something invented on top of it

dusk sonnet
inland oak
#

those are already details under the hood of the django channels library

#

any library can use under the hood any other library/stuff

#

the difference is only channel library requiring to have raised infrastructure object of redis

#

same when Django requires instance of postgresql if u wish to work with it (it utilizes Sqlite3 as default alternative though)

dusk sonnet
#

Ah right. Thank you this was very helpful and informative, i appreciate it.

tiny ermine
#

Hi guys, I have a website project powered by Flask. This website presents a visualisation of some common sorting algorithms. The sorting algorithms themselves are written in python, but the implementation of getting the data is written in Javascript atm. Is this a valid approach? Because, when I click on a "sort" button, Javascript sends many requests to Flask using requestAnimationFrame

midnight tundra
inland oak
#

as a fix, consider sending frames in bulk, all at once or just more frames per request

#

or implementing sorting at client side in js (the most performance wise approach to this problem)

tiny ermine
inland oak
#

it will make your job way way easier

tiny ermine
#

wdym

#

why

inland oak
#

because Vue.js will bind your data from its Model to be directly shown as in its View, in a MVVM scheme as far as I remember
You will be able just to have the data changed in Vue (sorting it when doing smth), and it will automatically rerender to user screen

#

everything at clientside, without any requests

#

this is the easiest approach to Client side javascript

tiny ermine
#

oh really?

#

so i don't have to use any python?

#

or can i still use flask

#

cuz i really like the templating

inland oak
#

Vue.js has 10 times more powerful templating

#

giving you also access to stuff like SCSS

tiny ermine
#

so don't even use flask?

inland oak
#

technically u don't need Flask at all in this task

#

pure frontend job

frank shoal
#

Using vue.js, I miss jinja's pipe syntax

inland oak
#

attempt to write js in jinja, and the piping problem will be seen like a minor 😆

tiny ermine
#

i want to make like a debugger sort of screen

#

so basically the data of the sorting algorithm is passed into a linked list

#

which can display the variable names of the current "step" or "pass" of the algorithm in a table

#

or some sort of display type

inland oak
#

xD, i did literally stuff like that once. I made debug shown from Ansible running playbooks 🙂

tiny ermine
#

and the user can go forwards and backwards

#

to see how the code is working

tiny ermine
#

so u saying all this is still a frontend task

inland oak
tiny ermine
#

how hard is it to pickup vue.js

inland oak
#

with learning frontend literally from zero

#

html, css, js, i knew nothing

tiny ermine
#

are there any good tutorials that get u up to speed

inland oak
inland oak
#

Then went through

#

then made a stop at

#

plus went through one less worthy to mention book
and then started learning vue.js docs

inland oak
#

a matter of using Patterns of Programming and having Clean Architecture in itself

#

just cool designed code and the data flow of data

#

which becomes a bit complicated if we remember that it works that well while being in browser and its ecosystem, DOM and browser APIs

#

amazing framework.

#

basically it is using as far as I know virtual DOM, which is reviewed to the user

frank shoal
#

How vue (and most other frontends) works: When state changes, it destroys the node and rerenders it instead of editing it inplace like you would do with jQuery and DOM traversal.

inland oak
#

and probably uses all those javascript listening stuff in order to get feedback back

inland oak
#

more complicated framework to use

inland oak
#

what if in higher component happens the change?

#

and we froze with v-once child components of this component

tiny ermine
frank shoal
#

If you need to manually rerender a node for whatever reason, (you're probably doing wrong reactivity, computed, watcher, key with v-for) you can use $forceUpdate()

#

if the element is in the child component, you can use emits to update the parent. There's also inject and provide for similar, global functionality

tiny ermine
#

any good guides to use vue.js quickly

frank shoal
#

emits is essentially making your own events, like @change="onChange"

#
#

Ben Awad for general javascript and react.js

tiny ermine
#

okay thanks!

tiny ermine
frank shoal
#

see the channel I posted.

#

Hey gang, in this Vue 3 tutorial series for beginners we'll learn Vue.js (using version 3 - the latest major version) from the ground up & use it to make a couple of nice web projects - a reaction timer & the beginning of a small, simple blog. In this video, I'll give you a quick intro to Vue & the new features Vue 3 has to offer.

🐱‍💻 🐱‍💻 BUY T...

▶ Play video
tiny ermine
#

thank you so much

hollow dragon
#

been working on my first Flask project for a while, i love Flask, so good.

frank shoal
#

That's a good looking frontend.

hollow dragon
#

thank you, I was learning / doing frontend before switched to python / flask

#

but I'd say it's 50% completed

frank shoal
#

Good luck on your way to full-stack

#

maybe soon, you can switch to fastapi as a rest backend for your react or vue app

hollow dragon
#

sure, I'm just working on Flask and building this project for my upcoming internship (company uses flask)

stoic lark
#

what about pyscript ? 🙂

hollow dragon
inland oak
#

not valid for real world production

stoic lark
#

still we have to know good javascriot right

#

:S

hollow dragon
#

i hate javascript

inland oak
hollow dragon
#

i used vanilla JS for like 9 months without a framework, it was a pain

stoic lark
#

😄 😄

inland oak
#

well technically there is typescript in addition. But you know, it is still javascript under the hood.

hollow dragon
#

i might do it later

inland oak
hollow dragon
#

but i feel like that would be an overkill for an internship

#

also i want to deploy this to heroku with docker lmao

stoic lark
#

flask

#

is more little projects right ?

hollow dragon
#

yeah

#

microframework

#

but u can use blueprints for larger apps

stoic lark
#

i use django

#

used*

#

there is lots different techs this development things going more complex always..

hollow dragon
#

yeah I'd like to learn django down the road long-term

covert yew
#

any good frontend tutorial?, I have my flask project and I want to stop using bootstrap and write my own styling.

serene matrix
#

Does it make sense to automatically create a new table for every use when they sign up? To keep record about that particular users activities

proper knoll
#

Hello there.
I'm working at a small company that already have a fully implemented java backend, but wants to start migrating to python, starting with some more costly endpoints.
Is there a more a more recommended framework ? A guy in another channel recommended me FastAPI, since my objective is exactly to go fast

#

But is it recommended for big and scalable servers ?

frank shoal
#

I've found fastapi to be similar to spring in some aspects.

serene matrix
#

Just user specific stuff

hollow dragon
serene matrix
next widget
#

anyone here familiar with selenium, also django, running locally?

serene matrix
next widget
#

well my app is trying to execute a chromium.exe file, but I get an error that it has the wrong permissions. I'm able to run it in heroku, and locally elsewhere, but not here locally through the procfile

#

I'm sure its a windows 10 permissions thing, chmod 777 apparently is not a thing here

#

I tried cacls myfile.txt /g everyone:f

#

on the exe, but I get the same error

thorny lake
next widget
short flax
thorny lake
next widget
#

that makes sense to me. I've added the full path to the .env file to the exe

#

(I am new to django)

thorny lake
#

If the .exe is for the chromedriver it just means you have to have it on your local machine - how are you calling it?

next widget
#
chrome_options.binary_location = os.environ.get("GOOGLE_CHROME_BIN")
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--no-sandbox")
driver = webdriver.Chrome(executable_path = os.environ.get("CHROMEDRIVER_PATH"), chrome_options = chrome_options) 
#

my workaround is to comment that code out and to use this code when I run locally and it works fine.

#
options.add_argument('--headless')
options.add_argument('--disable-gpu')  # Last I checked this was necessary.
driver = webdriver.Chrome(chrome_options=options)```
#

though the latter doesnt work when I push to heroku

#

Actually I havnt tried, but I'm sure it wouldnt.

thorny lake
#

and in your .env for the app the driver is stored in "GOOGLE_CHROME_BIN", correct?

next widget
#

yeah right

thorny lake
#

Scratch that, it's actually referencing where it is on your local machine - what is the "CHROMEDRIVER_PATH"?

next widget
#
GOOGLE_CHROME_BIN = "C:\Users\aa\Home-Finance-App"```
#

I set both to the same 🤷‍♂️

#

I might be spending too much time on it already... the work around isnt horrible for me.

thorny lake
#

Lol, ok well is that where it is ?

next widget
#

yes, ha I did put the chromium.exe file where the enviornment variable is pointing to, above

#

and changed its permission using some windows ca function

dense slate
#

@inland oak I updated my production server and I can still access the django admin but I'm getting an nginx gateway error when accessing the site. There were no nginx changes. Anything stick out as a possible reason I'm getting the gateway error?

silver horizon
#

how will you make the models for that/

#

?

#

Create a REST API for cars. It should contain accounts, CarBrand, UserCar, and CarModels. Each user has to be extended by default Django abstract class and should contain a few more columns (for your choice). Each car object contains relations to the user and CarBrand. Each CarModel contains relation to CarBrand. It is all your decision how you will distribute models to different apps. Please make the API URLs with filters (custom typed). All models should be with soft delete.

Models fields:
CarBrand [name, created_at, deleted_at]
CarModel [car_brand, name, created_at, update_at]
UserCar [user, car_brand, car_model, first_reg, odometer, created_at, deleted_at]

Auth:
Please extend the default Django user class and add some custom fields. Create login, and register functionality. User default Django permission classes.

thorny lake
inland oak
dense slate
#

Using DO

#

But nginx was working fine before, no changes to it.

inland oak
#

then we can ask questions in how you deploy your stuff, docker-compose, kubernetes or whatever system

dense slate
#

pulling directly from github

inland oak
#

manually?

dense slate
#

Yea

inland oak
#

that's already a reason in itself.

next widget
inland oak
#

it already means that you can't rely on that you did not change nginx / code of deployment

#

because your deployment is not automated / not a code

dense slate
#

But nginx is only on the prod server.

inland oak
#

even it is homelab, we still having staging / testing env

inland oak
#

your staging environment to test your stuff should be as close and similar to prod as possible

#

i see no reason why you have nginx only in prod

dense slate
#

You're suggesting to run it also locally?

inland oak
#

if you do it for work

dense slate
#

Yea I'm actually going to set that up now, but I'm going to have the same problem in the staging server.

inland oak
#

to discover it in staging before making deployment to prod

inland oak
dense slate
#

Yea, I'm not disagreeing with that. 😄

thorny lake
# next widget ok I'm not sure what that means, when I have run selenium in the past, I just do...

Ok this could be a django/windows thing, I've never ran selenium that way - strictly python/mac, most of the current errors since the update have to do with calling the executable path which has since been replaced with the Service() object, but doesn't seem to be the error you're encountering right now - if chromedriver is somehow enabled within the heroku app through the application source path solely that could also point to Heroku implementation taking care of the issue you're seeing locally. Have you ran it on this machine before?

next widget
#

anyway I have a workaround, its messy and annoying lol, but it works for what I'm doing just fine.

thorny lake
#

Just curious, when you launch the app locally are you running it in a virtual environment?

next widget
thorny lake
next widget
#

I guess I don't understand the heroku buildpacks, from the desription on heroku, they are scripts that are run when the app is deployed. is that considered a pipeline?

#

hi @native tide

wheat verge
#

Is there any documentation to lear about follow notation in django

thorny lake
# next widget I guess I don't understand the heroku buildpacks, from the desription on heroku,...

Heroku buildpack is basically a compiler service - different from the pipeline implementation I'm referring to, the buildpack can be a seen as a step in the pipeline towards deployment. When you upload your app to Heroku directly that transfer can be seen as part of the "pipeline process" independent on whether that step is automated or not. If you host your app in a GitHub repository and make updates to the codebase by pushing changes etc. you could set up a pipeline that connects to Heroku, any changes you make to the codebase and push to GitHub will be automatically processed by Heroku to update your application.

next widget
next widget
#

oh you asked about django... well that is django on heroku

hard whale
#

Hello guys, I'm using semantic ui to make my page look better but I faced some weird stuff... I have 2 tables and I want them to go one under another when browser window is narrow and they cant fit together. But what i get is they overlap before actually going one under another

#
<table class="ui black selectable collapsing table">
#

here is the table class i use

#

Both tables are in

#
 <div class="column">
thorny lake
hard whale
#

I want tables to keep their size ie no scaling to browser size

hard whale
#

And when the window is too narrow one should go under another

#

Its web page tho

#

Not sone offline gui

strange wing
#

only offline guis being classified as uis is an interesting take

hard whale
#

🤷‍♂️

strange wing
#

should work

hard whale
#

If u r sure that channel fits better i can move np

strange wing
#

If I've got a button in Django that is chained to both trigger a submit/post request and a JS script, is there any way I can make the JS execute first?
Right now I've got a view that takes a really long time to render, so I want to trigger a loading screen to pop up with a JS script before the next page starts loading.

hard whale
strange wing
strange wing
# hard whale I'm fine thanks

Okidoke, I'm not gonna judge you when you realize this is a python server, and this channel is mainly for web hosted python backends rather than UI.
Take it as a friendly server recommendation, not me telling you to go somewhere. They are a lot more general UI than you are going to find in this server.

hard whale
#

I got your point, i'll ask elswhere

hollow dragon
#

im trying to deploy to heroku but this is what i get:

ERROR: Could not find a version that satisfies the requirement dataclasses==0.8
ERROR: No matching distribution found for dataclasses==0.8

#

why?

next widget
thorny lake
#

The more comparable alternatives in terms of popularity and use-case to Heroku App integration would be AWS services, although I will say there's a higher learning curve dependent on chosen deployment option when it comes to networking and devops. Heroku is a pretty decent service as it's simplified some of the processes you'd have to configure manually via AWS, so it's a good option for production minimal applications. And there's always the perspective of looking at the glass half full, in this case, Heroku tightening up security on their end.. Heroku of which hadn't even recognized the breach until Github informed them. - https://thestack.technology/github-hacked-npm-data-downloaded-in-an-evolving-supply-chain-attack/
There's also GitHub pages which can act as a pipeline service similar to Heroku (i.e. pushing changes to the codebase configures the deployment app automatically) and is relatively easy to set up. - https://pages.github.com

hollow dragon
#

yeah, i officialy hate heroku

ionic raft
ionic raft
# hollow dragon yeah, i officialy hate heroku

Interesting. I tried to use Heroku for my Flask deployment. That went...ok.
Then I tried to use Heroku to test out a cron redis server for some Django Async. Went poorly.
Gotta say, Heroku gets left in the dust next to my Digital Ocean experience.

ionic raft
native tide
#

heyy I need some guide for starting programming... any professional who can help me.. pleasee dm me it's important😭

hollow dragon
#

holy shit

#

i just deployed my first docker app on heroku

#

spent like 10 hours straight bugfixing but now it works

#

cant believe itttttt

eternal blade
#

I'm serializing models and sending it through the websocket, for the serialization I'm using django-rest-framework
the models also contain images but when the images are being serialized the absolute url of the image isnt being shown (only the relative url of the image)
looks like to get the absolute url of the image i need to pass in the request object into the serializer context but I dont have access to a request object (since im using consumers)
one person suggested that to override to_representation and return the image url there but that doesnt seem like a very good way since the host of the backend can change which will lead to a lot of bugs

hard whale
#

Can anyone recommend some easy plot framework to draw plots in real-time from sqlite table

#

I use FastAPI + SQLite + website with semantic ui elements

#

I would like to implement a visualisation of 5 variables changing their value overtime

thorny lake
hollow dragon
#

is there anyone i can ask for Flask help?

eternal blade
hollow dragon
#

I have a flask app and I want to give different results for different users.

#

How is this possible?

#

I use flask-login ofc

dusk sonnet
#

im gonna ask a very stupid question here so just bare with me. I wanna build a Chat App with Django Channels + Redis right. And iv been watching alot of tutorials in the past few days and reading the docs however im so confused as to when i should stop watching the videos that makes a chat app and start implementing everything myself. Because right now all iv done is pretty much just copy paste from the Django Channels docs...and i, myself have not implemented anything. So should i just stop watching these videos and start thinking what i want in my app and start researching specific things i want instead of watching someone make the whole project? idek why im asking this lol

native tide
#

Ultimately, what is considered enough hand-holding will fall down to you as the learner. You might find that stopping watching now, and working things out yourself is helpful to you learning, or you might find that building the entire project while someone is holding your hand is more helpful

#

Over time, you'll find that you've developed skills, and picked up a few techniques that help you start working on your own

dusk sonnet
native tide
#

I wouldn't necessarily say there is no point

#

It can help you pick up skills and tools that are used in the video, you've just gotta find what works for you

dusk sonnet
#

ye true

unreal snow
#

what kind of code can i use to read the data in my database and show it in this page (m using flask)

hollow dragon
dusk sonnet
#

So for example, in apps.py if i select all the fields from the database and pass it to a variable called data, and then do something like data=data to pass that variable to ur template. Then in your template, you loop over data by doing something like:

{% for d in data %}
   {{ d.fieldname }} 
{% endfor %}
hollow dragon
hollow dragon
#

Also real time updating is so useful

#

Making working with databases an easy job

unreal snow
unreal snow
dusk sonnet
#

change all of them to user all lowercase letters because thats the variable looping through the User variable that has all the database data

unreal snow
#

even the class is named User ?

dusk sonnet
#

so in ur template ur using for example {{ User.fullName }}, change that to {{ user.fullName }}

#

remove that capital letter from all of them that are in the <td> tags

unreal snow
#

{% for user in User %} i should chage that too ?

#

change *

dense cedar
#

no

#

just change it inside

#

td

#

e.g:
for i in fruitsList:
print(i)

#

it will print that fruitsList array element which is on that index

whole sierra
#

anyone used htmx?

unreal snow
dusk sonnet
# unreal snow

all u need to do is just change User to user in every <td>

dense cedar
#

Yes. You should use dictionary

dense cedar
#

right?

unreal snow
dusk sonnet
#

its flask

dense cedar
unreal snow
dusk sonnet
unreal snow
dusk sonnet
unreal snow
dusk sonnet
# unreal snow

can you show the code where you pass the User variable to this template

unreal snow
dusk sonnet
unreal snow
dusk sonnet
# unreal snow

idk what current_user is but the variable u passed is called user not User

dense cedar
#

user = current_user?

#

can he iterate?

dusk sonnet
#

and ur looping through User which doesnt exist

dense cedar
#

the current user?

#

which is a single object?

dusk sonnet
#

idek what current_user is

dense cedar
#

request.user

dusk sonnet
#

but this is flask

dense cedar
#

it's similar as request.user

#

I meant

dusk sonnet
#

oh right

unreal snow
dusk sonnet
#

dont you want to pass the data in your database?

unreal snow
dusk sonnet
#

in your home function create a variable call it like data or something and in that variable select all the fields from the database you want

#

right now what ur doing doesnt make sense. u are looping through current_user which from what it looks like just gets the current user thats logged in

#

but how does current_user have the data you want form the database

dense cedar
#

yes

#

It's not an array like this :
Food = [

// FRUITS LIST
{
"orange":"good",
"Banana":"tasty",
"Pineapple":"nice"
},

// Vegetables List
{
"Carrot":"red",
"Raddish":"super"
}
]

It's only single object like this:

{
"orange":"tasty",
"pineapple":"fresh",
"apple":"red"
}

zealous oar
#

Hey, I have a model like this

class Task(models.Model):
    name = models.CharField(max_length=120)
    hours = models.SmallIntegerField()
    mins = models.SmallIntegerField()
    created_at = models.DateTimeField(db_index=True, default=timezone.now)

I wanna make a filter that returns every object created in the current year and month
I tried something like that, but this is not what I want

Task.objects.filter(created_at__date=timezone.now())

any thoughts?

whole sierra
#

Task.objects.filter(created_at__range=["2011-01-01", "2011-01-31"])

#

Task.objects.filter(created_at__year='2011', created_at__year='2011')

zealous oar
whole sierra
#

pretty sure it should work, try it out

zealous oar
dense cedar
#

created_at__year

whole sierra
#

show me your new code

#

ah my bad

#

the format didnt come out

dense cedar
whole sierra
#

i assumed you'd realise'

#

created_at__year

#

change it to this^

#

discord wouldnt let me add another _

dense cedar
#

can I ask u a q?

whole sierra
#

yh

dense cedar
#

Ive been asked what is best cbv or fbv

#

what should I answer?

whole sierra
#

depends what you want to do

dense cedar
#

ok

whole sierra
#

what are you creating your framework for?

#

maybe give this a read

dense cedar
#

Thanks

whole sierra
#

its the same a oop

#

@zealous oar did it work?

zealous oar
digital hinge
zealous oar
# whole sierra <@648426047771246607> did it work?

If you have a time, I need your help with another issue, I wanna return the highest month in which objects were created,
let's say we created three objects,
object_1 in month 2
object_2 in month 5
object_3 in month 5

so we have to return 5 with is the highest month
I did something like this and it works fine

mx, highest_month, dic = 0, 0, defaultdict(lambda: 0)
for object in Task.objects.all():
    month = object.created_at.month
    dic[month] += 1
    if dic[month] > mx:
        mx = dic[month]
        highest_month = month    

but my question is how can I optimize it using something like the aggregate method?

whole sierra
#

sorted_dates = sorted(chain(query var1, query var2, query var3), key=attrgetter('datetime')) @zealous oar

zealous oar
zealous oar
whole sierra
#

you mean you need it sorted in reverse order?

#

that will sort it in ascending order

#

sorted_dates = sorted(chain(query var1, query var2, query var3), key=attrgetter('datetime'))

this will sort from January to December @zealous oar

winter sinew
#

Hello ladies and gentlemen! Got a quick question regarding managing classes. I finally worked out a working webshop with a Item class. The Item class has many functions on it and is referenced in other classes to make the cart and checkout process running. Now i want to specify the products by creating new classes like "Shoe" or "Tshirt" which each has own attributes additional to the "Item" class attributes. What are my options to do that or what is recommended to do? I came around Abstract Base Model but i can not reference to abstract models. I read about PolymorphicModel, but is it really the way to go?

dusk sonnet
#

Hey theres something i have been wondering about django channels and its not really something i can specifically search about. So channels uses consumers.py which is their version of views.py. My question is that when i create an authentication system where user can register, login and logout, do i have to do this in consumers.py with new syntax that come with channels module since im using async and await or can i just do it normally in views.py?

fickle basin
#

Hello, any one using Django with vuejs !

inland oak
#

don't ask to ask, just ask (google it)

fickle basin
#

@inland oak I did google that found, axios, Django rest react , Django vuejs nothing really straight forward but thx 🙏

indigo kettle
#

I think they were just saying that you don't need to preface your question with an intro. Not that you should google it instead.

native tide
#

Hey, why would someone use django REST or Flask, instead of FastAPI + SQLalchemy?

indigo kettle
#

I haven't used flask or fastapi very much. But the reason I wouldn't want to change from django is because there are some features it has that I really like and don't know how they are in those other frameworks. Like django's orm, migrations, drf

frank shoal
#

flask uses sqlalchemy and alembic for orm and migrations

#

I have no idea what drf is

#

drf: django rest framework?

#

fastapi does that by default. Return a dict in your view, and it will output as json

#

there's also pydantic which helps with the schema

inland oak
inland oak
inland oak
#

...it forces u to marry the framework (with all of its out of the box solutions)

#

to accept its architecture and build on top of it

#

polluting your business layer of code logic

#

that could be seen as a literally a nightmare

#

and once u marry the framework, changing it to some other framework for the project becomes nearly impossible task

#

So... against of Clean Architecture stuff

#

we can also say that it also introduces the problem of upgrading the project

#

imagine upgrading the project to newer version, when Django stuff goes across entire your project in each code section?

#

once u upgrade django... since the dependency is not really in one place localized behind proper code layer separation, it becomes a bit of a nightmare when everything breaks everywhere

#

I did not check at the depth FastAPI, I wonder if it is different in this regard, it should be in theory since it said to be microframework like Flask

#

Flask is certainly not forcing anything.

#

for its downsides, Django gives in exchange blazingly fast development speed, and quite high familiarity of other Django devs with structure of the project. It is always essentially remains the same everywhere, regadless of the project

native tide
#

I have a Jinja template:

{% extends "boards/board.html" %}
{% import "macros.html" as macros %}
{% block title %}Threads • {{ super() }}{% endblock %}
{% block main %}
{% for thread in board.threads %}
{{ macros.post(thread, "article", url_for(".thread", slug=board.slug, token=thread.token)) }}
{% endfor %}
{% endblock %}

When I try to render it, I get jinja2.exceptions.UndefinedError: 'thread' is undefined. It looks like the thread variable defined in the for loop isn't accessible in the macro call. How can I pass thread to the macro?

native tide
#

Never mind it was a problem with the macro

visual bear
#

So im trying to have this collapsible information be auto un-collapsed when a link is pressed


<details>
  <summary>Click to show summary one</summary>

## Title One
...

## Title Two
...

</details>

This issue is that if someone was to click a link to my GitHub repo with a link in the following format:

  1. github.com/Username/Repo#title-one
  2. github.com/Username/Repo#title-two

The link would take them to the page but the section would still be collapsed, and it would not take them to the proper section/header. Is there a way so that when someone clicks the link it's automatically un-collapsed so they can see the information in the header instead of having to manually un-collapse it first?

Please ping when responding if you have the answer, thx

wind lotus
#

What's the relationship between a post and a comment? I know a post can have many comments, but can a comment have many posts? Should I use a foreign key?

indigo kettle
warm token
#

hey guys trying to learn how to host a flask website on cpanel and following this tutorial, https://www.a2hosting.com/kb/developer-corner/python/installing-and-configuring-flask-on-linux-shared-hosting
however when i try to access the webpage it shows 503 service unavailable
the error log shows this

Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
ModuleNotFoundError: No module named 'encodings'
#

any idea on what i need to do to get it working?

whole sierra
#
    $ch = curl_init('https://api.smsbroadcast.com.au/api-adv.php');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec ($ch);
    curl_close ($ch);
    return $output;    
}
 
$username = 'USERNAME';
$password = 'PASSWORD';
$destination = '0400000000'; //Multiple numbers can be entered, separated by a comma
$source    = 'MyCompany';
$text = 'This is our test message.';
$ref = 'abc123';
     
$content =  'username='.rawurlencode($username).
            '&amp;password='.rawurlencode($password).
            '&amp;to='.rawurlencode($destination).
            '&amp;from='.rawurlencode($source).
            '&amp;message='.rawurlencode($text).
            '&amp;ref='.rawurlencode($ref);
 
$smsbroadcast_response = sendSMS($content);
$response_lines = explode("\n", $smsbroadcast_response);
}
#

can anyone show me how to convert this to a python request?

serene prawn
whole sierra
#
"APIKeyUsername=": "xxxxxxxxxxxxxxxxx",
"&APIKeyPassword=": "xxxxxxxxxxxxx",
"&to=": "xxxxxxxxxxx",
"&from=": "Physio",
"&message=": request.POST['InstantMessage'],
"&ref=": "xxxxxxxxxxx",
"&maxsplit=": "5",
"&delay=": "1"}

url = "https://api.smsbroadcast.com.au/api-adv.php?"
y = requests.post(url, data=dict)```
#

shouldnt this work?

#

@serene prawn

#

I did this, its not working at all

serene prawn
#

I don't think you have to use & there

whole sierra
#

@serene prawn

#

page 3

serene prawn
#

It's a form data object, requests should take care of constructing request body

#

& is used to separate fields in form data

whole sierra
#

fuck

#

not working

serene prawn
whole sierra
#

data = {
"username": "xxxxx",
"password": "xxxx",
"destination": x.number,
"source": "Physio",
"text": "Some Text",
"ref": "abc123",
}
response = requests.post(
"https://api.smsbroadcast.com.au/api-adv.php",
data=data,
)
print(response)

#

@serene prawn

serene prawn
#

Check response.content

whole sierra
#

b'ERROR: No receiving number was entered.'

#

@serene prawn

serene prawn
#

add to parametr too

#

didn't see it in php code

whole sierra
#

then whats the destination for?

#

ah it worked, love u

#

ah the name

serene prawn
#

also change source to from

#
data = {
    "username": "xxxxx",
    "password": "xxxx",
    "to": x.number,
    "from": "Physio",
    "message": "Some Text",
    "ref": "abc123",
}
whole sierra
#

thank u so much!

native tide
#

Hello, can anyone help with this?

#

hello, can anyone help with this:

        'phone': phone_no,
        'message': msg,
        'key': 'textbelt'
    })```
I'm getting error: Positional argument cannot appear after keyword arguments
whole sierra
#

@serene prawn added u, got some difficult html questions

#

@native tide what is proxies?

native tide
whole sierra
#

what is your proxies variable

unkempt hill
#

I'm new to python can anyone give me tips??

keen berry
#

are all of the flask app routes available to the public?

molten thistle
#

I am starting up with Python backend development, what should I use? Flask, FastAPI or Django?

native tide
#

I want to iterate through the div and get all a tags and get the href from those a tags

#

How can I achieve this?

whole sierra
#
    # This statement searches for replies from the current date which match unique_num, primary_key, & datetime
    Replies_ = Replies.objects.all().filter(unique_num=unique_num)
    InstantMessages_ = InstantMessages.objects.all().filter(unique_num=unique_num)
    ScheduledMessages_ = ScheduledMessages.objects.all().filter(unique_num=unique_num)
    all_messages = sorted(chain(Replies_, ScheduledMessages_, InstantMessages_), key=attrgetter('datetime'))
    for x in all_messages:
        print(pendulum.parse(x.datetime).to_day_datetime_string())
    return all_messages```
#

does anyone know how I can change the x.datetime with the .to_day_datetime_string() method and return it as a regular django model?

whole sierra
#

?

native tide
#

I tried but it gives me NoneType with bs4

#

I try to get the page content with requests

#
from bs4 import BeautifulSoup
import time
import requests

headers = {
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36"
}

page = requests.get("https://www.spycolor.com", headers=headers)
soup = BeautifulSoup(page.text, "html.parser")

for grads in soup.find_all("div", class_="box small"):
    for grad in grads.find_all("a"):
        a = grad.find("a")
        print(a["href"], a.get_text())
#

This doesn't work.

#
Traceback (most recent call last):
  File "D:\Python Projects\Gradient-Of-The-Day\test.py", line 15, in <module>
    print(a["href"], a.get_text())
TypeError: 'NoneType' object is not subscriptable
whole sierra
#

print(a.startswith("href="))

#

see what that does

#

@native tide

#

ah shit nope

#

thats a boolean value

#

regex

agile pier
#

how do I get the path of the file uploaded in django?

worn crystal
#

is there any way to run selenium async of my flask app? I want to make the behaviour of when i load a certain page I want selenium to open up in the background while the original page that i started to load runs

slate narwhal
#

Hey everyone, how would I go about connecting to an sql database through VS Code?

#

I downloaded the mssql extension but I'm not sure what to do next, just looking for some guidance

native tide
#

someone judge my website pls

#

last time for now

#

try sending me an email in the contact form

#

the email can be fake

fringe fjord
#

I was wondering if I could get some help on this.
I'm using this method to update my website based on my git master branch: https://gist.github.com/noelboss/3fe13927025b89757f8fb12e9066f2fa
The issue I'm running into is that my whole repo is being push to my website (intended by the method above), but I want to just push a specific directory from my master branch to the web server
How do I modify the script above to do so?

Gist

Simple automated GIT Deployment using Hooks. GitHub Gist: instantly share code, notes, and snippets.

#

I have files on my master branch that I do not want to be pushed to my web server, for example README.md, .gitignore
I put the files I want on my webserver into /html in my git repo
I just want to push up the contents of /html to the web server

fallen spruce
#
from flask import Flask, render_template, request, redirect, url_for, flash
from flask import g as globally
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import null

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

# A decorator used to tell the application
# which URL is associated function
@app.route('/info', methods =["GET", "POST"])
def create():
    if request.method == "POST":
        global name
        global email 
        global profession
        global country
        global hobby
        global youtube
        global para
        name.globally
        # getting input with name = fname in HTML form
        name = request.form.get("name")
        
        # getting input with name = lname in HTML form 
        email = request.form.get("email") 
        profession = request.form.get("profession")
        country = request.form.get("country")
        hobby = request.form.get("hobby")
        youtube = request.form.get("youtube")
    return render_template("create.html")
@app.route('/info/themes', methods =["GET", "POST"])
def themes():
    return render_template("theme_select.html")
@app.route('/info/themes/black', methods =["GET", "POST"])
def theme_selected():
    title = f"Hello I am {name}" 
    para = f"Greetings, I am {name}. I'm a {profession} from {country}. I love {hobby}, Make sure to check out my blogs!"
    return title
    return para
    return render_template("/black_theme/index.html")
print(list)
if __name__ == '__main__':
    app.run(debug=True, port=2000)```
yo so like i wanted the variables to be accessable but am having some problems with it rn
flask can't do global because it breaks threading and i don't know what to do
wind lotus
#

how would i be able to access 2 parameters in class based views?

pearl vigil
#

Using Django, I am trying to do a @property on a model to sum a field, its returning a Sum(Value(Decimal('700.00'))) class, how can I just get the value?

native tide
#

hello

winter thorn
# wind lotus how would i be able to access 2 parameters in class based views?

```# urls.py urlpatterns = [ ... path("slug:category_slug/", views.category_blocks, name="category_blocks"), # Views all the series in that category path("slug:category_slug/slug:series_slug/", views.series_blocks, name="series_blocks"), # View all tutorials in series path("slug:category_slug/slug:series_slug/int:tutorial_id/", views.episode_blocks, name="episode_blocks"), # View spesific tutorial nr. ] # views.py def category_blocks(request, category_slug): # logic to display all tutorial with category is category_slug def series_blocks(requests, category_slug, series_slug): # logic to display all tutorial with category is category_slug and series is series_slug def tutorial_blocks(requests, category_slug, series_slug, tutorial_id): # logic to display all tutorial with category is category_slug, series is series_slug and tutorial is tutorial_id

# This is the way to access multiple slugs with different names

https://stackoverflow.com/questions/54748625/django-2-multiple-slugs-in-url
agile pier
#

how do i add a loader when there is a long operation being performed in my Django view?

dusk sonnet
#

hey, Im tryna use datbase queries with Django Channels however im not getting it right. Iv looked up that i need to use database_sync_to_sync but i cant find much examples online of how to use it properly. The only way i get it to work without error is something like the following code however all it prints out is <coroutine object SynctoAsync...>

    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.user = await database_sync_to_async(self.get_users)()
        print(self.user)

        self.room_group_name = 'chat_%s' % self.room_name

        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )
        await self.accept()

    @database_sync_to_async
    def get_users(self):
        return User.objects.all()
serene prawn
dusk sonnet
serene prawn
#

That's weird, where is it raised from?

dusk sonnet
serene prawn
#

The exception

dusk sonnet
serene prawn
#

try converting it to list?

return list(User.objects.all())
dusk sonnet
#

why did it work like that and not what i done before?

#

because i got it from the docs

serene prawn
#

.all() still returns queryset and then tries to do some database opreration in async context

#

Which is raising synchronous operation error

#

Example in docs is different

#

return User.objects.all()[0].name
This is example from the documentation

dusk sonnet
#

ye but isnt it similar i just didnt hard code it

#

i mean i did try it before exactly as teh docs and it didnt work

serene prawn
#

Now you know

dusk sonnet
#

ye thank you vm

elder nebula
#

I want to create a model, which lets you select break times for specific weekday. I don't know what is
the best way to link those two models together. I think manytomany field gets messy and confusing
really fast. I want to be able to keep it clean and organized.

Models.py

WEEKDAYS = (
        (1, 'Monday'),
        (2, 'Tuesday'),
        (3, 'Wednesday'),
        (4, 'Thursday'),
        (5, 'Friday'),
        (6, 'Saturday'),
        (7, 'Sunday'),
)
class Breaktime(models.Model):
    weekday = models.IntegerField(choices=WEEKDAYS, unique=False)
    break_starts = models.TimeField()
    break_ends = models.TimeField()

class Breaktimes(models.Model):
    
    weekday = models.IntegerField(choices=WEEKDAYS, unique=True)
    breaktimes = ??
#

I think many to many relationships are the only choice, but is there a way to filter out the weekdays?

lucid shuttle
#

Please if anyone could offer some guidance. I need to use Google Maps API to generate a custom map with a set of custom markers based on info stored in models in Django.

wind lotus
stable bear
#

when i scroll down, if i want all the content on the page to scroll except the bootstrap nav bar which should stay in the same place, how would i do that?

mental summit
#
dapper solar
#

Hi, I am trying to show a key inside each dict into an html, can anyone please tell me how to do it ? here is the code:

  {% for class in classes %}
  <li>
    <div  class="menu">
      <h2 class="menu-title menu-title_2nd">{class} </h2>
      <ul class="menu-dropdown">
        {% for i in range(1, 5) %}
               <a href="{{url_for('upload_marks_page',  grade='class_2', subject='maths', test_name='test_1'}}">           
                 <li>Test {{i}}</li>
              </a> 

        {% endfor %}
      </ul>
    </div>
  </li>
  {% endfor %}```
rocky saffron
#

how can i update e table with buttonclick

lofty sentinel
#

Hey fellas, I am a freelancer developer and customer asked for a simple website to serve my app on. There is like couple functionalities and some simple interfaces. What is a fast way to deploy this?

#

okay I think

#

Wagtail is a great start

hollow dragon
#

damn i love flask so much

wooden ruin
#

dorsia

copper juniper
#

How do e commerce website backend work?

hard whale
#

Hi guys! Can anyone recommend some big web dev discord for html/css topics? I have some issues with my Semantic UI implementation:)

vague ember
serene matrix
copper juniper
#

what programming language is best for website backend except for php?

native tide
#

i would say javascript

#

as nodejs

#

my website

#

has a expressjs backend

#

a websockets chat app is a good example of have a backend to a website

#

its very small

copper juniper
copper juniper
native tide
#

Can range from super primitive php

#

Like old school embed php in Python page

#

To modern laravel

#

If you gonna do a php backend

#

Learn Laravel

#

Its a lot like express js in Javascript

#

And flask in Python

#

But obviously it's php

hard whale
#

Can anyone recommend alive discord to ask about html, js, css issues?

#

I'm struggling with page layout

native tide
hard whale
#

I posted my question there

#

I'm new to web dev and trying to make my web page scale properly on any screen/browser size

timber jungle
#

Hello

How to secure a Flask app against CSRF ?

inland oak
# timber jungle Hello How to secure a Flask app against CSRF ?

using non GET request for important actions will increase a bit level of security. (making necessary for hacks to use JS injection at least)
Then we could CSP protection in order to protect us from unauthorized JS files, that will be a first level protection.

for 100% solution, any super important action should be verified by something like getting number from SMS sent to user / email sent to user (preferably email, it looks less bothersome)

#

plus i heard about CSRF tokens, perhaps they can improve situation a bit too

nimble berry
lethal marten
#

hey, anyone know how to partially fade an element using css?

open crag
#

like this?

tiny snow
#
opacity: 0.5;
#

Oh

#

What element is this

tiny snow
open crag
#

they said border up top

#
.your_class {
    height: 100px;
    width: 100px;
    margin: 100px;
    border: 10px solid rgba(255,255,255,.5);
}
#

i think that works

hollow dragon
#

getting better

open crag
#

niceee

hollow dragon
#

thanks mate

timber jungle
inland oak
#

Form works by submitting as post by default

timber jungle
#

@app.route("/form_area", methods =["GET", "POST"], endpoint="form_area")

frank locust
#

Hey, i'm trying to automate a get website orders script but I am running into HTTPSConnectionPool issues when I try to call it as an executable. Can give me a hand with this?

#

image of error message

frank shoal
#

The website might not be https

frank locust
#

It is, also it works most of the time, this error happens 10% of the time

frank shoal
#

maybe you go too fast

frank locust
#

Possibly, at what point would I try to slow it down do you think? the initial get or iterating through the orders? Somewhere else?

frank shoal
#

¯_(ツ)_/¯

#

robots.txt specifies a crawl delay of 600

#

so just time.sleep(.6) after each request

frank locust
#

ok i'll give that a try

#

appreciate it

lime jolt
#

Should I use help channels for django questions?

serene prawn
lime jolt
native tide
#

Hey, how would you call a file that initialize a connection with a db? Like by convention

lime jolt
#

dbconnect, connectiondb, dbconn, dbconnection I guess. Everyone would understand these.

#

ConnectionBuilder is my preference.

lime jolt
#

Help channel is closed, damn. Let me ask again. Submitting form doesn't do anything. Not even redirecting the url. But if I manually open the html file without server, it redirects.

frank shoal
#

use /createuser instead of createuser/ for the form action

lime jolt
#

didn't work, and normally it should be createuser/

frank shoal
#

Also, I think you're passing xedni to the redirect response

lime jolt
#

method is not called, nevermind the redirects.

frank shoal
#

form action path is relative if it doesn't start with /, meaning if the current path ends with /, it will be appended. If it doesn't, the last path item will be replaced

lime jolt
frank shoal
#

so clicking submit would take you to surveyville/createuser/

#

that's intended?

lime jolt
#

yes, it should. Btw, I can manually call the function with link.

#

But submit button does nothing

frank shoal
#

Anything in the console or network inspector?

lime jolt
#

I used jquery to test the button, it can give an alert(""). And directly writing the link activates the function. I can see print("") codes in console.

frank shoal
#

How are you submitting normally? pressing the submit button, or pressing enter on the password field?

#

Also, you should make the input type="password"

lime jolt
#

pressing button. password can wait 😄

frank shoal
#

But does anything show up in the network inspector when you press the button?

#

Ctrl+Shift+I, press network

lime jolt
#

looks like nothing happens.

frank shoal
#

Nothing in console either?

lime jolt
#

nope.

frank shoal
#

Did you register an onsubmit event and call preventDefault()

lime jolt
#

if you mean front end stuff, they work. I opened the html file directly and it redirects.

frank shoal
#

Can you share the entire html file?

lime jolt
#

sure

lavish prismBOT
#

Hey @lime jolt!

It looks like you tried to attach file type(s) that we do not allow (.html). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.

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

lime jolt
#

oppsie

frank shoal
#

!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.pythondiscord.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.

lime jolt
frank shoal
#

And /js/modal.js?

lime jolt
#

whats wrong with it?

frank shoal
#

idk, you didn't post it.

lime jolt
#

it does this, nothing else

frank shoal
#

Post the modal.js too please

lime jolt
frank shoal
#

You disabled the click event in all children in the modal.

lime jolt
#

holy....

#

i stole the code, that's why 😄

frank shoal
#

just use bootstrap's builtin features to dismiss the modal.

#

you're not using bootstrap, though....

lime jolt
#

not worth using bootstrap, idk

#

i created modal 3-4 times but forget how to do it 😄

#

it works, there are other problems but that's the only part i needed help

#

thank you

lime jolt
#

So, CSRF is important and @csrf_exempt doesn't disturb it?

#

should i use @csrf_exempt everywhere?

olive hazel
#

tell me something what goes on better. Django + python or html css Javascript and python

amber patio
hearty estuary
#

Hi, i have a webpage with 4 div's acting as buttons, and using ajax i want to send which button was clicked, and then update my <p> tag which uses class=text1 to show that direction. (I also want to create a MySQL database and then send that data to that database, so if anyone can help with that it would be much appreciated)

At the moment clicking on the buttons work, and the value is shown because im using the 'get' method, but i dont want to get that data, i want to 'post' the button click to the server, and on success: change my <p> to the value of the button clicked. Havent really understood online resources about each of those things, so any input/changes you guys can give me would be much appreciated ❤️
#main.py

from flask import Flask
from flask import render_template
from flask import request
from time import time
from flask import jsonify
app = Flask(__name__)

@app.route('/')
def index():
    direc = request.args.get('direction')
    print()
    print('Direction:', direc)
    print()
    return render_template('index.html')

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

#Javascript

$(document).ready(function() {
    $( "div[name='button']" ).on('click', function() {
      $.ajax({
        url: '',
        type: 'get',
        data: {
          direction: $(this).attr("id")
        },
        success: function(response){
          $(".text1").text(direction);
        }
      
      
      })
    })
  })

obtuse robin
hearty estuary
#

How

obtuse robin
#
var xml = new XMLHttpRequest();
xml.open("POST","{{url_for('new_data')}}", true);
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
dataSend = JSON.stringify([new_data, type]);
xml.send(dataSend);

make a http request on the javascript

#

then for the python

hearty estuary
#

but then the content isnt dynamic

#

its static

#

like

#

page reload

obtuse robin
#

nope

#

it isnt

hearty estuary
#

how?

obtuse robin
#

here

#

let me show you the python

hearty estuary
#

oh wait

#

XMLHttpRequest

#

ajax uses that

#

Ajax is XMLHttpRequest

obtuse robin
#

oh lol oops

#

then it is ajax

hearty estuary
#

well

#

ajax is XMLHttpRequest + extra stuff

#

but same thing i guess

obtuse robin
#

oh wait heres the video i followed

#

found it

hearty estuary
#

He doesnt show the end result tho

#

Only code devolopmenet

obtuse robin
#

wym, like he doesnt show it in action?

hearty estuary
#

Ye

obtuse robin
#

well you gotta experiment with it

hearty estuary
#

So not sure if its same functionallity as what i need

obtuse robin
#

its a good baseline

#

you just gotta change a few things around

hearty estuary
#

I dont see how he gets the button onclick

#

theres no function bound to it

#

No check of onclick

obtuse robin
hearty estuary
#

This is how the webpage looks

obtuse robin
#

just put an onclick for a function that has the httprequest in it?

#
function send_data(new_data, type){
        var xml = new XMLHttpRequest();
        xml.open("POST","{{url_for('new_data')}}", true);
        xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        dataSend = JSON.stringify([new_data, type]);
        xml.send(dataSend);

        if (type[1]){
            if (type[0] == "song"){
            window.location = "{{url_for('song_page')}}";
            }
        }
    }
#

i mean this is what i have

hearty estuary
#

What is urs sending?

obtuse robin
#

im sending a song's spotify id

hearty estuary
#

Can you show ur html so i can see how you bind the send_data function to it

obtuse robin
#

sure

rigid laurel
rigid laurel
hearty estuary
#

okay

#

gotcha

#

thanks

hearty estuary
obtuse robin
#

yes

iron magnet
#

Tested SQLModel for FastAPI. It’s a really good extension over “plain” SQLAlchemy and Pydantic.

wind lotus
#

i made a game with js, css, html, but i want to save the player's score into the django database automatically after each game. How would I be able to do that?

obtuse robin
#

what framework

wind lotus
hearty estuary
#

i finally understood not to touch it unless your creating a huge ass project

#

wasted 4 days learning that shite

#

"learning" kek

native tide
#

hello to all, I just wanted to ask a small question I want to make a bot to do research on the txid of the bscchain for example someone has a track to help me start I am a beginner

wind lotus
hollow dragon
#

is there anyone who could help me with connecting two tables in one database in Flask and SQLite?

stable coral
#

i want to make a webapp that uses the spotify api in python, is it better to download a library like spotipy or just use the web api directly in python?

wet hinge
#

I've been wondering: is there any particular single best order of these three in Django? Or something that should not be done?

MIDDLEWARE = [
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    [...]
]
hearty estuary
#

ButtonClick.query.first()) prints <ButtonClick 1> always(first id)
ButtonClick(content=request.form.get('direction')) returns <ButtonClick lastID>

I dont want ID, i want to get the last item(direction) that was just added to db, what i would get if i were to post directly in SQL (SELECT content FROM button_click ORDER BY id DESC LIMIT 1;)

The reason i want this is because the response gets sent to a <p> and i want it to update according to the value(unnecessary i know but i want to anyways), how can i go about doing this using sqlalchemy?

class ButtonClick(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String(5))


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

@app.route('/clicks', methods=['POST', 'GET'])
def clicks():
    if request.method == 'POST':
        direc = ButtonClick(content=request.form.get('direction'))
        db.session.add(direc)
        db.session.commit()
        print('To DB', direc)
        print('direc.query.first():', ButtonClick.query.first())
        return jsonify(direc)
$(document).ready(function() {
    $( "div[name='button']" ).on('click', function() {
      $.ajax({
        url: '/clicks',
        type: 'post',
        data: {
          direction: $(this).attr("id")
        },
        success: function(response){
          $(".text1").text(response);
        }
      
      
      })
    })
  })
gloomy haven
#

_ _
_ _
Hey! i'm building a search and i'm querying for 'plugins'
I want to match my query with the most relevant plugins but I don't know how I should get started with that.
Here is what I have:

#app.py
@app.route('/dashboard/search/', methods=['GET', 'POST'])
def search():
    if 'username' in session:
        user = mongo.db.users.find_one({'name': session['username']})
        if user:
            if user['account_active'] == False:
                print("Account is not active.")
                return redirect(url_for('index'))
            else:
                pass

        print(request, request.args)
        if request.args['search']:
            query = request.args['search']
            l=os.listdir('plugin_base/plugins')
            plugins_D = [x for x in l]
            try:
                plugin_file = importlib.import_module(f"plugin_base.plugins.{query}", f"exec")
                plugin_conf = importlib.import_module(f"plugin_base.plugins.{query}", f"config")
                pfc = plugin_conf.config
            except:
                plugin_file = "None"
                plugin_conf = "None"
                pfc = "None"
            print(pfc)
            if query[0] in plugins_D:
                pass
        
        return render_template('dashboard/search.html', search=plugins_D)

I want to add the plugins that are most relevant to some sort of list so I can do something like this:

<!-- search html -->
 {% for result in search %}
 <h2>Plugin Result</h2>
    <div class="card">
       <div class="card-body">
       <h5 class="card-title">{{ search['name'] }}</h5>
       <a href="/dashboard/plugin/{{ search['name'] }}" class="btn btn-primary">Use this Plugin</a>
    </div>
</div>
{% endfor %}

I think it's pretty easy to understand what I'm trying to do.
Thanks in advanced! :)

lime jolt
#

Is there any visible problem here? Or should I check somewhere else? I am trying to make a login system, the user exist but it leads to fail. I tested, it can get the username and password for x and y.

lime jolt
#

am I even using my database? Tutorials on internet shows it like this

native tide
#

Guys help

#
from django.urls import path
from . import views

urlpatterns = [
    path('cards', views.CardList.as_view()),
    path('cards/<int:pk>', views.CardDetail.as_view()),
    path('decks', views.DeckList.as_view()),
    path('decks/<int:pk>', views.DeckDetail.as_view()),
    path('folders', views.FolderList.as_view()),
    path('folders/<int:pk>', views.FolderDetail.as_view()),
]

# preferables
# deck list
# /api/decks 
# deck detail
# /api/decks/<int:pk>
# card list
# /api/decks/<int:pk>/cards
# card detail
# /api/decks/<int:pk>/cards/<int:pk>```
#

I'm using django rest framework. In the comments, you can see how I want to design my API

#

I don't get how I can have my routes set up so it's /api/decks/<int:pk>/cards <-- lists all cards within that deck

#

how does that work with API

opal verge
#

Hello @native tide
You need to create an urls.py into your app and list your views into that field. Later, list on urls.py of your project your urls.py of the app

obtuse robin
#

because youre not posting anything, youre getting the information from 'username' and 'password'

#

the request method is still post though

#

probably can just do request.form['name']

late gale
#
  class RecipeSerializer(serializers.ModelSerializer):
    rt = serializers.SerializerMethodField(source="ingridents",read_only=True)


    def get_rt(self, instance):
        try:
            return json.loads(instance.ingridents)
        except:
            print("Error")
    
    class Meta: 
        model = RecipeModel
        fields = '__all__' 

Can someone help me i'm trying to convert json into list but it returns null

#
    "rt": null,
#

though there are data in ingridents

#
    "ingridents": "2 cups cooked chicken chopped\r\n½ cup mayonnaise\r\n1 stalk celery chopped\r\n1 green onion diced (or chives or red onion)\r\n1 teaspoon dijon mustard\r\n½ teaspoon seasoned salt\r\npepper to taste\r\n1 teaspoon fresh dill optional",
#

I'm trying to convert this ingridents to something like this

  "ingridents": [
                        {
                           "2 cups cooked chicken chopped"
                        },
                        {
                          " stalk celery chopped"
                        },
                        {
                            " teaspoon fresh dill"
                        },
                        {
                            "  green onion diced "
                        },...
                    ]
#

that's ingridents in models.py
ingridents = models.TextField(default="")

runic sparrow
#

Noob question here, what would be the most secure way of me storing user OAuth2 tokens?
Do I just... chuck it in a database? There has to be some sort of more secure way, right?

zealous oar
#

Hey 👋 , is anyone working with Django channels in real-life projects?
I was wondering is it a good choice to accomplish this task, or do I have to think of another stack like Node, Elixir, Laravel, .. ?
Any advice/hints would be great to start my research.

dusk portal
#

hey i have db model named profiile
i wanna make a feature to let user download his/her profile

#

(i can't add a file/imagefield for downloading) cuz that data would be generated after thier profile would be created

#

by this data i need user to give a option to download it

#

and the main issue is ** if user clicks on download this template/img should open and then i want user to download this jpg** but how can i retrieve dynamic data inside a image file?

#

plz help

copper juniper
#

How to use python for website backend?

opal verge
covert yew
copper juniper
copper juniper
rigid laurel
agile pier
#

i m trying to create a chatbot using django as the backend, but i m having trouble showing the responses

#

when giving the result for a query, how do I also show the previous chat history?

dusk portal
rigid laurel
wheat verge
#

So i am using django to make an app and when i try to change the colour of my nav bar it wouldnt change my css wont reflect any changes its almost like my program is frozen even when i delete the css file nothing changes can anybody help

#

every other thing seems to be working like the html and backend part but not css

#

it takes minutes to show the change Why????

hidden kettle
#

hello

#

Any Django dev here who has worked with both Django & React?

serene prawn
#

Didn't work with react specifically but it's similar to other frameworks

hidden kettle
serene prawn
#

It's better to ask your question right away so people could see if they can help you or not

hidden kettle
#

I'm getting stuck when trying to build a feature for my Saas that allows users to log out of respective sessions or all sessions.How can I implement such a thing? Here's the overview of what I'm trying to build. I took this inspiration from Khalti which is a payment gateway of my country. It's built with Django & React. I will also create a mobile app.

#

How should I keep track of mobile logins with my app version and mobile device name? This is the API response of sessions. How can I implement this in an exact way?

#

What auth mechanism should I use here?

#

sessions?

serene prawn
#

It might be simpler if you choose to just invalidate all tokens before a specific date, since it won't require you to keep track of all active sessions

hidden kettle
#

Should I use DRF token auth/

#

?

serene prawn
#

I'm not familiar with django packages really

hidden kettle
serene prawn
#

I think we can discuss the specifics, other people might help you too

#

Invalidating user sessions should be a solved problem at this point

hidden kettle
#

I would be happy If someone joins the discussion

static spade
#

hi, how can i localize the datetime form fields in my django app?

#

my server is 4 hours behind my actual timezone, and when i pass a time of 8pm in my local time to the form it appears as 8pm in server time in the database. But ideally it should appear as 4pm in server time.

#

how can i fix this?

vivid canopy
#

guys how i can get access token use get method? djang rest framework

fading bough
#

is it possible to use js frameworks like reactjs along with pyscript? would this make the website really slow?