#web-development

2 messages · Page 195 of 1

pallid lily
#

it is like a help for programmer to understand the function further?

frank shoal
#

You could also use list[str] to say a list of strings

#

Yes. It's purely a devtime check. It's ignored at runtime

pallid lily
#

ahh thanks dude

#

alot for me to learn

frank shoal
#

BTW it's not really related to web. Are you using fastapi?

pallid lily
#

no no was just trying to learn more about OOP

#

befor learning Django

#

i still don't understand why some times i see @login_required as decorator befor some functions

#

things for me to understand 😄

frank shoal
#

Do you know what a decorator is?

pallid lily
#

not really

#

i think it splits classes

frank shoal
#

It's a function that takes a function and returns another function

#
def x(): pass

x = foo(x)

# shorthanded to
@foo
def x(): pass 
pallid lily
#

ohh

#

it is like a modification to an existing function

frank shoal
#

And the @ syntax merges it with the declaration

pallid lily
#

oh

#

thanks dude

frank shoal
#

Example creation of decorator

def foo(func):
    @functools.wraps(func)
    def decorator(*args, **kwargs):
        # do stuff before
        r = func(*args, **kwargs)
        # do stuff after
        return r
    return decorator
pallid lily
frank shoal
#

You can stack decorators too

pallid lily
#

okay i will try to understand it further maybe i will need it while coding

pallid lily
dusk sonnet
#

How can i fix images going outside my body's height?

#

the height property for my page is set as follows

#
    min-height: 100vh;
    height: auto;
#

increasing min-height to 200vh works but idk if its bad to do that or not

fair agate
#

How do I use Django to run a python function when a button is pressed?

glad creek
#

not sure if this is the right section for my question but has anyone worked on a fintech/blockchain project? Or with cryptocurrenies API's?

vestal hound
#

like on the frontend?

runic sage
#

