#web-development

2 messages · Page 49 of 1

earnest oak
#

not to derail BootsForCats' question but

#

do you have experience with AWS?

twilit drum
#

Not yet, why?

#

I'm using gdrive for resume, but tbh, embedding looks somewhat unprofessional. Someone suggested I just put everything in static folder, but I'm not sure if it's a good idea

native root
#

static folder is probably best imo

#

unless you want to code in download functionality

#

regardless, download or not some browsers are just going to render them as full page pdfs like they were static anyway

rigid laurel
#

You could use PdfToJS to render PDFs in the webpage if you liked

#

or just an iframe

#

embedding pdfs with an iframe is pretty easy

#

but you're still gonna end up storing them somewhere that is essentially the static folder

earnest oak
#

no worries

coral sorrel
#

@sonic moat we don't allow for recruitment in the server, sorry

sonic moat
#

I see, sorry about that

native tide
#

HI y'all
somehow my simple app that i just created does not seem to accept POST parameters
the logs display a weird format:
127.0.0.1 - - [24/Mar/2020 20:36:09] "POST /signup HTTP/1.1" 200 -
127.0.0.1 - - [24/Mar/2020 20:36:09] "GET /favicon.ico HTTP/1.1" 200 -
this has never happened to me. Everything is basically default flask
my code can be seen here:
https://www.reddit.com/r/flask/comments/fobrpx/get_and_post_methods_do_not_work_the_logs_display/
Any idea what is wrong?

coral sorrel
#

no probs @sonic moat, i see you're new. thanks for understanding!

proper hinge
#

@native tide Those look like ANSI escape codes for colours

#

Your terminal probably doesn't support them so it just displays them as plain text

#

It doesn't mean there's anything wrong with your flask code.

native tide
#

weird... but my route does not return "success" like it should after a POST

sonic moat
#

No worries.. I will post my question here. If one of you guys can help me I would greatly appreciate it.

import os
from flask import Flask, jsonify, request
from flask_pymongo import PyMongo

app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://localhost:27017/enforceDB"
mongo = PyMongo(app)
db = mongo.db

@app.route("/")
def index():
    return "Hello"

@app.route('/new', methods=['POST'])
def createTodo():
    data = request.get_json(force=True)
    item = {
        'todo': data['todo']
    }
    db.enforceDB.insert_one(item)

    return jsonify(
        status=True,
        message='To-do saved successfully!'
    ), 201

if __name__ == "__main__":
    ENVIRONMENT_DEBUG = os.environ.get("APP_DEBUG", True)
    ENVIRONMENT_PORT = os.environ.get("APP_PORT", 5000)
    app.run(host='0.0.0.0', port=ENVIRONMENT_PORT, debug=ENVIRONMENT_DEBUG)

I am not sure how the collections are created? And how would I go about creating a realEstate document with the schema name, address, etc

tired root
#

you should check if the request is actually a post

#

if request.method == 'POST':

sonic moat
#

yeah I am sending a post request and I am able to check that the JSON is correct

tired root
#

And what do you mean by collection?

sonic moat
#

if I do return data for example

tired root
#

It is just a list with db results, no?

sonic moat
#

a collection in mongoDB

#

a collection is a table

tired root
#

Then select the data from the table

#

I am not familiar with mongo, tbh, but it is just a db

#

and if you need data from the db, you gotta select it

#

maybe better suited for #databases, since this isn't really a flask issue

vagrant adder
#

@earnest oak no sorry, haven't had a chance to mess with aws

sonic moat
#

thanks, I am going to post the question there

kindred glacier
#

Do you guys know how I can return all data on my database with flask?

#

my code

#
@app.route("/viewdatabase")
def viewdatabase():
    db = db_get()
    cur = db.execute("SELECT * FROM user")
    row = cur.fetchall()

    return row```
#

I can return one item from database like this

#

return row[0]["name"]

#

but I want to return all

tired root
#

return row is correct

#

you need to walk the iterable though to display them

#

otherwise not sure what you are asking

#

SELECT * on that table is really a bad idea though

kindred glacier
#

Do I need to use a for loop?

tired root
#

yes

#
    print(each["name"])```
kindred glacier
#

I'm a flask beginner. Can I return for loop?

tired root
#

You can't return a for loop

#

flask or not

#

What are do you want to do here?

#

I suppose you want to display all users in the backend to an admin or something?

kindred glacier
#

return all the rows in my sqlite database

tired root
#

why?

kindred glacier
#

I'm learning flask

#

and sqlite

tired root
#

But there must be a reason you want all data

nimble epoch
#

Come on man🤪🤣

#

Are you bullying?

tired root
#

What?

#

Databases aren't meant to just pull all data from it, they are meant to build sensible queries

#

The issue with this query here is, that it would presumably pull all (hopefully) hashed passwords into memory

nimble epoch
#

Yeah yeah

tired root
#

And displaying them to anyone, even an admin, is a bad idea

#

So I am trying to teach this guy how to maybe achieve what he wants, but the better way

#

How the FLYING FUCK is that bullying?

kindred glacier
#

no its cool

tired root
#

but alright I go to bed

#

too late for this kind of discussion

nimble epoch
#

Yeah you look tired

kindred glacier
#

sweet dreams 💋

native root
#

You can return a for loop

#

Use ‘yield’

fallow warren
#

im new to web dev and i have written a project in python. im creating a webpage n html and css. how do i link the python file to the webpage

#

?

nimble epoch
#

What framework you are using?

fallow warren
#

im not sure

#

how do i chedck

nimble epoch
#

Flask or Django

fallow warren
#

i wrote the python program in the python shell and the html script on notepad ++\

nimble epoch
#

You can install flask using “pip install flask” if you already have python isntalled

fallow warren
#

after that what do i do

nimble epoch
#

pip install flask

#

Create a folder

#

Then a file like ***.py

fallow warren
#

already have that

#

how do i link it to the webpage

nimble epoch
#

And visit flaskproject website😁👍

fallow warren
#

lool

#

anyway thx for the help

nimble epoch
#

I can help more but if you want learn it probably you should learn it yaself

fallow warren
#

no i already have a folder withthe python file and .html file

#

how do i link the python file to the .html one so it runs on the webpage i created

lavish prismBOT
#

Hey @nimble epoch!

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

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

#

Hey @nimble epoch!

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

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

nimble epoch
#

The templates gotta be in a folder called templates

#

Need more help?

#

Try this book

kindred glacier
#

How do I return a for loop in flask?

nimble epoch
#

For newVar in var:
print(newVar)

#

Why dont you use flask_sqlalchemy?

kindred glacier
#

I'm using sqlite right now

nimble epoch
#

Ohh ok

kindred glacier
#

ahhhh

nimble epoch
#

Ooh dont look happy

kindred glacier
#

@app.route("/viewdatabase")

    db = db_get()
    cur = db.execute("SELECT * FROM user")
    row = cur.fetchall()
    for i in row:
        print(i.row)```
nimble epoch
#

Okk?

kindred glacier
#

what do I return?

#

TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
Traceback (most recent call last)""

nimble epoch
#

return the last line not print

#

did you know that everything after return wont be printed?

kindred glacier
#

no

nimble epoch
#

Ok can you send your whole file maybe i can fix it?

#

when you return stg everything after return wont be printed

#

Wodd say something can you help? Dont stand behind

kindred glacier
#
def viewdatabase():
    db = db_get()
    cur = db.execute("SELECT * FROM user")
    row = cur.fetchall()
    for i in row:
        return i["name"]```
#

it only prints the first row but why

#

I have 2 names in my name column

nimble epoch
#

I think that’s because of return but you cant use print in flask if you want to show data in the webpage

#

Ok wait a minute

#

Ok ok

#

Try: for i in db.execute(“select...”):
return i[“name”]

#

Worked?

kindred glacier
#

ok I'll try now

nimble epoch
#

But no difference

#

Ok im going to try too

kindred glacier
#

like this ?

