#web-development

2 messages · Page 153 of 1

spiral gate
#

can i send html files here?

#

prob not

#

but basically it is a interactive map, which when you click on a state on the map, it should generate the informations in a dropdown menu

#

so in this case we only use one view

#

maybe 2 if we want to include a summary of all information on another view/page

toxic echo
#

sorry to interrupt, but quick question, should my classes in django be named camelCase or PascalCase?

silver totem
#

Right, so any data you want to be in that page at the moment it loads should come from the server, unless you are willing to load it using JavaScript instead, which means still contacting the server but after the page load. The general consensus is that if you need anything beyond basic form functionality on a page - you use JavaScript. For stuff you want to be there from the beginning you use server side to template to html.

silver totem
toxic echo
#

ok thanks!

frozen python
#

I have a React + Django + Airtable project. I’m using Airtable for managing products. I want to integrate a “user” profiles, to make “bids” on items. Is Django good for that?

If I create the front end and integrate my DB..... how much would it cost for someone just to create the profile side and implementing being able to log in users and place bids?

silver totem
spiral gate
spiral gate
silver totem
toxic echo
#

in django do you usually put every view class inside views.py, every model inside models.py and so on?

#

im used to 1 file per class

inland oak
#

Basically, both good. But if someone is already more familiar than another one, better to choose more familiar tool I guess

frozen python
inland oak
#

How to use django, can be started from quickstart official documentation

#

Django rest framework requires usually already understanding of django though

#

A little big jump to make

#

Official tutorial with quick start

#

Django rest framework has separated quickstart tutorial, but I don't know how would you handle it without learning django first

frozen python
inland oak
#

I saw it integrates with django

frozen python
inland oak
#

Database planning

frozen python
#

@inland oak I can do that with Airtable, but I’m mainly just wanting to figure out a “user” side to do bidding

inland oak
#

I am not familiar with graphql though, only with rest

runic arch
#
Code (python)
from flask import Flask, redirect, url_for, render_template

app = Flask(__name__)

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

if __name__ == '__main__':
    app.run('localhost',5050)

Template (html)
<!DOCTYPE html>
<html>
<body>
<h1>My first Website</h1>
<p>Hi, this is my first website.</p>
</body>
</html>

The page stays blank and nothing loads. (flask)

lavish prismBOT
#

Hey @inland oak!

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

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

runic arch
#

Windows 10

inland oak
#

in Windows:

python -m venv venv
venv\Scripts\activate
pip install -r requirements.txt
python app.py

in Linux:

python3 -m venv venv
. venv/bin/activate
pip install -r requirements.txt
python app.py
#

have fun

runic arch
#

Thanks

inland oak
#

read the console debug btw

#

it had the erorr written there

runic arch
#

Yea the error there was that the template was not found

inland oak
#

you needed to put home.html to templates folder

runic arch
#

I had a template folder with the html code inside that

inland oak
#

download the archive, I already tuned there

#

recommending this tutorial btw

#

outdated, but still cool

runic arch
#

I'll check it out.

spiral gate
inland oak
#

you can assign different one if you wish thogh

spiral gate
#

ah i meant the python part

#

python doesn't work for my windows 10

#

only py

inland oak
#

shrugs, I used python only in windows 7 and linux

#

actually, I used in windows 10 too at my work

#

it worked as python pretty well

#

perhaps you are installing some different distribution

#

non standard one

spiral gate
#

hmm maybe i guess ye

robust canopy
#

i tried PWA on WAMP server and it worked

#

but when I try it on heroku app it didnt work?

#

idk wat went wrong

native tide
#

what would be the best way to host my flask webapp? it uses celery, a terminal to run the webserver and a terminal that runs a function each hour

chilly falcon
#

hello i have i query that can we use mysql logo in my portfolio website?

hoary brook
#

How can I get the full file path to a file in my Flask static folder?
I've tried url_for and app.root_path and joined it with os.path.join but the furthest I am able to get is C:/static/user/content/filename.pdf, which is obviously not correct...

spiral gate
#

good morning web developers, does anyone know a good place to look up open source projects to view their code?

languid dune
#

Most open source projects will have at least a mirror on GitHub

#

Is there a particular project?

sand glen
#

how do i access this image from that css file

#
.pm-icon {
  background: url("the url");
}```
im trying to do this
thorn igloo
#

are you using react or vue?

#

i think you have to import it if you're using that

sand glen
#

react

sand glen
thorn igloo
#

it's a file path

#

like ../images/image1.jpg for example

sand glen
#

if i do .. it doesnt work

#

i know its a file path but i can't access logo.png from the directory that index.css is in

thorn igloo
opaque rivet
#

@sand glen you just need the right path to the image. It's not ../images/image1.jpg because the .. points to the src directory (and public is not within that)

sand glen
#

i tried ../../public/logo.png

#

@opaque rivet

thorn igloo
#

i think it gets generated in a css folder if i'm correct, just assume that

#

else. put it in src and import it, that's the easiest way but it seems like you dont want to do that

sand glen
#

ok

native tide
#

So flask Or django for web development?

inland oak
native tide
#

Interesting

#

Thanks

#

Imma try both

daring isle
#

Hi all , I’m trying to decide on wether to use flask for a simple app I’m building . Ive done a small tutorial app and get the basics .
Can any of you that have created a more fleshed out app post a screenshot showing your interface designs - I’m trying to assess how good you can make a flask app look

inland oak
#

they all use Jinja like instrument%

#

no really big difference noticed so far for GUI

true ocean
#

Can I name my template same as my file name?
Like If i have a forms.py file Can Iname my template as forms.html?>

inland oak
#

why not, sure

true ocean
#

oh thanks!

daring isle
true ocean
#

hey, another problem!

#

suppose there is car option and If I added a car's name in adminsite now how can I direct or add in the car option?

#

I'm using django framework btw

inland oak
# true ocean suppose there is car option and If I added a car's name in adminsite now how ca...

by changing Admin list_display field

"module to render ships in admin interface"
from django.contrib import admin
from .models import Ship


class ShipAdmin(admin.ModelAdmin):
    """class to rewrite standard model view to
    what we need showing in admin interface"""
    # print(tuple([f.name for f in Commodity._meta.get_fields()]))
    list_display = (
        "nickname",  # str
        "info_name",  # str - infocardish real name

        "name",  # str - ini name

        "ship_class",  # int
        "typeof",  # str - type

        "hold_size",  # int - cargo hold

        "nanobot_limit",  # int
        "shield_battery_limit",  # int

        "capacity",  # int - powercore capacity
        "charge_rate",  # int - powercore charge

        "cruise_speed",  # int - engine
        "impulse_speed",  # int - engine

        "hit_pts",  # int - health points
    )

    list_per_page = 1000


admin.site.register(Ship, ShipAdmin)
#

you can select attribute names

#

or even function names which get your data

#

from your model

true ocean
#

no yes this register to the admin site

#

well, I want to Insert data from Select option to the database

true ocean
sly echo
#

I'm a beginner
What would you recommend
Django or Flask?

true ocean
#

I would recommend Django

keen ravine
#

He is a beginner bro

#

Flask is better for him

true ocean
#

well depends upon what kind of program he wanna build

keen ravine
#

I think he is just getting started

sly echo
#

I want to be a web developer

#

just getting started

keen ravine
#

Yeah Yeah

sly echo
#

I have done basic Python and even OOP

keen ravine
#

Start by Flask

#

Then Django

sly echo
#

Okay

#

How much time does it take to be expert in Flask

#

and kind of work can I do using it?

#

Btw I was practicing numpy and got stuck in a Matrix problem.
Can you help me in that problem too?

#

Help channels are not responding sadly

keen ravine
#

I didn't get too much in it actually

#

You can use it in the back-end for the web

#

Sorry I don't know about that library

#

Maybe they are just sleep or not online

#

Or can't help you that's it bro

sand glen
#

im trying to make a navbar but the icon in the top isnt going to the left of the <h1>

#

how do i make it do that?

#
<a className="navbar-logo logo-text" href="/"><i className="pm-icon" />PartMatcher</a>
north pollen
#

It's html-related question and you ask for the answer in Python discord 🙂

sand glen
#

where else do i ask?

#

and it says in the channel description you can ask for help in HTML

north pollen
#

float: left; gonna help you

sand glen
#

k

#

thanks

#

i didnt know what to search exactly

#

the stuff that was coming up wasnt relevant

north pollen
#

How to make <sth> left sided html + css

sand glen
#

now im having trouble centring the text with the image

#

i want it to be like that (ignoring colour)

#
.pm-icon {
  background: url("./img/logo64.png");
  height: 64px;
  width: 64px;
  background-size: contain;
  float: left;
}

.logo-text {
  color: #11df94;
  text-decoration: none;
  font-size: 20px;
}```