Hi I have a certain confusion while deploying my django project on heroku. When its deployed, the default domain would be no SSL (http://invid19.herokuapp.com). Ive tried to change my settings from ALLOWED_HOSTS = [f'{HEROKU_APP_NAME}.herokuapp.com'] to ALLOWED_HOSTS = [f'https://{HEROKU_APP_NAME}.herokuapp.com'] but it only make the deployed project had a bad request 400 on production then I revert to the old code.

Then, weirdly idk why if I type my domain manually using https (http://invid19.herokuapp.com), it will be no error, but the default domain still using http if we dont type it manually

#

does anybody now why my django project cant use SSL as a default domain

wooden ruin
fair agate
runic sage
#

here is one example of my deployed project that automatically using https as you type in browser

#

anti-maba-deadline.herokuapp.com

#

its weird now when I try to deploy a project once again and its appear http on its default

#

even though I use the same method to deploy my django project on heroku

pallid lily
#

is there like a certain Hashing library i can use in both Django and Tkinter?

stuck narwhal
#

Can someone please help me with api call and postman,I'm really lost

fading niche
#

Could someone help me? I have a button at the end of a form and am having trouble figuring out how exactly to make it submit the form answers to a function
I'm using an event listener but I'm not quite sure how to do it
This is what I have right now document.getElementById("addbtn").addEventListener("click", addEmployer.bind(null, ));
The js function I want to use is addEmployer and it has multiple parameters (which are the form fields)

#

This is like a super quick question for anyone with any actual knowledge, I just don't know what im doing 😦

civic crater
#

hey what is MultiValueDictKeyError ??

#

views.py

def addProd(request):
    form = addForm()
    if request.method == 'POST':
        if form.is_valid:
            product_name = request.POST['Product_Name']
            product_img = request.FILES['Image']
            product_desc = request.POST['Description']
            product_price = request.POST['price']
            product_seller = request.user
            print(product_seller)
    return render(request, 'addProd.html', context={"form":form})
#

Browser

MultiValueDictKeyError at /shop/add
'Image'
Request Method:    POST
Request URL:    http://localhost:8000/shop/add
Django Version:    3.2.4
Exception Type:    MultiValueDictKeyError
Exception Value:    
'Image'
Exception Location:    C:\Users\Rajiv\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\datastructures.py, line 78, in __getitem__
Python Executable:    C:\Users\Rajiv\AppData\Local\Programs\Python\Python38\python.exe
Python Version:    3.8.10
Python Path:    
['C:\\Users\\Rajiv\\Desktop\\Ishant Files\\main\\proj\\Back-end\\iCart',
 'C:\\Users\\Rajiv\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
 'C:\\Users\\Rajiv\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
 'C:\\Users\\Rajiv\\AppData\\Local\\Programs\\Python\\Python38\\lib',
 'C:\\Users\\Rajiv\\AppData\\Local\\Programs\\Python\\Python38',
 'C:\\Users\\Rajiv\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages']
Server time:    Fri, 15 Oct 2021 09:26:23 +0000
drowsy delta
#

Hey friends, what is learn Django or php Crouse for beginner? which better for web development?

pallid lily
#

Django

sudden quail
#

can anyone recommend a good django course

dusk portal
dusk portal
dusk portal
#

@civic crater I can help.
Ping when u're back online (free)

sudden quail
dusk portal
#

There are thousand
Learn 1 then try ur own
Try not to complete couses instead of it when u complete 1 concept
Try to get better at it and learn in depth

#

And apply in own use case

#

And different different parameters n different different uses cases

native tide
#

does anyone know about a dashboard builder drag and drop free?

vernal lotus
#

hello anyone how to remove when I remove or delimit this character?

#

I am using many to many field

smoky bane
#

Hi

#

who can help me create sit

#

e

indigo kettle
vernal lotus
#

<QuerySet [<ServerGroup and [ServerGroup

#

I want to display only CHANNEL SERVER, DATA WAREHOUSE SERVER

vernal lotus
#

nevermind I use this

#

all|join:", "

shrewd sand
lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @native tide until <t:1634324837:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

native tide
#

Hey guys, does somebody know why I'm not able to "stack" two serializers, please see: https://stackoverflow.com/questions/69588647/django-rest-framework-how-to-handle-a-serializer-instance

It seems that Django simply does not accept instance data from another validated serializer within one view

uncut spire
#

if i'm processing a number of events in some class methods, and want to batch every 100 events for insertion to a db, what's the best way to do this? was thinking a class attribute for a list that would contain event data, then when len >= 100 batch it up, send it off, clear the list, rinse and repeat--are there cleaner ways

frank shoal
#

Maybe a sql transaction?

fickle garnet
#

are you events coming very quickly ?

vestal hound
#

wrap adding to the list in a classmethod

#

singlethreaded, right

civic crater
#

@dusk portal i m online now

dusk portal
#

for that page

civic crater
#

yes

#
{% extends 'base.html' %}

{% block body %}
<div class="container">
<form action="/shop/add" method="post">
    {% csrf_token %}
    {% for formcontrol in form %}
    <label class="form-label" for="{{ formcontrol.id_for_label }}">{{formcontrol.label}}:</label>
    <div class="input-group mb-3">
    {{formcontrol}}
    </div>
    {% endfor %}
    <button class="btn btn-success" type="submit">Add</button>
</form>
</div>
{% endblock body %}
civic crater
dusk portal
#

<form method="POST" enctype="multipart/form-data" >

#

add this enctype

#

to ur form

civic crater
#

do i need to change the enctype value??

#

yes it worked

civic crater
dusk portal
#

done?

#

xD

civic crater
#

yup but..

civic crater
dusk portal
civic crater
dusk portal
#

nice

foggy geode
#

Anyone here who has an experience of django-autocomplete-light?

runic sage
#

tlaking about django html, whats the different between {%extends %} and {%include%}?

#

if I have 2 base html like navbar.html and footer.html

#

why I cant extends both of them

#

?

native tide
#

when i generate requirements.txt using pip freeze > requirements.txt in Django I am getting like this?. why i am getting @ and paths ?

inland oak
#

or used global env

hoary brook
#

What would be the best way to share a variable across my entire Flask project?
I am creating a project tracker and I want all my data in my dashboard, kanban boards etc. to change depending on the Project object stored in current_project. How would I go about initializing and sharing this variable? Currently I am setting it as None at the start of my file, then changing it when a user selects a project. But this naturally means that when I navigate to another site the variable will be reset to None again since all the code reruns...
If you have a solution, feel free to @ me so I don't miss it. Thanks.

versed python
#

Oh i see why that won't work

#

I think writing it to a file would work

hoary brook
#

I've never had to deal with those yet, this is my first time creating a complex project that's more than displaying a few database files.

versed python
hoary brook
#

Yes, I have a Projects page where a user can select the project he wants to view, and the other pages such as the dashboard should show the data of the currently selected project.

versed python
#

Write it to a file

#

To a database if you want a more permanent solution

#

But if it is a website then localstorage works too

hoary brook
#

I am using Flask-sqlalchemy as my database, so I would have to create a model to store that variable in, correct?

versed python
#

Yes but see if writing to file solves your needs

#

Database approach will come with The overload of maintaining an additional model

hoary brook
#

I'll look into it, thank you for your help!

vestal hound
#

hold up

#

doesn't that mean that

#

each user will have their own value?

hoary brook
#

Ah, that's true. I completely forgot about that.

#

Does that mean I have to store it in the browser cache or something like that?

vestal hound
#

if you want a user's selection to persist across browsers

#

use a database

#

otherwise localStorage is fine

hoary brook
#

Can I access this localStorage with python?

#

This is completely new to me, I'm sorry

vestal hound
#

localStorage is something that exists on the browser

#

and can only be accessed/written to with clientside code

#

i.e. JS

#

are you familiar

#

with how the frontend and backend interact

#

and what they are

hoary brook
#

Yes, but I'm not sure how I would handle this in any case

vestal hound
#

and don't know how to write JS

#

just use a database

#

it's simpler

#

and honestly

#

I, as a user

#

would expect my preference to persist across browsers

hoary brook
#

So just have a column in my User model for what project is currently selected?

#

What would be the best column type to use for this? Just store the ID of the project?

vestal hound
#

presumably the project has its own model

hoary brook
#

Currently I just have this in my user model

currect_project = db.Column(db.Integer, nullable=True)```
should I change it to
```py
currect_project = db.Column(db.Integer, db.ForeignKey('project.id'), nullable=False)```
vestal hound
#

I don't know the appropriate syntax

#

as long as you make it a foreign key you'll be fine

#

nullability

#

well

hoary brook
#

Okay, thanks!

vestal hound
#

I would think you'd want to represent

#

"no project selected"

#

so

hoary brook
#

I'll keep it on True then I guess

#

Thank you for your help, I'll test some stuff but I'm confident I'll get it to work 👍

vestal hound
#

yw 👋

#

atb!

noble torrent
#

is there any way for me to fix this error? I need the blue colour to be on top of the purple colour

#

this is the code

calm plume
#

If you want blue to be on top of purple, you need to use the z-index in CSS.

noble torrent
#

thought so

#

let me try it out

noble torrent
calm plume
#

Oh, I'm not sure since you're setting it with box shadow, sorry

#

Maybe it's just the order you put the items in?

noble torrent
noble torrent
calm plume
noble torrent
#

I'll just use blue instead of cyan, thanks

slate smelt
#

blink text

#

help

spiral blaze
#
<html>
    <head>
        <meta charset="UTF-8">
        <title>Website</title> 
    </head>
    <body>

        <input type='text' />
        <input type='password' />

    </body>
</html>```
#

how do i make the password input bar go down ?

#

its side to side with the text

calm plume
#

You need to use CSS

#

This should work, but you really should use a div or some other parent

body {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
}
spiral blaze
#

oh, is css super important?

spiral blaze
#

ah, im currently learning flask and html right now, do you think i should css next?

#

i heard theres this bootstrap thingy in flask that does things like this? im not really sure

jaunty magnet
#

anyone know differences between django allauth and django rest-auth?

calm plume
calm plume
spiral blaze
#

ah alright, so i heard what bootstrap does is that injects code into html right?

#

i dont think i enough attention to that course

calm plume
#

No, it's just a CSS framework

#

Helps to style different items

spiral blaze
#

ah alright, should i learn js after all these?

calm plume
#

If you want any reactivity (which is good), yes

spiral blaze
#

how do javascript and flask interact?

#

if i have js in the frontend and flask in the backend

calm plume
#

Yes

spiral blaze
#

im looking at the list right now, for web dev it says theres like php, sass, less i guess i do not need to know these yet right

calm plume
#

No

#

PHP is a server side language, but Python works just fine

#

Sass and Less are CSS preprocessors, but they aren't necessary

spiral blaze
#

ah alright, how long does it take to like know flask, css, html enough to make a website?

native tide
#

not long.

#

just paste some tailwind or bootstrap components into templates.

#

replace some variables in the templates for tags

#

{{ somvar }}

#

pass them to the templates

#

return render_template('index.html', somevar=mydata)

#

you're done

#

a day?

#

i mean you can learn x to the nth degree. but its pretty much it

craggy silo
#

hey, my dudes.
is there a api service to get images like this for weather?
i can't implement right now

ivory pumice
#

I hosted a django website at GoDaddy...
Can anyone help me in using smtp at GoDaddy so after submission of form mail will generate for individual...

swift steppe
#

can some one help me with selenium pls assert command

frank shoal
#

Material icons might have some

dusty moon
#

CSS question:
I'm learning about CSS transitions through W3Schools, and they show a transition example with an :hover element.

My question is: how can i direct a transition to different element states? like :focus for example.

grave raft
#

Any idea how can I create a side panel which shows all sub headings of a blog??
Anything related django, jinja, html or js will work
Thanks

swift steppe
#
from selenium.webdriver import Chrome
from selenium.webdriver.common import by   
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions, wait 
from selenium.webdriver.common.by import By 
from selenium.webdriver.common.keys import Keys  

 

PATH= 'C:\Program Files (x86)/chromedriver'
driver = Chrome(PATH) 

 
driver.get("https://google.com/")   

search=driver.find_element_by_name("q") 
search.send_keys("facebook") 

search.send_keys(Keys.RETURN)  
login = driver.find_element_by_partial_link_text("Фејсбук – пријавите се или се региструјте") 
login.click() 
wait = WebDriverWait(driver,5)

input_email=driver.find_element_by_name("email") 
input_password = driver.find_element_by_id('pass')

input_email.send_keys('pera_peric656@gmail.com') 
input_password.send_keys('pera_peric343') 


signinbutton=driver.find_element_by_class_name('_6ltg')
signinbutton.click()

wait.until(expected_conditions.element_to_be_clickable((By.TAG_NAME,'_6ltg')))

errormessage= driver.find_element_by_class_name("_9ay7")



assert errormessage.text =="The email you entered isn’t connected to an account. "

driver.quit() 


#

can some one help

#

why eror

clever needle
#

Hello, does anyone know if its good practice to save images as direct files on my website's file system? I was wondering whether it was better to hash, then store inside of a DB rather than the aforementioned method

vestal hound
clever needle
#

Sha1 or MD5

#

idk I saw something on github about hasing the files for security, but ppl seemed to be okay with it

vestal hound
#

hold up

#

so you store only the hash?

clever needle
#

well no but could hashing be better than other alternatives like base64

#

encoding

vestal hound
#

I don't get it

#

why do you want to store the hash at all?

#

like

#

can you help me understand what you think the purpose of hashing is

clever needle
#

security and ease of change ig

vestal hound
#

how does hashing add to security?

clever needle
#

isnt it better to store hashed instead of raw?

vestal hound
clever needle
#

also isnt there something about seeing if someone has messed with it, like a hacker; like you can tell

vestal hound
#

I feel like that stems from a fundamental misunderstanding of what hashing does for you

#

if you don't mind me saying so

clever needle
#

i dont mind at all. im still learning about how cryptography stuff works

vestal hound
#

maybe I can explain

#

in general, you don't store passwords in plaintext (unhashed)

#

instead, you store their hashes (with some modifications that I can go into later if you want)

#

then

#

when the user sends their password over

#

your app hashes it and compares it with what's in the database

#

this ensures that even if your database was compromised

#

the attacker wouldn't have access to the other accounts

clever needle
#

ah

vestal hound
#

since you can't get back the plaintext from a hash (assuming the hash is good)

#

so, not MD5, which is broken

clever needle
#

so it would be impractical for files to be hashed?

vestal hound
#

that's one use of hashing.

#

another use is

vestal hound
#

I'm coming to that

#

you may see when you download software

#

that the providers also state the expected hash

#

of whatever you're downloading

#

this is so that post-download

#

you can hash the program's files

#

and compare with the expected hash

#

and if they match

#

you know with very high probability that nobody intercepted and tampered with your download, or it just didn't get corrupted over the wire

clever needle
#

oh gotcha

#

so what do you think that I should do instead of hashing?

#

im finding mixed results on onlines searches

vestal hound
#

of storing those images?

#

just to display to users?

clever needle
#

yup

vestal hound
#

you can just store them

clever needle
#

pretty mich

vestal hound
#

on whatever file storage system you have available to you

#

what are you using?

#

like what web framework

clever needle
#

flask

vestal hound
#

hm

#

I don't know how Flask handles these things

#

there's probably an addon for this

#

but in general

#

you want to have a layer of indirection between your request handling code and your dynamic media management code

#

do you know what that means

clever needle
#

no lol

#

ill google it tho

vestal hound
#

basically

#

imagine a situation

#

where you're storing files locally

#

i.e. on the computer that also runs your Flask server

#

right?

#

now say whatever you're developing blows up

#

and you want to scale

#

so now you're running your app on 10 different servers

#

each of which is storing user data on its local filesystem

#

imagine if a user happens to connect to server 1

#

stores some files there

#

and later on on a different computer

#

they connect to server 4

#

and now their files are, from their perspective, gone

#

ideally

#

you build some sort of abstraction around fetching files and store them externally on, like, Amazon S3

clever needle
#

hmm okay ill keep that in mind

#

much thanks though for the help

vestal hound
glad creek
#

Hello folks, I would like some suggestions
I want to build a webapp in which I want to compare various cryptocurrencies prices from different exchange services and than recommend the user to buy the cryptocurrency from exchange service A instead of B.
The issue am having is should I use the API's from these exchange services or should I web scrape it?

calm plume
#

If there's an API, always use the API

#

If there's not, check the robots.txt and terms of service to see if you can web scrape

shadow vine
dusk sonnet
#

Hi, how can i get the first value of a button?
if i have the following values for a button

<button type="submit" name="home" class="button" value="{{ matches[1][0]['name'] }} {{ matches[1][1]['name'] }} {{ matches[0]['start_date'] }} {{ matches[1][0]['price'] }}">{{ matches[1][0]['name'] }}<br> <b>{{ matches[1][0]['price'] }}</b></button>

how can i only get {{ matches[1][0]['name'] }}

#

the current output is like this Everton West Ham United 2021-10-17

#

i wanna be able to only get for example "everton"

trim wolf
#

Hey Everyone!! I want to add Custom Cursor to my Django Website! How can I do so...?

civic crater
civic crater
peak scaffold
#

Hello~

native tide
#

why i am getting this error in django

#
BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = 'django-insecure-2e(@-ilm2ph7sx34c-0^!o4bcjt2#fx^j=l(m$ey@aqe823q62'

DEBUG = False

ALLOWED_HOSTS = ['labwebsitetest.herokuapp.com','127.0.0.1:8000']



INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'whitenoise.runserver_nostatic',
    'django.contrib.staticfiles',
    'lab.apps.LabConfig',
    
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'website.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
``` settings.py file
#
WSGI_APPLICATION = 'website.wsgi.application'


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'


STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/'

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
jaunty kelp
#

hey i wondered that flask servers are not for production deployment. But all my code is now written with Flask, so is there a way to turn this into a webserver which you can use for production deployment and which is very simple? and so that i have not to completly overwrite my code?^^

civic crater
# native tide

Evry thing is fine ig
try changing the debug to true and figure out the issue

native tide
cerulean badge
#

(context django) does doing queryset[:n]
query all rows that queryset requires or the only first n?

civic crater
dusty moon
#

So I can have an animation when I click on a button rather then hover?

fickle garnet
dusty moon
#

How?

civic crater
#

there is an example

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
    <style>
        .btn:hover ~ .change{
            background: red;
        }
    </style>
</head>
<body>
    <button class="btn">Hover</button>
    <button class="change">I m going to Change</button>
</body>
</html>
#

note the tilda(~) used in css

#

This is also possible
.btn:hover + .change

civic crater
dusty moon
#

The + doesn't mean elements that come after?

civic crater
dusty moon
#

Yeah so what do they have to do with transitions?

civic crater
# dusty moon Yeah so what do they have to do with transitions?

just check this now they will have transition

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
    <style>
        .btn:hover + .change{
            transition: .5s;
            background: red;
        }
    </style>
</head>
<body>
    <button class="btn">Hover</button>
    <button class="change">I m going to Change</button>
</body>
</html>
civic crater
dusty moon
#

Yes. How can I effect an element with a transition by clicking on it instead of just hovering on it? Can I specify a transition for each state of an element?

civic crater
dusty moon
#

Yes but how can I tell transition to effect the element with :active instead of :hover?

civic crater
dusty moon
#

Yes. But if have a :hover and an :active? How can I be specific?

civic crater
dusty moon
#

Like keyframes where you can bind it to different elements at different states.

civic crater
dusty moon
#

I'm not home now... Give me an hour.

civic crater
dusty moon
#

K

orchid olive
#

in flask, how can i send an empty parameter?

definition:
@option.route("/<Option>", methods=['GET','POST']
def SetOption(Option):
print(Option)

call:
return redirect(url_for("option.SetOption",Option="")

if Option = "" flask will not find a match and triggers error 400

second call, this will works
return redirect(url_for("option.SetOption",Option="x")

how can i send a empty Option?

orchid olive
#

i solve it, thanks

cerulean badge
#

is the django-ajax-select docs outdated? i am finding it hard to follow
any better package?

jaunty kelp
broken harness
#

with Django, how do I get my website to appear? I have it at the point where my website says "IT WORKS!" but the actual website isn't loading. What do I need to do?

dense slate
#

In Django+Graphene, my ArrayField looks like ["{'key': 'value'}"] but when I print the arrayfield in a loop, each element is {'key':'value}.

When I return this via graphql to my React front-end, each dict is instead a string so something like "{'key':'value'}". Is there some way to return these as actual dicts? I can't simply parse it because they are returned with double-quotes.

fickle garnet
#

but yea, your flask code is okay so long as its not inviting trouble

#

think about things like old school SQL injection

proven barn
#

Hello guys

So I'm working on a django web application. I wanted to know how can I make a random route on button click. Example I click a html button and it redirects me to a url which is not defined in urls.py but still is a valid page.

#

See now example I click a button, and the randomly generated url is /kljnsdfkjlnoasdjf

#

I need django to register that url on the go

#

rather than me going and routing the url manually

lilac solar
#

@proven barn Have you tried using a variable for the whole randomly generated url? something like path('/<slug:key>', ...) this would go to a single view from which you can decide what to do with it?

glacial yoke
#

Hey, so I've uploaded my django site to a server, and set everything up with apache, but for some reason my server just can't see static files.
I've tried everything, it just doesn't seem to work, at all
And before you say anything, yes I have setup the config files and etc., they all point towards my static folder which is situated like this:
/var/www/html/mysite/mysite/static
Someone, help me, please

carmine cipher
#

Hello guys!I want to start a project on visual studio code using html ,css,JavaScript,nodejs,Git . Can someone explain to me what path should follow on this IDE to get there?

static stone
#

which port i can host my app

static stone
#

is there free hosting servers?

boreal garden
#

So I have created a sidebar with django, the only issue is that it overlaps the text on the pages so you can't really see the words. Here is the CSS I wrote and is there any way to fix this problem?

   .sidenav {
            height: 100%;
            width: 160px;
            position: fixed;
            z-index: 1; 
            top: 0;
            left: 0;
            background-color: #111; 
            overflow-x: hidden; 
            padding-top: 20px; 
        }

        .sidenav a { 
            padding: 6px 8px 6px 16px;
            text-decoration: none;
            font-size: 25px; 
            color: #818181; 
            display: block;

        }


        .sidenav a:hover{  
            color: #f1f1f1; 
        }


        .main{
            margin-left: 160px;
            padding: 0px 16px;
        }
weak mango
#

Hello, I am trying to host my flask web application but I can't get it to work.

#

Can someone experience with hosting try to host it for me and see if it works for you?
I am thinking it's maybe problem with my code but it runs totally fine on my local machine.

crisp marsh
#

Hey everyone i just needed a suggestion regarding my website http://virathshuklla.com/
That is it good enough as a portfolio website or not??

drowsy mist
#

Hello everyone, I have a question. What requirements do I need to deploy an app with flask and jinja? 🤔

night tapir
#

Hey, I am thinking about learning python to build a website for a business idea and im wondering what the max i can do (web development wise) by using only python. Is it possible to get a full website up and running using only python? thanks.

calm plume
#

You can never do it with "only" python. You'll need HTML and CSS, and probably some JS too. But the whole backend? Absolutely.

night tapir
calm plume
#

I doubt you can use Python with Wix

#

And frontend is just the user facing side, the buttons, the links, the stuff that looks pretty

night tapir
calm plume
#

I doubt it. No site builder will ever get you the level of customization you need.

clever needle
#

How do people usually write good CSS code? Is there like a specific tool that people use? e.g side by side preview type thing

night tapir
calm plume
#

You need HTML and CSS, although you could learn the basics in even a week, and JS isn't mandatory, at least to start, but no, there's no "single language" you could use.

night tapir
calm plume
#

The MDN docs for HTML and CSS are pretty good

night tapir
proven barn
#

Is it possible if you can help me with an example so I can understand it better?

tepid lark
#

check out htmx for basic interactivity

tepid lark
autumn birch
#

wsgi flask apache2 ubuntu
Internal Server Error

ModuleNotFoundError: No module named 'init',...```

Is it correct to put init.py and app.wsgi in same folder? 

app.wsgi```py
from init import app as application
import sys
sys.path.insert(0, '/var/www/html/')```

init.py```py
from flask import Flask, render_template
from logging import FileHandler,WARNING
app = Flask(__name__, template_folder = 'template')
@app.route('/')
def hs():
    return render_template('index.html')
file_handler = FileHandler('errorlog.txt')
file_handler.setLevel(WARNING)```

apache2 conf
```<VirtualHost *:80>
ServerName www.example.com

ServerAdmin webmaster@localhost

WSGIScriptAlias / /var/www/html/app.wsgi
<Directory /var/www/html>
Order allow,deny
Allow from all
</Directory>```
lapis stratus
#

Hi, I have an error message of the ImportError I've pulled a django project from github but after I activated the env ,installed packages using python -m pip install -r requirements.txt and do python manage.py makemigrations it says that ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? is there anyone encounter this?

gentle ingot
#

Im trying to dynamically change the background using flask based on what is selected from a dict. Can anyone help? Ive tried this background-image: url("{{url_for('static', filename='/img/{{holiday}}.jpg')}}");

tepid lark
native tide
#

I am getting the result here <b><span id="smiles_container2"></span></b> and i want to get the out put in

 <input type="text" placeholder="Enter the Solute Molecule here" name="solute" id="smiles_container"><br> <br>
```                                                                how can i do this
lapis stratus
#

tried to pip install Django but already satisfied

#

checked the pip freeze as well can see the lib listed on it

umbral orbit
mild matrix
#

Do we need to learn js

#

Or python can do everything

#

I want to use python and it's libraries and MySQL only

gentle ingot
#

Can i use a variable for css? I want my background to change colors based on what webpage the user is on

regal fossil
#

hi there I was trying to extend user model so user can register with email instead of password but am getting error when i try to create superuser
here I asked a question of stackoverflow please look at this.
https://stackoverflow.com/questions/69611971/valueerror-field-id-expected-a-number-but-got-demogmail-com

regal fossil
lilac solar
proven barn
#

Yup got it

#

Thanks!

hoary brook
#

I am working on a Flask project but I am struggling with setting up the relationships between my models. I am getting an error saying I can't use multiple foreign key paths to link my tables. Do I need to use a join table for this and if so, how would I go about setting that up?
Below is a diagram of what relationship I am trying to accomplish. Any help is greatly appreciated, feel free to @ me when you answer.

raw compass
hoary brook
#

I should have specified. I'm using SQLalchemy, yes.

#

My models are set up, it's just the relationships I am struggling with since it's not just a single link, but multiple e.g. between User and Project.

#

Before I was using a workaround with a helped function that would store the ID of the current project as an integer in my User model, but that means I have to do a lookup my ID of all my Projects to get the right one if I actually want to get the data stored inside.

raw compass
hoary brook
#

The current project is the project the frontend currently displays. The user selects a project in their projects page and the dashboard, kanban board etc. will show only the data from that project.

raw compass
native tide
# gentle ingot Can i use a variable for css? I want my background to change colors based on wha...

Custom properties (sometimes referred to as CSS variables or cascading variables) are entities defined by CSS authors that contain specific values to be reused throughout a document. They are set using custom property notation (e.g., --main-color: black;) and are accessed using the var() function (e.g., color: var(--main-color);).

hoary brook
#

Do you mean post them here? Sure

#
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password = db.Column(db.String(50), nullable=False)
    current_project_id = db.Column(db.Integer, nullable=False, default=0)
    projects = db.relationship('Project', backref='owner', lazy=True)

    def __repr__(self):
        return f"User('{self.username}', '{self.email}')"
        

class Project(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    description = db.Column(db.String(300), nullable=False)
    owner_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    issues = db.relationship('Issue', backref='parent_project', lazy=True)
    kanban_cards = db.relationship('KanbanCard', backref='parent_project', lazy=True)

    def __repr__(self):
        return f"Project('{self.title}')"


class Issue(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    status = db.Column(db.String(50), nullable=False, default='New')
    parent_project_id = db.Column(db.Integer, db.ForeignKey('project.id'), nullable=False)

    def __repr__(self):
        return f"Issue('{self.title}', Parent project ID: '{self.parent_project_id}')"```
#

As you can see I currently have my workaround in place with current_project being a regular int instead of a reference to the actual current project

native tide
#

you don't have any hashtables. m2m tables

#

i..e project_issue

hoary brook
#

I am very new to using databases, I've only had to deal with the regular o2m relationship before

native tide
#

user_project

#

ok. its cool

#

often you need another table. with the id of each record in a 3rd table to keep many to many relationships

#

user_project

#

user_id, project_id

hoary brook
#

Is that the join table? I heard about it but I'm unsure how to properly implement it

native tide
#

then you can use sqlalchemy to backref them

#

so if you storing one relationship. you just need 1 id. so you can store it on the same table as a foriegn id.

#

but if you need a list of tihngs. then you often want another table

#

that is just the id of the 2 things you want to relate

#

it takes years to get your head around it if you're not natural at it. and due to different ORMs etc you can get confused. also if you don't do it for a year you forget a lot

#

but it's just a look up table

hoary brook
#

So do I have to do something like this?

user_projects = db.Table(
db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False),
db.Column(db.Integer, db.ForeignKey('project.id'), nullable=False)
)```
native tide
#

yes

#

then somethign like this

#

roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users'), lazy='dynamic', cascade="all")

#

in the model

hoary brook
#

I don't really understand that last part to be honest

native tide
#

so my model. need to have teh relationship plumbed in

#

class User(db.Model, UserMixin):

hoary brook
#

What does the Role stand for?

native tide
#

projects = db.relationship('Projects', secondary=user_projects, backref=db.backref('users'), lazy='dynamic', cascade="all")

#

sorry i was pasting from my own model as example. that would be more like it

hoary brook
#

Ah, okay. And cascade deletes the projects when the user is deleted?

native tide
#

only if you tell it to

#

cascade="all,delete"

#

so dependso n the relationship

#

and if you want it to

#

i.e. you might have load sof user notificatoni setc and shit

hoary brook
#

I understand. So, with this table does every project only have one owner, or does it have multiple now?

native tide
#

so if that user leaves. delete their crap

#

the projects_owner table can do many 2 many

#

and you have bound the relationship with the ORM to your model

#

so it will now fetch the records auto

#

wihout you having to do code to update etc. or do joins

hoary brook
#

How would I go about making sure a project only has one owner or that a user only has one current_project? (they can have multiple projects, but only one selected at a time)

#

As far as I understand this only handles Users having Projects

native tide
#

create a owner column on teh project table? with a foreign key to the owner

hoary brook
#

Ah okay, so this is where the FK comes in.. Got it.

native tide
#

ye think about the relation first

#

then do either a mapping table or whatever they are called with an id for each.

#

or just do a column with a key you can join on

hoary brook
#

And when I want to limit the m2m table to o2m, I use the uselist=False parameter?

native tide
#

to be honest. understanding that. is the only thing that separates a front end dev from a back end one.

hoary brook
#

Well, I'm really thankful you helped me this much

#

I feel like I have a basic understanding now and can maybe do some research on my own now that I know the general idea

native tide
#

ye. it will set you apart frmo 75% of other devs. and its relatively simple concept

hoary brook
#

I just wanted to combine creative frontend stuff with my previous Python knowledge, so I thought I should give it a try

proven barn
#

Hello guys

So I am unable to access the static files. The thing is that when I have direct routes, example- https://website.com/first/ I am able to fetch the static files. But when I add another route before first example- https://website.com/second/first/ then the static files are not leaded. Why is that so? And how can I fix it?

lyric trench
#

anyone that can help with flask just to send an email attachment with the help of gmail api

proven barn
#

It's a django framework btw

mellow citrus
#

can anyone please help me related to an api project i created in python how can i manage project dependencies.. like in node apps we have a package.json file how we deal in python ????

frank shoal
#

you've got a few options. The vanilla way is using requirements.txt and running pip install -r requirements.txt

#

I prefer to use poetry since it has a nice cli

dusty moon
#

Weird question: what was used in before JavaScript became a thing?

frank shoal
#

nothing

#

Actually, Java

dusty moon
#

So Java was used in web development before JavaScript became a thing?

frank shoal
#

it all started in the mossaic browser, then netscape came up with javascript.

dusty moon
#

I see.

#

Cool.

crisp marsh
frank shoal
#

fun fact: Flash uses a subset of javascript called ActionScript. (It's actually ECMA3)

dusty moon
#

So people only used HTML, CSS or CSS wasn't a thing either?

frank shoal
inland oak
# dusty moon So people only used HTML, CSS or CSS wasn't a thing either?

lets see.
CSS date release: December 17, 1996
HTML date release: 1993

Before CSS, nearly all presentational attributes of HTML documents were contained within the HTML markup. All font colors, background styles, element alignments, borders and sizes had to be explicitly described, often repeatedly, within the HTML

heh, between 1993 to 1996 people were forced to write all styling parameters only directly to html ;b

dusty moon
#

So, inline styles were talking about?

wraith cypress
#

Django Roadmap

I've been having trouble finding a good roadmap for python Django developers, any good suggestions?

wraith cypress
#

it's been the second time I ask for a roadmap and provided a course XD. I need a roadmap to know all of what's needed for a django developer to be known as an expert

#

I bet every new self taught django dev knows dennis ivy, he's a GOAT on this

#

very informative and for experts

#

is there a similar one for django devs?

autumn birch
frank shoal
#

when a from import starts with a ., it means import from the current package

autumn birch
#

Sorry i fixed it
app.wsgi

import sys
sys.path.insert(0, '/var/www/html')
from init import app as application```
#

the .init is unnessary

#

But the line order is important

#

Thank you so much

rain wasp
#

I facing issues while uploading static file in django app on heroku
Anyone please help

frank shoal
#

I used <form autocomplete="off"> on my form. Why are my inputs still auto-filling the username and password? (firefox)

#

it works in chrome. Sigh

wintry yew
#

How to make website

frank shoal
#

static or otherwise?

proven barn
#

Hello guys

So I am unable to access the static files. The thing is that when I have direct routes, example- https://website.com/first/ I am able to fetch the static files. But when I add another route before first example- https://website.com/second/first/ then the static files are not leaded. Why is that so? And how can I fix it?

regal fossil
#

I have two forms one for User and one for user Profile
after successful form validation for both form user is created and profile object also created (i am using signal post_save) .

user = register_form.save()
profile_form.instance = user.profile
user.profile = profile_form.save()
user.save()

profile form data is not inserted into profile of user but its get created. when
register_form.save() called.

drowsy mist
#

Hello everyone, I have a question. What requirements do I need to deploy an app with flask and jinja? 🤔

frank shoal
#

I'd use gunicorn

olive tiger
drowsy mist
drowsy mist
drowsy mist
#

I do not know if with a page made with flask you can do that.

#

Sorry my english is not very good 😆

olive tiger
drowsy mist
#

Ok, thanks you

proven barn
#

Hello guys

So I am unable to access the static files. The thing is that when I have direct routes, example- https://website.com/first/ I am able to fetch the static files. But when I add another route before first example- https://website.com/second/first/ then the static files are not leaded. Why is that so? And how can I fix it?

#

guys any idea with django framework?

native tide
#

Hi

#

i need some help

#
const game = {
    elements: {
      progressLabel: document.querySelector("#progresslabel"),
      progress: document.querySelector("progress#file"),
      levelBtn: document.querySelector("#btnLevel")
    },
    level: parseInt(localStorage.getItem("level") ?? 1),
    clicks: parseInt(localStorage.getItem("clicks") ?? 0),
    multiplier: parseInt(localStorage.getItem("multiplier") ?? 1),
    prestige: 0,
    rebirth: 0,
    requiredClicks() {
      return game.level * 250 + game.multiplier * 50;
    },
    nextLevel() {
      return parseInt(game.level + 1);
    },
    updateProgress() {
      game.elements.progress.value = game.clicks;
      game.elements.progress.max = game.requiredClicks();
    },
    levelingEnabled() {
      game.elements.levelBtn.disabled = game.clicks < game.requiredClicks();
    },
    updateStorage() {
      ["level", "clicks", "multiplier"].forEach((key) => localStorage.setItem(key, game[key]));
    },
    buttonFunctions: {
      click() {
        game.clicks += game.multiplier;
        console.log("h")
        game.updateProgress();
        game.levelingEnabled();
      },
      levelUp() {
        console.log("level up");
        ++game.level;
        game.clicks = 0;
        game.updateStorage();
        game.levelingEnabled();
      },
      menu() {
        console.log("menu");
      }
    }
  };
  
  game.elements.progressLabel.textContent = `Progress to Level ${game.nextLevel()}`;
  game.updateProgress();
  
  document.querySelector(".btn-wrap").addEventListener(
    "click",
    (e) => {
      if (!e.target.matches("button, button img")) return;
      const btn =
        e.target.tagName === "BUTTON" ? e.target : e.target.parentElement;
      game.buttonFunctions[btn.dataset.func]();
    },
    { passive: true }
  );
  
#

okay so

#

progress.max is not a number (NaN)

#

game.elements.progressLabel.textContent = Progress to Level ${game.nextLevel()};

#

its being set there

#

and it says nan

#

?

#

can someone help

astral pagoda
#

flask question

What is profile 'profilepicture' = to in the routes.py example? And in the register function do I need to commit profile picture from the database or is it automatically a commit ?

routes.py in register function
picture = request.files['profilepicture']
models.py`

profilepicture = db.Column(db.LargeBinary, nullable=False, default='default.jpg')

somber hull
#

https://pypi.org/project/wtforms-validators/#Alpha Why can't I use this validator method in my Flask app anymore? It just says:
ImportError: cannot import name 'Alpha' from 'wtforms.validators' (C:\Users\magnus\AppData\Local\Programs\Python\Python39\lib\site-packages\wtforms\validators.py)

I have installed it via pip install wtforms-validators... Might it be outdated?

halcyon dragon
#

Hi anyone know how to make a eccomerce website what language I should use all packages/imports/frameworks I should use or would you send me full video tutorial because I have no clue I’m pretty fluent in most of the big languages JavaScript,python,java are my main ones so any and all tutorials will do if I need to learn a new language I’m happy to do so so please help me out

cerulean remnant
#

and not: from wtforms.validators import Alpha

somber hull
cerulean remnant
somber hull
cerulean remnant
cerulean remnant
cerulean remnant
native tide
cerulean remnant
quasi atlas
#

Why does my <img show red and why does it not work? what mistake am i doing that is not showing? pls any help would be appreciated

cerulean remnant
#

do you see anything wrong?

somber hull
# cerulean remnant send the code you have rn

I solved it with using some python code after the sumbit.onvalidation() but looks like reloading VSCode made wtforms_validators work for some reason. Im gonna test it if it works now If i remove my .isalpha() code

native tide
#

i think ik whats wrong

#

you need

#

wait

quasi atlas
#

no 😅

native tide
#

a normal img thing is

quasi atlas
native tide
#

<img />

#

i think

cerulean remnant
native tide
#

ending tag

cerulean remnant
quasi atlas
native tide
#

oh yeah

#

i see it lol

#

u need to close the a tag

cerulean remnant
#

it should be```html
<a href="link"> <!-- you are missing the > -->
<img src="link">
</a>

somber hull
#

@cerulean remnant It did work now 🙂 Do you know how I can set the value in the StringField to be '' ?

quasi atlas
astral pagoda
#

Sorry for posting twice but in flask python question I am trying to upload a image from the database

What is profile 'profilepicture' equal to in the routes.py example below? And in the register function do I need to commit profile picture from the database or is it automatically a db.commit ?

routes.py in register function
picture = request.files['profilepicture']
models.py

profilepicture = db.Column(db.LargeBinary, nullable=False, default='default.jpg')

cerulean remnant
#

i didn't even know it existed

thorny shadow
#

<h1>mother fucker<h1> not working helpppp

thorny shadow
somber hull
quasi atlas
#

i think he is a troll

thorny shadow
thorny shadow
cerulean remnant
lavish prismBOT
quasi atlas
cerulean remnant
thorny shadow
thorny shadow
#

think soooooooo

#

i need to

#

youtube

#

or google

quasi atlas
#

definitely a troll

#

dont waste my time

cerulean remnant
thorny shadow
thorny shadow
astral pagoda
#

Can someone answer my question?

thorny shadow
#

plsssssss

cerulean remnant
thorny shadow
astral pagoda
#

do you want me to post it for the 3rd time

#

?

thorny shadow
thorny shadow
astral pagoda
#

flask python question I am trying to upload a image

What is profile 'profilepicture' equal to in the routes.py example below? And in the register function do I need to commit profile picture from the database or is it automatically a db.commit ?

routes.py in register function
picture = request.files['profilepicture']
models.py

profilepicture = db.Column(db.LargeBinary, nullable=False, default='default.jpg')

astral pagoda
#

Its where you keep your routes

thorny shadow
#

in it

astral pagoda
#

well if you don't know don't anser

thorny shadow
thorny shadow
thorny shadow
cerulean remnant
astral pagoda
#

followup question brb just need to post a error I am getting

cerulean remnant
#

ping me btw

astral pagoda
#

nevermind that is it

thorny shadow
# astral pagoda followup question brb just need to post a error I am getting
from playsound import playsound
playsound('helllo.mp3')
a=(input('type code:'))
if a == 'help':
    print('1 =  google')
    print('2 = text into word')
    print('3 = play song')

else:
    print('type ?Help')
    
a2 = input('type command:')
if a2 == '1':
    a3 = input('type website name:')
    import webbrowser
    webbrowser.open(a3)

else:
    print('wrong statement')

if a2 == '2':
    text=input('type here:')
    from gtts import gTTS
    tts=gTTS(text)
    tts.save('byee.mp3')
    from playsound import playsound
    playsound('byee.mp3')

else:
    print('wrong command')

if a2 == '3':
    from playsound import playsound
    playsound('song.mp3')
    print('playing song.')
    print('playing song..')
    print('playing song...')
    print('playing song....')```
cerulean remnant
thorny shadow
cerulean remnant
thorny shadow
cerulean remnant
#

interesting

#

alr

thorny shadow
cerulean remnant
#

sad

thorny shadow
thorny shadow
#

heekki

#

@kind steppe hiiiiiiiiiiiiii

#

whoppy

#

whoopty

#

f

#

fuck

#

!pypi gtts

lavish prismBOT
#

gTTS (Google Text-to-Speech), a Python library and CLI tool to interface with Google Translate text-to-speech API

shy bane
# thorny shadow ```print('hello i am bot if you want to use my commands type help') from playsou...

print('hello i am bot if you want to use my commands type help')
from playsound import playsound
playsound('helllo.mp3')
a=(input('type code:'))
if a == 'help':
print('1 = google')
print('2 = text into word')
print('3 = play song')

else:
print('type ?Help')

a2 = input('type command:')
if a2 == '1':
a3 = input('type website name:')
import webbrowser
webbrowser.open(a3)

elif a2 == '2':
text=input('type here:')
from gtts import gTTS
tts=gTTS(text)
tts.save('byee.mp3')
from playsound import playsound
playsound('byee.mp3')

elif a2 == '3':
from playsound import playsound
playsound('song.mp3')
print('playing song.')
// set time out for audio when end
then print('end')
else :
print ('wrong command')

shy bane
#

@thorny shadow cool

thorny shadow
thorny shadow
shy bane
#

it's error ?

thorny shadow
#

one min

loud roost
#

Hi, I have a question.
Suppose we want to use face recognition in a mobile application using Python language, what library do we use or how do we link these both together?

static stone
#

what wsgi production free servers can i use?

frank shoal
#

heroku?

#

that's a host with a free tier.

#

if you're looking for a production server you can install yourself, gunicorn is my go-to

dusk sonnet
#

Hey i have a question about flask.

Im making a betting simulator web-app where i get upcoming soccer games and results from 2 API's. And after im done my project i will most likely use Heroku to host it. My question is when i do flask run and server is open does the code update? for example when the server is open and lets say a game has finished and the results have come out...does the server automatically update? or do i need to rexecute the code by restarting the server?

clever needle
#

if so all you have to do as the user is refresh the page? as long as the backend code is correct

clever needle
#

np!

orchid olive
#

is there a way to create a bootstrap navvar with menus accesible by user-rol?
where can i get a simple example?

clever needle
#

w3schools

#

what is user-rol btw?

orchid olive
#

a menu access by rol,
common user see 1 menu
expert user see 3 menus includin common user rol
admin user see 4 menus
but common user cannot see expert or admin menus

clever needle
#

you need to control that with web templating langs dont you?

orchid olive
#

could be, but ... is it possible by using only 1 template? i really do not like to create 200 templates

#

got it?

clever needle
#

no like web templating "languages"

#

like flask, django, etc

orchid olive
#

what are you doing in web-development???

clever needle
#

?

orchid olive
#

python web dev = flask, bootstrap and dyango (and html)

clever needle
#

and?

orchid olive
#

"no like web templating ""languages"" "

clever needle
#

flask is not python

orchid olive
#

what do you mean wiht that?

clever needle
#

google web templating languages

orchid olive
#

this is python channel for flask or django

clever needle
#

flask and django are web templating "languages"

#

if you dont trust me google it

orchid olive
#

btw, thank for the link, good expamples with bootstrap

#

that is exactly my point

clever needle
#

So in your back end you can pull the account type, whether it is a common user, expert, etc

orchid olive
#

that is the problem i trying to fix

#

well, thanks, nice chat, cya later

clever needle
#

then with Jinja (part of flask), you can do
{% if account.type is 'expert' %}
Or something similar to this if you want

#

like if statements in the HTML code, done by jinja

orchid olive
#

that is in the form, the change i need in in the base

#

bye man!

tepid lark
#

Do I use Flask or Django. ohhh

#

Or Pyramid. lol. Ultimately I think they're all as capable as each other in good hands, but I'm working with a lot of non crud data sources!

#

Django has the nicest experience so far, but I've run up against some stuff with our special snowflake requirements.

native tide
#

can anyone send me some reference material for html css and js?

#

thanks

valid pelican
#

Hey guys

#

How much time would take to learn react js

native tide
#

I want to do this visualization as shown in the figure. as i change the molecules on the left side and on the top it should change the middle showing number iteractively using javascript. I know this can be done using d3.js but can anyone share similar examples

wintry yew
#

How to make a website

#

I'm new

native tide
wintry yew
native tide
wintry yew
native tide
wanton storm
#

I think he wants to ask how to display site ongoogle

#

You can make site either with HTML CSS JS

#

Or use a framework like React

#

And then buy a server and domain for webpage

#

And then pay a monthly fee to host it

swift elm
#

Hey how can I send the request made to a particular endpoint in flask to a list (or) a queue so that I can process and send response one by one.

Goal : Is to build a unique file allocation endpoint will be running windows(don't ask to change to linux its requirement). Where user will hit the endpoint and gets
files. But the file have to be unique one consider all the files are maintained in a single folder. I need some mechanism or tools that can help me in this.

patent abyss
#

hey all. I've finished a django course and have been exploring it more by creating a project of my own. However, it takes me forever to finish things. I keep thinking that what takes me days and weeks could be done by a senior in two hours, and get really discouraged.
I just want to know, is this normal? was that how it was for you when you were new to django? and also, any tips for making me faster?

pallid lily
#

summary of it strong foundation of python language will help you save lots of time and code try vising list of comprehension, lambda, decorators, eval(), compile() etc...

jovial cloud
# swift elm Hey how can I send the request made to a particular endpoint in flask to a list ...

Check out background jobs on Miguel grinberg's blog for queueing tasks and running them in the background
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xxii-background-jobs

This is the twenty second installment of the Flask Mega-Tutorial series, in which I'm going to tell you how to create background jobs that run independently of the web server.For your reference,…

carmine cipher
#

Hello guys!I want to start a project on visual studio code using html ,css,JavaScript,nodejs,Git . Can someone explain to me what path should I follow on this IDE to get there?

patent abyss
# pallid lily summary of it strong foundation of python language will help you save lots of ti...

Thanks for the help! I'll make sure to spend some time brushing up my python knowledge!
One more question: how do you make designing easier? I mean deciding what view should do what and what things should be in the same page and what should be separate? I feel like this is one of the things that I spend too long on, so it would be great if there were resources I could read or things I could practice.

pallid lily
patent abyss
#

hmmm, but it does affect the back-end too, right?

pallid lily
#

nop

#

try to copy cat certain platforms with same features you want to create and later on implement your own design to the frontend

native tide
#

hi

#

i need help

#

it says NaN

#

and i get that error

tropic prism
#

i'm not familiar with any of this, but it appears that it might have something to do with game.nextLevel

tepid lark
# native tide hi

what's the value of requiredClicks() when you're trying to set the progress element?

native tide
#

Hello is this the correct chat if i need help with a data scraping script>

#

?

dull isle
#

hi im trying to develop some code that sends a request to https://md5hashing.net/hash/sha256/ along with a SHA256 hash. i want it to search through the parsed html and retrieve the "unhashed" value--if it exists.
here is my code: ```py
import requests # !pip install requests
from bs4 import BeautifulSoup as bs4 # !pip install beautifulsoup4
from hashlib import sha256

def checkHash(sha):
url=f"https://md5hashing.net/hash/sha256/{sha}"

hashPage=requests.get(url)
hashSoup=bs4(hashPage.content, "html.parser")

result=hashSoup.find("span", id="decodedValue").text

return result

if name=="main":
sha="cf80cd8aed482d5d1527d7dc72fceff84e6326592848447d2dc0b0e87dfc9a90" # hash of "testing"

print(checkHash(sha))
#

however, hashSoup's body only contains a script doing some kind of JSON query

<body>
  <script type="text/javascript">
   __meteor_runtime_config__ = JSON.parse(decodeURIComponent("%7B%22meteorRelease%22%3A%22METEOR%401.5.4.2%22%2C%22meteorEnv%22%3A%7B%22NODE_ENV%22%3A%22production%22%2C%22TEST_METADATA%22%3A%22%7B%7D%22%7D%2C%22PUBLIC_SETTINGS%22%3A%7B%22stage%22%3A%22production%22%2C%22secure%22%3Atrue%2C%22ga%22%3A%7B%22id%22%3A%22UA-46347216-1%22%7D%7D%2C%22ROOT_URL%22%3A%22https%3A%2F%2Fmd5hashing.net%22%2C%22ROOT_URL_PATH_PREFIX%22%3A%22%22%2C%22DDP_DEFAULT_CONNECTION_URL%22%3A%22https%3A%2F%2Fmd5hashing.net%22%2C%22appId%22%3A%221yyb8dxdjzh9kehs7f7%22%2C%22autoupdateVersion%22%3A%2201a99ac41f6328d0b161779bb728ca366cf4223d%22%2C%22autoupdateVersionRefreshable%22%3A%227807a4994675d2b6b87126e81a90597e65f93071%22%2C%22autoupdateVersionCordova%22%3A%22none%22%7D"))
  </script>
  <script src="/86a575c16d520b06dd112d530721e721a820067c.js?meteor_js_resource=true" type="text/javascript">
  </script>
 </body>
#

please ping me if you know how to either wait for the JSON query to update the page or execute it from Python...

lilac solar
gaunt belfry
#

Is there anyone who know to make a dashboard with all features and connected to my bot. Please ping me if someone replies

cerulean vapor
#

we do not allow recruitment on this server. Stop.

open forum
#

Recruitment is not allowed on this server, as you've already been told.

#

You're not going to get another warning.

native tide
#

How can I handle two different domains on one website in the best way? My problem is quite simple and I thought it was easy to solve with a URL redirect until i found out that DNS cannot resolve specific pages of a website. So here is the deal:

  1. I have a website running at www.company.com
  2. The website has a special product route at www.company.com/product
  3. The company just bought www.product.com and wants it redirect to www.company.com/product

Now I thought I could identify the root domain with:

print(flask.request.url_root)  
print(flask.request.headers['Host']) 

And then redirect it to the corresponding route. But now what if a user trys to go to www.product.com/abc? I cannot check for all hundreds of www.company.com routes if the root domain is product.com

There must be an easier way to solve this but i am unable to think of a better way to do this. Any suggestion is appreciated

gaunt belfry
#

Someone please answer me also

fossil pond
#

Hey guys! When I add app_name = 'main' to urls.py I get this error: "Reverse for 'contact' not found. 'contact' is not a valid view function or pattern name."

#

I need reverses to use my other views which use ListView and DetailView

#

How do I fix this?

fossil pond
#

Nvm stupid doubt. Lesson to learn: don't blindly follow tutorials because they have different settings applied.

orchid olive
#

could somebody help me with my code?

source bin/activate
export FLASK_APP=test.py
export FLASK_ENV=development
export FLASK_DEBUG=1
flask run --host=0.0.0.0

import os
from app import create_app
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
if name=='name':
app.run(port=2021)

it always runs on port 5000, it ignore command "port=2021"

orchid olive
#

thanks, i just have started the project as usual

wooden ruin
modern pivot
#

Hi, flask dev here ? 🙂

warm igloo
#

Like, is a flask dev here, or the Flask dev here?

modern pivot
#

It doesn't matter as long as someone can help me x)

#

So, I start a Flask project :

#
  from flask import Flask

app = Flask(__name__)
if __name__ == "__main__":
    app.run(
        debug=True,
        port=3000
    )
#

I don't know how to link the app.run () and routes in /controllers/XXX

#

my __init__.py

from . import controllers
pallid lily
#

or from controllers.dbscan import thing

modern pivot
#

It doesn't work

#

My home.py

from flask import render_template

from main import app

@app.route("/")
def home():
    return render_template('/home.html')
#

Error : 127.0.0.1 - - [19/Oct/2021 23:10:10] "GET / HTTP/1.1" 404 -

native tide
#

does anyone know why this wont autoplay html <audio src="./song.mp3" autoplay="autoplay" loop="loop"></audio>

indigo kettle
#

Note: Chromium browsers do not allow autoplay in most cases. However, muted autoplay is always allowed.

twilit needle
#

guys how do you do server side redis sessions with fastapi?

night tapir
#

Hey guys, I was wondering about the web service "webflow". I just found out that you can export the website you build to only code and im wondering if I could just build a website through a website builder, export the code and use that code as my front end website code to keep me from having to learn JS,HTML,CSS,etc

indigo kettle
#

kind of?

#

If you're using something like django, you want to display data from a database and to do that you need to understand how the templating engine works and you need to go in and edit the html and add those things in

#

You'll probably need to use forms and so you'll want to send forms to the frontend as well

night tapir
#

im really stuck lol I have a really good idea for a WebApp business but as far as coding I only know a bit of python. And I dont have thousands to pay somone to do it for me

indigo kettle
#

trying to build a website without knowing the basics of html,js,css sounds very hard

#

I wouldn't bet on it

night tapir
#

Cause like, Ive build plenty of websites with wix and such and its not a problem... I just wounder how it will work with somthing like this and what all the downsides are

indigo kettle
#

I think the time spent learning web languages would be a much better time investment than trying to figure out how to frankenstein a wix site code output into a python backend

#

html/css are very simple

night tapir
indigo kettle
#

Until you want to get super fancy and build apple's landing page or something

#

That is an understandable worry

#

It will not take you that long

#

reactjs is harder

#

but if you want to build something dynamic and you need that single page app feeling then it may be worthwhile doing that as well

night tapir
indigo kettle
#

I've built sites without a frontend framework and it can get messy pretty fast. Using something like react or vue makes things much more manageable

#

I think you should just start building something with django and you'll be forced to learn on the way

night tapir
indigo kettle
#

I think that sounds just fine. Follow some django tutorials and then build something that you want to build

indigo kettle
#

you're welcome!

strange parrot
#

What can I use for reading dynamic websites that will do it fast?. With selenium I have to wait for 2 seconds to load me 50 elements

native tide
#

when i right click to open with live server no image comes

#

can anyone help

swift elm
#

any idea about that ?

#

its running in windows

jovial cloud
chilly falcon
#

code

class OrderItemModelSerializer(serializers.ModelSerializer):
    total = serializers.SerializerMethodField('get_total')
    
    class Meta:
        model = OrderItem
        fields = ('id','order_quantity','medicine_id','order_id','rate','total')
    
    def get_total(self,obj):
        return self.order_quantity*self.rate

error

#

can anyone help

#

it has order_quantity in it but it says there is no other quanotity

#

quantity*

lilac solar
#

@chilly falcon what does the OrderItem model look like?

swift elm
# jovial cloud What's the error message? Are you running the redis in wsl?

yes I'm running redis in wsl but

import rq
queue = rq.Queue('file-allocation-process', connection=Redis.from_url('redis://'))
job = queue.enqueue('common.queue_task.perform_task')
print(job.get_id())```

when i run this program I'm getting 

`redis.exceptions.ConnectionError: Error 10061 connecting to None:6379. No connection could be made because the target machine actively refused it.`
#

can't we connect to program running in wsl ?

chilly falcon
jovial cloud
somber hull
#

Anyone knows if Flask-Login is still legit to use? Or are there better alternatives for handling user auth in Flask nowadays? 🙂

patent abyss
# lilac solar When you say design, do you mean visual design or designing your python code to ...

I meant it being maintainable and readable, but also deciding where to do what. for example lets say I have a page where people can log some symptoms to track them, but all symptoms are in categories. would it be better to have one form per category in a separate page, or just have them all in one place? These sort of questions are what I mean...I think part of it also comes from the fact that I dont know frontend so I dont know the possibilities there are....but Im not sure if that is all

gaunt belfry
#

Is there anyone in this servers who can make a dashboard for bot

#

Please ping me if anyone replies

limpid pivot
#

i have some query on selenium can anyone help?

swift elm
native tide
#

Hi I am having problems with importing stuff on my Flask project, this is the error shown:

Traceback (most recent call last):
  File "C:\Users\Backup\Desktop\furkanvas\py-env\backend\server.py", line 1, in <module>
    from app import app, db
  File "C:\Users\Backup\Desktop\furkanvas\py-env\backend\app\__init__.py", line 5, in <module>
    from app.api.routes import User
  File "C:\Users\Backup\Desktop\furkanvas\py-env\backend\app\api\routes.py", line 4, in <module>
    from app.models import Users, Profile
  File "C:\Users\Backup\Desktop\furkanvas\py-env\backend\app\models.py", line 1, in <module>
    from app import db
ImportError: cannot import name 'db' from partially initialized module 'app' (most likely due to a circular import) (C:\Users\Backup\Desktop\furkanvas\py-env\backend\app\__init__.py)

can anyone help me with this? i can provide some code if requested

lilac solar
#

You have a circular import, in that you are trying to import the db thing from app before app has finished initialising it's imports. The typical way to solve this is to move one of the relevant imports inside a function, with Flask from what I remember this is typically in your server.py but I may be wrong

native tide
#

that worked thanks

#

Hello

#

when i do this

#

why is their a gap?

#

can anyone help me fix?

lilac solar
# patent abyss I meant it being maintainable and readable, but also deciding where to do what. ...

Broadly sounds like you want to be looking into general software design patterns and architectures and how they implemented in Python/Django. In terms of Django I prefer defaulting to class based views and tend towards and API based approach which allows for good separation of concerns. If your part of a team then get your code reviewed regularly, otherwise try to think about coming back to any particular code after a period of time (3-6 months) or if you had to hand the code off to someone else.

native tide
native tide
#

anyone have any ideas

#

on how to fix

#

it

native tide
spiral blaze
#

is a <div> just to contain stuff inside? like a <header>

native tide
#

we dont see the whole code

#

ok wait

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @native tide until <t:1634745451:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 110 newlines in 10s).

daring gust
#

!unmute 899531995191853106

lavish prismBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @native tide.

daring gust
spiral blaze
#

rip

native tide
#

thanks!

#

@native tide any ideas now?

#

can you give me the nav part aswell

#

of html

#

ok

slate smelt
#

hii

native tide
slate smelt
#

how host

#

my site

#

for free

pallid lily
#

why do we create class inside a class?

slate smelt
#

why do you think

red ice
#

Is there any way to handle errors in Django forms? If there is a problem while user is sign up(custom Sign Up Form) to just display an error box rather than displaying the original form

slate smelt
#

what do you mean

toxic jungle
#

im not sure if this is the right channel or not, but I've got a question.
I want to able to control the contrast in a web picture:
lets say there is this site that has a picture map https://www.legacysurvey.org/viewer#IC 2989
I can make a picture with specific coordinates (dec, ra) like so https://www.legacysurvey.org/viewer/jpeg-cutout?ra=0.8642482&dec=27.6547253&layer=ls-dr9

what I want to know is: is it possible to add a something to the url that controls the contrast of the pic? something like &contrast=1

indigo kettle
#

no

#

you can go into dev tools and add a css filter

toxic jungle
# indigo kettle

oh nice! my follow up question would be is it possible to produce a url with this filter and contrast already set it? is it possible to save this setting is my question, instead of adding it each time?

indigo kettle
#

not really

#

what you can do is get a web (chrome/firefox whatever) extension which allows you to define your own stylesheets

#

then you can target that img tag and add the filter yourself

#

so you'd have to create a stylesheet which targets legacysurvey.org/viewer/jpeg-cutout* and ```
img {
filter: constrast(1.5);
}

#

but this only sets that contrast for you, if this custom stylesheet is set up

#

a url which has this preset is only possible if the website frontend/backend is expecting a contrast param and actually does something with it

signal bronze
#

actually are sliders even a thing in html? You can create a range of numbers then selecting the input amount

indigo kettle
#

there already is a slider

toxic jungle
#

hmm, maybe if I elaborate it would help:
I have this google docs excel table which draws pics from different sites (legacy is one of them for example) using a url command.
is there any way somehow to make it draw a picture with a specific requested contrast?
If I understand what you are saying, its something that needs to be done for every picture every time I want to open it?
I have around 4000 pictures in the table, and I want to get the images to the table with a certain contrast if possible

indigo kettle
#

maybe google docs has an image filter option

#

let's see

toxic jungle
#

ty so much btw, my knowledge is very poor in this area

indigo kettle
#

np!

#

unfortunately I don't see a way to do this through google sheets

toxic jungle
#

yea I didnt think they would have such a specific setting 😄 thank you for your help!

indigo kettle
#

You can try to find a site that is able to take an image url / contrast as query params and return a new image

#

or write a script which retrieves the images and downloads them -> applies contrast

toxic jungle
proper hinge
#

I want to build an CRUD API with DRF which has some sort of auth that only allows users to operate on resources they own. What's a good solution for this?

#

I have been looking into oauth2, but I find the flow to be confusing. I need to register my app and I get a client ID & secret. For users to get their tokens, they'll need to provide they user and pass in addition to this client ID and secret, which seems awkward. I saw a solution which wraps the token endpoints and auto-injects the client ID and secret, but this seems redundant.

#

I have a feeling oauth2 may not be the right tool for the job

dense slate
#

There is one for graphql

proper hinge
#

JWT seems simpler. If I understand correctly, a user can request a token by only providing their user/password. Then they can pass that token to protected API endpoints. No need for a client id/secret.

cedar cove
#

Is there a reason why I can request.user and get my user info but on others I can't?

#

I'm on the same session

#

Ah, nvm

#

I'm dumb

indigo kettle
#

@proper hinge does session authentication not work for you?

proper hinge
#

Not sure. I thought that was mainly used for websites. I am building an API. No frontend at all.

#

I got JWT set up and I'm gonna be trying it out, but I think it is more in line with what I was looking for.

indigo kettle
#

it sounds like sessions may not work for you. Great! good luck

proper hinge
#

Thanks

strong wren
#

Hey everyone, I have small question regarding routing for Flask. I have a dynamic route @app.route('/v1/<parameter>') but I want know what is the best way to constrain parameter to a set of values.

proper hinge
strong wren
proper hinge
#

Does it not make sense for you to just define a separate route for each option?

#

The way you phrased it makes it sound like they represent different routes rather than just being a parameter

strong wren
#

To be more specific

#

It accepts a parameter in which it grabs data and runs an algorithm on it. i.e if I have country called canada it will run the data on canada

#

However the list of routes is different and volatile which switches around quite a lot

proper hinge
#

If it's volatile then you should probably just perform the validation within the function

#

If it was more static, you could do @app.route('/v1/<any(option1, option2, option3):parameter>')

strong wren
#

Hmm maybe volatile isnt the right word, it doesnt just disappear randomly but more so it can change by deployment

#

The list will be static for each ran deployment, it will auto-generate the required list on each deployment

proper hinge
#

It is just a string, so I suppose you could format it with whatever values you generated

strong wren
#

Hmmm

#

Is this possible to do in the converter you mentioned

#

I would also like to give a specific message for invalid routes too

#

i.e app.route('/v1/<param>/<resource>/' There is no <resource> that exists for <param>. Rather than a generic route error

proper hinge
#

Yeah you could use the any converter or define your own. I think it's like this, though I am not sure if the values need to be quoted or not.

# this list is generated during deployment
# you could e.g. read a file instead and then parse it into a list
choices = ",".join(["choice1", "choice2"])

@app.route(f"/v1/<any({choices}):parameter>")
def foo(parameter):
  ...
proper hinge
strong wren
#

I see, thanks for your input Mark. I greatly appreciate it.

wicked nest
#

I am in need of some help serializing data with DRF and ModelSerializer. When serializing my foreign keys it is returning the ids and I cannot get it to return the value

proper hinge
#

How have you defined your serializer?

#

There are several ways to represent the value of an FK.

wicked nest
#

`class CadetModelSerializer(serializers.ModelSerializer):

class Meta:
    model = Student
    fields = '__all__'`
proper hinge
#

Which field is an FK?

wicked nest
#

In the models say it looks like
class Student(models.Model): class = models.ForeignKey( Class, on_delete=models.CASCADE, default=None )

#

It returns the ID (PK) of the class instead of the class name

#

I have tried multiple SO solutions and cannot figure it out

proper hinge
#

You need to define a class attribute on your cadet serializer class = serializers.SlugRelatedField(slug_field="name"). I'm assuming "name" is the the name of the field containing the class's name.

#

You probably also want read_only=True in the slug parameters

wicked nest
#

This is the error I keep consistently getting __init__() takes 1 positional argument but 3 were given

proper hinge
#

Can you show what your serializer looks like now?

wicked nest
#

`class StudentModelSerializer(serializers.ModelSerializer):
_class = serializers.SlugRelatedField(slug_field="name", read_only=True)

class Meta:
    model = Student
    fields = "__all__"`
proper hinge
#

Oh yeah, class is a keyword in Python...

#

That's awkward. I'm sure there is an alternate way to specify this but I don't remember.

wicked nest
#

I used _class my bad

proper hinge
#

And I am assuming the Student model also has it with an underscore?

wicked nest
#

Yes

#

C:\Repos\ATS\venv\lib\site-packages\django\db\models\query.py in get
num = len(clone) …
▼ Local vars
Variable Value
args
(<Q: (AND: ('id', 1))>,)
clone
Error in formatting: TypeError: init() takes 1 positional argument but 3 were given
kwargs
{}
limit
21
self
Error in formatting: TypeError: init() takes 1 positional argument but 3 were given

#

This is the traceback I believe

proper hinge
#

Can you paste the full traceback?

#

!paste

lavish prismBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

wicked nest
#

Seems pretty cryptic to me

proper hinge
#

The error is coming from this line

  File "C:\Repos\ATS\ATS\cadet_manager\views.py", line 43, in get
    cadet_attributes = CadetModelSerializer(cadet_obj).data```
#

Well, maybe not directly

wicked nest
#

All I'm doing there is passing in the object of the student model

proper hinge
#

Yeah I guess that's fine

#

But it leads to some internal error later

#

Looks like it's trying to create the model but it's failing

#

I would suggest you place a breakpoint at ```py
File "C:\Repos\ATS\venv\lib\site-packages\django\db\models\base.py", line 512, in from_db
new = cls(*values)

and see what model it's trying to create and what the values are
mortal talon
#

Hello, I was wondering if there was a way I could adjust the server response based on the OS/device mentioned in the HTTP request? (preferably with flask) Thanks

wicked nest
#

@proper hinge What's the difference between the slug field and the Primary Key related field

daring isle
#

Anybody use mysql with django ? Or do you use the django native method for databases ?
I have experience with sql and it seems easier to make quick changes

proper hinge
proper hinge
daring isle
# proper hinge I suppose it is possible to use Django without its ORM, but I feel like that kin...

That’s a very valid point . I was using Flask before , I’m partly trying to expand my knowledge base across stuff and also was keen to see what results I could get with Django since people have said it’s more feature packed and less manual.

My main concern is even when using flask and sql alchemy I had to resort to raw sql to achieve some moderately complex queries , maybe due to lack of skill.

#

The authentication feature is a big deal for me so maybe I’ll just stick to django orm for now and see .
I suppose migrating later wouldn’t be too much hassle if I code myself into a corner

eager coral
#

Do u think python is a good language for web-development?

inland oak
eager coral
#

Haha right

#

Which one do y’all recommend I use between django and flask?

#

I’m trying to get into web development but not sure which one I should get in to

inland oak
#

flask can be easier to get started, but django should be better for serious thing

inland oak
eager coral
#

I also do have a book who guides a whole web developing using django

#

But I am guessing it’s not that advanced guide maybe a basic one

dusk sonnet
#

hey, how can i pass the value of {{ home_data.split("|")[3] }} into JS?

inland oak
dusk sonnet
inland oak
#

transform it better being the same in your Python code before submittng it to template

#

keep it as a simple {{home_data}} variable

#

or transform it later in javascript, your choice

dusk sonnet
inland oak
dusk sonnet
inland oak
dusk sonnet
#

so what i want to do is calculate what the user inputs in the field. I want to multiply the number after @ with the number inputted and display it in "potential winnings"

#

in real time

#

so whilst they are entering a numberpotential winningsis showing the amount inputted x the number on top

#

so im trying to get the number after the @ but since its in jinja idk how to pass it to JS

#

iv bearly worked with JS

#

{{ home_data.split("|")[3] }} {{ draw_data.split("|")[4] }} {{ away_data.split("|")[3] }} are all inside elif statements in html (jinja)

#

i want to pass their value to JS

#

to perform the calculations

tepid lark
#

JS! Add an on change event handler to dynamically update the text of the potential winnings tag.

dusk sonnet
#

Why is it that as soon as i enter the else if statement, i get an internal server error

        var cost = document.getElementById("amount")
        var potential_payout = document.getElementById("payout")
        var odds;
        var total = odds * cost
        if ('{{ home_data.split("|")[3] }}' != null) {
            odds = '{{ home_data.split("|")[3] }}'
            alert(odds)
        }
        else if ('{{ draw_data.split("|")[4] }}' != null) {
            odds = '{{ draw_data.split("|")[4] }}'
            alert(odds)
        }
        else if ('{{ away_data.split("|")[3] }}' != null) {
            odds = '{{ away_data.split("|")[3] }}'
            alert(odds)
        }
#

shouldnt it check through the if statements until one returns true

#

if i enter one if statement, it works, if i enter multiple it doesnt

tepid lark
#

Those will all return true?