#
def viewdatabase():
    db = db_get()
    cur = db.execute("SELECT * FROM user")
    row = cur.fetchall()
   for i in db.execute("SELECT * FROM user"):
       return i["name"]```
nimble epoch
#

Yeah but i dont think that the row variable and the line above is needed

kindred glacier
#

I don't think it'll work

nimble epoch
#

Ok im trying

native tide
#

Hi all, I have a question. Would only knowing Python be enough for the entire backend development field?

nimble epoch
#

Nope

#

Ok @kindred glacier i found something

#

You can use templates

#

No need to return data list

#

If it helps

#

?

quasi ridge
#

@native tide nah, you'd have to know a bit about your OS (likely Linux), your deployment system, your storage system (a database probably)

kindred glacier
#

@nimble epoch

#

I'm here

#

left to get something to eat

#

thanks I'll try it

nimble epoch
#

ok

kindred glacier
#

I'll give you an update

nimble epoch
#

I think it wasnt that necessary

#

Was it?

#

😄

kindred glacier
#

what was not necessary?

nimble epoch
#

Ya question

#

Flask sqlite3

kindred glacier
#

ok

nimble epoch
#

Try: use that row variable in the template

kindred glacier
#

@nimble epoch it worked 🙂

nimble epoch
#

Ooo

#

How?

kindred glacier
#

I took your solution

#

added for loop in html file

nimble epoch
#

👌🏿

kindred glacier
#

❤️

nimble epoch
#

😊

cloud condor
#

Hi. Is there a standard/preferred way to handle switching between data layouts? For example, between a table view and a grid view? I'm tempted to simple hide one and use an onclick function to (un)hide.

mighty herald
#

Hey I'm a new flask developer. Every time I submit my form the data does not get posted. I've been trying to find the solution to this for the last 3 days lol hope someone can help out! I attatched images of schedule.html, forms.py that has wtforms and my app.py. Cheers and thankyou!

quasi ridge
#

@mighty herald are you submitting via a web browser?

mighty herald
#

yes in localhost 5000

quasi ridge
#

turn on the browser's developer tools, and watch the network traffic

#

you should see the request, its headers and body, and the response

mighty herald
#

okay ill check that out

quasi ridge
#

if that all looks ok, then look in your server's logs

mighty herald
#

@quasi ridge any idea?

quasi ridge
#

lemme see

#

can't tell, you need to click on the little rows on the right side to see them expanded

mighty herald
quasi ridge
#

hm no

#

click on the thing under "name"

#

oops that's not it

mighty herald
quasi ridge
#

yeah

#

that

#

ok, that's a GET so that's not the one you want

#

maybe it's the first one

mighty herald
#

so its an issue in my routing page?

quasi ridge
#

no idea

mighty herald
#

damn i need to change that to post somehow do you have a clue

#

anyways thanks for your help!

quasi ridge
#

I wonder if your form isn't quite right

#

it needs a button, I think, with an "action" attribute

mighty herald
#

i added an action for the button to the same page and the data still didn't post

quasi ridge
#

you might hack on the html locally, and keep reloading it in the browser; probably faster than doing it on your server

mighty herald
#

yes thats what im doing

quasi ridge
#

I have exactly one web site, and it turns out it doesn't use forms 😦 Otherwise I'd show you how I did it

mighty herald
#

haha i appreciate your help anyways! maybe someone will see this later and know how to do it, thank you though

upper pawn
#

Is a rest api w flask considered development

#

Web

quasi ridge
#

yep

weary arrow
#

also your route already redirects to schedule when it validates, so in your html you can just <form method="POST" action="">

native tide
#

I am doing a challenge right now in JavaScript

#

i need to use the .reduce method to return the amount of times a specific item in that array occurs.

#

exmple: js numbers = [1,2,3,1,2,3,3]; numbers.reduce(???, 3); //should return 3

#

without the reduce it's easy:js function countOccurencies(array, item) { let occurence = 0; for (i of array) { if (i === item) { occurence++; } } return occurence; }

#

but the creator of the course wants us to do it with the reduce method

#

and that's hard

#

i am now thinking if it's even possible

#

so i am asking: is it possible?

#

that's all i want to know cuz i would like to solve it all by myself

rustic pebble
#

sec

native tide
#

cuz if it is possible, i can and i will solve it.

rustic pebble
#
let nums = [1,2,3,1,2,3,3];
const map = nums.reduce((acc, e) => acc.set(e, (acc.get(e) || 0) + 1), new Map());
console.log([...map.values()])
#

this should work

#

@native tide

#

acc is accumulator

#

the reduce function takes 4 args, acc: accumulator, cur: current value, idx: current index, src: source array

#

According to developer.mozilla.org this is the syntax you should follow:

arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])
#

callback Is a function that should get executed for each element in the array

#

Accumulate just gets the latest element before the callback

#

currentValue is self defined

#

index is the index of the current element

#

initial value is the starter value upon the first callback

#

array is the array on which the reduce was called

native tide
#

oh

#

let me collect this

rustic pebble
#

😄

native tide
#

exected

#

i saw that lol

rustic pebble
#

Haha

#

Btw did it work?

native tide
#

no

rustic pebble
#

wdym?

native tide
#

what do the get and set methods do

rustic pebble
#

Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection.

#

the get is a method of map that returns a specified element from the map object

native tide
#

i got this error: index.js:18 Uncaught SyntaxError: Identifier 'numbers' has already been declared

#

from this

rustic pebble
#

well you have predeclared numbers somewhere

#

can I see index.js?

native tide
#
const map = numbers.reduce((acc, e) => acc.set(e, (acc.get(e) || 0) + 1), new Map());
console.log([...map.values()])```
rustic pebble
#

u are getting the error on line 18

#

what where the rest

#

try this:

native tide
#

this is the whole thing

#
const numbers = [1, 2, 1, 3, 4, 5, 1, 5, 5, 5];

/* WITHOUT reduce method
function countOccurencies(array, item) {
    let occurence = 0;
    for (i of array) {
        if (i === item) {
            occurence++;
        }
    }
    return occurence;
}

console.log(countOccurencies(numbers, 5));*/

/*WITH reduce method */

let numbers = [1, 2, 3, 1, 2, 3, 3];
const map = numbers.reduce((acc, e) => acc.set(e, (acc.get(e) || 0) + 1), new Map());
console.log([...map.values()])```
rustic pebble
#

you are setting numbers twice

#

one is const so it cant get changed

#

delete the const numbers = [1, 2, 1, 3, 4, 5, 1, 5, 5, 5];

native tide
#

so i deleted that

rustic pebble
#

You are trying to mutate an immutable reference

native tide
#

yeah my bad😅

rustic pebble
#

😄

#

It worked?

native tide
#

and i got this

#

[2, 2, 3]

#

not what i was expecting

rustic pebble
#

these are the occurences for each element

#

what where you expecting?

native tide
#

one element

rustic pebble
#

which one?

native tide
#

one you need to pass as the second argument

#

like this

#
const numbers = [1, 2, 3, 6, 5, 5];
function countOccurencies(array, item) {
    let occurence = 0;
    for (i of array) {
        if (i === item) {
            occurence++;
        }
    }
    return occurence;
}

console.log(countOccurencies(numbers, 5))```
#

the output is: 2

rustic pebble
#

well you can just take the index

native tide
#

of?

#

so basically the same functionality

rustic pebble
#

hmm

native tide
#

but only a reduce method

rustic pebble
#

reduce is not that easy to do tbh

native tide
#

that's the problem i've been dealing with

rustic pebble
#

you need to make a small if

native tide
#

i've tried that

#

i went slowly towards messing things up

#

then deleted all code again

#

and i don't want to go back to the video to get the solution

#

I'd like to solve it myself

rustic pebble
#

So basically what you want to do is this:

#
//say you have got the array with the elements earlier
let target_element = prompt('Enter the number you want');
let elements = [...map.keys()];
let values = [...map.values()];
let index = 0;
for (element in elements){
  if (element == parseInt(target_element){
      console.log(values[index]);
  }
  index += 1;
};
#

you can optimize that

#

but its the essence I think

native tide
#

so that returns a number?

#

no it doesn't nvm

#

what do you need the values for?

#

nvm

#

i didn't know parseInt was a thing

rustic pebble
#

Did you get what you want?

#

I fast typed it

#

not sure if its correct

mighty herald
#

thank you @weary arrow i didnt catch that!

#

Anyone have an idea why im getting a 404 not found after submitting a wtform?

mighty pulsar
#

Okay this is a really specific niche question but I need some advice. I'm trying to host my flask app with a digital ocean droplet. Since it needs to access mysql, I used their "one-click" application which comes preinstalled with mysql, phpmyadmin AND apache2. I've looked around but I can't see how I can host my python3 application with apache2, all of the things I've read discuss python2. Should I disable apache 2 and then get something like nginx with gunicorn or what should I do? I really inexperienced when it comes to hosting with a server

rustic pebble
#

@mighty pulsar nginx with gunicorn is perfect

#

try that

mighty pulsar
#

So when I go to my ip at port 80 it shows the directory for var/www/html and then has apache 2 at the bottom, but I feel like apache2 is only installed to support phpmyadmin so how could I change it so that I'm using nginx along with gunicorn on port 80 and not apache?

#

@rustic pebble

nimble epoch
#

@mighty herald is your schedule.html in templates file? If it is try redirect(url_for(“schedule”)) once

mighty herald
#

@nimble epoch

nimble epoch
#

Im Right here

mighty herald
#

i have one of these divs for each day of the week

nimble epoch
#

First use redirect(url_for(“schedule”))

#

Worked?

mighty herald
#

(request.url) worked

nimble epoch
#

Ok but try redirect url_for once

#

Well check other things later

mighty herald
#

but now im having issues with the jinja syntax. Okay ill try that now

#

its giving me an error saying day is not defined

#

after using (url_for(“schedule”))

nimble epoch
#

probably its looking for day variable in render_template

#

Yeah i think thats right there is no day variable in your code

mighty herald
#

theres day in my forms.py file and session['day'] = form.day.data in my app.py file

nimble epoch
#

Ok use session[“day”] or form.day.data

#

You have not assigned it to any variable

mighty herald
nimble epoch
#

Ok wait ill try

mighty herald
#

thanks

#

i just deleted made my code for the div of tuesday and the page loaded. it worked

#

although the data is now posting to both

nimble epoch
#

Ohh😃

mighty herald
#

Yeah 🙂 I'm trying to post the monday data in one div and the other days of the week data in their corresponding containers. Do you know how I can do that? I tried with an if statement in jinja but it was giving me that error

nimble epoch
#

Use for loop

#

You want like this?
Monday
2
3
....

#

Can see your files

#

Maybe it can help

mighty herald
#

you want me to send you the github repository?

nimble epoch
#

No just a kind of screenshot

mighty herald
#

okay got you

nimble epoch
#

No you gotta use for loop for these

mighty herald
#

ive been searching all over google to know how to do it the way i want. Do you have any pointers for the for loop?

nimble epoch
#

for newvar for var:
newvar

mighty herald
#

so using jinja {% for days for day %}

nimble epoch
#

Yeah

mighty herald
#

how do i make it so that if the user selects monday it goes to that container?

nimble epoch
#

Just dont forget endfor

#

What

#

Ok

#

Wait

#

I think i didnt get you

#

You want the whole data or you want sth like if condition to do sth else by different inputs

mighty herald
#

right now just the whole data

nimble epoch
#

For loop

mighty herald
#

well i was thinking if statement because if day == monday post data here.. type of thing

#

but im not sure how to make the for loop in jinja im fairly new to flask

nimble epoch
#

Ok you gotta use if
You can use if in for loop

#

Okk which one you want to do

#

?

#

You said you want whole data

mighty herald
#

right now just for monday but ill use that and change the day variables for the other container

nimble epoch
#

Can you type an example

#

Im confused

fossil swift
#

why is it 'Monday', 'Moday' or is that a typo

mighty herald
#

@fossil swift whoops that was a typo

fossil swift
#
{% for x in list %}
  {% if x == 'something' %}
    <p>{{ x }}</p>
  {% else %}
    <p>eek</p>
  {% endif %}
{% endfor %}
#

Thats a for loop in Jinja2

mighty herald
#

ohh nice let me try that out

fossil swift
#

Is there anyway to find the height of an image either using jinja2, html, css, or js? I'm trying to make my images load smoothly without affecting the divs around it.

nimble epoch
#

I think if you open the picture you will see the height and width under

#

Of course in some text editors like sublime or atom

fossil swift
#

I'm loading it from a database and from files, it's not hard coded.

#

I'm trying to do it within the code

nimble epoch
#

That a file?

#

Ohh

fossil swift
#

?

nimble epoch
#

Not sure but some libraries like pillow ...

#

Maybe they help

#

I just searched

#

I think you can use pillow

#

Try: image = PIL.Image.open("sample.png")
image to open
width, height = image.size
extract width and height from output tuple
print(width, height)

mighty herald
nimble epoch
#

Did you assign your list to the infos

#

Like database.query.all()

mighty herald
#

infos?

nimble epoch
#

Yeah

mighty herald
#

how do i do that?

nimble epoch
#

Is that list assigned to anything?

mighty herald
#

no i just used the for loop that harry sent and tried changing it

nimble epoch
#

🤣

#

Come on man

mighty herald
#

Haha give me a break im a beginner loll

nimble epoch
#

Sorry

#

What is your html file name

mighty herald
#

schedule.html

nimble epoch
#

No the file that shows the data

#

Not form

mighty herald
#

its the same file

nimble epoch
#

Im a little tired

#

Im fucked in the head

mighty herald
#

no worries man your good

nimble epoch
#

Do you have database

#

Created?

mighty herald
#

not yet

nimble epoch
#

I think database should be created first

#

I myself create database before templates

#

Come on man i am wrong again

#

F

mighty herald
#

i see. Is there a way to do it with out a database just to see how it works then make it with one afterwords?

nimble epoch
#

Yeah i said im wrong

#

Dummy data if im right

#

Using list and objects

#

list = [
{
“Day”: “sth”,
“Event”: “sth”
},

{
“Day”: “sth”,
“Event”: “sth”
},
]
for i in list:
if i == “sth”:
return
else:
return

#

for i in list:
if i.Day == “”:
return
else:
return

mighty herald
#

okay cool will this code go above my schedule route in my app.py file?

nimble epoch
#

The list and objects in app.py and for and if in template (jinja2)

mighty herald
#

Nice! okay ill try it out

fossil thicket
#

when working on a server - and needing to sync some files from google storage, is it best to

  • sync the files to a local directory
  • move the local dir to var/www (or wherever)

or to try and sync directly to var/www

because when I try the latter I get

sudo: gsutil: command not found
nimble epoch
#

Not sure but i dont think that its related because it is saying that the command is not found

fossil thicket
#

@nimble epoch the command works for the use

#

*user, but not for sudo

nimble epoch
#

I dont know man

fossil thicket
#

well don't answer then i guess

nimble epoch
#

Search for it

mighty herald
fossil thicket
#

@nimble epoch i have searched, if you don't know that's fine, i posted here because i wasn't sure tho

nimble epoch
#

Can i see you app file

mighty herald
nimble epoch
#

DID YOU ASSIGN LIST TO LIST IN THE RENDER_TEMPLATE

#

Right after if

mighty herald
#

no sir i did not

nimble epoch
#

Do it sir

mighty herald
#

so do list = list?

nimble epoch
#

Yeah after where your form=form

mighty herald
#

just did that. still no posted data

nimble epoch
#

Did you know that its just going to show you the data not posting data

#

?

mighty herald
#

the data that i type in right?

nimble epoch
#

Yeah

mighty herald
#

that would make my day

nimble epoch
#

Whatt wait

#

What is that day: sth after day:sth

#

Man are you good?

#

👍?

mighty herald
#

thats what you did!!!

nimble epoch
#

Sorry sorry

#

🤤

#

I thought the event is day

mighty herald
#

event is for the text area for the schedule post

nimble epoch
#

It show any error?

mighty herald
#

and day is day of week

#

no no error just no posted data in the container

nimble epoch
#

That’s because of you if statement

#

Try:
{% for i in list %}
{% if i.day == “sth” %}
<p>Sth</p>
{% else %}
<p>Sth</p>
{% endif %}
{% endfor %}

mighty herald
nimble epoch
#

Can i see the template again

mighty herald
nimble epoch
#

<p>i.day</p>
<p>i.event</p>

#

It prints two sth because your day and your event are equal to sth

mighty herald
#

you mean {{ i.day }} ?

nimble epoch
#

Yeah

mighty herald
#

still posted sth

nimble epoch
#

Because your day:sth and your event:sth check the dummy data that youve created in the app.py

mighty herald
#

okay its working by posting dummy data but how can it post the data i entered in the form?

nimble epoch
#

Here you should create a database

#

Use sqlalchemy

#

Flask_sqlalchemy

mighty herald
#

perfect! i just wanted to make sure i had a functioning form before i moved on to create the db but wow man i appreciate your time. Real helpful

nimble epoch
#

Yourewelcome

fallow warren
#

so to display a python program i need to use either flsk or django right?

jagged lark
#

If you want to make a program interface accessible from the web, you have to use a web framework, such as flask or django yep

fallow warren
#

and then how do i display it on html

plucky current
#
<input ng-keyup="$event.keyCode === $ctrl.keyCodes.enter &amp;&amp; $ctrl.getMember($ctrl.keyword)" ng-model="$ctrl.keyword" class="form-control input-field ng-valid ng-valid-maxlength ng-dirty ng-valid-parse ng-touched ng-not-empty" type="text" placeholder="Search Members" maxlength="120">
#

how do i get the element of this searchbar?

#

i've tried everything xpath, class name

#

and nothing works

nimble epoch
#

In the flask project that you have created create a templates folder and put the html files in it then you create routes to access the created html pages

tired root
#

Routes don't have anything to do with templates per se, what @fallow warren needs to do is to import render_template and return that from a route with the template required as a parameter and pass the wanted values to that template via that function.

nimble epoch
#

Ye i meant it

native tide
#

CORSonavirus

fallow warren
#

wait can someone explain how to convert the python file into one using django or flask

#

im kinda confused cuz im new to this stuff

nimble epoch
#

Download django or flask using pip and and import it

fallow warren
#

ok ill try that thx

shell garden
#

print("Hello Guys")

vagrant adder
#

hello knickles

#

how's it going

shell garden
#

good you ?

vagrant adder
#

eh, browsing through some express.js docs :p

maiden juniper
#

Noob here. When would be a good example of when to use Django and when to use flask? I've only used django...but i've heard flask is more "lightweight" but not really sure what they mean by that.

native tide
#

I recently learned both. My opinion is that Django is good if you are making a full featured news/magazine/blog site. But if you are building something different than that, a big part of the Django dev process is finding the classes you need to inherit to write a new class over them. It's massive. It has... everything. But sometimes modifying that stuff is more of a pain in the ass than just writing it from the bottom.

In Flask you have to do most things yourself. For example, it doesnt encrypt passwords for you. It doesnt have built in user class for you. You have to do more of it. But sometimes thats easier than knowing everything about Django that you need to know to edit that stuff if you want it to work differently.

#

So, TLDR: Django is great if you are making a very traditional site. But if you plan to edit a lot of things, you might prefer just doing Flask.

vagrant adder
#

flask is like buying an old car

#

you can definitely get it up and running like it was once, but it will take time and will

#

and django is like buying golf 7 lol

#

you buy it, you drive it, you enjoy it

#

django is more corporate-aimed

#

and flask is "i want to do it my way"

rigid laurel
#

Flask is much better if you're trying to do something non-standard. If you're doing a basic CRUD style web app, where you're just storing, manipulating, and presenting data from a database, Django comes with everything you need out of the box

#

But Flask comes only with the basics, then you have to hanle everything beyond the actual web bit yourself

#

For the most part thats just an ORM

sharp veldt
#

@maiden juniper If you're new to web development, Django will hold your hands more and possibly be more educationally beneficial at your level, both in terms of documentation and the general scaffolding it provides that show you various elements and web application concepts you should become familiar with. Once you get more experience would be a good time to look into Flask if you feel that Django seems a little to heavy for some simpler need.

native tide
#

I think that overall I learned more about backend from Flask because it didn't do so much for me. Django made come out of the whole process feeling like, "Well thats cool. There's no way I could have done this on my own though."

#

The docs for Django are much better though, that is for sure.

#

What I learned from Django is how I should organize my big projects in the future.

cloud dock
#

Should I post here my beginner's question for Django or in #help channels? Nobody is answering me 😦

#

not exclusively related to Django, but how do you know you're writing an acceptable code without peer review? I mean my Django code is working, but I'm pretty sure I did very bad coding, but how can I be sure of that?

rigid laurel
#

Its quite difficult to know. The way you get there is with lots of practice, both of reading and writing code; but thats difficult to get on your own. Working with others on some random open source project is very useful

cloud dock
#

Yeah.. I should get some Python buddies

#

I should have gone to Computer Science.. damn Civil engineering

rigid laurel
#

You can still reasonably get a software dev job after graduating

cloud dock
#

Going back to my original question: should I paste my code here?

rigid laurel
#

Yeah, thats probably fine/a good idea

cloud dock
#

I graduated 6y ago, I'm thinking every year to switch my career to dev but I've got a decent position ATM. I'd love to dedicate my day to programming

rigid laurel
#

oh yeah

#

that is harder

cloud dock
#
    """Basic / render
    """
    latest_todo_list = Todoitem.objects.order_by('todo_duedate')[:20]
    context = {
        'latest_todo_list': latest_todo_list,
    }
    return render(request, 'todo/index.html', context)


def add(request):
    new = Todoitem()
    new.todo_text = request.POST['new']
    new.save()
    return HttpResponseRedirect('../todo/')``` 

Is there anything wrong with this code? Like SQL injection on the POST? or the hardcoded url in the HttpResponseRedirect()
#

I read that Django is SQL injection proof but we never know

#

@rigid laurel why would it be harder? age?

rigid laurel
#

Because you're already probably invested in your current job. The switch requires more of a life investment it seems to me

cloud dock
cloud dock
#

@rigid laurel any comment regarding my code?

rigid laurel
#

I haven't used Django enough to give any meaningful comment. All I can say is that your docstring isn't perfect

native tide
#

It's not SQL Injection proof

#
Django’s querysets are protected from SQL injection since their queries are constructed using query parameterization. A query’s SQL code is defined separately from the query’s parameters. Since parameters may be user-provided and therefore unsafe, they are escaped by the underlying database driver.

Django also gives developers power to write raw queries or execute custom sql. These capabilities should be used sparingly and you should always be careful to properly escape any parameters that the user can control. In addition, you should exercise caution when using extra() and RawSQL.
#

Its fairly okay though if you're not doing that stuff.

rigid laurel
#

Using the ORM is query injection proof, but executing SQL directly isn't

native tide
#

yeah just didnt want someone to go around thinking something is not possible. Just think about where you are accepting user input and make sure its escaped. For the most part, it is. But a mentality that is not possible isnt good.

#

Ive never gotten to the point where I have a web app that I wanted to put into production but if I did... I would probably boot up kali and scan it aggressively on one of my test servers. It would be kind of fun to do that, having the full authority to do that legally on your own application.

#

If there were forms where SQL injection was possible I gurantee thats the first thing they find

#

Many of those web application tools on kali I have never touched because I have no interest in breaking the law.

#

But maybe I will put it up against some things Ive made in Django and Flask just to see what it says

cloud dock
#

@rigid laurel haha I know that docstring is terrible. It was just to get this linter to shut up (I know it's bad)

rigid laurel
#

Its a reasonably good habit to build just always writing a docstring for a function/method I think - although not the most important thing in the world

native tide
#
class Whatever:
  """
  docstring
  """
  def ...
#

Ive gotten to the point where I write all my docstrings before I even start coding.

cloud dock
#

Ok regarding the SQL proof, but the hardcoded part of the HttpResponseRedirect() there must be a better way

native tide
#

Some people say "less is more" but I think they are wrong.

#

Comments help me

rigid laurel
#

Less is more is definitely true is often the case, and no comments is infinitely better than comments that lie to you. But I think always having a docstring is good, I'm not a huge fan of inline comments though

native tide
#

Right.

rigid laurel
#

Normally inline comments lead to me thinking it should just be multiple smaller functions

native tide
#

Well, I once was told less is more in response to having docstrings at all.

rigid laurel
#

yeah, thats rubbish IMO. Docstrings are great

native tide
#

I agree

#

I mainly use docstrings in the planning stages to tell me what I need to do. So I can see how after building, if you neglect to edit them thats a problem.

rigid laurel
#

I have caught myself out with copying and pasting function definitions and not changing the docstring - and then having a function evolve beyond the docstring. I kinda wish there was some true AI that could lint and check my docstrings make sense

native tide
#

@cloud dock I believe you can do something like HttpResponseRedirect(reverse('urlconf-name'))

#

Look into that I cant remember exactly rn.

#

But that makes it to where it will work no matter how you change the url

#

It gets the url from the name in the urlconf

#

The idea behind reverse is that typically the name gets the view. In this case, the name gets the url

cloud dock
#

Hmm, well I will do again the Get's started tutorial of Django

#

without trying to apply it directly to my own project

native tide
#

There is a tutorial by Corey Schafer that I found more helpful than the polls app.

#

If you are familiar with him

cloud dock
#

I love Corey lol

native tide
#

yeah.

#

Check his Django class out

cloud dock
#

I actually thanked him, he is sometimes online here

native tide
#

He's the best at videos by far.

cloud dock
#

To learn python, for sure

#

I like CodeBullet for fun and also sentdex

rustic pebble
#

flask is like buying an old car
@vagrant adder which one is closer to a lambo?

pallid loom
#

lmao

cold socket
#

Do you guys know if I can use a modal on an existing page as a route?

#

I have a single page app (index.html) that displays posts. When I click 'Edit' it will open up a modal with the specific info

#

and I want to use it as my /edit/ route

mighty herald
#

Whats up guys I just organized my project into folders using Blueprint in flask. I'm just wondering how the url_for() works now that the views and templates are in different directories. In my home page i have 2 buttons that should take me to my register.html and login.html page. How do I code the url_for for each?

manic siren
#

Anybody here use React and Flask?

#

I have some questions!

mighty herald
rustic pebble
#

@manic siren whats ur prob?

manic siren
#

Sooo on React I have 3 components.

  1. Train Component:
    Which is just a drop down menu with a list of trains.

  2. Station Component.
    Which is a second drop down menu that populates itself with a list of stations specifically for that train ONCE the user selects a Train from the train menu.

  3. Incoming Time Component:
    This component is supposed to spit out the time it takes for the train to reach that station once the user selects a train and station.

----So my problem right now is with the third component. How do I pass the train, and station value in my last two components to my third component which will then go back to my flask route and call the necessary functions to get the result I want

#

Does that make sense? Am I thinking about it the wrong way? React feels foreign to me and have only been using it for about 2 weeks

rustic pebble
#

Yea it makes total sense

#

The solution is quite easy. Basically you want to pass the train and station once the user has selected what they want correct?

manic siren
#

Yess~

#

Would seeing my code help?

rustic pebble
#

I can link you to a video, generally you should just call a function after the user has selected the station which passes the state, js objects if passed through http can be accessed as json ones on python

#

This, although is for a form, explains how to pass data from one component to the other very well

#

I am currently not on my pc, if you can wait ~5 hours I can help you more

manic siren
#

Its 11:40pm here might be asleep by then. Ill def take a look at the video. Whats your time zone? Would it be okay to pick this up in the morning if possible? @rustic pebble

rustic pebble
#

For sure, it is 5:40 am. Gmt +2

manic siren
#

@rustic pebble gotcha thanks! gosh thats kinda late lol

rustic pebble
#

Yea it is

cold socket
#

When pushing my Flask project to a GitHub repo what files should I push and ignore?

#

I also have the app running in a virtual environment

grizzled harness
#

usually you don't push the virtual environment itself

#

it is just your code and things that help reproduce the environment

cold socket
#

What is the best practice?

grizzled harness
#

this is kind of a tricky question unfortunately - there are so many concurring "best practices" right now

cold socket
#

These are the folders I have in there

#

There is also a .db (sqlite) file in there as well

grizzled harness
#

I push only app.py, static and templates

cold socket
#

But the db would of course contain unique data for ever person

grizzled harness
#

usually I make my code automatically generate a empty db if one is not found

cold socket
#

Oh I see

#

What I did was open an interactive shell and then use these lines

#

from app import db
db.create_all()

#

How can I automatically create an empty db with the models I defined?

rustic pebble
#

you can sth like

#
if not os.path.exists("./dbname.db"):
  db.create_all()

If you have defined table/models in your app, they will get included upon db creation

nimble epoch
#

@mighty herald still have problem or solved it?

vagrant adder
#

@rustic pebble django definitely

grim tangle
#

so I have flask running with SocketIO
when I run my application, this is what I get

Server initialized for eventlet.
http://localhost:5000 is not an accepted origin.
http://localhost:5000 is not an accepted origin.
http://localhost:5000 is not an accepted origin.

I guess this is CORS error, but any ideas why is happening?

#

though this isn't on my end, it's on someone elses machine

#

it works good on my end

#

I tried and run it inside a vm and it still works

#

so, it's running well on win10/64bit and ubuntu/64, but not on win7/32, could it be issue with the OS or something

vagrant adder
grim tangle
#

nvm

rustic pebble
#

Question: Is there a way to have server -> client updates without client request, without using socketio?

rigid laurel
#

Server sent events

#

Or server side events

#

I forget what the second s means

rustic pebble
#

Do you know how that is possible?

mighty herald
#

yea @nimble epoch i figured it out, thanks though

fallow warren
#

i have a python file i want to convert to django

#

do i have to rewrite, is django different from thhe original python?

#

how do i do it

earnest oak
fallow warren
#

is django different or is it similar

#

will i have to rewrite my program

#

@earnest oak thx for the vid

earnest oak
#

They are both web frameworks for python with their own pros and cons you could look into if you want.

#

Np

static comet
#

hey good day with all, flask-restfull + gunicorn + NLTK good or bad ?

#

simple API

halcyon heart
#

does anyone know a registar that accept paysafecard ?

vagrant adder
#

@static comet yes, that would be good

static comet
#

@vagrant adder do you have experience with that ?

vagrant adder
#

i have experience with flask restful and gunicorn

onyx scroll
#

@static comet good

static comet
#

@vagrant adder any good documentation or example around ?

vagrant adder
#

flask restful docs are great

mighty herald
nimble epoch
#

Try login_manager = LoginManager(app) except login_manager.init_app = “login”

#

If you have that already the login_manager.init_ap... is extra

#

Like this

from flask_login import LoginManager

login_manager = LoginManager(app)

....

#

If its not working yet there gotta be another problem in your code

tired root
#

Here is a little tip if you host your server as root or vps: Block packages for RFC1918 and RFC6598 from leaving your server

#

Implement proper ip tables for that

#

and you won't have an issue

pallid loom
#

I don't understand about models on django, what is it for?

#

is it like a summary of the application?

mighty herald
nimble epoch
#

Can i chack you python files

vagrant adder
#

can you paste your code in here?

mighty herald
nimble epoch
#

Put it under your app variable

mighty herald
#

i just got a funky error

nimble epoch
#

When you put it there its something like you havent created your flaks init yet

#

Let me check

mighty herald
nimble epoch
#

Chenge your werzeug to werkzeug

#

Whereever you have imported it

#

Guys do you have any idea about liquid server?

#

But its in my members now

mighty herald
nimble epoch
#

You have error in your code in attributes part hard check your code again

mighty herald
#

what is the attributes part

nimble epoch
#

I mean sth like this funcname(attr1, attr2)

#

Sth like form=form or ...

#

Got me?

mighty herald
#

somewhat yeah

#

thanks

nimble epoch
#

Yawelc..

mighty herald
#

Nice catch on the werkzeug i wasnt gonna find that on my own!

nimble epoch
#

Dont you check the errors yaself?😀

#

Readem once theyre helpful

mighty herald
#

I do but first time seeing them Im not sure what they mean at times

nimble epoch
#

They look scary 😵

mighty herald
#

haha no joke

nimble epoch
#

😁

sly drum
#

Hello guys

#

who used django

native tide
#

Hi guys,

I have a drop-down menu “velo” in which I have four categories “Urbain”, “VTT” … And I do not find how to pass value to “velo” to be able to recover it in my view
https://paste.pythondiscord.com/qocequdoze.py

nimble epoch
#

@sly drum not a lot but maybe i can help if you want?

mighty herald
nimble epoch
#

Did you use db.create_all() in command line before you use your database

native tide
#

I did a challenge recently

#

pick all the movie objects that have the year property set to 2018 and which their rating is larger than 4. Sort them in a descending order and console.log their title values on the console.

#

In your opinion, which code do you think does it better?

#

this one:```js
const movies = [{
title: 'a',
year: 2018,
rating: 4.5
},
{
title: 'b',
year: 2018,
rating: 4.7
},
{
title: 'c',
year: 2018,
rating: 3
},
{
title: 'd',
year: 2017,
rating: 4.5
},
];
movies.sort((a, b) => b.rating - a.rating);
for (movie of movies) {
if (movie.year === 2018 && movie.rating > 4)
console.log(movie.title);
}

#

or this one:```js
const movies = [{
title: 'a',
year: 2018,
rating: 4.5
},
{
title: 'b',
year: 2018,
rating: 4.7
},
{
title: 'c',
year: 2018,
rating: 3
},
{
title: 'd',
year: 2017,
rating: 4.5
},
];

const titles = movies
.filter(m => m.year === 2018 && m.rating >= 4)
.sort((a, b) => a.rating - b.rating)
.reverse()
.map(m => m.title)
console.log(titles);```

quasi ridge
#

I don't think => works in Python

#

maybe ruby or perl?

#

oh, JS

sly drum
#

@nimble epoch Sorry , I will get up early and send you a screenshot for my problem from my Computer, Good Night

mighty herald
#

@nimble epoch yes thanks that seemed to work! Although I'm having an issue redirecting to my about page after the user logs in. It's giving me a 404. I cant seem to figure out my issue

pallid loom
#

Does django work well on large projects?

rustic pebble
#

Yup

earnest oak
#

With Flask, how would you go about making asynchronous loading for a page? E.g. I have forms and a 'Calculate' button. Soon as the user hits calculate it returns output, loads, then prints another output below that one.

rustic pebble
#

With ajax

#

@earnest oak

#

That is not really a flask thing, it is more of a client side tackle

earnest oak
#

yeah true

#

I was wondering if there was a simpler fix, as someone without js knowledge

#

maybe websockets?

rustic pebble
#

I can guarantee sockets will be harder for you to setup than js

#

Take a look at fetchapi for js

#

It is incredibly intuitive and will get you running in 0 time

fallow warren
#

whats the point of using the blockqoute tag in html

#

is it even used norm?

tired root
#

@fallow warren Yes, you can use it to style quotes with css. I mean you can just use a div and set a class, but using html tags where appropriate is the better way because it increases accessibility. For example, a screen reader for a blind person does not care about css, it uses the html tags to describe content.

rustic pebble
#

Anybody have any ideas on why ./electrocute_logo.svg doesn't get found?

surreal tangle
#

Does anyone have experience with flask and websockets? I'm wondering if it's possible to keep a python object alive in the backend as long as the websocket connection is up

#

Not sure if the question even makes sense, I might be approaching this all wrong

sly drum
#

When I finish writing a code for django in pycharm and go to live server to test it , it doesn’t work although my code is 100% right

#

Is configuration cause this problem ?

sly canyon
#

@rustic pebble because it's not in the same folder of your html file?

#

maybe ./src/loggedout/electrocute_logo.svg would work
or or ../src/loggedout/electrocute_logo.svg depending on the current file path

#

@sly drum I don't play with Django, but I don't think liveserver is meant to run flask/django applications, only pure html,css,js. You should run your local django server to render it correctly. Specially if you're using Jinja on your templates

jagged lark
#

Wdym by “it doesn’t work”?

native tide
#

Hi, very new to Web Dev here. I am trying to send in a form and not refresh the page to show the results. I learn we use something called AJAX to do this. However, not sure how to do this with Django. How do I send a JSON response when the form is submitted?

quick cargo
#

django has a JsonResponse() return you can use to return a json or use a serializer if getting from a db

#

iirc django does also support ajax on top aswell

native tide
#

Yes, I saw that. But not sure how to code the logic. What do I do when the form is submitted, if I return the JsonResponse I get redirected

earnest oak
#

@native tide whadya know, I'm trying to do just that except with Flask

native tide
#

nice

earnest oak
#

I think ajax may not even be necessary here though, by using fetch api instaed

native tide
#

hmm idk very new to web dev... but i guess u needed to learn jquery and ajax anyway so

#

i did, a little bit

frozen tinsel
#

Hello everyone!
I am a not really new to python user, meaning that I know the basics but I have not done any projects to showcase my skills.
I was looking in the python ecosystem for web framework and 2 of them particularly interested me: flask and pyramid.
There are enough ressources for me to grab flask, but I would also like to explore pyramid. Unfortunately other than the documentation I can’t find more ressources, any suggestions where I might go?

glossy nova
#

what about django

#

have you seen that

frozen tinsel
#

Django is great but I planned to do projects that don’t need all the features it provides.

glossy nova
#

ok

frozen tinsel
#

I planned on using it but not now.

glossy nova
#

?

#

official docs

#

just making sure you have seen this?

frozen tinsel
#

Yes I have!

#

Is there any community for it?

#

Other than their IRC channel on freenode.

glossy nova
#

hm

#

i have not used pyramid a lot so im not really sure

#

they have a google group?

frozen tinsel
#

Yes

glossy nova
#

yes

frozen tinsel
#

Then I guess I’ll stick with flask.

zinc scroll
#

hey guyz,
i wanted to ask if there's a possibility to use Python for Front End too? i mean without using JS?

#

like Full Stack Python?

#

i ain't deep into Python or something i'm just asking before i do anything....

rigid laurel
#

You can render static templates with Python

#

but if you want to add dynamism to your site

#

you can only really do that with JS

cunning cradle
#

I'm using Flask with SQLAlchemy. Does anyone know if it is possible to use multiple databases and have relationships that cross the databases?

rigid laurel
#

I don't know if its possible (I'd guess not). But it sounds like a very bad idea