```html
<a className="logo-text" href="/"><i className="pm-icon" />PartMatcher</a>```
north pollen
#

It isn't html5 code, why do you use background instead of simple <img src="..." class="someclass" />

sand glen
#

so that its an icon

north pollen
#

Try googling your questions before asking someone for help. Googling is a primary ability for coders.

sand glen
#

i know

#

i tried all the solutions i could find

#

none of them worked

north pollen
#

I don't know wdyu such strange structures and can't find definition for <i> tag. It is html-based but I don't know its behaviour.

sand glen
#

<i> is the icon tag

north pollen
sand glen
north pollen
#

I can't help you with that, the first time I see it :c

inland oak
latent cosmos
#

[Q] requests lib:
website has in html:

<form id="formLogin">
    <div class="login">
    <input id="inputName" placeholder="Enter your name" type="text"/>
    <button type="submit">
... etc...

It's under url lets say abc.gg, I want to log in so I can access next page, I do:

url = 'http://abc.gg'
payload = {'inputName' : 'JohnDoe'}
r = requests.post(url, data=payload) 

It says cannot post 404 error, so I do get:

url = 'http://abc.gg'
payload = {'inputName' : 'JohnDoe'}
r = requests.get(url, data=payload) 

Still doesn't work. How do I access payload of inputName this html tag:
<input id="inputName" placeholder="Enter your name" type="text"/>
How to acces that inputName to set my value and send to website?

mortal mango
#

nginx: [emerg] duplicate upstream "django" in /etc/nginx/sites-enabled/short_url.conf:2 Does anyone know how to fix this error from nginx?

terse vapor
#
@app.route("/edit/<string:sno>",methods=["GET","POST"])
def editing(sno):
    if 'uname' in session and session['uname'] == params['admin-user']:
        if (request.method=="POST"):
            __title__=request.form.get('title')
            __subtitle__ = request.form.get('subtitle')
            __content__ = request.form.get('content')
            __slug__ = request.form.get('slug')
            if sno == 0:
                post = Posts(title=__title__,subtitle=__subtitle__,content=__content__, slug=__slug__)
                db.session.add(post)
                db.session.commit()
                return render_template('edit.html',sno=sno,params=params,post=post)
            else:
                post=Posts.query.filter_by(sno=sno).first()
                post.title=__title__
                post.subtitle=__subtitle__
                post.content=__content__
                post.slug=__slug__
                db.session.add(post)
                db.session.commit()
                redirect('/edit/0'+sno)
                post=Posts.query.filter_by(sno=sno).first()

        return render_template('edit.html',params=params,post=post)```
terse vapor
opaque rivet
terse vapor
#

good idea

opaque rivet
# terse vapor good idea

also what's with the dunder variables? That's not the right way to name them, if you want them to be private use _variablename but even that is irrelevant because your variables do not extend your functions scope.

thorn haven
#

Hello how to add comment section in my existing app. Comment in CRUD

#

?????????????????????????????????????????????????????????????

mortal mango
#

nginx: [emerg] duplicate upstream "django" in /etc/nginx/sites-enabled/short_url.conf:2 Does anyone know how to fix this error from nginx?

quasi relic
#

hey anyone can help me with this??

#

<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}">

#

flask doesnt load the changes only once and then nothing

#

i can easily change elements in the template but in css nothing

naive crater
#

or cmd-shift-r on mac

quasi relic
cloud saffron
#

Because you cannot expect a user to force refresh the page himself after deployment

quasi relic
#

lets say I enclose it with a div tag then I target it but nothing happens

calm plume
#

Resizing buttons?

#

You can just add width and height

quasi relic
#

that changes only the box size of the div tag

calm plume
#

Then do it on the actual button

quasi relic
#

the problem is I use form from the flask framework

#

not html form button

calm plume
#

It's still html code, right?

quasi relic
#

let me shot an image for you wait

calm plume
#

Ohhh

#

I'm not sure how to help with that, sorry

quasi relic
#

okay thanks anyway

hoary brook
nova sonnet
#

i have a question regarding cbv

#

how does the class know what template to use

#

or would i have to set it as an attribute before hand?

quasi relic
manic frost
#

Has anyone succeeded in building a frontend app with svelte, parcel and typecript? The official svelte+typescript tutorial uses rollup, which seems a little bit too complicated for me

#

Or maybe I should just give up on parcel?

calm plume
#

I haven't used it yet (I'm working on it), but I've heard that webpack is better for anything that's not an SPA (and even in general).

#

Idk about Rollup

sand glen
#

hi! i have this code:

<a className="logo-text" href="/"><i className="pm-icon" />PartMatcher</a>

i'm trying to make "partmatcher" vertically aligned with the icon, but can't get it to work

#
.pm-icon {
  background: url("./img/logo64.png");
  height: 64px;
  width: 64px;
  background-size: contain;
  float: left;
}

.logo-text {
  color: #11df94;
  text-decoration: none;
  font-size: 20px;
  vertical-align: center;
}

these are my CSS rules

calm plume
#

Vertically aligned?

#

Do you mean you want it to be centered?

sand glen
#

yeah

#

mb

#

vertically centred

#

the <a> tag is inside a <navbar> tag

calm plume
#
.logo-text {
  margin: 0;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}```
sand glen
#

i will try that

#

wtf

calm plume
sand glen
#

its gone to the center of the screen

#
.pm-icon {
  background: url("./img/logo64.png");
  height: 64px;
  width: 64px;
  background-size: contain;
  float: left;
}

.logo-text {
  color: #11df94;
  text-decoration: none;
  font-size: 20px;
  margin: 0;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}```
#

did i do something wrong

calm plume
#

Uhhhh

#

I think we'd need to see the rest of your css

sand glen
#

sure

calm plume
#

Can you show the html around that?

sand glen
#
import React, { Component } from "react"


const menuItems = [
    {
        title: "Featured",
        url: "/featured"
    },
    {       
        title: "Build Guides",
        url: "/build-guides"
    }
]


class Navbar extends Component {
    state = { clicked: false }

    render() {
        return (
            <nav className="navbar-items">
                <a className="logo-text" href="/"><i className="pm-icon" />PartMatcher</a>
                
                <div className="menu-icon">
                </div>
                <ul>
                    { menuItems.map(
                        (item, index) => {
                            return (
                                <li key={index}>
                                    <a className="navbar-item" href={item.url}>{item.title}</a>
                                </li>
                            )
                        }
                    ) } 
                </ul>
            </nav>
        )
    }
}

export default Navbar```
this is my jsx
#

im using react

calm plume
#

Uh

#

Can you replace

<a className="logo-text" href="/"><i className="pm-icon" />PartMatcher</a>

with

<a href="/"><i className="pm-icon" /><p className="logo-text">PartMatcher</p></a>
sand glen
#

alr

#

haha

#

this is so weird

calm plume
#

What the heck did I screw up

#

Oh wait

#

Can you make it position: relative; instead?

sand glen
#

ok

calm plume
#

Instead of position: absolute;

sand glen
woeful vapor
#

anyone familiar with gunicorn here?

#

I'm trying to scale up my project on heroku and a bit confused

manic frost
#

🙂

#

webpack has a very complicated configuration system, I don't really want to touch it

#

parcel is extremely simple because it needs zero configuration in the most basic case

misty tulip
#

hi all what is an easy way to change my measurements from px to % and everything look the same?

#

nvm i got it sorry

calm plume
#

At least from what my research on the internet says

zenith comet
#

can anyone recognize the auth method this website is using? im a total noob trying to build something that will sync this shitty wesites calender with mine

turbid tiger
#

Can someone help me with a quick flask question?

zenith comet
zenith comet
#

anyone

#

it's for personal use btw and the accounts are on invite only

