#web-development

2 messages · Page 205 of 1

lapis glade
#

what is living_area_lights.state set as?

hushed vortex
#

its my lights ip

#

it tells me if the light is on or off

lapis glade
#

try adding print(living_area_lights.state) before the if

#

also is the hi geting printed

hushed vortex
lapis glade
#

is any html being returned to the browser?

hushed vortex
lapis glade
#

open elements

hushed vortex
#

yea its because of the while loop

#

i removed it and it loads

lapis glade
#

is the pic working now?

hushed vortex
#

it doesnrt load any other elements because its stuck on the while loop

native tide
#

can someone one help me setup and @native tide setup up a site

native tide
#

ash may u be so kind and generouis to help me setup my website

lapis glade
native tide
lapis glade
#

using what

#

flask

#

or

#

flask is best for beginners imo

native tide
#

html

lapis glade
#

do you need the web server or help making the site itself @native tide

hushed vortex
#

@lapis glade you there?

inland oak
# hushed vortex

you know, the thing u a doing could be done 100 times easier and better... if u would be using frontend framework like Vue.js instead of trying to make in backend python frameworks

#

as far as I see u try to implememt pure frontend

hushed vortex
#

the thing is i only know python

inland oak
# hushed vortex the thing is i only know python

if a person knows only how to screw with screwdriver, does it mean he will be nailing nails with screwdriver too? or he would learn how to wield hammer?
Perhaps for one nail it would be still reasonable to use screwdriver, but for 2+ nail it would be faster to learn wielding hammer in order to have the job done

hushed vortex
#

hmmm

thorn igloo
#

what's the issue here

hushed vortex
#

it works now ty tho

thorn igloo
#

ok

hushed vortex
#

can i dm you for a sec? @thorn igloo

thorn igloo
#

what are you trying to achieve exactly?

hushed vortex
#

@thorn igloo i tried this

#

but it doesent seem to work

thorn igloo
#

that's wrong syntax

hushed vortex
thorn igloo
hushed vortex
thorn igloo
#

fix your mistake

#

it's not directly using url for static here, but you can apply what they are doing to what you are doing

native tide
lament otter
#

Hmm

#

So u want to display index.html

#

In templates folder

native tide
#

yeah

lament otter
#

Whats the prob?

native tide
#

what is the error?

lament otter
#

Yes

#

Any error?

native tide
#

only white screen

lament otter
#

hmm

#

Anything in index?

native tide
#

yeah

lament otter
#
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def home():
   return render_template('index.html')
if __name__ == '__main__':
   app.run()
#

Pls send the contents of index

native tide
lament otter
#

It's empty

#

Bro

#

Write smth inside body tag

#

Is it workin now?

native tide
#

No

lament otter
#

hmm

#

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
Hello world
</body>
</html>

#

Use this

lament otter
#

Ok

#

Listen

#

Comment ur whole py file

#

And use this

#
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def home():
   return render_template('index.html')
if __name__ == '__main__':
   app.run() 
native tide
# lament otter Comment ur whole py file

from flask import Flask, render_template

app = Flask(name, template_folder='templates')
app= Flask(name)

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

if name=='main':
app.run(debug=True)

lament otter
#

I mean remove that code for sometime paste it somewhere

#

And use above

native tide
#

No change

lament otter
#

Ah

#

what command r u using for running file?

native tide
#

run python file |>

lament otter
#

Oh

#

Bruh this is working for me fine

native tide
#

firstly tell me how to create folder

#

app.py
static
templates
|-index.html

lament otter
#

This is fine

native tide
lament otter
#

Ig error is in html file

#

Use this instead

#

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

#

It should work now

native tide
#

No

lament otter
#

Ugh

#

It works for me

native tide
#

Idk what is the problem

lament otter
#

Ye

sudden sierra
#

Did you save your files?

native tide
sudden sierra
#

Ctrl + S

#

Make sure to save index.html

lament otter
#

Wha

#

Yes it can be

#

Wait

#

For running make sure to end the previous program

#

By Ctrl + C

native tide
lament otter
#

:)

native tide
#

Thanks Both of you for my help

lament otter
#

Welcome 😄

sudden sierra
#

👍

hushed vortex
#