cunning cradle
#

I have to share some tables between mutliple apps. Do you have any ideas for doing that?

#

I've been looking into MySQL triggers, but that also seems super clunky.

rustic pebble
#

@cunning cradle Your best bet could be having a function which binds all tables from all dbs to local tables in an sqlite instance and then create relationships through the sqlite instance

cunning cradle
#

A python function?

pallid loom
#

does every django app follow the same logical pattern? map URLs, write views and create templates?

rustic pebble
#

@cunning cradle Yup

cunning cradle
#

Thanks for the help!

rustic pebble
#

I have actually done this before, It is fairly easy

cunning cradle
#

Do you have any examples? Or resources to point to?

tired root
#

is the first db a copy of the second?

#

@cunning cradle ?

cunning cradle
#

My plan was to have three DBs. One would be shared between the two apps while each app ad their own DB with tables only for that app. But I need to have relationships between the app and shared DBs, like to show that a User in the shared DB was the last to update an object in the app DB.

tired root
#

Because even if it just some tables, you can do a simple master-master replication

cunning cradle
#

How do you do that?

tired root
#

however, you can only replicate data, not have relationships between databases

cunning cradle
#

Yeah, so the other way I could do it is have certain tables in a single DB copied back and forth with the second app's DB.

#

No shared DB with that route.