oblique kite
#

hello guys..
I'm getting "ImportError: No module named environ" this error

pip list:
django-debug-toolbar 1.11
django-email-extras 0.3.4
django-environ 0.4.5
django-forms-builder 0.14.0
django-heroku 0.3.1
django-jenkins 0.110.0

How to fix it?

inland oak
#

perhaps you missed import os

#

and called without os.environ

#

you have similarily named module though

#

django-environ, I have no idea what it is

cerulean thicket
#

hello

fast jewel
#

cerulean thicket
true ocean
inland oak
#

you probably meant to ask this

true ocean
#

no wait I'll explain

inland oak
#

it makes for the chosen field

#

selector

#

from admin interface

#

not sure if I remembered right the choices format though

true ocean
#

so I want to build sth like this

#

and I want to build sth like when you expand author name then it should automatically dropdown the author name list

#

I hope you get it

cerulean thicket
inland oak
#

for admin interface

true ocean
#

when I add a new book then that book should be able to include in that list

#

you know what I mean?

true ocean
#

wait I''ll upload my forms file

#

forms.pyfile

#

I did this.

true ocean
#

these are my views file

calm plume
#

Because that screenshot isn't really enough to know their auth method.

#

That website is just the content of the website.

#

But that's a very hard thing to gauge, even if we know the website.

shadow python
#

i'm stuck in ajax pagination who can help me please?

#

bootstrap doesn't apply to my ajax pagination anyone can help?

native tide
#

Is it possible/a good idea to run a Flask app and mail server on the same server?

calm plume
#
Allow: /```
Is this the correct way to allow everything in robots.txt?
woeful vapor
#

Anyone can help with heroku plus gunicorn? I'm having some performance issues on my site not sure the best remedy

native tide
# shadow python

are you using django or flask as the backend? bc with django you dont need that. there are prebuilt function to check if you should paginate etc.

shadow python
sand glen
#
<a href="/"><i className="pm-icon" /></a>
<a href="/">PartMatcher </a>```
is this a janky solution?
native tide
desert snow
#

I need some help with Django rest framework

#

I have never worked with it before

#

but I need to use it for an internship

#

Can I ask here?

native tide
#

can some one explain parse_qs and explain what does this mean ```py
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.log_message("Incoming GET request...")
try:
name = parse_qs(self.path[2:])['name'][0]

cerulean panther
#

hello guys

zenith comet
#

i think it's the landing page

#

stopping me from using youtube guides to get in 😛

calm plume
#

I don't think we can tell from that

zenith comet
#

How could i?

#

i'lll try for hour i just need some direction mate

calm plume
#

Why do you need to know how they do auth?

zenith comet
#

it's the website they invited me to when i got sick and they have their own calendar

#

i wanna sync it with my google one

calm plume
#

Then ask them

zenith comet
#

i did

calm plume
#

Don't try to bypass their auth system

zenith comet
#

their team is on it but it could take months

#

well... it's autosigned in on my pc

#

can i use i that in any way?

calm plume
#

You're still trying to bypass their auth

#

Unless I'm misunderstanding

zenith comet
#

no i would auth with my account'

#

just automatically

calm plume
#

But you're trying to get access to things they aren't giving you access too.

zenith comet
#

is it really?

#

im just trying to sign in

calm plume
#

But you're still going around their auth system in a way that they didn't allow

#

And anyway, there's literally nothing I could tell you, except to maybe watch the "Network" tab in dev tools and see if you find anything. But without some advanced knowledge of how auth works, that's be hard.

zenith comet
#

im no expert

#

im an autistic fuck that wants his calendar synced thanks for the tips tho 🙂

#

any help can send me the right way

wheat skiff
#

hi, i really need help with building a chat app in django. i built already the site now i need to make the chat with socket or django channels. can some one help me with it?
im very new to django so it is very difficult for me to do this app
(i tried lots of tutorials but its hard for me to understand when i cant ask questions)

#

If you can help me please send me a message
Thank you

#

@opaque rivet you know maybe work with django channels?

opaque rivet
wheat skiff
#

does any one else know django channels?

calm plume
#

Many people ask if they can make a website with only Python. The answer is usually no. It's much better to make a website frontend using HTML, CSS, and JS, and then use Python for the backend with a tool like FastAPI, Flask, or Django.

Why HTML, CSS, and JS are used
HTML, CSS, and JavaScript are better for front end web dev, simply because that's exactly what they were made for.

  • HTML is a markup language made for creating the content of a website.
  • CSS is a styling language, used to change colors, sizes, placement, and various other things on elements.
  • JS is used for providing logic to the web. Neither HTML nor CSS have the logic required to be able to write complex logic that allows you to write custom, client-side scripts (at least, not easily). That's what JS provides, allowing you to have a dynamic and interactive website.

Is it possible to make a website with only Python?
Yes. Making a website with only Python is possible by compiling it to web assembly for the frontend or using Brython. However, that isn't viable for most people, since it's hard to set up and a hard thing to learn to do.

How you can add Python to websites
Although making a frontend with Python is rather hard, making the backend is possible using various tools. This includes interacting with the database, processing user data, and various other backend operations. A couple are:
FastAPI - A fast, modern framework built for API creation that's based on Python's type hinting.
Flask - A micro web framwork that has no database abstraction layer, form validation, or anything else that requires other tools or libraries (although you can use them).
Django - A high level web framework that is fast, secure, and scalable that's powered based on it's template language.

In short, although it's possible to make a website using only Python, it's a much better idea to use html/css/js for the frontend and make the backend using Python.

true ocean
#

@inland oak
I made a new one to get rid of confusion

inland oak
#

shrugs. I willl point only to the direction

#

where to seek for answers

#

don't expect from me answers

true ocean
#

these are my adminsite

inland oak
#

oh, nice, it is black

#

overriden css?

true ocean
#

no It's default

inland oak
#

huh? weird

#

default is white

#

do you have outdated Django version?

true ocean
#

wait, I'll show u my html page

true ocean
inland oak
#

shrugs

#

I am busy anyway

true ocean
#

oh okay

#

thanks anyways

calm plume
keen ravine
#

Hey guys

#

Can I store functions inside an array?

native tide
native tide
# zenith comet i wanna sync it with my google one

@zenith comet I guess you want to web scrap that site if you want to login with your credentials and then just iterate somehow through all events on the calendar (they all have the same class i guess) and store them in your db. Idk how you can synch with googles calendar bc i dont use/like it but i guess that can help and i hope you dont do smth illegal

opaque rivet
native tide
keen ravine
#

What do you mean?

#

def one(num):
print(num)
def two(num):
print(num)
def three(num):
print(num)

arr= [one(1), two(2), three(3)]
print(arr[1])

#

This should print 2

#

But it print: 1,2 and 3

#

@native tide

native tide
#

@keen ravine i didnt call it like that instead i iterate throught it and passed the arguments. In my case i had a summarise,multiply etc. functions with 2 arguments and those i passed in

vivid canopy
#

Where I can learn Django?

#

Without documentation

calm plume
#

It's wonderful

vivid canopy
#

Emmm so documentation it's the best choice?

calm plume
#

The tutorial

#

It's not docs

vivid canopy
#

It sry so I should find official tutorial?

#

Oy

#

??

calm plume
#

Yes

native tide
#

when it comes to doing post and get methods what ip adress dou i need to put so people can use my web site ?

grim yarrow
#
[<div class="trn-defstat__value" data-stat="CasualKills">
113
</div>]

anyone know how to get only text inside these tag ?
Example 113 is the text that i want 0002gun 0001gun

vivid canopy
#

Thx

native tide
#

i puted my ipv4 ip and the web page didnt work for my friend in slovakia

#

but it works for me

manic frost
#

@keen ravine You should check out #❓|how-to-get-help and claim a help channel, because this is an on-topic channel about web development.

What' you're doing is you're first calling one(1), two(2) and three(3), and each of them prints something, not returns something.
As you can see on the screenshot, f() doesn't return anythinig (it return None). Instead, it prints something on the screen when you call it. But g() does return the number 42.

For more info, check out https://www.youtube.com/watch?v=9Os0o3wzS_I

native tide
native tide
grim yarrow
#

what ?

manic frost
grim yarrow
#

How can i seperate 113 out of these tag

calm plume
vivid canopy
#

@calm plume u know Django?

mighty narwhal
#

Hey guys, I ran into a problem if anyone can help I’d be really great.
So I created a flask app and trying to make graph using Apexcharts.JS. I’ve got a json file feeded into the webpage under script tag but I can’t see the chart. I’m not sure if flask can provide variables inside script tag in a webpage

native tide
grim yarrow
#

thank

native tide
native tide
native tide
native tide
# native tide locally

thats the problem. Only you can visit your page if you dont host it or send him the code and he runs it himself.

native tide
#

But better would be hosting with heroku or smth. takes 5 minutes and is free

native tide
quick schooner
#

hello ! i have a strange issue with a json i'm working on. i get the json from an api call no problem. but i cant access some part of the json but if i copy the json in another python file and try to access the data i can

lavish prismBOT
#

Hey @quick schooner!

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

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

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

https://paste.pythondiscord.com

native tide
native tide
#

this is the code i gave him

#

he downloaded

#

that is my ip

quick schooner
#

the json is here

calm plume
native tide
#

and this is the python part

quick schooner
#

i can acces json['sections'] but not in my code. only if i copy paste it in another file

native tide
#

wich is also on my ip

#

so when i gave him the html code and run the python code from my pc the requests woudent work but it works from me

#

so yeah

#

u say i need to host it ?

native tide
native tide
#

why is that ?

native tide
# native tide when i put my local ip it doesnt work

bc its your local ip its the ip of that device in the current network and ips are kinda unique even tho they change. and sry i think you didnt even put your local ip rather your local default gateway and for that to work for him he needs to put his local default gateway or you host it

native tide
native tide
#

how dou i transfer my python script and yeah i would have to get an ip adress so it connects to its server

native tide
native tide
native tide
#

i tought it works like that

#

no. u just upload the code and heroku has a server which serves your code and then you get the url and you send the url to everyone who should see it

#

btw thx for helping me and teaching me about how to use ip adress for web site developing

native tide
native tide
native tide
#

i tought when u make an acc or get a host u get their ip adress, wich connects to the script u made ,wich then every one could use, wich makes this confusing to me why will it work when i put my ip adress on another lets say pc and work on my pc if u get what i say

#

thats what im confused XD rn

woeful atlas
#

Hi

#

How can I resolve that ?

native tide
# native tide thats what im confused XD rn

it works locally with your current local default gateway which is also kinda connected with your local ip and if the other perso isnt in the same network he also probably cant connect to that default gateway. And by creating an acc you kinda buy/reserve a place in their server with a specific ip-address which is covered with the url like google.com. bc you can also find google.com with their ip which is currently "172.217.23.46"

#

ok thx for letting me know that

native tide
#

could u tell me how to upload the py script on that server ? heroku

woeful atlas
#

pip3 install goodbyecaptcha

native tide
midnight valve
frail drift
#

[FLASK & HEROKU]

Hey folks.

i made a flask web app and i am now willing to deploy it on heroku.

The app works just perfectly on my machine. (LOL)

I did the whole process on Heroku, creating a Procfile, requirements.txt.

I am doing the deployment and it turns ok, but the app doens't load.

I checked almost anything. I didn't use the heroku git but doing directly with git command prompt.

Any idea on what could be the issue?

*2021-05-03T16:20:03.000000+00:00 app[api]: Build succeeded
2021-05-03T16:21:28.289934+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET

velvet yew
#

Can someone help me with some basic Django? I've got a views.py that goes like this:

from django.shortcuts import render

value = 1


def home(request):
    
    return render(request, "monitor/index.html")

And an index.html in my templates/monitor that goes like:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <p>Value: {{ value }}</p>
</body>
</html>
#

When I visit the page I only see Value:

#

How would I write this correctly so it can print the variable?

native tide
#

pass the value into ur render object

opaque rivet
deep mason
#

hey guys, im building a flask website

#

and ive this piece of code

#
@app.route('/rooms/<int:room>/message/<int:id>/delete')
@login_required
def delete_msg(id, room):

    msg = Message.query.get(id)
    current_room = Room.query.filter_by(code=room).first()

    if msg.sender == current_user.username:

        db.session.delete(msg)
        db.session.commmit()

    return redirect(f"/rooms/{room}")
#

but it gives me this error:

#

AttributeError: 'scoped_session' object has no attribute 'commmit'

#

but i dont even understand why im in a scoped_session

#

can i somehow change that?

odd crest
#

i'm front dev and do u have front-end server? i will sell my websites and buy full course of front-dev

#

for 5$

#

hey

random lava
#

Hi, when using a jsonify return in flask how do i use a result in html?

@app.route("/prices", methods=['GET'])
def get_prices():

    test = 1
    return jsonify(test=test)
<h1> {{test}}</h1>

^ gives a blank result

terse vapor
#
@app.route("/prices", methods=['GET'])
def get_prices():

    test = 1
    return render_template('file.html', test=test)
#

try this

#
<h1> {{test}} </h1>```
random lava
terse vapor
#

