#web-development
2 messages · Page 205 of 1
try adding print(living_area_lights.state) before the if
also is the hi geting printed
yea
is any html being returned to the browser?
open elements
is the pic working now?
it doesnrt load any other elements because its stuck on the while loop
can someone one help me setup and @native tide setup up a site
@lapis glade
ash may u be so kind and generouis to help me setup my website
oh wait so its not loading
interactive or what?
its a interactice
html
do you need the web server or help making the site itself @native tide
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
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
hmmm
what's the issue here
it works now ty tho
ok
can i dm you for a sec? @thorn igloo
what are you trying to achieve exactly?
that's wrong syntax
im doing what the site says
show me what the site says
now look at this, you're clearly not doing the same thing
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
yeah
Whats the prob?
what is the error?
yeah
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
<!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>
</body>
</html>
No
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
No change
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()
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)
No change
run python file |>
This is fine
so what is error
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
No
Idk what is the problem
Ye
Did you save your files?
How
Wha
Yes it can be
Wait
For running make sure to end the previous program
By Ctrl + C
Thanks it's work ctrl +C
:)
Thanks Both of you for my help
Welcome 😄
👍
yea im sorry i dont know whats wrong
i need to have the {{url_for('static', filename= since i am using flask
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>
your thing has 3 parameters
the one i showed you only has 2
why are you defining it in jinja2?
it should be defined from the backend, that's how these things work
what ever youre using to run your server
so the .py file
it is defined in the backend
if thats the case
but dont i need to this
what are you doing here
in my case its "imgg = onnn"
why do you have 3 parameters?
look, i didnt say copy this code
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
what about this
here it's explained how to use a predefined variable in the url_for syntax
that is what i need to do
dude, this is a string, not a variable
so fix it
{{}} right?
ignore the {{}} part for now
just imagine url_for is a python function
how are you gonna pass the filename as a variable?
filepath = "this"
def url_for('static', filename=filepath):
i didnt say define the function
but do the same for your thing
pass the variable you want to filename
again, ignore {{}}
was that so hard
what did you define onnn as?
did you pass it to your template
Hi there, How to enhance the security of unauthenticated endpoint in DRF ?
Dropping free books for that
nginx cookbook:
https://www.nginx.com/resources/library/complete-nginx-cookbook/
- read DRF throttling: https://www.django-rest-framework.org/api-guide/throttling/
Available compliments of NGINX, this O’Reilly Media eBook features practical security tips and advice that your development and security teams can use right away.
Level up on NGINX with this free O'Reilly eBook, updated for 2021. Get sample configurations for the most popular NGINX deployments: load balancing, caching, security, cloud deployment, automation, containers and microservices, high availability, performance tuning, and more.
Django, API, REST, Throttling
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
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:
Thanks for the help !
u a welcome. make sure to go through this page too: https://docs.djangoproject.com/en/3.2/topics/security/
All we need just to enable security that is already there
Indeed !
make the z-index of that white area 999
Please can anyone tell me what's the use of below lines in django
class Meta:
verbose_name_plural =" "
I think this is used in Django Admin panel at least
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
Hello, what should know python backend developer to have a work?
Thank you,
Should I know python very very good?
<link href="css/login.css" rel="stylesheet" type="text/css" />
why isnt this working lmao
depending on which job rank you are targeting, obviously junior has less required level than middle+
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
Okay, thx I think I am junior at backed, but I scared about my knowledge
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?
@app.route("/", methods=['POST', 'GET'])
So 3 different urls?
yeah
But I want everything to be on 1 page
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
Variables also depend on input
So if I put everything in 1 route, idk if that'd work
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
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
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
So plotting is done in home page, and calculating u and o in 2nd route?
yeah
Makes sense
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
What code would I be seperating into different functions then
what makes mae and kita different
They have different n variables
Wdym by that?
like you can use same variable names for both of these if they serve the same purpose in both places
That's already the case
~~@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 🙂
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
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?
Ah
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
yea you will
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
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.
Check the network tab of your browser's dev tools
What are the basic python skills I need before starting with django?
try the django tutorial and see how far you get
the network tab? what do i do on it?
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') }}"/>
What django tutorial?
The official one or the django one
Give it a go and see how you do?
can I ask about folium here?
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
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?
ok thanks!
Show your code and full Traceback?
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
!code
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.
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'))```
and where do you call this function?
its running in a seprate thread
and what are you trying to do with the return value?
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
then why are you returning?
how else can i refresh the page?
btw, you should probably add some sleeps in there. Otherwise your CPU usage will go to 100%
yea
maybe you should use javascript and setInterval to check for updates.
or use a websocket to push updates to the client.
i dont know js
yea
then you can't update the page.
i mean i can update the page using the meta tag
if you want to do things after the page is loaded, you need to use javascript
<meta http-equiv="refresh" content="5">
yea
!paste
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.
@frank shoal can i dm you?
No
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
like this
and then it updates
So you want to do server sent events?
Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page.
Developing a web application that uses server-sent events is straightforward. You'll need a bit of code on the server to stream events to the front-end, but the client side code works almost identically to websockets in part of handling incoming events. This is a one-way connection, so you can't send events from a client to a server.
Did you try right click on it in your browser and "inspect element"?
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.
Yes
What's the difference between an "app locally" and a "py script"?
how do i create an admin panel in django?
vague question, what do u mean , there is an admin panel already built in if u wanna manage ur models etc
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 ....
you're replacing everything in body, why? if you dont mind me asking
why not just target like a certain part etc
well basically in my response, it also loads some thing else , (an alert) and so that alert for some reason only works when i load the whole body
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 ?
the alert is for a notification?
yea so im using sweet alerts
<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
before i answer this, how is the swal.fire script triggered normally?
I mean I would love to access a web page where I paste the link and it downloads. I just want that web page available locally
im using django, so the backend does it ( button pressed - > post reqest sent using AJAX - > backend django checks stuff and ADDS a single js line which i sent above (<script>Swal.fire (.....) ) to the response (data)
let me try something, i'll get back to you
sure thanks, here is a visual example
when i clicked reject
run a local flask/django server
usual response when i load the page (no button /ajax call done )
Okay. I’ll look into that
you can even use the eel library to make this into an executable
this is the response when i load the page, no button pressed
this is when i have clicked the button, and the html reponse is the picture i have sent
so u see, the response now contains an extra script line ONLY if i have clicked the button
can you explain like the process from when a user accesses the webpage to when the popup appears
i'm trying to make sure i understand the process here
ok:
user loads the web page :
user has clicked teh reject button
ajax post request done as soon as reject button clicked,
oh i see
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
i want to create a seperate one for the client
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
i could but, the js is triggered after a response from the django backend
instead of everything
yes, you could wait on the ajax call to be done
this
nah, this is why i am stuck and just resultedin replacing the whole body 😅
so django loads a new page with that script? is that correct?
yes
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 😂
if it loads a new page, why not just load it with the new/modified data etc?
or is this like an api
this is what im stuck on
at the beginning i replaced ONLY the table
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
bro, this django endpoint, what does it return?
??
what do you mean separate from client?
i want to have two admin panels -- the main one and another for the client.
entire page
new page
this is a new html page from teh AJAX response
so create it like any normal page but restrict it to admins only
so you make an ajax call to the endpoint?
yup
$.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',
})
},
});```
oops, wrong reply here
and it returns html?
yes the variable data is the html
oh ok
$("body").html(data); u see, this replaces the current page BODY with the new htmls data
i thought the button click refreshed the whole thing
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?
then the alert is not received XD
but you can trigger it no?
what do u mean by this ?
what is the best book to learn django?
the django thing just inserts this script
why not conditionally render it, depending on a variable you can change during post etc
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>
youre using jquery
yh
the thing is this doesnt have an id
.
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
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
okl ill try that if this way doesnt work, but just anotyher question, ive managed to add another field in the swal.fire () to include a custom class
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
$(".class_name") i believe
thing is im not really using sweetalert2 directley, im using sweetify
if they had a simple way to just add an id to the script tag -_-
ok. i just realized something
yea?
which script are you using to make the ajax calls
the type ?
in this list
sweetify
sweetify.success(request, 'Application Rejected', icon='success', timer='3000', backdrop="false", customClass ='xClass')
backend django generates that
where is the ajax call coming from exactly?
ajax coming from the webpage when u click teh button
sends teh request to the url, which django forwards to a function
yeah, what script enables that ajax call
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")```
where is this located
bruh
append it to the end
okay
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
the backend does checks first
and depending on the output u get different swal.fires
one many be a sucess alert, one may be reject alert
with different titles..
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
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?
form and ajax post same thing
with the ajax post i need to pass multiple values needed for the backend check
such as these
but the form reloads the page with the new data
so just replaces the body ?
or an actual reload
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">```
yh works, not sure what these errors are tho, maytbe cause its writing to the document again
looks like it
yh. well ill leave it as this for now until i figure out how to select that script
thanks for the help!
Yes that's possible
You should avoid templating script tags
Put your JS in a JS file and load it with <script src="{% static '...' %}" type="module"></script> and avoid inline JS completely
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;
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
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.
!rule 9
even if its gifted? not looking for freelancer but help...
i am struggeling for days now on the project
Best to just ask your question you'll probably get free help
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?
Remember to use ```javascript when pasting code
Uhh wait that's a traceback just ``` will do
or just js instead of javascript
does classList.toggle only apply to the first element it finds?
classList doesn't find elements
I have document.querySelector(".nav-label").classList.toggle("nav-label-hidden");
But it's only changing the first nav-label class
what do the docs for document.querySelector say?
what happened when you tried?
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.
right so do you see the error message?
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?
rn i wanna open in
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
?
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
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
there is querySelectorAll to choose them all
You don't know why what?
i just removed everything that was related to that
then too
rn also it's showing error
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?
Related to what?
..
this
Ok but the permeant redirect is still cached
SECURE_SSL_REDIRECT= True this might be your issue tbh
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).
Hello guys my image not loading in my website in other device
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?
Can you give some more details?
Heroku free tier?
Do you know, can I use Tensorflow there, store photo and view photo?
Yes
Nice
But probably not many
Is it hard to deploy project on Heroku? Can you pls explain process?
You mean many photos?
I see
What would you use instead?
Hmm that's for Django, I need for Flask, or I can use that tutorial?
Or is it anyway also easy to do it with Django?
There are loads of tutorials online for deploying Flask apps on Heroku, here's one that looks good https://realpython.com/flask-by-example-part-1-project-setup/
thanks man, I don't have a lot of time for finding tutorials so I appreciate it
<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?
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
If you can share a link to a repo here requesting feedback, you may get some.
Hi guys , anybody switch front end to react late in development before ?
Backend is django .
Is it comparable to starting from scratch ?
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!
Also fun fact, the parallax background changes based on your system dark theme
I've been rick rolled,
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?
dude, why are you using document.write in react?
that defeats the purpose of react
even though i remove document.write and run this as a function inside {} it is not working
do you understand how react works?
I am new to react
I guess keeping this inside {} runs this as a jsx ?
?
https://stackoverflow.com/a/70318833/16668992 I was trying to implement this answer in reactjs app
What should i need to change to make it work in react?
Is there any way around the solution?
I have little knowledge. I have been working on it from past 1 week building a website
ok, what are you trying to do?
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.
this is a 1d array though
no after using map function it converted into 1 d array
can you send a sample of the data, if you dont mind
is this your question on stackoverflow?
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:
yes you can see the stack over flow question I have share above
This is real nice man
I have some conflicting css I’m working around - materialize and materialize md .
You reckon tailwind is better to switch to ?
I can see you listed it in your stack
https://codesandbox.io/s/naughty-shannon-tmmc1?file=/src/App.js no styling but this might work
gigles
indeed. it is like having paid for the bus ride
but instead of being in the bus, you run along with it
which is better flask django
question you should be asking is which is better to use for my project
Hey can anyone send me any video recommendation or blog on how to clone a django project from github?
Yeah I know the git commands you can directly jump on to setting up the virtual enviornment part
I am trying to make a simple portfolio
right, so you know exactly what this portfolio needs right?
yes
so you can make a decision on whether to use flask or django
which one u use
i'm a flask guy
but i'm not saying it's better than django
i just prefer to use flask
Thank you so much.
ok I wanted to use flask in the first place because look nicer to me thx
https://github.com/NotSoYeezy/django-NoteShare
It probably is bad, because it is my first django project but I hope to here some feedback :))
how do i create a serializer for custom user models ? can someone point me to docs ??
I absolutely love tailwind! I would recommend it to at least try for most people!
hey i get the error:
git: The name git was not recognized as the name of a cmdlet
do u know how to fix that?
install git
should be fine right?
it's not an npm module
https://git-scm.com/ here
do I have to pay attention to something during the installation?
not really, just install and select the recommended options
ok installed but same error again
use git bash
always the same
use the git bash terminal!
how do i use it? 😅
how did you open powershell?
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
Welp, just found it LOL. For reference: https://pytest-django.readthedocs.io/en/latest/faq.html#how-can-i-give-database-access-to-all-my-tests-without-the-django-db-marker 🤦🏾♂️
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]```
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
is not even related to web development at all, better to speak about it in one of off-topic channels #ot0-fear-of-python, #ot1-this-regex-is-impossible , #ot2-the-original-pubsta
Sorry
I think I’ll definitely give it a go , I’ll get work to pay for it . It’s one off right ? 🤣
It’s actually free!
What really ? What’s the one time charge option then ? I’ll look into it tonight !
I’m not sure what you mean, at https://tailwindcss.com ?
You can also try it out at https://play.tailwindcss.com kind of like code pen but no account needed
I think i was on something else lol
is there any practice project for django channels?
Yeah tailwindui is nice too I’ve heard, but it’s pre built components using tailwind. They look great imo but they aren’t tailwind 🙂
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
might be a flask version error
im using venv
i thought venv was supposed to use the same version between environments
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
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
you can simply solve this by just using app.route instead of app.get
or you can upgrade the versions i guess
yeah rip will do
wanted to reuse urls with different responses dependant on the request typoe but i guess that isnt happening
you can do that
here's an example
same route, different methods
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
Yes
help me pls
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 👍
@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
i dont get this
why is it returning a function called increment
but the kinda shorthand function is assigned to the constant increment
Thank you!!
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.
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)
In my forms.py
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
Also in my forms.py
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
My models.py -
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
And in my console, it logs that 'User provided ivalid data'
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?
This - Did you create the form from scratch or form as p?
In html
What’s past month field in your form ? Why not use date Input ?
I didn't use form as p
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 %}
No w3school is really bad
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
I eventually discovered what the issue was. It was my description and not the datefield that was the issue
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
I was literally going to suggest it was your clean data , but I thought it was wiping it completely . Glad you sorted it man
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 🤔
You can use recaptcha or verify the emails
there's a select tag i believe
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)
Hello everyone
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
use js probably
some elem in the navbar can store the data
give that elem an unique id
and access it using js
document.getElementById()
can one send me link for python + django free hosting
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
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
Guys is it fine to just use the session module and not the login manager in flask, when implementing the Login/Registration feature?
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
how would i do a local post request?
i got that fixed but
i also need help sendign a request from my public site to a local site on the server
Should I learn django or flask first?
hey there. for front-end is it necessary to learn bootstrap and Sass or directly learn frameworks?
bootstrap is not necessary. it is just a crutch for people who are lazy to learn CSS
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
ok so first Sass and then frameworks?
@haughty isle hi sorry to ping but im a bit confused about something u told me yesterday, wondering if ur still here to help ?
I would say, learn CSS first, then you are free to dive into framework at the same time with SASS
because.... frameworks have installed SASS out of the box usually
it is just easier to launch it there
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
ok thanks which framework would u recommend btw?
React or Vue.js 😉
I chose Vue.js and like my choice very much
there is a third choice Angular, but I am not sure about it
React is more in demand, but Vue.js is just in general nice
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
What happened when you tried?
thanks for the help
is the variable called { currentClub} that i will use ?
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>
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
ok
Frontend is just tertiary direction for me, that's why I prefered nicer but less in demand framework
You should learn it, but highly likely you aren't ever going to use it at job unless as a crutch
General javascript knowledge is still required being known for more efficient use of framework anyway
alright
also this is the js file
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',
})
},
});
}```
Jquery is just vanilla on steroids ;b
Frontend framework replaces Jquery. Not really need to learn it
anyone know any good sources for handling account management with flask?
It's a constant
You need to use const { postUrl, path } = document.getElementById("navbar-js").dataset;
alright. however im getting another problem 😭
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>```
Is it possible to use custom url dispatcher with DRF action decorator?
E.g:
@action(url="/some_action/<foo_id:int>")
def some_action:
don't use onclick= it's unsafe inline js
instead give the element you want to listen to a class:
<button class="dropdown-item remove-all-messages" type="button">Mark as all Read</button>
yh tried this as well but unfornatley it does nothing
ah so it would have to be within a <script>
ah okay
tysm, it works :)
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>```
note: this does not pass the right applicant-id , {{ user.id }} is not within the button so this wont work, it will just pass the id of the client, within my table, every single row has a different id (for different members)
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));```
How did you call the function when it was inline js?
sorry i thought i sent it
<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>```
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
ah i also forgot to mention, so u see the buttons
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
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.
Yes well you ought to be able to access the primary key of the object you are iterating over?
thing is this is outside the table
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
You don't pass variables when loading the script from a file, that only makes it available to the html
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' )
The call to the JS function (with the onclick) would be the same whether loaded from a file or from inline JS
funx x (y){
runtheexternaljsfile(y)
}```
yh exactly, this is what im stuck on and just defeats the purpouse of me trying to make my code more structured
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.
im not sure ifu understand the issue, {{ user.id }} in the js script would load it only once, and it would have the value of the CLIENT (so id = 1 for example )
as here
this is my html stctructure
<html>
<head>
<body>
table is within here
</body>
<script> INSIDE HERE
</head>
</html>```
Your structure ought to be:
<html>
<head>
</head>
<body>
<table></table>
<script>
</body>
</html>
ah yh it is like that, idk what my head was doing writing the structure above 😂
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
have you tried going back to this?
thats for inline js
u cant call the changeListner () function if u have moved it to an external js file
or can u ?
have you tried?
yes, changeListner is not defined
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 }}' ...>
ah okay thanks
Wrong. @fierce grail
<!DOCTYPE html>
<html>
<head>
<title>blabla</title>
<meta charset="utf-8">
</head>
<body>
</body>
</html>
That is how looking correct template
Don't miss Doctype word
In order to be Html 5
Email verifications aren't hard to bot and I don't want to use 3rd party services
If you're using flask, you can use Flask-WTF (an extension) and get a recaptcha field without 3rd party services
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
ok
It depends on what you want/need
simple website
a menu with sublinks, forms and evtl. login area
Flask should be enough for a simple website and it also has an easier learning curve
so e.g as sublink a welcome page, an about us page etc
ok thx
@unkempt dome I started with flask and moved to django for the last project .
I prefer how django projects are organised a lot more
@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 🤣
Migrations are tough at first but worth it once you figure it out. I can't imagine a life without the ORM now.
even after reading this https://www.geeksforgeeks.org/difference-between-terminal-console-shell-and-command-line/, i don't rly get what's the difference between a terminal, command line and shell?
What’s even tougher is not migrating for a long time and changing the database without djangos permission and then not being able to migrate 🤣
Infrastructure as a code. That what makes it a life change.
Defining database structure as a code. Changing infrastructure control versioned as a code
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??
Asynchronous programming + Chat = using Web sockets technology
honestly i hate web sockets, its just something about me eughghghhghghghghghgh thats why i continuously try to steer clear of them
I would recommend Django Channels, as it is ready out of the box solution for that
is there like a template I can work off/look at ^^
Flask is too fresh in async to have smth for that, better to apply Django or to find solutions in FastAPI as alternative
in its docs, yes
found it
and i suppose i should switch out the database system the tutorial uses for firebase
??
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.)