tired root
#

It's fairly simple, get the binlog position of db2, start the replication at the current binlog position on db 1. Set db2 as master, db1 as slave. Then repeat the same on db2, get binlog position from db1, set db1 as master of db2

#

Then add replicate-do-table as parameter

#

However, you need to add measures for concurrency, so they don't play ping pong with the dml statements and overflow your tables

#

As in, when db1 gets the same command as db2 and they try to replicate the same data at once

#

That would lead to an iffy situation

cunning cradle
#

And this would be all in SQL? Not Python?

tired root
#

It's on the mysql level. It is a function of the db

#

Nothing to do with Python, yes

#

Here is a rundown on SO that I've found

cunning cradle
#

Nice. I only mess with MySQL when I have to so I don't know all of the capabilities. Thanks. That's a big help!

tired root
#

no problemo

candid moon
#

do you guys know how to add an expiring_date field to a post class?, i need also to create a method to delete all the posts that are expired or set them to draft in Django

proper hinge
#

You'd start by adding a DateTimeField to the model

#

You could filter for expired posts with roughly Post.objects.filter(expiring_date__lt=datetime.now())

candid moon
#

oh okay

lofty matrix
#

I'm working with a frontend developer who is creating the css/js/html for a Django site. The frontend developer is only writing standard HTML, and then I am converting it to Djano templates which gets dynamic content from the database. When changes are made to the frontend, we want to see them with the dynamic content. Is there a workflow that can make it so I don't need to almost completely re-make Django template for each frontend change?