oh ok

random lava
#
@app.route("/prices", methods=['GET'])
def get_prices():

    #database request that returns 
    test = "hello"
    return jsonify(test=test)
{% if "h" in test %}
  <h1>good</h1>
{% else %}
  <h1>bad</h1>
{% endif %}
random lava
terse vapor
#
@app.route("/prices", methods=['GET'])
def get_prices():

    #database request that returns 
    test = "hello"
    if "h" in test:
        return "Good"
    else:
        return "Bad" 
    return jsonify(test=test)```
#

maybe like this?

#

it shows "Good" in my browser

#
@app.route('/', methods=['GET']) 
def initialization():
    for i in User.query.all():
        ip = request.host 
        if ip in i.host:
            return redirect(url_for('login'))
        else:
            return render_template('initialization.html')

@app.route("/login", methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('doctor_information', name=user.name))
    form = LoginForm() 
    if form.validate_on_submit():
        user = User.query.filter_by(name=form.name.data).first()
        if user and bcrypt.check_password_hash(user.password, form.password.data):
            login_user(user, remember=form.remember.data)
            next_page = request.args.get('next')
            user = User.query.filter_by(name=form.name.data).first()
            return redirect(next_page) if next_page else redirect(url_for('doctor_information', name=user.name)) # error: UnboundLocalError: local variable 'user' referenced before assignment
        else:
            flash('Login Unsuccessful. Please check email and password', 'danger')
    return render_template('login.html', title='Login', form=form)```
#

How can I make this right?

keen ravine
#

Use global

#

global 'your variable'

#

@terse vapor

terse vapor
#

Yes?

keen ravine
#

I just answered you

terse vapor
#

Ok

#

I was confusing at first

#

Lol

#

Oh ok, now it makes a bit more sense, thanks!

keen ravine
#

let's say that your variable name is count

#

All you have to do is type global count

#

I think you should use it for the variable user

#

If you still didn't understand, read the article I've sent

#

Guys, how can I scrape all those emails in this pic using selenium python?

#

I just want to print them in my console

native tide
keen ravine
#

Am struggling find the correct class or id

native tide
random lava
#

Hi, asked the same question before but still cant figure it out.
How do i use a jsonify return in html ?

@app.route("/prices", methods=['GET'])
def get_prices():
    #database request that returns
    test = "hello"
    return jsonify(test=test)

html:

{% if "h" in test %}

<h1>good</h1>

{% else %}

<h1>bad</h1>

{% endif %}
keen ravine
#

Whatever I use css selector, x path, class or id

#

It print what I use and what I pass

#

emails = (By.CSS_SELECTOR, 'grid1cbd304ad-c72f-4e7e-b01e-503faa0ae02d > div > div > div > div.azc-grid-tableContainer.azc-br-muted > div.azc-grid-tableScrollContainer.azc-br-muted > div > table > tbody > tr:nth-child(1) > td:nth-child(4) > div') for email in emails: print(email)

#

the output: css selector
grid1cbd304ad-c72f-4e7e-b01e-503faa0ae02d > div > div > div > div.azc-grid-tableContainer.azc-br-muted > div.azc-grid-tableScrollContainer.azc-br-muted > div > table > tbody > tr:nth-child(1) > td:nth-child(4) > div

limpid python
#