i need to have the {{url_for('static', filename= since i am using flask

sweet karma
#

anyone here?

#

<div class="row">
<div class="col-lg-6">
<h1>Meet new and interesting dogs nearby.</h1>
<button type="button" class="btn btn-dark btn-lg"><i class="fab fa-apple"></i> Download</button>
<button type="button" class="btn btn-outline-light btn-lg"><i class="fab fa-google-play"></i> Download</button>
</div>
<div class="col-lg-6">
<img class="dog-image" src="images/iphone6.png" alt="iphone-mockup">
</div>
</div>
</div>
</section>

thorn igloo
#

the one i showed you only has 2

hushed vortex
#

yes but i also need to define imgg

#

should i define it outside?

thorn igloo
#

why are you defining it in jinja2?

#

it should be defined from the backend, that's how these things work

hushed vortex
#

oks wait let me get this clear

#

which file is the backend?

thorn igloo
#

what ever youre using to run your server

hushed vortex
#

so the .py file

hushed vortex
thorn igloo
#

if thats the case

hushed vortex
#

but dont i need to this

thorn igloo
hushed vortex
#

in my case its "imgg = onnn"

thorn igloo
#

why do you have 3 parameters?

hushed vortex
#

btw in the backend onnn is the path to img

thorn igloo
#

the idea is to apply this to your situation

#

obviously if you just copy it's not going to work cause this is not what you are trying to do

hushed vortex
#

what about this

thorn igloo
#

here it's explained how to use a predefined variable in the url_for syntax

hushed vortex
thorn igloo
hushed vortex
#

exactly

#

how do i fix this

thorn igloo
#

so fix it

hushed vortex
#

{{}} right?

thorn igloo
#

ignore the {{}} part for now

#

just imagine url_for is a python function

#

how are you gonna pass the filename as a variable?

hushed vortex
#
filepath = "this"
def url_for('static', filename=filepath):
thorn igloo
#

i didnt say define the function

#

but do the same for your thing

#

pass the variable you want to filename

#

again, ignore {{}}

hushed vortex
thorn igloo
#

was that so hard

hushed vortex
#

i tought you were talking about img= onnn

thorn igloo
#

what did you define onnn as?

hushed vortex
thorn igloo
#

did you pass it to your template

hushed vortex
#

😅

#

sorry

#

ty

untold sluice
#

Hi there, How to enhance the security of unauthenticated endpoint in DRF ?

inland oak
# untold sluice Hi there, How to enhance the security of unauthenticated endpoint in DRF ?
#

make sure to enable such stuff like CORS and other stuff

#

don't disable it

#

allow only requests coming from your frontend to access the backend, and reject all others

sweet karma
#

How to make image not to expand the whole title?

#

<div class="row">
<div class="col-lg-6">
<h1>Meet new and interesting dogs nearby.</h1>
<button type="button" class="btn btn-dark btn-lg"><i class="fab fa-apple"></i> Download</button>
<button type="button" class="btn btn-outline-light btn-lg"><i class="fab fa-google-play"></i> Download</button>
</div>
<div class="col-lg-6">
<img class="dog-image" src="images/iphone6.png" alt="iphone-mockup">
</div>
</div>
</div>
</section>

#

currently have like that:

#

want to make it like that:

inland oak
native tide
serene depot
#

Please can anyone tell me what's the use of below lines in django

class Meta:
verbose_name_plural =" "

inland oak
#

it has mentioning of objects in plural name

#

standard one just says
if u have object cat it will add s making it cats
which will not work well for every word

vivid canopy
#

Hello, what should know python backend developer to have a work?

vivid canopy
native tide
#

<link href="css/login.css" rel="stylesheet" type="text/css" />
why isnt this working lmao

inland oak
#

just check hiring web sites local to you, and see requirements in 10+ job positions related to your desired position

#

compare with roadmap.sh and draw the path for yourself

vivid canopy
#

Okay, thx I think I am junior at backed, but I scared about my knowledge

tight ocean
#

Guys

#

I currently have this code ```# Home page
@app.route("/")
def home():
return render_template('index.html')

@app.route("/", methods=['POST', 'GET'])
def reclaim_mae():
# Variables for the images
global i
i = 1
# If there's a request, increment i by 1
if request.method == "POST":
i = i + 1
# Get burn_chance from html, turn that into a float, divide it by 100
burn_chance = request.form['burn_chance']
burn_chance = float(burn_chance)
burn_chance = (burn_chance / 100)
# Set reclaim_rate to "1 - whatever value burn_chance has"
reclaim_rate = (1 - burn_chance)
# Create the infinite series, turn that into a float
p = nsum(lambda runs: ((reclaim_rate)(runs-1) * 0.5runs), [1, inf])
p = float(p)
# Get mae_fused from html, turn that into a float, divide it by 100
mae_fused = request.form['mae_fused']
mae_fused = float(mae_fused)
mae_fused = (mae_fused / 100)
# Set n to equation below
n = (331796 * mae_fused) / 10
# Set u to equation below
u = p * n
# Set o to equation below, convert it to a whole integer
o = math.sqrt(u * (1-p) * p)
o = int(o)
# Create the interval
x = np.linspace(u - 3o, u + 3o)
# Plotting, converting it to an image and saving that to server
plt.clf()
plt.xlabel('X axis represents the value')
plt.ylabel('Y axis represents the frequency')
plt.title('Mae')
plt.xticks(np.arange(min(x), max(x+1), o))
plt.grid()
plt.plot(x, stats.norm.pdf(x, u, o), color='pink')
plt.savefig('static/images/reclaimMae/plot' + str(i) + '.png')
# Return the html page with the graph
return render_template('index.html', urlReclaimMae='static/images/reclaimMae/plot' + str(i) + '.png')

@app.route("/", methods=['POST', 'GET'])
def reclaim_kita():
# Variables for the images
global i
i = 1
# If there's a request, increment i by 1
if request.method == "POST":
i = i + 1
# Get burn_chance from html, turn that into a float, divide it by 100
burn_chance = request.form['burn_chance']
burn_chance = float(burn_chance)
burn_chance = (burn_chance / 100)
# Set reclaim_rate to "1 - whatever value burn_chance has"
reclaim_rate = (1 - burn_chance)
# Create the infinite series, turn that into a float
p = nsum(lambda runs: ((reclaim_rate)(runs-1) * 0.5runs), [1, inf])
p = float(p)
# Get kita_fused from html, turn that into a float, divide it by 100
kita_fused = request.form['kita_fused']
kita_fused = float(kita_fused)
kita_fused = (kita_fused / 100)
# Set n to equation below
n = (52089 * kita_fused) / 10
# Set u to equation below
u = p * n
# Set o to equation below, convert it to a whole integer
o = math.sqrt(u * (1-p) * p)
o = int(o)
# Create the interval
x = np.linspace(u - 3o, u + 3o)
# Plotting, converting it to an image and saving that to server
plt.clf()
plt.xlabel('X axis represents the value')
plt.ylabel('Y axis represents the frequency')
plt.title('Kita')
plt.xticks(np.arange(min(x), max(x+1), o))
plt.grid()
plt.plot(x, stats.norm.pdf(x, u, o), color='pink')
plt.savefig('static/images/reclaimKita/plot' + str(i) + '.png')
# Return the html page with the graph
return render_template('index.html', urlReclaimKita='static/images/reclaimKita/plot' + str(i) + '.png')```

#

I want it to go to a different route and function based on the input in html

#

Right now it always goes into the 2nd route no matter what input has been put in

#

So if mae_fused is put in, go to 2nd route
If kita_fused is put in, go to 3rd route

#

I also want everything to be on 1 page, hence why all the urls are "/"

#

Any idea?

verbal wind
#

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

tight ocean
#

So 3 different urls?

verbal wind
#

yeah

tight ocean
#

But I want everything to be on 1 page

verbal wind
#

handle it inside one route then

#

one route - 1 page

#

maybe you can do it

#

by

#

redirecting to home page

#

that way u can still have three routes

#

but u willl have to use 3 different urls

tight ocean
#

Variables also depend on input

#

So if I put everything in 1 route, idk if that'd work

verbal wind
#

have 3 sepreate urls - routes

#

and then redirect them to home

#

that is /

tight ocean
#

Will all graphs be shown on 1 page then?

#

I need them to be next to eachother

verbal wind
#

at one graph at a time or

#

or u want both at same time

tight ocean
#

The user can basically put in the reclaim rate and mae %

#

That will plot 1 graph with u and o

#

But then the user can put in another reclaim rate and kita %

#

And that graph should be plotted next to the 1st one

verbal wind
#

yeah it can be done in many ways

#

like u can have 3 routes and

#

1 for /

#

1 for kita

#

1 for mae

#

and redirect the output of kita and mae to /

#

handle how they are shown accordingly

#

or youy can just have a single route

#

where u can take a keyword and then created some functions to handle the outputs

tight ocean
#

Hmm

#

Would I have to make an if statement for that?

verbal wind
#

yeah

#

u need to check the graph type

#

and also u have to set the positioning of graphs on home page

#

ideally u should have 2 routes

#

1 for home and 1 for graphs

tight ocean
#

So plotting is done in home page, and calculating u and o in 2nd route?

verbal wind
#

yeah

tight ocean
#

Makes sense

verbal wind
#

you'll just u figure out a bit on how u position the graphs

#

in your template

#

and u can break ur logic for grpah into functions and keep the routes less occupied

tight ocean
#

What code would I be seperating into different functions then

verbal wind
#

what makes mae and kita different

tight ocean
#

They have different n variables

verbal wind
#

make them different in logic

#

not in variable naming

tight ocean
#

Wdym by that?

verbal wind
#

like you can use same variable names for both of these if they serve the same purpose in both places

tight ocean
#

That's already the case

last scaffold
#

~~@sturdy sapphire I sneaked a peak on the Django workshop a while ago and you were using a very nice framework for generating tests, more specifically the fixtures, it was called maybe like "something"-boy.

I am reworking the test framework and thought that it would be nice to use it, do you know what I'm talking about?~~

Found it 🙂

verbal wind
#

like for example if u make two functions one to calcute happy number and other to calulate armstrong number then the variable number serves the same purpose in both cases and these function differ in how they make use of the number - the calculations

#

so seperate ur functions based on logic

tight ocean
#

Also if I plot graphs in home, but the variables are defined in the other route, they are not yet defined in home

#

Do I then just make everything global?

verbal wind
#

no no

#

you pass those variables to home

#

from other routes

tight ocean
#

But return can only have a finite parameters right

#

So how do I pass all variables

verbal wind
#

list

#

u can return a list

tight ocean
#

Ah

verbal wind
#

dictionary will be even better if u want more clarity

#

you'll just have to stackoverflow a few things up and you'll achieve ur task

tight ocean
#

I'm so confused lmao

#

I will figure it out

verbal wind
#

yea you will

tight ocean
#

from flask import Flask, render_template, request, session
import matplotlib.pyplot as plt
import scipy.stats as stats
from mpmath import *
import numpy as np
import matplotlib
matplotlib.use('Agg')
import math


app = Flask(__name__)

# Home page
@app.route("/")
def home():
    if request.method == "POST":
        mae_fused = request.form['mae_fused']
        kita_fused = request.form['kita_fused']
        if mae_fused == True:
            # Plotting, converting it to an image and saving that to server
            plt.clf()
            plt.xlabel('X axis represents the value')
            plt.ylabel('Y axis represents the frequency')
            plt.title('Mae')
            plt.xticks(np.arange(min(x), max(x+1), o))
            plt.grid()
            plt.plot(x, stats.norm.pdf(x, u, o), color='pink')
            plt.savefig('static/images/reclaimMae/plot' + str(i) + '.png')
            
        if kita_fused == True:
            # Plotting, converting it to an image and saving that to server
            plt.clf()
            plt.xlabel('X axis represents the value')
            plt.ylabel('Y axis represents the frequency')
            plt.title('Kita')
            plt.xticks(np.arange(min(x), max(x+1), o))
            plt.grid()
            plt.plot(x, stats.norm.pdf(x, u, o), color='pink')
            plt.savefig('static/images/reclaimKita/plot' + str(i) + '.png')
            

@app.route("/graph", methods=['POST', 'GET'])
def calcGraph():
    # Variables for the images
    global i
    i = 1
    # If there's a request, increment i by 1
    if request.method == "POST":
        i = i + 1   
    # Get burn_chance from html, turn that into a float, divide it by 100
    burn_chance = request.form['burn_chance']
    burn_chance = float(burn_chance)
    burn_chance = (burn_chance / 100)
    # Set reclaim_rate to "1 - whatever value burn_chance has"
    reclaim_rate = (1 - burn_chance)
    # Create the infinite series, turn that into a float
    p = nsum(lambda runs: ((reclaim_rate)**(runs-1) * 0.5**runs), [1, inf])
    p = float(p)
    # Get mae_fused and kita_fused from html, turn that into a float, divide it by 100
    mae_fused = request.form['mae_fused']
    mae_fused = float(mae_fused)
    mae_fused = (mae_fused / 100)
    kita_fused = request.form['kita_fused']
    kita_fused = float(kita_fused)
    kita_fused = (kita_fused / 100)
    # Set n to equation below
    n = (331796 * mae_fused) / 10
    # Set u to equation below
    u = p * n
    # Set o to equation below, convert it to a whole integer
    o = math.sqrt(u * (1-p) * p)
    o = int(o)
    # Create the interval
    x = np.linspace(u - 3*o, u + 3*o)
    lst = [x, u, o]
    return lst

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

Now I'm stuck

white delta
#

Good evening everyone. I had been coding outside a virtual environment for quite some time, so i decided it was finally time to put my project on a django app/environment/server/whatever lol. However, my fontawesome icons did not load when i did so. I tried everything i could possibly do -- I tried using both internal and external links to fontawesome. My icons are still loading perfectly outside the virtual environment, so I'm not sure what the problem is.

frank shoal
#

Check the network tab of your browser's dev tools

strange moat
#

What are the basic python skills I need before starting with django?

tawny gazelle
#

Hi guys

#

I need help.

haughty isle
white delta
frank shoal
#

Look for the request to download fontawesome.

#

if it's an error, you should be able to see why it errored.

#

btw, I would recommend installing fontawesome via npm and sourcing it via node_modules/fontawesome/dist/css/fontawesome.min.css

#

or something like that.

#

you can also add fonts via @fontsource/fontname/index.css

#

I added a static route for node_modules.

    <link rel="stylesheet" href="{{ url_for('node', filename='font-awesome/dist/font-awesome.min.css') }}"/>
    <link rel="stylesheet" href="{{ url_for('node', filename='@fontsource/roboto/index.css') }}"/>
strange moat
haughty isle
strange moat
#

Where can I find that @haughty isle

#

And what basic python do I need to know

haughty isle
red vault
#

can I ask about folium here?

red vault
#

so is there a way to save a map I got using folium in some other file format than html?

#

because I want to use the map in another html file

tight ocean
#

Hey guys!

#

app = Flask(__name__)

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

def home():
    return render_template("index.html")

def burn_chance():
    burn_chance = request.form['burn_chance']
    burn_chance = float(burn_chance)
    burn_chance = (burn_chance / 100)
    return burn_chance

def reclaim_mae():
    
if __name__ == "__main__":
    app.run(debug = True)```
#

I want my function "burn_chance()" to pass the variable burn_chance to "reclaim_mae()"

#

How would I do it the most efficient?

hushed vortex
#

please help with flask

strange moat
haughty isle
hushed vortex
frank shoal
#

we'll need more than that.

#

Is this inside a view function?

#

you can only use url_for inside a view function or jinja template

hushed vortex
frank shoal
#

!code

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

hushed vortex
#
def check_lights_on_or_off():
    global living_area_lights_on_off
    global center_lights_on_off
    global dining_room_potlights_on_off
    global porch_lights_on_off
    while True:
        try:
            if living_area_lights.state == "OFF":
                living_area_lights_on_off = 'bulb_off.png'
                return redirect(url_for('Home_page'))
            if living_area_lights.state == "ON":
                print("living")
                living_area_lights_on_off = 'bulb_on.png'
                return redirect(url_for('Home_page'))
                
            if center_light.state == "OFF":
                print("living1")
                center_lights_on_off = 'bulb_off.png'
                return redirect(url_for('Home_page'))
            if center_light.state == "ON":
                center_lights_on_off = 'bulb_on.png'
                return redirect(url_for('Home_page'))
                
            if dining_room_potlights.state == "OFF":
                print("living2")
                dining_room_potlights_on_off = 'bulb_off.png'
                return redirect(url_for('Home_page'))
            if dining_room_potlights.state == "ON":
                dining_room_potlights_on_off = 'bulb_on.png'
                return redirect(url_for('Home_page'))
                
            if porch_lights.state == "OFF":
                print("living3")
                porch_lights_on_off = 'bulb_off.png'
            if porch_lights.state == "ON":
                porch_lights_on_off = 'bulb_on.png'
                return redirect(url_for('Home_page'))```
frank shoal
#

and where do you call this function?

hushed vortex
#

its running in a seprate thread

frank shoal
#

and what are you trying to do with the return value?

hushed vortex
#

it just checks if a light is on or off if its on it sends the bulb_on.png if its off it sends bulb_off.png

frank shoal
#

then why are you returning?

hushed vortex
#

how else can i refresh the page?

frank shoal
#

btw, you should probably add some sleeps in there. Otherwise your CPU usage will go to 100%

hushed vortex
#

yea

frank shoal
#

maybe you should use javascript and setInterval to check for updates.

#

or use a websocket to push updates to the client.

hushed vortex
#

i dont know js

frank shoal
#

then you can't update the page.

hushed vortex
#

i mean i can update the page using the meta tag

frank shoal
#

if you want to do things after the page is loaded, you need to use javascript

hushed vortex
#

<meta http-equiv="refresh" content="5">

frank shoal
#

I guess that works

#

but it's just refreshing the page.

hushed vortex
#

yea

haughty isle
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.

hushed vortex
#

@frank shoal can i dm you?

frank shoal
#

No

hushed vortex
#

ok so here is an issue

#

if i click the buttons on the website to turn on the lights or off

#

it updates like this

#

but i do it manually using the light switch it doesent update the website

#

in order to update the website i have to refresh the page

hushed vortex
#

and then it updates

haughty isle
golden bone
#

Did you try right click on it in your browser and "inspect element"?

violet field
#

Hey everyone. I wrote a py script that will take in a youtube video url and will download the video as a mp3 into a folder on my local machine. is there a way now to create an app locally such that i can just enter the url into the app and it downloads the mp3 into the same folder. any help would be appreciated.

haughty isle
white delta
#

how do i create an admin panel in django?

fierce grail
#

i have a question, i get a response from an ajax response, and i replace the body of the html, however this breaks my js code (dropdowns etc dont seem to be working) i think its because the js is not executed when the DOM is loaded, anyone got a clue ?

#
            success: function (data) {
                $("body").html(data);
            },```
#

the weird thing is, if i call the response second time round, it then works ....

thorn igloo
#

you're replacing everything in body, why? if you dont mind me asking

#

why not just target like a certain part etc

fierce grail
#
success: function (data) {
                //var responseData = $('#tableDiv',data).html();
                //$('#tableDiv').html(responseData);

                //fix for the alerts, loading the response for body only
                $("body").html(data);
            },```
#

the commented line at the top was what i originally used

#

or is it possible to load multiple seperate elements ?

thorn igloo
#

the alert is for a notification?

fierce grail
#

<script>Swal.fire({"showConfirmButton": false, "timer": "3000", "allowOutsideClick": true, "confirmButtonText": "OK", "icon": "success", "backdrop": "false", "type": "success", "title": "Application Rejected"})</script>

#

this is one examplke, basically my webpage has a table, with two buttons on ever row, accept or reject, when i accept/reject it does some backend stuff and then returns a swal.fire () script

#

it will either be sucess/failure with a different title

#

@thorn igloo so my main question now is, is it possible to firstly , replace only the table ( i already done this look atthe commented lines in the code i sent above) and two, can i load the swal.fire script to the webpage after sucess response

thorn igloo
violet field
fierce grail
thorn igloo
#

let me try something, i'll get back to you

fierce grail
#

when i clicked reject

thorn igloo
fierce grail
#

usual response when i load the page (no button /ajax call done )

thorn igloo
#

i see

#

so this is triggered when the page is loaded?

violet field
thorn igloo
fierce grail
fierce grail
#

so u see, the response now contains an extra script line ONLY if i have clicked the button

thorn igloo
#

i'm trying to make sure i understand the process here

fierce grail
#

ok:

#

user loads the web page :

#

user has clicked teh reject button

#

ajax post request done as soon as reject button clicked,

thorn igloo
#

oh i see

fierce grail
#

backend stuff is done, now the response is the new html

#

now we have replaced the entire body with the response

#

meaning the application has been removed from the table (because we have rejected it )

#

and the swal fire script is that nice alert u see in the second pic

white delta
thorn igloo
#

well, you can trigger the popup from javascript right?

#

why not just make a function that does that for you

#

and then replaces the table

fierce grail
thorn igloo
#

instead of everything

thorn igloo
fierce grail
#

like look

#

this is in my django backend

thorn igloo
#

ok

#

what is sweetify

#

what does that do rather

fierce grail
#

its a django plugin for sweet alert

#

so it generates that one line script u saw

thorn igloo
#

ohh

#

i thought this was just a frontend only library

fierce grail
#

nah, this is why i am stuck and just resultedin replacing the whole body 😅

thorn igloo
#

so django loads a new page with that script? is that correct?

fierce grail
#

and my ajax call u see , it has the variable data , which is the "new" html file !

#

many things have been loaded

#

this is the new html response

#

which i litreally copy replace the whole body with 😂

thorn igloo
# fierce grail yes

if it loads a new page, why not just load it with the new/modified data etc?

#

or is this like an api

fierce grail
fierce grail
#
            success: function (data) {
                var responseData = $('#tableDiv',data).html();
                $('#tableDiv').html(responseData);

            },```
#

but idk how to also add the one line swal script atthe end

#

so this is why i just left it as replacing the whole body for now

thorn igloo
thorn igloo
#

api data or an entire page

#

that's where im confused now

thorn igloo
white delta
#

i want to have two admin panels -- the main one and another for the client.

fierce grail
#

new page

#

this is a new html page from teh AJAX response

thorn igloo
thorn igloo
fierce grail
#
$.ajax({
            type: "POST",
            url: "{% url 'application_approval' %}",
            data: {
                "decision": decisionBool,
                "applicantID": applicantID,
                "currentClub": '{{ club.id }}',
                csrfmiddlewaretoken: window.CSRF_TOKEN,
            },
            success: function (data) {
                //var responseData = $('#tableDiv',data).html();
                //$('#tableDiv').html(responseData);

                //fix for the alerts, loading the response for body only
                $("body").html(data);
            },
            error: function () {
                Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                    text: 'Something went wrong, Please try again',
                })
            },
        });```
thorn igloo
thorn igloo
fierce grail
#

yes the variable data is the html

thorn igloo
#

oh ok

fierce grail
#

$("body").html(data); u see, this replaces the current page BODY with the new htmls data

thorn igloo
#

i thought the button click refreshed the whole thing

fierce grail
#

no no its thhis ajax stuff

#

ajax post request when button is pressed

thorn igloo
#

hmm i see

#

so why not make the reject button do a post action so that the page is refreshed with the new data instead of doing ajax calls?

fierce grail
#

then the alert is not received XD

thorn igloo
#

but you can trigger it no?

fierce grail
white delta
#

what is the best book to learn django?

thorn igloo
#

why not conditionally render it, depending on a variable you can change during post etc

fierce grail
#

i thjink i got an idea

#

i should just select this elemnt and just .append() to the body

#

but how do i select this element without an id ?

#

<script>Swal.fire({"showConfirmButton": false, "timer": "3000", "allowOutsideClick": true, "confirmButtonText": "OK", "icon": "success", "backdrop": "false", "type": "success", "title": "Application Rejected"})</script>

thorn igloo
#

youre using jquery

fierce grail
#

yh

thorn igloo
#

?

#

should be $(#id) i believe

#

but just double check

fierce grail
thorn igloo
#

conditionaly render with jinja2

#

i.e

#
{% if some_variable %}
<script>Swal.fire({"showConfirmButton": false, "timer": "3000", "allowOutsideClick": true, "confirmButtonText": "OK", "icon": "success", "backdrop": "false", "type": "success", "title": "Application Rejected"})</script>
{% endif %}
#

this is syntax you would use for flask, don't know if it's the same for django

sour lichen
#

Read the SweetAlert2 docs, I know for a fact that SweetAlert1 has an attribute “content” which accepts HTML.

#

You Swal call should be inside the success callback function block

fierce grail
#

so "customClass" : "x class"

#

how can i access this element using jquery as i dont know how to do this, onnly know how to do via id/class name

thorn igloo
#

$(".class_name") i believe

fierce grail
#

if they had a simple way to just add an id to the script tag -_-

thorn igloo
fierce grail
thorn igloo
#

which script are you using to make the ajax calls

fierce grail
#

the type ?

fierce grail
#

sweetify

#

sweetify.success(request, 'Application Rejected', icon='success', timer='3000', backdrop="false", customClass ='xClass')

#

backend django generates that

thorn igloo
#

where is the ajax call coming from exactly?

fierce grail
#

ajax coming from the webpage when u click teh button

#

sends teh request to the url, which django forwards to a function

thorn igloo
#

yeah, what script enables that ajax call

fierce grail
#

the function checks if the request was a post

#

then does stuff

#

e.g:

#
                    Club.add_member(club,applicant)
                    Club.remove_applicant(club,applicant)
                    sweetify.success(request, 'Application Accepted', icon='success', timer='3000', backdrop="false")
                    #print("Application accepted")```
thorn igloo
fierce grail
#

html webpage

thorn igloo
#

bruh

fierce grail
#

ik u supposedto have it seperate

#

but for now ive left it up there

thorn igloo
#

append it to the end

fierce grail
#

okay

thorn igloo
#

make sure the sweetify cdn is above it or so

#

then in your ajax call, just do this.

#
Swal.fire({"showConfirmButton": false, "timer": "3000", "allowOutsideClick": true, "confirmButtonText": "OK", "icon": "success", "backdrop": "false", "type": "success", "title": "Application Rejected"})
#

this thing is literally just calling the function

#

you don't need django to do that for you

fierce grail
#

and depending on the output u get different swal.fires

#

one many be a sucess alert, one may be reject alert

#

with different titles..

thorn igloo
#

ok, if that's the case, i dont really see the need for ajax calls

#

you can just use django to render the stuff for you

fierce grail
#

what do u mean by that ?

#

a post must take place when a button is clicked, otherwise how would django know what to do with what button u pressed?

thorn igloo
#

you can trigger a post with a form

#

your thing is literally returning back html

fierce grail
#

with the ajax post i need to pass multiple values needed for the backend check

#

such as these

thorn igloo
#

but the form reloads the page with the new data

fierce grail
#

or an actual reload

thorn igloo
#

an actual reload

#

plus, you can pass those things as hidden inputs

#

in a form

fierce grail
#

mmmm ok

#

omgod i fixed it 😭

#

i just reload the page as u said @thorn igloo

#
            success: function (data) {
                document.open();
                document.write(data);
                document.close();
            },```
#

@thorn igloo however i m getting some errors in console when it loads other stuff

#

this is in my head of my html

#
<!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.0/font/bootstrap-icons.css">```
thorn igloo
#

yeah that's not what i was suggesting really

#

but if it works i guess

fierce grail
thorn igloo
#

looks like it

fierce grail
#

yh. well ill leave it as this for now until i figure out how to select that script

#

thanks for the help!

haughty isle
#

Put your JS in a JS file and load it with <script src="{% static '...' %}" type="module"></script> and avoid inline JS completely

fierce grail
#

yh

haughty isle
# fierce grail yh

If you want to put data in there you can pass it with:
<script id="some-id-here" src="{% static '...' %}" type="module" data-current-club="{{ club.id }}"></script>

#

Then grab it with with

const { currentClub } = document.getElementById("some-id-here").dataset;
fierce grail
#

yh thanks for that, i think ill do it once i fixed the issue, and move this to a js file during the refactoring process

native tide
#

Looking for help getting a 2 year old github project webapp (python+nodejs/npm) to run. After troubleshooting some inital problems i'm stuck with a "subprocesserror". Paying reward in cryptocurrency on success! DM me please.

lavish prismBOT
#

9. Do not offer or ask for paid work of any kind.

native tide
#

even if its gifted? not looking for freelancer but help...

#

i am struggeling for days now on the project

haughty isle
#

Best to just ask your question you'll probably get free help

native tide
#

OK.

Error:

subprocess error:

(/root/.npm/_npx/20002/lib/node_modules/ionic/node_modules/@ionic/utils-subprocess/dist/index.js:40:23)
at ChildProcess.<anonymous>
(/root/.npm/_npx/20002/lib/node_modules/ionic/node_modules/@ionic/utils-subprocess/dist/index.js:124:27)
at ChildProcess.emit (events.js:315:20)
at maybeClose (internal/child_process.js:1048:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5)
  ionic Error
  ionic     at new SubprocessError (/root/.npm/_npx/20002/lib/node_modules/ionic/node_modules/@ionic/utils-subprocess/dist/index.js:40:23)
  ionic     at ChildProcess.<anonymous> (/root/.npm/_npx/20002/lib/node_modules/ionic/node_modules/@ionic/utils-subprocess/dist/index.js:124:27)
  ionic     at ChildProcess.emit (events.js:315:20)
  ionic     at maybeClose (internal/child_process.js:1048:16)
  ionic     at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5) +1m```
thats error with --verbose log

WHY?
haughty isle
#

Uhh wait that's a traceback just ``` will do

inland oak
warped aurora
#

does classList.toggle only apply to the first element it finds?

haughty isle
warped aurora
#

I have document.querySelector(".nav-label").classList.toggle("nav-label-hidden");

#

But it's only changing the first nav-label class

haughty isle
dusk portal
#

can any1 help me

#

deploying django site

haughty isle
dusk portal
#

This site can’t provide a secure connection127.0.0.1 sent an invalid response.
ERR_SSL_PROTOCOL_ERROR

#
[11/Dec/2021 21:38:19] You're accessing the development server over HTTPS, but it only supports HTTP.
haughty isle
#

you need to access the development server with http not https

#

but also if you're deploying a django site - why are you using the development server?

dusk portal
#

development server

#

SESSION_COOKIE_SECURE= True
CSRF_COOKIE_SECURE= True
SECURE_SSL_REDIRECT= True

SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_PRELOAD = True
SECURE_HSTS_INCLUDE_SUBDOMAINS= True

haughty isle
#

You can't hsts preload 127.0.0.1

#

And the development server can't do https and you're not allowed to use it in a deployment

dusk portal
#

@haughty isle idk why

#

i cant fix that error

haughty isle
dusk portal
#

then too

#

rn also it's showing error

terse vapor
#

For flask, if I want to create a one to many relationship(parent and child), and the class for many relationship are all based on one child class(so one class name child would contain multiple data for different child), how can I do that?

haughty isle
haughty isle
#

Ok but the permeant redirect is still cached

dusk portal
#

yeah\

thorn igloo
dusk portal
#

ohk cool it works when i open in incognito

#

lol

golden bone
#

anyone good with Hugo? I want to direct http://localhost:1313/staticfile to static_file.html . I've been playing around with permalinks and aliases per https://gohugo.io/content-management/urls/ but can't figure out how to get this working (or if maybe there's a better way to do this).

Hugo supports permalinks, aliases, link canonicalization, and multiple options for handling relative vs absolute URLs.

normal hatch
#

Hello guys my image not loading in my website in other device

native tide
#

I would like to do backend with flask that receive photo from my Android app, it just for practice so I wouldn't like to pay for server, what's easiest way to do that?

haughty isle
native tide
haughty isle
#

Yes

native tide
#

Nice

haughty isle
#

But probably not many

native tide
#

Is it hard to deploy project on Heroku? Can you pls explain process?

native tide
haughty isle
#

No

#

I mean not many photos

native tide
#

I see

haughty isle
#

The only free storage is the 20k rows of pgsql

#

So you have to use blob storage

native tide
#

I wouldn't use SQL

#

Can you pls explain process of deployment?

#

@haughty isle

haughty isle
native tide
#

Or is it anyway also easy to do it with Django?

golden bone
native tide
woeful nymph
#
<li class="nav-item">
    <a class="nav-link" style="color: lawngreen; font-weight: bold">
       <i class="fas fa-coins"></i>
       {{ current_user.budget }}
    </a>
</li>
```Why doesn't the "fas fa-coins" display a coin sign?
livid mural
#

Hello guys, is there a place where someone can somehow review my django code? I'm just starting to learn django and wondering if I can somewhere get some feedback about my code

golden bone
daring isle
#

Hi guys , anybody switch front end to react late in development before ?
Backend is django .
Is it comparable to starting from scratch ?

thorny rover
#

I just got my portfolio rough draft done. I would love feed back and help with device/browser testing! Keep in mind this is a rough draft. For me that means;

-no performance optimizations
-image files usually too large
-only basic breakpoints added
-Very little to no functionality
-little to no cross browser testing

But besides that it shows the core of the design and basically what it should look like 95% of the way. just respond or @ me if you take the time to look and have feed back! Thanks a ton!

https://portfolio-520bb.web.app

#

Also fun fact, the parallax background changes based on your system dark theme

thorn igloo
#

I've been rick rolled,

sacred crane
#
table = function(a){
        var cols = row => row.map(c => `<td>${c.toFixed(4)}</td>`).join(""),
                 rows = tbl => tbl.map(r => `<tr>${cols(r)}</tr>`).join("");
             return `<table><tbody>${rows(a)}</tbody></table>`;
           }
document.write(table(array));
``` I was trying to run this code in reactjs but unable to do it?
thorn igloo
#

that defeats the purpose of react

sacred crane
#

even though i remove document.write and run this as a function inside {} it is not working

thorn igloo
#

do you understand how react works?

sacred crane
#

I am new to react

thorn igloo
#

ok

#

what are you trying to do exactly?

sacred crane
#

I guess keeping this inside {} runs this as a jsx ?

thorn igloo
sacred crane
thorn igloo
#

that will not work in react

#

that's not how react works

sacred crane
#

What should i need to change to make it work in react?

#

Is there any way around the solution?

thorn igloo
#

do you understand how to use react?

#

let's start here

sacred crane
#

I have little knowledge. I have been working on it from past 1 week building a website

thorn igloo
#

ok, what are you trying to do?

sacred crane
#

I am trying to display a multidimensional array as a table in react js. I have tried to use the map function and I got all the numbers in the multidimensional array as a single array but unable to convert them into proper columns and rows.

#

what i am expecting is this

#

and I can't use list indexing as the number of rows keeps on changing.

sacred crane
#

no after using map function it converted into 1 d array

thorn igloo
#

can you send a sample of the data, if you dont mind

#

is this your question on stackoverflow?

lavish prismBOT
#

Hey @sacred crane!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

sacred crane
sacred crane
daring isle
thorn igloo
inland oak
silver nexus
#

which is better flask django

thorn igloo
#

question you should be asking is which is better to use for my project

tropic blaze
#

Hey can anyone send me any video recommendation or blog on how to clone a django project from github?

thorn igloo
#

git clone <url>

#

you need git installed ofcourse

tropic blaze
#

Yeah I know the git commands you can directly jump on to setting up the virtual enviornment part

silver nexus
thorn igloo
thorn igloo
silver nexus
thorn igloo
#

i'm a flask guy

#

but i'm not saying it's better than django

#

i just prefer to use flask

silver nexus
livid mural
# golden bone If you can share a link to a repo here requesting feedback, you may get some.

https://github.com/NotSoYeezy/django-NoteShare

It probably is bad, because it is my first django project but I hope to here some feedback :))

GitHub

NoteShare is a Django Web Application. Its purpose is to help with sharing and finding school notes. - GitHub - NotSoYeezy/django-NoteShare: NoteShare is a Django Web Application. Its purpose is ...

manic crane
#

how do i create a serializer for custom user models ? can someone point me to docs ??

thorny rover
deft heart
deft heart
thorn igloo
thorn igloo
deft heart
thorn igloo
#

not really, just install and select the recommended options

deft heart
thorn igloo
deft heart
thorn igloo
deft heart
thorn igloo
novel stream
#

Hey folks, I'm using pytest with Django. does anyone know how I could avoid adding to all my tests that touch database the usual @pytest.mark.django_db to the classes/methods? I was reading the docs about any global fixture I could add to the conftest or even a marker to pytest.ini but nothing worked so far

#

I think I'm missing something really obvious, but can't see

native tide
#

How can i make "users/?id=1/&mode=Profile" into /users/1/profile this is my htaccess ```
RewriteEngine On

RewriteCond %{QUERY_STRING} ^id=(\d+)&mode=([^/.&]+)
RewriteRule ^(users)/index.php$ /$1/%1/%2? [R,L]

RewriteRule ^(users)/(\d+)/([^/.]+)$ /$1/index.php/?id=$2/?mode=$3 [R,L]```

ancient totem
#

hi

#

not really python related but

#

if I want to post long code

#

in wiki

#

is there an alternative to <source lang=python> </source>

#

I want to post a scrollable box of code in wiki

inland oak
ancient totem
#

Sorry

daring isle
daring isle
thorny rover
#

You can also try it out at https://play.tailwindcss.com kind of like code pen but no account needed

Tailwind Play

An advanced online playground for Tailwind CSS that lets you use all of Tailwind's build-time features directly in the browser.

daring isle
#

I think i was on something else lol

pallid lily
#

is there any practice project for django channels?

thorny rover
bold bolt
#

im having issues with flask

#

im getting the following error after running the server

#

it works on my other machine, but not my pi

#

AttributeError: 'Flask' object has no attribute 'get'

#

but i get no such error on my rig or server

thorn igloo
bold bolt
#

im using venv

#

i thought venv was supposed to use the same version between environments

thorn igloo
#

check if the same version is installed

#

if that's the case, might be something else

#

cause the get method was only introduced in the recent version

bold bolt
#

no its 2 different versions

#

pi is using 1.01

#

pc is usintg 2.something

#

pi is running python v3.7

#

pc is python v3.9

thorn igloo
#

or you can upgrade the versions i guess

bold bolt
#

yeah rip will do

#

wanted to reuse urls with different responses dependant on the request typoe but i guess that isnt happening

thorn igloo
#

here's an example

#

same route, different methods

simple garden
#

can someone explain this piece of code to me

opal robin
#

hi

#

is it possible to make a web crawler that gets data from a site that requires log in?

#

i am already registered at that site

vivid canopy
#

help me pls

blissful fiber
#

If I wanna buy a membership for a company/service that allows me to set up a back-end server for my website instead of setting up my own hardware as a server, how much would it cost per month??

#

just a rough estimate from your knowledge will be good 👍

mint folio
#

@blissful fiber Hosting servers can be as cheap as a few euros per month. If your looking for also a server management and site deployment service then it would be maybe around 10-20 euros per month. All on basic plans I guess.

#

You can checkout w3 schools links, they explain it well with examples, and editor to play with. https://www.w3schools.com/html/default.asp

finite wagon
#

i dont get this

#

why is it returning a function called increment

#

but the kinda shorthand function is assigned to the constant increment

scenic furnace
#

For websites what would be a good "human test" to bar account creation? Preferably it would be done without using external services and would be something I can make a lot of variations on to avoid bots being able ot just put in the same answer every time to get past.

ebon beacon
#

I'm trying to create a CRUD app in django but each time I try using CreateView module I get this error for my datefield - This field cannot be null

#

Whereas I am passing a value

#

In my views.py

class MovieCreateView(CreateView):
    template_name = 'movie_create.html'
    form_class = MovieForm
    success_url = reverse_lazy('list')

    def form_invalid(self, form):
        LOGGER.warning('User provided invalid data.')
        return super().form_invalid(form)
#
class MovieForm(ModelForm):
    class Meta:
        model = Movie
        fields = '__all__'

    title = CharField(validators=[capitalized_validator])
    rating = IntegerField(min_value=1, max_value=7)
    released = PastMonthField()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'form-control'

    def clean_description(self):
        initial = self.cleaned_data['description']
        sentences = re.sub(r'\s*\.\s*', '.', initial).split('.')
        cleaned = '. '.join(sentence.capitalize() for sentence in sentences)
        self.cleaned_data['description'] = cleaned

    def clean(self):
        result = super().clean()
        if result['genre'].name == 'Comedy' and result['rating'] >= 6:
            raise ValidationError(
                "Comedies have not been so good recently to be rated above 5"
            )
        return result
#
def capitalized_validator(value):
    if value[0].islower():
        raise ValidationError('Value must be capitalized.')


class PastMonthField(DateField):
    def validate(self, value):
        super().validate(value)
        if value >= date.today():
            raise ValidationError('Only past dates allowed here.')

    def clean(self, value):
        result = super().clean(value)
        return result
#
class Genre(Model):
    name = CharField(max_length=128)

    def __str__(self):
        return self.name


class Movie(Model):
    title = CharField(max_length=128)
    genre = ForeignKey(Genre, on_delete=DO_NOTHING)
    rating = IntegerField()
    released = DateField(null=True)
    description = TextField()
    created = DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title
ebon beacon
#

And in my console, it logs that 'User provided ivalid data'

daring isle
#

Django :
Anybody know how to access a variable from the navbar on any page .
Want to do a pending notification system . Only working in 1 view atm , I could recreate it for every view but that seems like the silly way

#

Did you create the form from scratch or form as p?

daring isle
#

In html

#

What’s past month field in your form ? Why not use date Input ?

ebon beacon
#

My movie_create.html

#
{% extends "base.html" %}

{% block content %}
    <form method="post">
        {% csrf_token %}
        <table>{{ form }}</table>
        <input type="submit" value="Submit" class="btn btn-primary">
    </form>
{% endblock %}
hollow marlin
#

Hey everyone, i'm getting this error in a django proyect, this is from heroku logs, i'm trying to send emails, everything works well at local but in heroku its not working, the enviroment variables are there

ebon beacon
#

Appears in my clean_description method, I was not returning the cleaned data but passing it to self which eventually ensured the data would return as None thereby rendering it invalid

daring isle
#

I sorted my problem out too .
I made a method in my views and returned the variable I needed .
Then just imported and called the method on each template view and passed the variable into the context .

It’s still a bit hacky but luckily I don’t actually have many pages for users to navigate

#

Maybe I could have just created a view for my navbar tho 🤔

jovial cloud
thorn igloo
#

there's a select tag i believe

inland oak
#

it depends on if it is enough for you to have Standard HTML dropdown, or if u wish to make custom dropdown (better customability in terms of style)

balmy salmon
#

Hello everyone

inland oak
#

if first choice (the easy one), just use select as one of input fields in your form https://www.w3schools.com/tags/tag_select.asp
with some adjustments (or perhaps with none?) it should pass value to your POST request to backend

The second option available only with usage of frontend frameworks, or with usage of CSS frameworks (if they have JS components) perhaps. Well and there is always option to make a crutch out of vanilla JS on its own 🤔

Actually if to think about it. It should be possible to make a custom dropdown with pure CSS without JS. With CSS target property and anchor usage to enable/disable dropdown and select choices
https://developer.mozilla.org/en-US/docs/Web/CSS/:target
example for that u can find at the bottom of the page

inland copper
#

some elem in the navbar can store the data

#

give that elem an unique id

#

and access it using js

#

document.getElementById()

hard spoke
#

can one send me link for python + django free hosting

inland oak
#

what are u using for its implementation?

#
<select id="language">
    <option value="en" selected>English</option>
    <option value="es">Español</option>
    <option value="pt">Português</option>
</select>
var select = document.getElementById('language');
var value = select.options[select.selectedIndex].value;
console.log(value); // en
#

anyway if it is real select, just a bit of JS will surely help to extract the value

#

u a probably having a custom dropdown though

#

Vanila JS it is

#

how do you expect to select the H1?

#

select by class perhaps

#

querySelector(".space")

#

and then from it get your ID

#

a minute

#
let elem = document.querySelector(".space").id;
console.log(elem)
#

u a welcome 😉

#

how do u mark visually selected elements

#

selection-outline u need basically ID element of this class then?

#

yes, is it marking the selected element?

#

anyway, what happens with selected element?

#

there should be some sort of change that allows you to find if something was selected

#

okay. Lets think

#

U need basically

#

to find am Option element (in order to access ID), which has InnerHTML value matching with selectText value

#

basically find javascript usage

#

lets rewrite to accommodate it

#
let elements = document.querySelectorAll(".space");

var result = elements.find(obj => {
  return obj.innerHTML == selectText.innerHTML
})

console.log(result.id)
#

well, I did not test it, try find then

inland oak
#

straight version

<div id="selection-field" class="selection-field">
    <p id="welcome-embed-selectText" class="start-text">a2</p>
  </div>
  <h1 class="space" id="b1">a1</h1>
  <h1 class="space" id="b2">a2</h1>
  let elements = document.querySelectorAll(".space");
  var selectText = document.getElementById("welcome-embed-selectText");
  console.log(elements)
  console.log(selectText)


  var result = null
  elements.forEach(function (currentValue) {
    console.log("elements comparing")
    console.log(currentValue.innerText)
    console.log(selectText.outerText)
    if (currentValue.innerText == selectText.outerText) result = currentValue.id
  })

  console.log(result)

it assumes getting correctly text from selectText, be sure to check what u extract from it

#

provided you HTML example that surely works

#

as I said, u need to make sure that u extract just text out of elements

#

without <p> and e.t.c. stuff

#

and when u change selectText innerHTML, to make sure it still selects text properly

#

try to find out which properties work best for you, innerHTML, outerText, innerText

#

or just make it consisted

#

don't delete p tag from selection-field

#

change text of it, and compare with its text

fickle saddle
#

Guys is it fine to just use the session module and not the login manager in flask, when implementing the Login/Registration feature?

inland oak
#

your text field selectField contains just Select a channel...

#

null means nothing is chosen

#

feel free to write your own default value instead of null

#

or make selectField with some default value in advance

#

that would be more appropriate

#

u selected wrong value to compare with

#

instead of selectText, you are wishing to compare with smth else

#

write appropriate selector

native tide
#

i got that fixed but

#

i also need help sendign a request from my public site to a local site on the server

native tide
#

Should I learn django or flask first?

quasi sierra
#

hey there. for front-end is it necessary to learn bootstrap and Sass or directly learn frameworks?

inland oak
#

SASS is highly recommended, it makes life VERY MUCH easier, but in order to use it efficiently, you need to know CSS first

#

SASS can be applied together with frontend frameworks. So they both should be learned

quasi sierra
#

ok so first Sass and then frameworks?

fierce grail
#

@haughty isle hi sorry to ping but im a bit confused about something u told me yesterday, wondering if ur still here to help ?

inland oak
#

because.... frameworks have installed SASS out of the box usually

#

it is just easier to launch it there

fierce grail
#

If you want to put data in there you can pass it with:
<script id="some-id-here" src="{% static '...' %}" type="module" data-current-club="{{ club.id }}"></script>
Then grab it with with
const { currentClub } = document.getElementById("some-id-here").dataset;

#

this is what u said, im stuck on passing the values

quasi sierra
inland oak
#

there is a third choice Angular, but I am not sure about it

inland oak
#

Angular is required in more advanced companies and at the same level of demand as Vue.js

#

Angular has higher learning curve, it requires to use Typescript at the start

haughty isle
quasi sierra
fierce grail
#

this is what i got so far :

#

const { ? } = document.getElementById("navbar-js").dataset;

#

<script id="navbar-js" src="../static/js/navbar.js" type="module" data-post-url = "{{% url 'remove_all_messages' %}}" data-path = "{{ request.path }}"></script>

inland oak
# quasi sierra thanks for the help

u a welcome. If frontend is your main speciality, I would recommend React I guess.
because there are just 2-3 times more job vacancies for it

quasi sierra
#

ok

inland oak
#

Frontend is just tertiary direction for me, that's why I prefered nicer but less in demand framework

quasi sierra
#

oh i see

#

what about vanilla?

inland oak
#

General javascript knowledge is still required being known for more efficient use of framework anyway

quasi sierra
#

alright

fierce grail
#
function removeAllMessages() {
    //ajax post method, 

    var script_tag = document.getElementById('navbar-js');
    var postUrl = script_tag.getAttribute('data-post-url');
    var path = script_tag.getAttribute('data-path');

    $.ajax({
        type: "POST",
        url: postUrl,
        csrfmiddlewaretoken: window.CSRF_TOKEN,
        data: {
            "path": path,
            csrfmiddlewaretoken: window.CSRF_TOKEN,
        },
        success: function (data) {
            var responseData = $('#notificationDropdownID', data).html()
            $('#notificationDropdownID').html(responseData);
        },
        error: function () {
            Swal.fire({
                icon: 'error',
                title: 'Oops...',
                text: 'Something went wrong, Please try again',
            })
        },
    });
}```
inland oak
#

Jquery is just vanilla on steroids ;b

quasi sierra
#

😆 oh didn't know about that

#

i should learn js before jquery ig

inland oak
#

Frontend framework replaces Jquery. Not really need to learn it

quasi sierra
#

oh really

#

ok

native tide
#

anyone know any good sources for handling account management with flask?

haughty isle
haughty isle
fierce grail
#

it saying the method is not defined

#

the js file loads in the network tab on inspect element on my browser

#

and this is how its triggered in html

#
<button class="dropdown-item" type="button" onclick="removeAllMessages()">Mark as all Read</button>```
wraith dagger
#

Is it possible to use custom url dispatcher with DRF action decorator?
E.g:

@action(url="/some_action/<foo_id:int>")
def some_action:
haughty isle
haughty isle
fierce grail
haughty isle
#

right you need to add a listener

fierce grail
#

ah so it would have to be within a <script>

haughty isle
#

no your .js file

#

just after your function removeAllMessages() {

fierce grail
#

ah okay

fierce grail
fierce grail
#

ive searched online for this however there isnt an answer i could find for my use case

#

i have a table , and that has two buttons per row, accept or reject

#

right now it runs a script, on button onclick, it runs the function which is an inline js , and passes two variables, (boolean and a int)

#

now as im trying to move my inline js to js files, im stuck as to how to pass the int, boolean has been solved as ive just changed it so that within my js file, if the eventlitner has listened to the accept button, it will run the changeListner () and pass the value of true , the opposite for false

#

so im stuck as to how i pass that int

#
<button id = "applicationAcceptButton" class="btn btn-outline-primary" >Accept</button>
<button id = "applicationRejectButton" class="btn btn-outline-primary" >Reject</button>```
#
<script id="applicationApproval-js" src="../static/js/applicationApproval.js" type="module" data-post-url = "{% url 'remove_all_messages' %}" data-applicant-ID = "{{ user.id }}" data-current-club = "{{ club.id }}"></script>```
fierce grail
#
function changeListener(decisionBool) {

    var script_tag = document.getElementById('applicationApproval-js');
    var postUrl = script_tag.getAttribute('data-post-url');
    var applicantID = script_tag.getAttribute('data-applicant-ID');
    var currentClub = script_tag.getAttribute('data-current-club');

    //ajax post method, either accepted or rejected
    $.ajax({
        type: "POST",
        url: postUrl,
        data: {
            "decision": decisionBool,
            "applicantID": applicantID,
            "currentClub": currentClub,
            csrfmiddlewaretoken: window.CSRF_TOKEN,
        },
        success: function (data) {
            $("body").html(data);
        },
        error: function () {
            Swal.fire({
                icon: 'error',
                title: 'Oops...',
                text: 'Something went wrong, Please try again',
            })
        },
    });
    
}

document.getElementById("applicationAcceptButton").addEventListener("click", changeListener(true));
document.getElementById("applicationRejectButton").addEventListener("click", changeListener(false));```
lilac solar
fierce grail
#
<button id = "applicationAcceptButton" class="btn btn-outline-primary" onclick="changeListener(true, '{{ user.id }}' )">Accept</button>
<button id = "applicationRejectButton" class="btn btn-outline-primary" onclick="changeListener(false, '{{ user.id }}' )">Reject</button>```
lilac solar
#

So that would stay the same regardless if the JS function is inline or in a file. What you need to figure out is the other django/flask variables within the function that you need, most notably the url

fierce grail
#

they are within the table right

#

and django basically goes through a list, and creates a row depending on how many users there are

#

so this is still a django issue ?

#

so essentialy the html would actualyl be changeListner(true, '1' ) and every row would have a different int

lilac solar
#

It's an issue common with Django Templates & JS interacting, essentially you working out how to cleanly pass django data through to your JS. My default for this over the years has been to default to a cleanly defined Django API and then have the frontend interact with that, rather than pass template variables around.

That doesn't help immediately though.

lilac solar
fierce grail
#

the script

#

see

#

the script is only loaded once

#

so now im thinking, is the onlny possible way is to also inclide an onclick ()

#

and then pass that variable to another inline script

#

and then run the external js script

lilac solar
#

You don't pass variables when loading the script from a file, that only makes it available to the html

fierce grail
#

what im thinking which defeats the purpouse of not having inline js is to still havethe onclick function

#

and when button pressed onclick = x(' user id' )

lilac solar
#

The call to the JS function (with the onclick) would be the same whether loaded from a file or from inline JS

fierce grail
#
funx x (y){
 runtheexternaljsfile(y)
}```
fierce grail
lilac solar
#

Your issue is possibly where you are loading the file. Browsers process HTML documents top to bottom so ensure the script tag is before when you call it.

fierce grail
fierce grail
#

this is my html stctructure

#
<html>
 <head>
  <body>
    table is within here
  </body>
    <script> INSIDE HERE
 </head>
</html>```
lilac solar
#

Your structure ought to be:

<html>
  <head>
  </head>
  <body>
   <table></table>
   <script>
  </body>
</html>
fierce grail
#

so basically i narrowed the problem down

#

so my question is now :

#

how can i pass a value to an event listner

#

<button id = "applicationAcceptButton" class="btn btn-outline-primary" >Accept</button>

#

i wanna add a value in the button ^^ lets say value = {{ user.id }}

#

now how do i pass that vlue to my event listner

lilac solar
fierce grail
#

u cant call the changeListner () function if u have moved it to an external js file

#

or can u ?

lilac solar
#

have you tried?

fierce grail
lilac solar
#

ah ok, in that case you with you want to be creating 2 Eventlisteners per row so you need to iterate over them. In terms of passing values you could add data attributes to your buttons like <button data-user='{{ user.id }}' ...>

fierce grail
#

ah okay thanks

inland oak
#

Don't miss Doctype word

#

In order to be Html 5

fierce grail
#

yup it is within my file

#

as !doctype html

scenic furnace
jovial cloud
warped aurora
#
sidebarToggle.addEventListener("click", function(){
    document.querySelector("body").classList.toggle("active");
    document.getElementById("sidebarToggle").classList.toggle("active");
});

body.active .page .sidebar{
    width: var(--nav-icon-width);
    background:red;
}
body.active .page .sidebar .sidebar-header{
    color: red;
}```
trying to figure out why the sidebar color change works but the headers doesn't
unkempt dome
#

Which framework would u recommend for web development?

#

django? flask? other?

jovial cloud
unkempt dome
#

a menu with sublinks, forms and evtl. login area

jovial cloud
unkempt dome
#

so e.g as sublink a welcome page, an about us page etc

daring isle
#

@unkempt dome the front end side of it (for me atm) is just html and jinja , so they’re very similar when you’re designing ui .
I do want to learn react eventually

#

@unkempt dome a big caveat to watch out for in django is , you need to use django to edit your database tables .
Since using flask I had a habit of manually editing my table layout and data type in MySQL workbench ….did it in django and didn’t realise any issues for a long time , then got shat on .
Took me a whole evening to salavage my db 🤣

unkempt dome
#

okay

#

Thx @daring isle

dense slate
#

Migrations are tough at first but worth it once you figure it out. I can't imagine a life without the ORM now.

subtle hamlet
daring isle
inland oak
#

Defining database structure as a code. Changing infrastructure control versioned as a code

vocal prism
#

Python, Google Firebase, Flask and Asynchronous Programming!
If you know much/anything about this, then I ask you to read on!

I aim to create a chat website making use of the resources highlighted above!

Anyone got any ideas on how to do this effectively??

inland oak
vocal prism
#

honestly i hate web sockets, its just something about me eughghghhghghghghghgh thats why i continuously try to steer clear of them

inland oak
#

I would recommend Django Channels, as it is ready out of the box solution for that

vocal prism
#

is there like a template I can work off/look at ^^

inland oak
#

Flask is too fresh in async to have smth for that, better to apply Django or to find solutions in FastAPI as alternative

inland oak
vocal prism
#

found it

#

and i suppose i should switch out the database system the tutorial uses for firebase

#

??

inland oak
#

As far as I know Firebase is a no code solution and it is alternative to backend (So it would be alternative to usage of Python / Flask / Django and .e.t.c.)