tired root
#

Why does the frontend dev not write a django template to begin with?

#

If he does not want to learn it, deliver the data as json

#

so he can fetch it with js

tired root
#

guess 2 minutes was too long to wait for an answer

nimble epoch
#

🤪🤤😒

native tide
#

how can i have the numbers above each cell too? in proper spacing, any easy way?

rigid laurel
#

css

native tide
#

very helpful

#

thanks

rigid laurel
#

can't really help without more code or details

native tide
#

its just inputs looped for an input n in two for loops

#

using django template

#

didn't try with tables, not sure if they can have input fields

rigid laurel
#

Need to see the current HTML or JS that you're using

native tide
#

ok one sec

rigid laurel
#

to be able to provide any useful suggestions

native tide
#

should i send the code or ss

#

btw in general

rigid laurel
#

have you tried just putting a div with a number above the each input?

#

oh

#

a label is probably the right thing to use

native tide
#

yeah i was trying that

#

didnt try label

rigid laurel
#
<div class="inputWrapper">
    <input id="something_that_will_be_unique" ...>
    <label for="something_that_will_be_unique">
</div>```
#

something roughly like that might work

native tide
#

ok, will try it out, thanks

native tide
#

i am doing this challenge right now
Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.
for example:

uniqueInOrder('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
uniqueInOrder('ABBCcAD')         == ['A', 'B', 'C', 'c', 'A', 'D']
uniqueInOrder([1,2,2,3,3])       == [1,2,3]```
i've spend an hour already on it **Or more!**
i've never did a challenge this hard.
#