how do I make my website computer, ipad only using flask

buoyant shuttle
#

For some strange reason my div elements won't show on my browser, nothing is wrong so far

calm plume
#

Is there anything inside the div?

buoyant shuttle
#

Yeah

calm plume
#

Can you share the code?

buoyant shuttle
#

It's a modal that's suppose to pop when button clicked. I was about to style it then I tested it didn't work sure

#

Sure 1 sec

#
<div class="modal" id="modal">
        <div class="modal-header"> 
            <div class="title"> Example Modal</div>
            <div class="close-button"> &times;</div>
        </div>
        <div class="modal-body"> 
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
        </div>
    </div>
    <div id="overlay"></div> 
#
.modal{
    position: fixed;
    top: 50%;
    left: 50%;
}
``` not done styling but bothers me why it doesnt show?
buoyant shuttle
#

The styling doesn't even work with fixed width

random lava
cold ether
#

When I Run a HTML Code in vscode it shows me this. How to fix this?

calm plume
#

That's not how you access an html file

cold ether
#

Oh then?

calm plume
#

file:///C:/pathtofile/learning.html

#

Put that in your browser

cold ether
#

ok

jade lark
cold ether
#

Oh ok thanks!

#

So i choosed a new file and it didnt work

#

this is the code

jade lark
#

couple of things. Your HTML isn't valid.

calm plume
#

Not the words pathtofile

jade lark
#

Second, make sure to read the link I sent you. It shows you how to run it with live server if you'd rather that

#

also file type should be lowercase

cold ether
#

ok i will do those things brb got some work.

marble spade
#

can I display a metalabs graph into django?

inland oak
marble spade
echo valve
#

any django dev here?

#

what is the best django ODM supports mongodb?

quartz ravine
#

For those who need to build integration between teams and have a large amount of fake data, check out https://github.com/ghandic/jsf - it has a seamless integration with FastAPI

GitHub

Creates fake JSON files from a JSON schema. Contribute to ghandic/jsf development by creating an account on GitHub.

prime venture
#

is it possible to serve remote html files in flask? in context, i want to serve discord attachments which are html. trying to avoid downloading them and then serving them

quartz ravine
#

you could return a redirect?

weary dragon
#

Hello, can someone recommend me a way to generate refresh tokens for a web api?

sonic ferry
#

Can a wtforms class, containing only a SubmitField, have a customer validator? (validator will check something in database)

late tree
#

I am new bee to python should I dive into django or flask inweb development?

calm plume
#

Also, if you're new to Python, I suggest you don't jump into web development yet.

#

You should focus on learning the basics of Python, not jump into a bunch of different libraries.

#

But to answer your question, Flask is probably better if you're new

late tree
#

I also currently working on cakephp

#

Backend

late tree
rapid spindle
#

hello, is anyone can help me to figure out my problem? i'm making a website with django but when i'm making my models from model.py, and then, when i try to make the migrations, it fails and says: name "model" is not defined... been tryna check google to get some informations about it but still doesn't working...

#

for example, here is one of the class: ```py
from future import unicode_literals

from django.db import models

class PretReservation(models.Model):
id_groupe = models.IntegerField(null=True)
date_pret = models.DateTimeField(auto_now_add=True)
id_module = models.IntegerField(unique=True)
statut = models.IntegerField(null=True)
pret = models.ForeignKey(Composant, on_delete=models.CASCADE)
groupe = models.OneToManyField(Groupe, related_name="groupe", blank=True)
module = models.ManyToManyField(Module, related_name="module", blank=True)
composant = models.OneToManyField(Composant, related_name="composant")```

native tide
rapid spindle
#

@native tide yep thanks, it works out!

void summit
#

I'm not happy with django async 😦

#

sure wrappers can be a solution but I find myself writing sync_to_async wrappers to everything ...

quartz ravine
#

Use FastAPI 😄

frigid frigate
terse vapor
#
@app.route("/delete-patient/<int:patient_id>", methods=['POST', 'GET'])  
@login_required 
def delete_patient(patient_id): 
    detail = Detail.query.get_or_404(patient_id)
    patient = Patient.query.get_or_404(patient_id) 
    db.session.delete(patient)
    db.session.delete(detail)  
    db.session.commit() 
    flash('患者已被删除!', 'success') 
    return redirect(url_for('patient'))```
Detailed information is connected with patient_id, so a patient_id = 1 will match with detail_id = 1, but if I did not create a detail_id for the patient, I cannot delete that patient. How do i fix it?
woeful atlas
#

How can I change of context with selnium python ?

#

I have do:

seq = driver.find_elements_by_tag_name('iframe')

print("No of frames present in the web page are: ", len(seq))```
#

but he say there are one iframe

#

but in my console, he say there a many iframe

prime venture
quartz ravine
prime venture
thorny rover
#

how would i use a logged in users name for the file path like this?

<img src='{% static "assets/user_profile_pic/"+{{name.username}}+".png" %}'```
north pollen
quartz ravine
north pollen
prime venture
#

btw is it common to server html with fastapi?

#

heard it was great

north pollen
prime venture
#

just wanted to know if your supposed to do that

north pollen
#

Kinda meh, I think it's overload

prime venture
#

and not flask

north pollen
#

No.

prime venture
#

yea i see

north pollen
#

FastApi is for developing, surprise, API asap 🙂
It is a good tool, but it doesn't have built-in template lang, orm and so on..

terse vapor
#
from flask import Flask 
from flask_sqlalchemy import SQLAlchemy 
from flask_admin import Admin 
from flask_admin.contrib.sqla import ModelView

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///admin.db'
app.config['SECRET_KEY'] = 'mysecret'

db = SQLAlchemy(app)

admin = Admin(app)

class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30))

admin.add_view(ModelView(Person, db.session))

if __name__ == '__main__':
    app.run(debug=True)```
This work only like this, but if i seperated the code into init.py model.py, the code doesnt work anymore
#

The error says the admin.add_view(ModelView(Person, db.session)) the model is not defind

north pollen
terse vapor
#
from flask_script import Manager 
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView

app = Flask(__name__)  
db = SQLAlchemy(app) 
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
login_manager.login_message_category = 'info'
admin = Admin(app)
admin.add_view(ModelView(User, db.session))


from flaskblog import routes```
#
class User(db.Model, UserMixin):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20), unique=True, nullable=False)
    number = db.Column(db.String(11), unique=False, nullable=False) ```
north pollen
terse vapor
#

so u want me to from app import Patient?

north pollen
#

from .models import User

terse vapor
#

ok

#

but now it have ImportError: cannot import name 'db' from partially initialized module

north pollen
#

Oh man I've seen what you've done totally. It is a bad structure at all. I can't help u with it, read about project organisation in Flask. The stuff you've done is kinda....awful

terse vapor
#

lmao

#

i know

north pollen
#

So I can describe how to finish this awful structure... TO MAKE IT MUCH MORE AWFUL.
Seriously, read the docs to make it beautiful 🙂

terse vapor
#

😅

terse vapor
north pollen
terse vapor
#

ok

shy spade
#

Hi all. I have a question related to Django. I have a report script that I need to adapt into a django app.

#

The issue is the report can take a very long time (sometimes up to 8-14 hours)

#

I have a question in help-apple if anyone is interested in the report. But my question is any ideas on how to keep the session active? I am not well versed in async although I think this is the solution. Any places to start?

shy spade
#

ok thanks @north pollen

terse vapor
north pollen
#

Yet another awful, but working project, gooood job xD 👍

terse vapor
#

😁

native tide
#

How do I put the text on the same line:

#

<h1>

<p style="text-align:center;
font-family:Georgia;
font-size:50px;
color:#CC0000">Big Hero 6</p>
<p style="text-align:right">2015</p>

</h1>

#

I am new to html so please help

#

...

#

...

#

@

#

HELP

#

PLEASE

calm plume
#

On the element/div around it, you can do display: flex;

terse vapor
north pollen
terse vapor
halcyon quest
#

Can anybody here help@me with restapi’s ?

thorny rover
#

why would not logged in not all be on one line here

#
<div class="sidebar">
            <a href="/home">Home</a>
            <a href="#inventory">Inventory</a>
            <a href="#did">DID Database</a>
            <a href="#did">CER / 911</a>
            <a href="#did">Admin</a>
            <a class="active" href="/accounts/login">Login</a>
            <div style="position: absolute;bottom:0%;left:50%;transform: translate(-50%, 0%);">
                  {% if user.is_authenticated %}
                      <img src='{% static "assets/user_profile_picture/"|add:user.username|add:".png" %}' height="100px" width="100px">
                      <p style="color:white;">{{ user.get_full_name }}</p>
                      <p><a href="{% url 'logout' %}">Log Out</a></p>
                  {% else %}
                    <img src="https://i.imgur.com/2nLLtVN.png" height="100px" width="100px">
                    <p style="color:white;margin-bottom:5px;">Not Logged In</p>
                  {% endif %}
              </div>
        </div>```
#
.sidebar {
  margin: 0;
  padding: 0;
  width: 200px;
  background-color: #363636;
  position: fixed;
  height: 100%;
  overflow: auto;
  box-shadow: 3px 3px 3px #000;
  font-size: 20px;
}```
calm plume
thorny rover
#

im brand new to html/css, what do i put so it doesnt?

#

when then code looked like this it was all on one line

#
            <div style="position: absolute;bottom:0%;left:50%;transform: translate(-50%, -50%);">
                <img src="https://i.imgur.com/2nLLtVN.png" height="100px" width="100px">
            </div>
            <div style="position: absolute;bottom:0px; left:20%;">
                <p style="color:white;">Not Logged In</p>
            </div>```
calm plume
thorny rover
calm plume
#

You need to have a space iirc

thorny rover
#

oh!

calm plume
#

After the semicolon after white

thorny rover
#

sadly same issue

calm plume
#

But if the text can't squish, it might break onto a new line

#

You can make the text smaller

#

Or decrease the margin/padding

thorny rover
#

i think padding and margin are 0 on the sidebar

willow lava
#

Is it breaking on large screens as well?

thorny rover
#

this is a full screen window at 1080p

calm plume
#

Then you should probably just make the text smaller

thorny rover
#

the text should fit though right? like i said, before i added in the if/else it fit

#

this is it without the if/else

limber laurel
#

Is tgere a way I could use django with react wothout using an api

opaque rivet
#

how do you guys handle periodic tasks with fastAPI?

#

celery can be used?

opaque rivet
#

yolo, gonna switch from django to fastapi and just main it over node.js, feels bad learning it for months and not getting a job as planned

mystic wyvern
#

Hi there , just a simple question How do I sync my project and the database between two devices regularly?

terse vapor
#

Is there any way to secure flask-admin dashboard like login_required thing? Most answers on google are using current_user and login_user, which I have been used on the User role, so what should i do?

thorn igloo
scenic pendant
stable zinc
#

hi, i have a problem to solve but i don't know how 😄 let me explain :

#

i'm building a webapp to calculate your kalories, my webview :

#

my models :

class Product(models.Model):
    name = models.CharField(max_length=200)
    kalories = models.IntegerField(default=0)
    protein = models.IntegerField(default=0)
    glucide = models.IntegerField(default=0)
    sugar = models.IntegerField(default=0)
    lipide = models.IntegerField(default=0)
    satured = models.IntegerField(default=0)

    class Meta:
        ordering = ("name", "kalories")


class Menu(models.Model):
    name = models.CharField(max_length=200)
    products = models.ManyToManyField(Product, through='TProductMenu')
    instructions = models.CharField(max_length=1000)

    def __str__(self):
        return self.name


class TProductMenu(models.Model):
    menu = models.ForeignKey(Menu, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    number = models.IntegerField(default=0)
    weight = models.IntegerField(default=0)
#

i don't know how to calculate total kalories

#

my view code :

<ul>
    {% for menu in menus %}
    <ul>{{ menu.name }}</ul>
        {% for TMenuProduct in TMenuProducts %}
        {% if TMenuProduct.menu.name == menu.name %}
        <li>{{ TMenuProduct.product.name }} | kcal : {{ TMenuProduct.product.kalories }}</li>
        {% endif %}
        {% endfor %}
    <li>tt kcal : </li>
    <br>
    {% endfor %}
</ul>```
#

i can calculate with JS but i think there is a better way to do

formal geode
#

Ok, If you need HTML help just message, just got on

lament bronze
#

@stable zinc is there more code that you aren't showing us

stable zinc
#

hmm oh, yes my view code :

def menu(request):
    menus = Menu.objects.all()
    TMenuProducts = TProductMenu.objects.all()
    context = {
        'menus': menus,
        'TMenuProducts': TMenuProducts
    }

    return render(request, 'alimentary/menu.html', context)
lament bronze
#

is TMenuProducts collection of Product type objects

stable zinc
#

No Tproductmenu is a through table in bdd between Menu and Product

lament bronze
#

ok, are the total kalories taken from a collection of Products?

stable zinc
#

kalories are fields in the product table

#

there is no total kalories in BDD, but i don"t know if i can add a total kalorie field in the tmenuproduct

#

maybe an aggregate function ?

lament bronze
#

I don't know what framework, database, or what you are using but you could either

  1. use a function like sql's SUM at the database to aggregate a sum from all rows of interest from the table
  2. iterate over a list of objects of type Product in python to add all of the calorie fields of each object
#

I'm sorry I wish I could do more

#

Also, if you are using a client side technology like React or Angular you could aggregate it in the client before displaying, it's really up to you

stable zinc
#

at the moment i'm using sqlite for the dev, and if i use an iteration list on product i have to make an additionnal dictionary to link menu, product and tproductmenu in the backend to send in the context

#

but yeah i think i'll code the display in JS

#

thx for your time 😉

lament bronze
#

bonne chance

#

j'espere pouvoir vous aider

valid prairie
#

where would you store django signals? in project structure?

dense gyro
#

yeet

valid prairie
dense gyro
#

nothing

valid prairie
#

are you stupid?

vestal hound
terse vapor
#
if auth and auth.password == 'secret':
        token = jwt.encode({'user' : auth.username, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(seconds=15)}, app.config['SECRET_KEY'])

        return token.decode('utf-8')```
It shows:
`AttributeError: 'str' object has no attribute 'decode'`
but I did follow the instruction from the tutorial, so is there anything i did wrong or there is another format to write this😅 ?
inland oak
#

thanks to help of the users here

#
if auth and auth.password == 'secret':
        token = jwt.encode({'user' : auth.username, 'exp' : (datetime.datetime.utcnow() + datetime.timedelta(seconds=15)).isoformat()}, app.config['SECRET_KEY'])

        return token.decode('utf-8')
inland oak
lavish prismBOT
#

@inland oak :white_check_mark: Your eval job has completed with return code 0.

001 | '2021-05-05T03:09:42.110323'
002 | datetime.datetime(2021, 5, 5, 3, 9, 42, 110323)
terse vapor
terse vapor
inland oak
#

!e

import datetime

date = (datetime.datetime.utcnow() + datetime.timedelta(seconds=15)).isoformat()
print(repr(date))
lavish prismBOT
#

@inland oak :white_check_mark: Your eval job has completed with return code 0.

'2021-05-05T03:11:35.292740'
inland oak
#

everything completely fine

vestal hound
#

show the tutorial.

inland oak
vestal hound
terse vapor
# vestal hound that should be `token.encode`

In this video, I show you how to use JSON Web Tokens (JWT) to authenticate users of your API. First, a user will have to login using a specially created route which returns a token. Once a token is generated, it can be sent along with the rest of the request to other parts of your API to verify the user's identity without the user having to prov...

▶ Play video
vestal hound
#

and it's already been converted to a string in that code

#

see the .isoformat

vestal hound
lavish prismBOT
#

Hey @cunning crown!

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

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

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

https://paste.pythondiscord.com

velvet yew
#

Can a Django (and probably JS) guru help me with a simple task? I want to update a variable on the front end dynamically that's pulling data from my API

inland oak
opaque rivet
#

wait... so if you have django on an asgi server you can use async/await to speed up tasks a lot. This will brings its performance closer to fastAPI?

tropic otter
#

How do I write test for a django viewset?

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated, IsManagerOrSuperUser]
    filter_class = FoodieFilter
inland oak
#

with using

from rest_framework.test import APIClient
# arrange
client = APIClient()