I need to solve this in JavaScript by the way

fiery portal
#

Hey guys, I made a minimal demonstration repo to show you how to can use the built-in @dataclass decorator to easily serialize HTTP response body JSON objects into @dataclass classes so PyCharm will recognize your API response bodies as normal class members! Here's the repo link, I just posted it: https://github.com/wanderrful/reqres_tool

native tide
#

hey all

#

is anyone free to help me with css?

#

i'm trying to position an image

#
 <div class="html">
            <div class="logo">
            <img src="html1.png" alt="html.logo";>
            </div>
            <div class="content">
                
            </div>
        </div>```
#
.html-logo {
    position: absolute;
    right: 20px;
    bottom: 20px;
}```
#

this does nothing

native root
#

@native tide your css selector is incorrect. The one you have there will select any element wiht a class of "html-logo" not one with "logo" contained by "html". You can separate the selector levels with a space " " to do so easily

native tide
#

@native root what you mean by separate with a space?

native root
#

for example, ".red" selects something like "<div class='red'>", and ".red .small" selects something with "small" inside "red"-- like "<div class='red'><div class='small'>"

native tide
#

oooh

#

gotcha

#

ty ty!

native root
#

There's a variety of other options but spaces are simplest and probably enough for you!

native tide
#

soo

#

.html .logo should work?

#

@native root

native root
#

yep

native tide
#

it hasnt moved:(

native root
#

do you have something inside content yet?

native tide
#

nope

native root
#

Try putting some dummy text there, might clarify the issue

native tide
#

nope

#

@native root

native root
#

screenshot?

native tide
#
        <div class="html">
            <div class="logo">
            <img src="html1.png" alt="html.logo";>
            </div>
            <div class="content">
                <span>HELLO
                    
                </span>
                
            </div>
        </div>```
native root
#

You don't have a width or anything set on "html" or it's container, do you?

native tide
#

nope

#

i can show you my css

#

if you want

#
@import url('https://fonts.googleapis.com/css?family=Montserrat:500&display=swap');

* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    background-color: #24252a;
}

li, a , button{
    font-family: "Montserrat" , sans-serif;
    font-weight: 500;
    font-size: 16px;
    color: #edf0f1;
    text-decoration: none;
}

header {
    display: flex;
    justify-content:flex-start;
    align-items: center;
    padding: 30px 10%;
}

.cta {
    margin-left: auto;
}

.nav_links {
    list-style: none;
}

.nav_links li {
    display: inline-block;
    padding: 0px 20px ;
}

.nav_links li a {
    transition: all 0.3s ease 0s;
}


.nav_links li a:hover {
    color: #0088a9;
}

button {
    padding:  9px 25px;
    background-color: rgba(0,136,169,1);
    border: none;
    border-radius: 50px;
    cursor: pointer;
    transition: all 0.3s ease 0s;

}

button:hover {
    background-color: rgba(0,136,169,0.8);
}

.html .logo {
    position: absolute;
    right: 100px;
    bottom: 20px;
}
#

ping if you reply 🙂

native root
#

I'm not sure. I've copied the bit of your code that isn't working for you into a blank page for me and it's functioning (albeit without the image itself but the alt text showing)

native tide
#

oh

#

so the image is moving for you?

#

also with this html

#
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Navbar</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="CSS_Style.css">
    </head>
    <body>
        <header>
            <nav>
                <ul class="nav_links">
                    <li><a href="#">Home</a></li>
                    <li><a href="#">HTML</a></li>
                    <li><a href="#">CSS</a></li>
                    <li><a href="#">JS</a></li>
                </ul>
            </nav>

            <a class="cta" href="#"><button>Bio</button></a>

        </header>

        <div class="html">
            <div class="logo">
            <img src="html1.png" alt="html.logo";>
            </div>
            <div class="content">
                <span>HELLO
                    
                </span>
                
            </div>
        </div>

    </body>
</html>```
native root
#

position: absolute positions absolutely relative to the nearest parent element that has position: relative or position: absolute

#

Well, I'm running the code you posted and its down in the bottom right for me

native tide
#

wot

native root
#

Are you sure your file isn't being cached?

native tide
#

how do i check that?

#

sorry im super new to this

native root
#

are you using chrome or firefox to look at your site?

native tide
#

chrome

#

i just used IE and it was in the same position

native root
#

right click anywhere on the page, and select "inspect"

native tide
#

ye

native root
#

It'll open a useful tool. One of the tabs on the top is labeled "network"

#

If you click it, there's a checkbox to "disable cache"

#

If you reload the page with the tab open, it'll display every file the browser grabs from your server, whether it was fetched from cache or remotely or successfully, and even the contents

#

So, standard check is 1. Not cached, 2. Returning the right file

native tide
#

ok just disabled it

native root
#

now give it a reload and see

native tide
#

hasnt moved

#

should i restart the broswer

native root
#

No, what you should do is check the list of requests it did

#

it should be in the formerly empty panel in that network tab

#

There should be one labeled "index.html" or whatever your html file is, and one "CSS_Style.css"

native tide
#

yep

native root
#

click on the Css_style one

#

and scroll to the bottom, and make sure it matches what it should be

native tide
#

clear cache?

#

yep

#

its diff

native root
#

Did you remember to save your css changes?

native tide
#

yep

#

all saved

#

oh wait

#

ok wow

#

it was referencing an old version

native root
#

Yep. All fixed?

native tide
#

YEP

#

you are a legend

#

thank you for your patience!!!

native root
#

👍

native tide
#

if you have this under a css file, for example bootstrap.css

:root {
  /* ... */
  --breakpoint-sm: 576px;
  /* ... */
}

can you do this in style.css assuming both are imported on the html page.

@media (max-width: var(--breakpoint-sm)) {
    #rightbar {
        display: none;
    }
}
#

It seems like you should be able to.

#

But its not working

#

maybe I mixed up using max-width instead of min-width or something....

#

Well it worked when I just copied the value and didnt try to use var(--some-name)

native tide
#

Does 576px sound like a reasonable size to break into phone displays to you
It seems slightly too big to me.
You can still fit more than single 100% width containers into that space sometimes.

rustic pebble
#

it sounds ok

zealous igloo
#
class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    is_active = models.BooleanField(_('active'), default=True)
#

I was looking at a tutorial and saw this and just curious, whats the naem of the property taht _('email address') and _('active') is specifying the value of?

native tide
#

At one point I read something along those lines but its been to long since I was reading the infinite Django docs to remembner haha. I know that _ is some kind of alias but I just cant remember because I didnt use it long enough.

#