# act
resp = client.post(
        f"/api/main/ip?api={settings.APIKEY}",
        format="json",
    )
dict_ = resp.json() # data you get, you can assert it further

# assert
assert resp.status_code == 200
tropic otter
inland oak
#

functional testing is sub category of unit testing

tropic otter
#

I am so confused between all these types of tests: functional tests, unit tests, integration tests, e2e tests.

winter atlas
#

Any body can help me to make a bot dashboard in django

inland oak
# tropic otter I am so confused between all these types of tests: functional tests, unit tests,...

lets try to be less confusing then, if I get them right...
everything is test

but unit test is super duper fast test, which checks only your unit of code piece and runs isolated from other tests.

functional test is the same as unit test, but makes sure to test only results of the tested piece of code, using your part of code as black box. The most effective type of unit tests btw. Not always can be applied though, or can be but only after refactoring. It needs your code to be not having... 'secret'/'global' input/outputs to other app sections?

integration test is unit test which is not meeting one of criterias (being fast, not using dependencies, or checking too much of your code behavior), usually used to test work of app with integration of one of dependencies, database or file system and e.t.c. Usually can't be paralleled, because tests use only one existing dependency, which is hard to have isolatingly paralled. Filesystem? Database?

e2e is... like integrating test, but with all dependencies included. Instead of testing one dependency per time, it tests all of them at the same time. The category of this test should be as close to real user as possible perhaps. Using Seleinium to test web site deployed to hoster, should qualify as e2e?

thick cove
#

Does it make sense that a cors library would close websocket connections if there is no "origin"?

quick cargo
#

Yes

#

Because websockets are initialised via a htto request

#

So the normal rules of cors still apply

#

Providing this is in reference to. Browser connection

tiny furnace
#

I'm using Heroku to host a Flask application. The idea of the flask application is to manage a discord bot that I am coding. I can't figure out how to host an web application that runs this discord bot simultaneously (A worker dyno is used for the discord bot, and a web dyno - Gunicorn - is being used for the web app, and I can't get the discord app to run simultaneously with the web app - Using just a web dyno to run both). Any help available would be appreciated - I'm trying to keep to a free hosting option with Heroku :)

gritty cloud
#

it never works (for me)

#

for hosting

inland oak
#

and enough space to run multiple pet projects

#

I get 25 GB SSD, 1 GB RAM, and 1 Core with an OS of my choice for this price

tiny furnace
# gritty cloud i would use replit.com

My problem with repl is that I found it really slow to develop in - it takes a lot of time t install dependancies, and when running a web app with flask, there are alot; I prefer to use pycharm instead. Is there any way to automatically pull into repl from github after every push, similar to heroku?

tiny furnace
opaque rivet
#

@thick cove since when did websockets have no origin?

slim ether
#

which is more suitable for backend work, django , flask , or laravel (php)?

thick cove
native tide
#

how do i make a button in django?

thick cove
#

I'm just thinking it's bad practice for a CORS library to automatically abort websocket connections just because there is no Origin header

quick cargo
#

Not really

#

That would defeat the whole purpose of cors otherwise

thick cove
#

How so, it doesn't deny requests with no origin?

quick cargo
#

Though generally cors is aborted by the client not the server

lavish prismBOT
#

src/quart_cors/__init__.py lines 305 to 309

async def _apply_websocket_cors(*, allow_origin: Optional[Iterable[OriginType]] = None) -> None:
    allow_origin = _sanitise_origin_set(allow_origin, "QUART_CORS_ALLOW_ORIGIN")
    origin = _get_origin_if_valid(websocket.origin, allow_origin)
    if origin is None:
        abort(400)```
thick cove
#

oh that's sick 👀

tired wadi
#

If I go to localhost:port/url will it return a value of a function with a decorator @app.route("/url") in Flask?

quick cargo
#

Try it and see

idle karma
#

Has anyone come across a good clean solution for implementing django-style formsets in Flask with WTForms?

thorn igloo
#

what?

#

what would the benefit of that be?

idle karma
#

Is that aimed at me?

thorn igloo
#

yes, just curious

idle karma
#

It seems pretty obvious what the benefits of a formset are no?
From what I remember of using Django it allowed easily having a form-per-entity of which the user could fill in an arbitrary number and the backend was smart enough to know which ones needed handling

#

Maybe I've mis-remembered

loud flame
#

Hey am working on portfolio website.
Can someone tell me how to divide code and give comments acc. In html file.

thorn igloo
#

i see

calm plume
idle karma
#

My use case is that I want to have a page which displays a "single" form, within which there is a field per object (from a reference table, lets call it R) which allows the user to adjust the number of that object which they "own". Changing this would create or update a row in another table (lets say U) which holds the id of the object from R and the quantity thew user "owns". I want the user to be able to edit all the related object quantities in a single page/form

opaque rivet
#

has anyone used tailwindUI components?

idle karma
#

With formsets you'd just have a form-per-object which were all neatly handled by django

calm plume
opaque rivet
#

ooh, nice. what do you think of them? I'm on the verge of buying it now.

calm plume
#

They're amazing. I've only used the free version, but it seems like a really nice thing to buy because the code is so clean and the components are really nice.

gritty cloud
#

tailwind?

calm plume
#

Yup

gritty cloud
#

what is it

calm plume
#

It's a framework with a bunch of predefined utility classes so you don't have to write custom css

gritty cloud
loud flame
#

@calm plume bro i was asking how to divide d code

gritty cloud
#

is it special in any way?

calm plume
gritty cloud
calm plume
opaque rivet
#

https://tailwindui.com/#components
alright, I'll buy it then. hopefully i can reuse for future projects too.
i'm a bit surprised there's no leaks of them. I've used chakraUI and antd before, but I don't really like them too well.

Beautiful UI components by the creators of Tailwind CSS.

calm plume
#

Tailwind is things like w-1 for width: 0.25rem, h-4 for height: 1rem

#

Also, Bulma is no js

#

With Tailwind's JIT compiler, it's very flexible

gritty cloud
#

interesting

calm plume
#

And some of the better components are new too.

#

So I'm not surprised that there aren't leaks

wooden ruin
opaque rivet
#

yeah they provide react components instead of the html with css classnames

#

i believe

#

$315, hopefully it'll pay off 😄

wooden ruin
#

oh ok, that's cool. i've tried using vue with things like bulma and bootsrtap, but tailwind sounds really exiciting from the looks of it :)

#

oh so tailwind has separate plans right? based on your needs?

opaque rivet
#

welp, I just found you can go on a US vpn and the price drops to $250, nice to know

opaque rivet
#

but that's just tailwindUI, prebuilt UI components (as I'm lazy). tailwindcss differs

wooden ruin
#

ohhh, so tailwindUI has all the builtin support for things like vue/react, while tailwindcss is just a raw css framework?

calm plume
#

TailwindUI is a component library, TailwindCSS is utility classes.

wooden ruin
#

ohhhhhh ok

opaque rivet
#

if you guys wanna use it you can use my account, it works for react/vue

rain ledge
#

can anyone help me with a django query?

native tide
#

Hello friends

#

Anyone can help me with Visual Studio Code?

#

I'm working with a web page

calm plume
valid prairie
#

Hey yo, i have django and celery, and should i create task to every email sending, or should i deley only django.core.mail.send_mail

#

wich point is better?

opaque rivet
calm plume
#

True

#

free is free

opaque rivet
#

so far the component library is real good

quick cargo
#

CoffeeSip Other than Tailwind doesnt have a direct dependency on JS

#

as well as being able to compile down to a much smaller size

quick cargo
#

Bootstrap last i checked has a dependency on JS which means if a browser doesn't support X JS version it'll break your components along with CSS

#

Bootstrap will always come with the extra bloat of JS

calm plume
#

Yeah

#

Well, tailwind has a compiler too

#

And relies on PostCSS and PurgeCSS

#

Unless you use the CDN, which is very slow

quick cargo
#

the cdn is generally ~20ms

#

but yes it's slower because it's serving everything

#

and also the dependency on JS is for the compiler not in order to be user friendly on the deployed site.

calm plume
#

True

#

Headless UI is nice too

steel kindle
stable hemlock
#

I need help with apache on a vultr VPS. I installed apache, opened all the ports, made sure the configuration is correct and that the server is running, disabled the firewalls (And allows the ports through) and I still do not get the default splash page. I have already done a clean reinstall of apache. The server can be pinged fine, my postgresql database on the server works fine.

buoyant shuttle
#

how do i get pictures, or animations like this.

past cipher
#

@opaque rivet did you buy the tailwind ui

opaque rivet
thorny rover
#

so i know in a table you can make it editable with this
<td contenteditable='true'>045FB9B6DEC5</td>
but how do i make it editable and it persists for all users or through refresh?

wooden ruin
thorny rover
#

yeah i was hoping to avoid a database, because while ive used sqlite with python a lot, i have 0 clear how to implement a database with a website

#

but i figured i might get that answer when i asked the question

#

@wooden ruin would i have to use mysql or would a simple csv or sqlite work well with django/html

wooden ruin
#

it depends on how much data you want to store and how you plan on using it

#

are you using django?

#

django has builtin support for sqlite3 which is nice for quick database development

thorny rover
#

well maybe a few thousand entries across 3 tables

#

and yeah im using django

wooden ruin
thorny rover
#

oh nice! ill look up a tutorial, unless you know of a good one

wooden ruin
thorny rover
#

its looks lie this right now

wooden ruin
#

ok that makes it easy because you can represent your table as a table in your database

thorny rover
#

excellent! thanks, ill read up on it

pastel blaze
#

React Native or flutter

dawn heath
pastel blaze
#

I dunno

dawn heath
opaque rivet
lime mist
#

I recently started learning about browser fingureprint technology and I have a doubt. Acc to my understanding, After getting all the identifiers like screen res, canvas, fonts and more the algorithm generates some hash string which is unique to that browser. So, my question is how is this fingur print passed to the servers? Via. Headers? Inside header cookies? As a body? And when? Does it go with each and every request or it has some other behaviour?

#

Pls @me before writing your answer. Thanks

opaque rivet
#

It should be sent with every request, & you can enforce that with middleware on your server to ensure that header is present in every request.

prime shuttle
#

how do I get started with django

#

what's a good resource to start a data extracting website

sand glen
#

hi! im using react.js and i was wondering how to make my react page have multiple pages.

#

do i use react-router? or are there better options

opaque rivet
sand glen
#

ah

#

next.js

#

i always wondered what it did...

#

if im not using SSR, do i just use react-router?

opaque rivet
#

honestly, my understanding of it isn't great either. next.js improves SEO compared to CRA because when a request reaches your frontend, it returns a blank html page and then hydrates the page by manipulating the DOM and changing the content. Thus web crawlers can't index your site too well (there's lots of parameters involved with it). Next.js pre-renders HTML pages with your page information (static generation) thus helping with SEO (and performance).

next.js also has it's own, really nice & simple routing.

#

yeah, if you're not using SSR use react-router - but using next.js will have SSR out of the box as it has its own express.js server

sand glen
#

im not sure whether i should use SSR or not

#

i know that CSR is simpler but apparently you should use a mix of both for the best results

opaque rivet
#

i have more research to do on the topic, but I think it's better to do due to the importance of SEO. with next.js there's SSR out of the box with no setup, so that's a bonus. But one downside is that if you're using modules which require client-side APIs like window, they need a bit of tinkering

sand glen
#

i guess i will use next.js

#

but i have no idea where to start

opaque rivet
#

they have a tutorial on their docs, and ask a question after each lesson. it's pretty decent. apart from that I would read articles / go on youtube - which i still need to do 😁

sand glen
#

alright, thanks for all your help

opaque rivet
#

it's not a big learning curve

sand glen
#

i've been learning react and JS itself for about 15 days now and i've been doing pretty good so far

opaque rivet
sand glen
#

will do

opaque rivet
#

also if you ever get bored of making your own UI components, I can provide you with tailwindUI comps.

sand glen
#

i've heard of tailwind, im fine with my own components for now

#

that might change when i need to make more complex ones

#

but for now im good

opaque rivet
#

👍 also if you want any good resources for learning redux / typescript (which are a killer combo for react) codeacademy is quite good, i might have a few spare pro accs

valid prairie
#
password = forms.CharField(label="Password", widget=forms.PasswordInput, validators=get_default_password_validators())
#

any idea why it wont work?

#

django forms th.

dawn heath
#

what is the effient way to do the following?
# try:
# vulnerability_id = Vulnerability.objects.get(cveid=cve_objects.get('cveid'))
# except Vulnerability.DoesNotExist as err:
# pass

#     try:
#         exploit_id = Exploit.objects.get(vulnerability=vulnerability_id)
#     except Exploit.DoesNotExist as err:
#         pass
opaque rivet
#

@sand glen found a good article explains why next.js is better than CRA for SEO, giving examples too.

pale swift
#

it shouldnt return any errors

dense zephyr
#

this login form redirects me to an external website

#

this to be more precise

#

i don't know why it does that

nova storm
#

Hey guyz, plz have a look on it! I am totally confused about what I did wrong here 😢

nova storm
wooden ruin
nova storm
#

I only want to update the old task

wooden ruin
#

right, so wouldn't it be task, not Task?

nova storm
#

It worked Thanks a lot

#

I have one problem will catch you if I found it again!

native tide
native tide
#

yes

rugged needle
prime venture
#

trying to decide between vue and react.. i dont have much experience in js and really want to learn ts, and have more knowledge in backend like flask. any suggestions?

thorn igloo
#

i don't think it matters that much whether you go with vue or react

dawn heath
small pebble
#

Hey guyz, i am bit confused on choosing a vps(virtual private server) for deploying my django project, i want to know minimum system requirements for it? Is there some method to test the stress on my django website.

muted lion
#

Hello guys, I have a challenge and I would be grateful if you could give me some clue...

I want to run a Dash-Plotly (a framework based on Flask) application inside a Django app. I know Dash has a framework called django-plotly-dash but what I want is a Django app that our developed Dash(aka Flask) apps can easily be imported and run

is there any idea???🙏 🙏 ♥️

thorn nexus
#

Is it possible to use formset for just one specific field out of many fields when submitting a form having several fields with same name?

dawn heath
summer grove
#

does anyone have experience with django websites and can help me? for the life of me i cant figure out how to load static files into a production website

summer grove
# nimble epoch use whitenoise

I tried using whitenoise but they require a lot of setup that doesnt seem to work with my website basically it asks me to use certain commands that dont line up with my files and what i have installed

nimble epoch
#

"it asks me to use certain commands" what commands?

summer grove
nimble epoch
summer grove
nimble epoch
summer grove
opaque rivet
#

Why can't you serve static files from django in production?

summer grove
summer grove
#

but it's bad practice

#

and im deploying the website live

#

I have it working locally

opaque rivet
#

Yeah, but in production you'll want debug off. I'm just wondering why the production sever can't serve static files.

summer grove
#

Well i have njinx and I'm trying to have that serve the static variables but the .sock file wont generate

opaque rivet
#

So the static-file settings in settings.py are only for development? e.g. STATIC_ROOT

nimble epoch
#

not only

#

when a user uploads an image itll go to that folder

vestal hound
#

it’s not secure

#

nor optimised

summer grove
#

@nimble epoch do you have experience with gunicorn?

nimble epoch
#

yes

summer grove
nimble epoch
#

.sock?

#

i never used that typa file

summer grove
#

This is the tutorial ive been looking at

nimble epoch
#

what does .sock do?

summer grove
#

it indicates the file did not start correctly

#

gunicorn*

#

it would be something like this

nimble epoch
#

aha never used it. so you think the problem is in here?

summer grove
#

yea since that file never gets generated

#

so in here

#

i think i messed up one of the variables

#

because my project's file hierarchy is VERY different

#

this is the issue gunicorn tells me too

#

gunicorn.service: Failed to determine user credentials: No such process

nimble epoch
#

never deployed one on linux. gotta try that.

summer grove
#

do you know what im supposed to set user as?

nimble epoch
inland oak
nimble epoch
#

@summer grove does it through any error?

summer grove
#

returns with

opaque rivet
#

@vestal hound not secure? In what way?

#

Also for static files, does nginx serve them in production?

nimble epoch
#

or remove it?

summer grove
#

setting it to that user crashes it and removing it has no effect