I have another question though... it's a Jinja2 question.
I have a block as per {% block leftbar %} that a media query completely removes at a certain screen size.

      <!-- Leftbar -->
      <div id="leftbar"
           class="col-xs-0 col-sm-0 col-md-0 col-lg-3 col-xl-3">
        {% block leftbar %}{% endblock %}
      </div>

It works like that, and then it disappears by the id in CSS.

@media screen and (min-width: 576px) and (max-width: 992px)  {
    #leftbar {
      display: none;
    }
    #leftbar-moved {
      display: block;
    }
}

in my base.html I have something like

         {% block content %}{% endblock %}
         {% block leftbar_moved %}{% endblock %}

If you don't know how blocks work on jinja, they are inherited by other templates using {% extends 'base.html' %} and then you are able to rewrite those blocks on that template, so that they vary based on the page you're on. It's pretty simple.

In every page I have content, sidebar, and other blocks. As you can see in the CSS, when the sizes are right, the leftbar appears and then when they are not, it goes away and a new set of elements appear in another location. The main reason for this is, when the screen is big, the left bar works great on the left. When it goes down to phone size, the left bar is not what you want to see at the top of the page.

#

Its secondary content that should be at the bottom.

#

So my question is how can I make it so that the sidebar block on any template is also the leftbar_moved block on every template. The same exact things.

#

The only way I can think to do this is to repeat myself.

#

which is obviously a terrible idea.

#

{% block sidebar and sidebar_moved %} or something

#

I refactored leftbar into sidebar so its confusing somewhat ha

tired root
#

@native tide I don't quite understand. When the screen goes smaller, the content of sidebar-moved is the same as sidebar right?

#

It is just displayed differently?

#

The first mistake is, you cannot account for screen sizes while generating the template. Well, you could, but that's a bad idea

native tide
#

Well, the content is the same. Most likely the presentation will have to be different. This is most likely something I will have to solve with JavaScript.

#

At least, I dont know a way to do it otherwise.

#

I wanted to do some kind of fancy templating magic if I could.

tired root
#

solve with javascript?

native tide
#

I am working on committing to my repo in a sec and maybe that will clarify

tired root
#

Just write different css rules in your selector

#

so it displays differently on different sized screens

#

there is no javascript required

native tide
#

But like, how do I move the content entirely.

tired root
#

You want it to be a sidebar on desktop and a top banner on mobile I presume?

#

or a slide in?

native tide
#

well, that might work too. But I was just going to have it (for simplicity) moved to the bottom beneath the content. Its basically just like... its stuff that is in the way that you dont want to see at the top of the screen when thats all you have room for. At the same time, it should be assessable to maybe I should consider implementing something

But there is ALREADY a top banner. There is kind of a lot of stuff to figure out where I want to put it. I really dont like any option for the sidebar on mobile that I can think of.

#

The only thing that makes sense to me I think is...

#

some type of button that pulls up a collapsable or dismissable modal

#

to display the info

#

and then it goes away

tired root
#

If you want it at the bottom, change it to something like:

#
.sidebar{
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: 0;
}```
native tide
#

The bottom will work until i figure that out

#

let me play with that, that is some CSS i have never done before.

tired root
native tide
#

the transform is the one ive never used at all. Ive use position on occasion.

tired root
#

if you set left: 50% the anchor for moving it is the top left corner

#

so transform moves it back another 50%

#

which centers it on the parent

native tide
#

damn I didnt even know about being able to relatively affect things with left, bottom, etc by the position property.

#

I dont necesarily want to center it anywhere. It needs to be out of the way more than anything for mobile but im still curious ot see what this does. I have a variety of frontend things to figure out so i might as well get familiar.

#

let me play with this an ill be back

tired root
native tide
#

https://jsfiddle.net/pnymst2x/20/ -- this was more along the lines of what I was initially planning, the lorem ipsum representing content divs and the red div representing the moved side bar content, which to be honest the way I was gonna do it was a bad idea.

The way you have it is cool, I just need to make dismissable/collapsable because it cant be just there in the way.

the purpose of it is... a breif overview of the protagonist of the story that you're playing / your character. Its perfectly fine as a side bar but its stuff that needs a seperate page or dismissable container otherwise. So I think I will write something like what you have since I already have to make a thing that does that, too. lol.

this project uses kind of a lot screen space but I ahve to be thinking of mobile first i guess.

#

it is hard for me to know what works well for mobile users because I am not a mobile user for the most part.

#

I mean I have but I mostly prefer not to.

#

bootstrap uses some css that is fairly beyond my knowledge. Im pretty sure a lot of it is generated with sass.

#
.media {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: start;
      -ms-flex-align: start;
          align-items: flex-start;
}

I have no idea what that says. I could look it up I guess. Is flexbox different thatn the 12 point col display method that I use via bootstrap?

#

and webkit, is that some browser hack thing?

#

what does the - before a property name indicate?

#

is there such a thing as a device less than 288px?

#

width

rustic pebble
#

webkit is apple’s browser render engine

#

Ms is microsoft’s one

#

Bootstrap gives out different instructions for different engines

native tide
#

I thought it was something like that. Still, what its doing exactly is beyond me. I could read into it but there are just other CSS thingsr to look at right now. Sort of why I rely on Bootstrap despite tearing it apart and rewriting it a bunch.

#
  <link href="static/css/slate.css" type="text/css" rel="stylesheet">
  <link href="static/css/bullstrap.css" type="text/css" rel="stylesheet">
  <link href="static/css/responsive.css" type="text/css" rel="stylesheet">
  <link href="static/css/ripped_google_fonts.css" type="text/css" rel="stylesheet">
  <link href="static/css/style.css" type="text/css" rel="stylesheet">

my css organization is import bootstrap theme, write a file just for writing over things in that file so that I dont break anything or get stuck not able to go back easily, responsive is all my space consuming particular media queries, fonts, and then finally the actual selectors I think of/need to pull out of my html inlines.

tired root
#

flex boxes allow for dynamic position of the boxes

#

as the user changes screen size

#

e.g. turning the phone, resizing the browser etc

native tide
#

its essentially what is going on here

.col {
  -ms-flex-preferred-size: 0;
      flex-basis: 0;
  -webkit-box-flex: 1;
      -ms-flex-positive: 1;
          flex-grow: 1;
  max-width: 100%;
}

I def use that but ive never put it together from scratch myself. I have done more css than a lot of people but not all stuff either.

#

that cols thing is the main reason i use bootstrap.

#

I mean, its not a bad starting point generally but I end up editing almost everything a lot anyway

#

But that cols thing is just too good

tired root
#

Resize it

#

IN this example, it just changes the size of the flex boxes

#

It's a simple example

#

You can control the behaviour with grow, shrink wrap

#

There is also grids

native tide
#

still that is huge. I had huge problems with elements overlapping and running into each other when i first started css when i didnt know about boostrap. I got around that with media queries. But that is a a great thing.

#

I essentially use it through the bs frameowork already.

#

I should eventually learn how to edit it and thjen write it myself

#

but again, so much stuff

#

so grids != flex?

#

are you talking about grids as in that minimal framework you showed me before? I still have it book marked.

tired root
#

no

#

Gridboxes are a bit different to flexboxes

#

The basic difference between CSS Grid Layout and CSS Flexbox Layout is that flexbox was designed for layout in one dimension - either a row or a column. Grid was designed for two-dimensional layout - rows, and columns at the same time

#

So basically, use grid for the grand scheme layout of the website, flexboxes for the content

native tide
#

that is good to know.

#

* {box-sizing: border-box;} why is this in the codepen?

#

example link from that page you showed me

tired root
#

It makes all boxes the same size

#

in this case, it applies it to all elements

native tide
#

You are supposed to put that with an asterisk at the top of the css? Ive never seen that before. That means... uhh oh. That means all the selectors. select all?

tired root
#

You are not supposed to

#

but you can

native tide
#

right

tired root
#

Nifty for debugging

#
*{
  border: 2px solid red;
}```
native tide
#

So in this example, that grid doesnt responsively change with resizing? It doesnt seem to

#

flex: 1 1 150px; what is each argument here?

tired root
#

flex: flex-grow flex-shrink flex-basis|auto|initial|inherit;

native tide
#

ty

#

ah the only reason it didnt flex in example is because the outter wrapper was set at 800px

#

if you take it out it automatically assumes you want to flex. I think

tired root
#

Yes, because it is a static size, with the px