#web-development

2 messages ยท Page 151 of 1

inland oak
#

btw you are probably missing installed dependency or activated venv

summer echo
#

Should I learn django or flask?

dawn shard
#

?

dawn shard
summer echo
#

Better just overall?

inland oak
#

python -m pip install Django

#

although I would advise installing in venv

#

which means...

#

what is your OS?

dawn shard
inland oak
#

python -m venv venv
venv\Scripts\activate
python -m pip install Django

#

in next sequence, commands then

#

be sure to activate your venv, when you start to work

tulip beacon
#

hey guys, anyone good at react? I have a startup idea to discuss. If you are good at react dm me

inland oak
#

pip freeze > requirements.txt
a way to... copy all your current requirements dependencies to quick install file

rare ibex
#

can someone help me with this please

dawn shard
inland oak
#

pip install -r requirements.txt in just started venv, in order to reinstall them

inland oak
dawn shard
#

ok. got it

summer echo
inland oak
#

shrugs
standard is good one
i recorded it to my .bashrc file

alias ac='[ -d "venv" ] && . venv/bin/activate || (python3.9 -m venv venv && echo "created venv" )'
alias de='deactivate'
alias dj='python manage.py'
alias sc='python scripts.py'
#

in order to have quick venv activation with ac (creates venv if there is no one)

summer echo
#

Good luck though

dense slate
#

I cannot find anything in the docs to answer this, but was there a major change to on_delete in Django 3? I upgraded from 2 to 3 on a project (working on version 2) and I get TypeError: on_delete must be callable. on a model field that has no on_delete at all. When I add one,it states that there are multiple values for the argument on_delete. Any ideas?

dawn heath
opaque rivet
#

you're raising a 404 error, is that not what you wanted?

limber laurel
#

could someone help me to do something?

vivid canopy
#

help me! i can't howl my photo

#

i don't understand which path i should past in html

native tide
#

Hey guys anyone has expereince using flask and firebase

serene prawn
summer echo
#

So what are the differences?

serene prawn
#

Flask would be better for api's

summer echo
#

Oh ok

#

and django is more advanced right?

serene prawn
#

And allow more freedom in your app architecture

#

I would say that flask is more advanced ๐Ÿ˜…

summer echo
#

Oh

serene prawn
#

Since you have to pick all components you want (orm, etc)

summer echo
#

So why does the majority pick django?

#

Ooh I see

serene prawn
#

But it's more simple too

summer echo
#

there are more features i suppose

#

yes

serene prawn
#

Yes, django has built-in auth, orm and admin

summer echo
#

Yeah ok

serene prawn
#

But actually i would use fastapi over flask

summer echo
#

For API's or just in general?

serene prawn
#

For api's

summer echo
#

Yeah ok

serene prawn
#

If you use server rendering (jinja/django tempaltes or something like this) then i would go with django

#

Django isn't that great for api's

summer echo
#

So if I want to build a web app which does not include api's Django would be the best option?

serene prawn
#

With server side rendering? ๐Ÿค”

summer echo
#

I just started with web development

#

I have no idea what that means ๐Ÿ˜‚

serene prawn
#

html templates that server populates with some info and give to the client

summer echo
#

Okayy

serene prawn
#
Smashing Magazine

Statically generated sites or pre-rendering and server-side rendered applications are two modern ways to build front-end applications using JavaScript frameworks. These two modes, yet different, are often mixed up as the same thing and in this tutorial, weโ€™re going to learn about the differences between them.

summer echo
#

Thanks!

serene prawn
#

Scroll down to like definition of server side rendering

#

Again, it's like just populating your html templates with some data you have in your database

#

Do you have any sql knowledge?

summer echo
#

Not much

serene prawn
#

I guess django can be easier in what comes to sql

summer echo
#

Okay

serene prawn
#

It does many things for you

summer echo
#

I think I'll try both out

serene prawn
#

If you would like to make use of type annotation i would go with fastapi

summer echo
#

Yeah

serene prawn
#

And fastapi has everything flask has, so imo there's no point in using it

summer echo
#

using flask?

serene prawn
#

Yep

summer echo
#

Fair enough

#

I guess i'll look at that as well then ๐Ÿ‘€

serene prawn
#

Sure do

summer echo
#

Ty!

dense slate
#

I think i figured it out. But regarding SSR, i love using Django but have recently learned about the benefits of Next.js. what are your thoughts on using next vs React with Django? I love python and want it for my backend but needa better solution for the front end and React seems to have poor SEO. @serene prawn

serene prawn
#

I don't have much experience with react

#

And i talked about template rendering really

dense slate
#

What's your optimal solution for front end with Django then?

#

I know, just thought you might have an opinion. ๐Ÿ™‚

serene prawn
#

I won't really use frontend framework with django ๐Ÿ˜…

dawn heath
#

does anyone oculd help me with celery?

opaque rivet
opaque rivet
dense slate
#

Right. I'm hoping to take advantage of the caching in next to speed up my Django projects.

#

Guess I'll just have to try it!

quick cargo
#

Django doesnt serve static content anyway (and shouldnt for that matter)

#

and if you're using just to make the API at that point just use FastAPI

serene prawn
opaque rivet
# quick cargo NGL at that point why use Django

yeah I know it's not the best, personally I learnt django for employability and it doesn't seem like FastAPI is that sought after. But once I've had my time with django I'll 100% move over, either that or a JS backend

quick cargo
#

FastAPI is generally a very sought after backend as client side rendering becomes even more prominent

opaque rivet
#

i don't doubt it, but just searching "fastapi" vs "django" for jobs and seeing what is available is what is keeping me from it

quick cargo
#

It generally depends on it

opaque rivet
#

but also, if you are using next.js and want server side rendering, why not use django?

quick cargo
#

Django certainly isnt used to be an API

#

because it really doesnt do a great job at it

#

You basically dont make use of any of the pre-built boiler plate stuff, model validation is a pain and throughput isnt the best

#

Doing a E-Commerce site? highly cached? Sure use Django

#

and thats what alot of these contractor jobs do because it's quick and doesnt really need to be api based like that

#

but as soon as you get to API only type setups then Django kinda a meme really

dawn heath
serene prawn
quick cargo
#

DRF yikes

#

I cannot tell you how much i hate my life when writing rest and api frameworks in Django vs FastAPI

dapper tusk
#

I remember there being a django module for graphQL

quick cargo
#

As much as Django's orm is cool and all

dapper tusk
#

Patryk used to recommend it

quick cargo
#

its still such a yikes compared to FastAPI or a micro framework

dapper tusk
#

honestly, I have found fastAPI extremely painful once I needed to do anything that required metaprogramming

#

since it parses the signature

quick cargo
#

Just mod it ๐Ÿ˜‰

dapper tusk
#

I ended up using stalette

quick cargo
#

I actually made a framework wrapper for that tbh

opaque rivet
#

so how about node.js? I heard deno is good

quick cargo
#

Deno inst NodeJS firstly

#

and also IIRC atm Deno is still a beta system

dapper tusk
#

node is ok, but I am not fond of nodes dependency style

quick cargo
#

Deno is mostly for TypeScript because of the auto compile

#

but again, not recommended for prod as of yet

#

My experience with Node frameworks is sad

opaque rivet
#

ah yeah it's not the same thing, thought it was as they have the same creator

#

but typescript is lovely ngl ๐Ÿ™‚

quick cargo
#

Typescript is great

#

just alot of web frameworks suck in places, mostly cuz JS tings

#

bit like go tbh

#

as much as i like some of what Go does

#

i cant write backend frameworks with it

#

PepeHands Doc strings or lack there of

dapper tusk
#

I don't really know what server framework to suggest. starlette/fastAPI are probably my best bet, but ORM integration is pretty obnoxious last I saw it.

serene prawn
quick cargo
#

ORM stuff kinda blows for async in general tbh

#

Atm im working on a async orm built of PyDantic

dapper tusk
#

raw SQL works OK, but it is an extra hour of messing with queries per project

quick cargo
#

cuz i got so fed up of SQLAlchemy core not supporting model inheritance

dapper tusk
#

another 2 if you need migrations on top of that

serene prawn
dapper tusk
#

sometimes

opaque rivet
#

tbh I've been on the brink between django and node.js for a while

quick cargo
#

I mean learn both

opaque rivet
#

what do you guys say?

quick cargo
#

but NodeJS is an entire language

#

its not really a HTTP framework

#

well, it has support for it

opaque rivet
#

mhm, well specifically express

quick cargo
#

but no one uses just it

#

Express sucks

dapper tusk
#

to be perfectly honest, for 90% of projects, any reasonably popular web framework will do the job perfectly

serene prawn
#

nest js seems cool ๐Ÿ™‚

dapper tusk
#

what you need to do is identify which parts of your project are going to hard, and decide around those

opaque rivet
#

hmm yeah that's quite true

dapper tusk
#

there are some really cool things in node, like https://blitzjs.com/, but you have to figure out how its deps look and such

quick cargo
#

tbh at that point Next.JS is probably enough

#

although im not a fan of Next

serene prawn
#

Wouldn't nestjs be more powerful? ๐Ÿค”

quick cargo
#

shrug In most cases it literally doesnt matter

#

Its like when people argue over using a framework "cuz framework x got n score on techempower vs framework y that got n score on there"

serene prawn
#

Yeah, but nestjs makes good use of typescript and allows you to encapsulate your logic into services

#

so why not

serene prawn
quick cargo
#

benchmarks mean nothing in reality

serene prawn
#

But if one thing is ~10 times faster than other and it's similar to it then why not?

quick cargo
#

generally because it doesnt tell you the reality of the performance

serene prawn
#

Say fastapi and flask, that's nobrainer even if fastapi was the copy of flask

dapper tusk
#

most web services are IO bound

#

CPU load is more or less meaningless

quick cargo
#

a framework thats really good at pipelining vs a framework thats really good a real world requests

#

the pipeliner will win but at a cost

serene prawn
#

Btw does sqlalchemy has async support? ๐Ÿค”

quick cargo
#

not really

#

there's databases or orm but they only support a very minimal amount of alchemy core

#

and so no model inheritance sad

serene prawn
#

I guess i would stick with sync sqlalchemy for now then ๐Ÿ™‚

quick cargo
#

yeah

#

core

serene prawn
quick cargo
#

personally i dislike alchemy

serene prawn
#

I use future mode though ๐Ÿค” so it should work

#

What would you use then?

quick cargo
#

I generally dont use ORMs like that

native tide
#

What if

#

I put my web app's url in here ๐Ÿ˜ณ

#

what are the chances that I get hacked

serene prawn
#

hacking intensifies

quick cargo
#

recently what i've been working on my more official ORM for pydantic

#

just because i see no point in a ORM without inheritance angryeyes

native tide
#

SQL Alchemy? ๐Ÿ˜ณ

serene prawn
quick cargo
#

not really

#

for example what we have alot of it a entity base

#

then extensions of that

serene prawn
#

Exclude/Include fields, relationships?

quick cargo
#

going onto specific setups

#

class Entity(BaseModel):
  ...

class ExtendedEntity(Entity):
  ...

class User(Entity):
  ...

class Area(ExtendedEntity):
  ...
#

inheritance is by far the most powerful thing imo with ORMS pithink

serene prawn
quick cargo
#

not really bloblul

serene prawn
#

Though there might be many use cases for it

quick cargo
#

i dont want all these duplicate models n shit

serene prawn
#

I guess i can stay on sync sqlalchemy for not then ๐Ÿค”

#

Though it sqlalchemy fully supports async @quick cargo

#

Is it okay to ping you?

quick cargo
#

CoffeeSip Sure

serene prawn
#

It just returns weird list of Rows ๐Ÿ˜…

#
async def retrieve_all(self) -> List[Entity]:
    async with self.async_session_factory() as session:
        query = select(Entity).order_by(Entity.name).options(selectinload(Entity.children))
        result = await session.execute(query)
        return [row[0] for row in result.all()]
#

But it works ๐Ÿค”

quick cargo
#

pithink Curious that all() isnt async tbh

serene prawn
#

It should be cpu bound ๐Ÿค”

quick cargo
#

although if i remember i think it selects all every time so ig maybe not

serene prawn
#

It shouldn't do any io

quick cargo
#

I mean generally it should be IO bound because typically you dont wanna fetch every row every time you do a query

serene prawn
#

because this works ๐Ÿค”

async def retrieve_all(self) -> List[Entity]:
    async with self.async_session_factory() as session:
        query = select(Entity).order_by(Entity.name).options(selectinload(Entity.children))
        result = await session.execute(query)
    return [row[0] for row in result.all()]
#

it's a small table in this case

quick cargo
#

lets say you have some massive DB with multiple matching rows, you dont always want to select all the data and send it over the network

serene prawn
#

But limit works

quick cargo
#

yeah

serene prawn
#

In my case it's a table with tags so i can safely return all of them

#

It wouldn't be bigger than ~50 rows and i want to display all of them in my vue frontend ๐Ÿค”

#

Anyway i don't like how it returns the data ๐Ÿ˜…

quick cargo
#

It's the standard SQL way

#

AsyncPG does a nice job with its Record class

serene prawn
#

How can you can have multiple entities in single row?

quick cargo
#

because each row can return several column values which are apart of the row

#

all() returns all the rows

#

but each row has a set of columns

serene prawn
#

But it returns model instance ๐Ÿค”

quick cargo
serene prawn
#

[(<tags.models.Tag object at 0x00000292917B0820>,)]

#

๐Ÿ™‚

quick cargo
#

Im guessing maybe Many to Many then

serene prawn
#

๐Ÿค”

#

Anyway i could use a little helper function then...

quick cargo
#

or just not use alchemy mmLol

serene prawn
#

ffs

#

๐Ÿ˜…

#

I already switched from django to fastapi

quick cargo
#

Raw SQL ๐Ÿฆพ

serene prawn
#

no no no

#

NoSql in my py files ๐Ÿ™‚

#

I can use a decorator though ๐Ÿ˜…

winged agate
#

I'm gonna go to sleep now, but leaving this here overnight:
How could I go about making a web dashboard so my bot can be controlled from there?
Please ping me if you can help, hope this doesn't break any rules lol

dawn heath
wanton forge
#

So I'm making an application that I want to deploy as a website and I am running around in circles unsure of what to do

#

It is a computatinally intensive app so it needs to connect to an AWS EC2 instance with vCPU's in order to serve the user's requests

#

Im just not sure what the overall structure of the website is supposed to look like

#

is the entire thing supposed to be within a docker/kubernetes container that starts a new instance every time a user visits the site?

brisk spindle
#

There must be nothing computationally intensive on a visit of a website.

wanton forge
terse vapor
#
@app.route("/addpatient", methods=['GET', 'POST']) 
@login_required 
def addpatient(): 
    v = Newpatient.query.first()
    a = Totalpatient.query.first() 
    form = PatientForm() 
    if form.validate_on_submit(): 
        patient = Patient(name=form.name.data, number=form.number.data, gender=form.gender.data, year=form.year.data, month=form.month.data,
        day=form.day.data, street=form.street.data)   
        db.session.add(patient) 
        db.session.commit()
        patient = Patient.query.all() 
        for i in patient:
            if Patient.name not in i: # Error: TypeError: argument of type 'Patient' is not iterable
                a = Totalpatient() 
                a.count += 1
            else:
                a.count += 0
        if not v:
            v = Newpatient() 
        v.count += 1
        db.session.add(a) 
        db.session.add(v) 
        db.session.commit()```
#

Im not sure where i did wrong

serene prawn
#

@terse vapor
Is Patient.name nullable?

terse vapor
#

False

#

its False

serene prawn
#

What you're trying to do then?

terse vapor
#

Im trying to do if the new patient has come to the clinic before, it will just save to db with adding 0, and if its first time here, it will add as a new patient and save to totalpatient db

serene prawn
#

First name is unreliable but you can just find it in the database

#

By it's name

terse vapor
#

the name its actually use in a different language

#

so in that language, there's no first or last name

serene prawn
#

Wdym

#

You can just query a patient by it's name from database

#

to see if the record is there

#

And you usually don't want to have duplicate rows in your database

#

That's a bad database design

terse vapor
#

hmmm

#

good idea

serene prawn
#

And what are TotalPatient and NewPatient?

terse vapor
#

Totalpatient = All patients with different name, like how many different people have came
Newpatient = All records of patient

serene prawn
#

Ehm ๐Ÿค”

#

I still don't understand what NewPatient is

#

Can't you have like Patient table and PatientVisits?

terse vapor
#

its basically all patient that have came to the clinic

serene prawn
terse vapor
terse vapor
serene prawn
#

You literally don't need TotalPatient and Newpatient ๐Ÿ˜…

terse vapor
#

๐Ÿ˜…

#

btw, how can u filter the patient by this month or like today?

serene prawn
#
from dataclasses import dataclass
from datetime import datetime


@dataclass
class Patient:
    id: int
    name: str
    ...


@dataclass
class PatientVisit:
    id: int  # every database record should have an id to identify it
    patient_id: int  # a foreign key to Patient
    #  Any info you want there
    date: datetime  # The date for example
#

I think sqlalchemy can compare datetime and build queries from it

#

I wrote these 2 as dataclasses just as an example

terse vapor
#

Ya, i tried like

current_month_expenses = Patient.query.filter_by(patient_id=patient.id).filter(Patient.create >= from_date).filter(Patient.create <= datetime.now()).all()```
serene prawn
#

That should work

#

But you would filter on PatientVisit

terse vapor
#

but patient visit only records number

#

so i have to go to patient

serene prawn
#

You can filter by patient id...

#

Also there's a foreign key so it's easy to obtain related entities

terse vapor
#

ok

serene prawn
#

That should work ๐Ÿค”

patient = Patient.query.get(patient_id)
visits = patient.visits.filter(start_of_month <= PatientVisit <= now).all()
#

You can also make sql do the sum ๐Ÿ™‚

terse vapor
#

ok, im going to try it rn

serene prawn
#

What orm are you using?

#

@terse vapor

terse vapor
#

im sorry, whats a "orm"?

serene prawn
#

Object Relational Mapper ๐Ÿ™‚

#

A layer that maps your table entities to models

terse vapor
#

well no

serene prawn
#

Well you do use one...

#

Django? Peewee?

coral bluff
#

Hello, how do I convert the first word into uppercase or capitalize in php html?

serene prawn
#

PHP ๐Ÿ‘€

coral bluff
#

for example i input Web DevelopMent then the result should be WEB Development

terse vapor
serene prawn
#

That's not an orm but a web framework ๐Ÿ˜…

#

Show your imports on top of that file

terse vapor
#
import os
import secrets
from flask import render_template, url_for, flash, redirect, request, abort, session, jsonify
from flaskblog import app, db, bcrypt, mail
from flaskblog.forms import PatientForm, MedicineForm, RegistrationForm, LoginForm, DetailForm, AddWorkLogForm, UpdateDoctorForm, AdminLoginForm, AdminRegistrationForm, AddannouncementForm, RequestResetForm, ResetPasswordForm
from flaskblog.models import User, Detail, Medicine, Patient, Worklog, Admin, Announcement, Newpatient, Totalpatient
from flask_login import login_user, current_user, logout_user, login_required
from flask_mail import Message
from datetime import datetime```
coral bluff
#

am i in the right cahnnel?

serene prawn
#

show flaskblog.models imports?

terse vapor
#

User, Detail, Medicine, Patient, Worklog, Admin, Announcement, Newpatient, Totalpatient

#

these?

serene prawn
#

@coral bluff You are but it's more or less a python server ๐Ÿ˜… I have some experience with php but don't really want to touch it

#

@terse vapor Just imports on top of models file

coral bluff
serene prawn
#

@coral bluff What are you using php for?

coral bluff
#

for my project

serene prawn
#

I mean what kind of

coral bluff
#

only input and output in display

#

lemme screenshot

serene prawn
#

Just plain php? ๐Ÿ˜…

coral bluff
#

yes

#

just plain

#

the web word should be capitalize

serene prawn
#

I wouldn't develop anything in plain php
If you want it to be manageable after it grow to like 5 files ๐Ÿ˜…

coral bluff
#

ooooh!

serene prawn
coral bluff
#

yeah im still learning in php and also in html ๐Ÿ™‚

serene prawn
#

I asked you to show the imports...

terse vapor
#

๐Ÿ˜…

#

my bad

serene prawn
#

@coral bluff

>>> s = "Web Development"
>>> words = s.split(" ")
>>> words[0] = words[0].upper()
>>> " ".join(words)
'WEB Development'

๐Ÿค”

#

I would just find methods that do the same in php

thorn nexus
#

I have a url pattern that looks like this:

re_path(r'var1/(?P<var1_id>[0-9]+)/edit/(?P<var2_id>[1-5]+)', view_1),

This should match var1/47/edit/3 for example. Is there a way to dynamically set the view function the URL is handed to based on the last integer (3 in this example)?
So, var1/47/edit/3 is routed to view_3 in views.py, while var1/47/edit/4 is sent to view_4

serene prawn
#

You can pass variable with that number into view itself

thorn nexus
#

Maybe I'm just over thnking it.

serene prawn
#

Why would you have a bloated view in a first place? ๐Ÿค”

#

What these last digits mean?

thorn nexus
#

I'm using the digit to determine which model to edit.

serene prawn
#

So they're different models or different model instances (rows)?

thorn nexus
#

they are different models

serene prawn
#

๐Ÿค”

#

And what's first id for exactly?

#

var1_id

thorn nexus
#

a parent model. When var1_id is created, new object for var2 is also created. model for var2 has a fk relationship with var1 model.

serene prawn
#

Would be better if you name your id's accordingly

#

like user_id

#

for example

thorn nexus
#

agree. var names posted here are just placeholders for actual variables I'm working with.

#

logic is same though

serene prawn
#

You're is it SPA or server rendered app?

#

via templates or something

thorn nexus
#

yes, templates

serene prawn
#

You can have 5 view that would modify their own models

#

That would be a good approach

thorn nexus
#
re_path(r'var1/(?P<var1_id>[0-9]+)/edit/(?P<var2_id>[1-5]+)', view_1),

In this case above, all 5 possible options will be routed to view_1 method.
Then while inside view_1 check for int and send them to their respective view?
I want to cut out the intermidieta view_1 to start with.

serene prawn
#

You can have something like

path("something/<int:someting_id/edit/another-thing", edit_another_thing_view)
...
#

For all five of them

thorn nexus
#

yeah, explicitly state the urls.

#

I guess that is the way to go without tripping up myself

serene prawn
#

๐Ÿค”

#

At least that would be easier if you use templates

thorn nexus
broken oar
#

Hey, I've got my code down to ```py
@app.route("/api/postmethod", methods=['put'])
def journal_put_controller():
req = request.get_json()
absolute_path = os.path.dirname(os.path.abspath(file))
file_path = absolute_path + "/data/journal_testfile.json"
with open(file_path, mode="a") as outfile:
json.dump(req, outfile)

return {"message": "JSON Received"}
```json
{
    "journals": [
        {
           "date": "01/03/2021",
           "name": "Test",
           "note": "Testing"
        },
        {
           "date": "07/03/2021",
           "name": "Test",
           "note": "Testing"
        }
    ]
}
rare ibex
nimble dawn
#

how is it

#

i will fix the image

hard quail
#

@nimble dawn would you like the color not to be white?

#

or to fit it differently?

#

Hello, this is a web dev help question so not exactly python related, but I would like to see if anyone knows how I could get the following code:


<div class="Hamburger_menu">
    <img src="{% static 'images/logo.jpeg' %}" class = "logo">
    <input class="hamburger_checkbox" type="checkbox" id="hamburger_id">
    <label class="hamburger_icon" for="hamburger_id">&#9776 </label>
    <label class="hamburger_cross_icon" for="hamburger_id">โœ•</label>
    <div class="header">
        <ul>
            <a>
            <input class="dark_mode_button" type="checkbox" id="dark_mode_id">
            <label class="dark_mode_button_display" for="dark_mode_id">DarkMode </label></a>
            <a href="/logoutpage"> Logout</a>
            <a href="/logoutpage"> Logout</a>
            <a href="/logoutpage"> Logout</a>
            <a href="/logoutpage"> Logout</a>
        </ul>
    </div>
    <div class="news_div">
        <h1>{{Article_name}}</h1> 
        <h1>{{Article_author}}</h1> 
        <h1>{{Article_title}}</h1> 
        <h1>{{Article_desc}}</h1> 
        <img src={{ Article_img }} alt={{Article_name}} class="acticle_img">
        <a href= {{ Article_url }} >link text</a>
    </div>
</div>

@media only screen and (max-width:600px) {
  .hamburger_icon{
    display: block;
  }
  .header{
    text-align: center;
    width: 100%;
    display: none;
  }
  .header a{
    display: block;
    border-bottom: 1px solid red;
  }
  input:checked ~ .header{
    display: block;     
  }
  input:checked ~ .hamburger_cross_icon{
    display: block;     
  }
  input:checked ~ .hamburger_icon{
    display: none;     
  }
}
/* Dark Mode Button */
/* .dark_mode_button{
  display: none;
} */

input:checked ~ .a{
   background: red;
}

What I am trying to do is to get the dark_mode_button to change the backround color of tag a. I'm not sure how to do this because I have already used an input tag, therefore input:checked does not work!

Any help would be appreciated!!!

grand oriole
#

I use python flask, and to make a path, normally it's this:

app.route('/path')
def path_funct():

how would i create a new one without actually editing the code (when it receives a POST request, it makes a new path)?

glad patrol
#

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
how to fix this error
i install log4net but it still giving me error

hard quail
#

Hey guys, how do I get this to work:

input#dark_mode_id:checked ~ #header{
  background: green;
}```
```html
div class="header">
        <ul>
            <a>
            <input class="dark_mode_button" type="checkbox" id="dark_mode_id">
            <label class="dark_mode_button_display" for="dark_mode_id">DarkMode</label></a>
            <a href="/logoutpage"> Logout</a>
            <a href="/logoutpage"> Logout</a>
            <a href="/logoutpage"> Logout</a>
            <a href="/logoutpage"> Logout</a>
        </ul>
</div>```
serene prawn
native tide
#

@inland oak You can automate stuff in windows too yakno ๐Ÿ‘€

#

treat $PROFILE as .bashrc ๐Ÿ‘

inland oak
#

like... what's the point to be in Windows
if we need to adapt our project to run in Linux anyway?

native tide
#

well, most regular users, including developers use windows, that'd be one major reason

inland oak
#

web dev projects are run at Linux servers.

native tide
#

yea

inland oak
#

users get their results through browsers
no need for the work to be windows compatible

native tide
#

but development itself is mostly done on windows devices, I'm not saying this is how it should be

#

but that's how it is

#

and there are applications that are not happening on web

#

a decent few in fact ๐Ÿ™‚

inland oak
#

same can be said about Windows

you can't launch without pain there... (or just can't)
Docker (+compose)
Kubernetes
Redis / Celery
Postgres
Nginx

#

if you want to be python backender, which can deploy his own project

#

better be in Linux

native tide
#

launch what?

inland oak
#

All right, easy example

#

for any web project, Flask, Django, or whatever

#

there is requirement often to be able

#

settings tasks in Celery

#

which use Redis database

#

how are you supposed to debug it in Windows?

native tide
#

I've never worked with celery so i wouldn't know

inland oak
#

or... deploying your project in Docker

#

this is.. like super often requirement

native tide
#

deploying docker is simple on windows

inland oak
#

only Windows 10 supports docker

native tide
#

and win server

inland oak
#

yes, we can blindly write instructions from Windows for Linux

#

but why to endure pain (in form of increased time to debug)

#

when it can be tested directly

#

if you are in Linux?

native tide
#

you're making very broad statements I'm trying to understand

#

why imply debugging takes more time in windows?

#

i wish to know

inland oak
#

because
you have no direct/easy access to install services like Docker/Redis/and e.t.c. in literally few commands
Your dependencides only where tested to work OK in Windows
Your application paths were tested only to work OK in Windows

#

all it leads to...

native tide
#

You do know Docker on windows uses WSL right?

inland oak
#

testing application through... some ssh connection

#

on Linux Server

#

but it is not really convinient

#

when it can be tested on main machine

#

yes, some could write piplines

native tide
#

and you're wrong

inland oak
#

for automated testing for Linux compatibility

native tide
#

there are scripts that automate installing those

inland oak
#

but, I think it is just not enough

#

well, I suppose so, Chokolatey exists after all

native tide
#

correct

#

and powershell is extremely powerful shell in itself

#

thanks to it's .NET bindings

inland oak
#

but, we are usually needing linux scripts to automate our CI

#

windows scripts are next to useless

native tide
#

if you have linux server sure

#

i'd image that being the case

#

I mean, depends on your workload, powershell as shell is available on linux freely

#

so if you work with python and pip, pwsh script is "cross platform" in that sense

inland oak
#

it can work as substitution
but it smells weird to me

native tide
#

ยฏ_(ใƒ„)_/ยฏ

inland oak
#

after all, it is not even available in any Linux

native tide
#

it is

inland oak
#

without installation of it

native tide
#

in all of them

#

it's open source

#

oh

#

yea, you have to install program to use it

#

that's how things work yes

#

it's not preinstalled

#

๐Ÿ™‚

inland oak
#

it will make usage of public docker images harder

native tide
#

why so

inland oak
#

well, you would have to... you know...
being finding how to install powershell to every differently used docker image
and you don't for sure always, which is even Linux version is there

#

Ubuntu/Alpin/Debian

#

stable, or super freshly new ones

#

shell scripts work always

native tide
#

so you're discussing scripts inside docker images now?

inland oak
#

yup.

#

which use Linux most of the time

native tide
#

I was under the impression docker images are supposed to be immutable, so majority of it's use should be with just dockerfile

#

running shell script directly on image seems unconventional

inland oak
#

well, yes. But from project to project, to different goals
you are usually changing which docker image you use

#

because some of docker images already have everything preinstalled

#

in terms of going to be used services

#

saves a lot of time, from doing on your own

native tide
#

doing what, on your own?

#

managing different containers?

inland oak
#

for example
docker image with preinstalled
python
or npm
or even with preinstalled docker inside of it
continue the list with any required service

native tide
#

yes, what about it?

inland oak
#

forget about it

manic current
#

Hello, does anyone know the HTML language here? If anyone knows, the link does not work when adding the link, if you know why can you write please, thanks

limber laurel
#

I am trying to run django in production mode, but for some reason I am getting a 500 error

native tide
#

href attribute is http reference (aka link)

manic current
#

Okey thanks :)

inland oak
#

you have probably static file problem

#

this is bad solution to test it

limber laurel
#

still the same error

inland oak
#

the error can't be silent

#

try to read it

limber laurel
#

nothing was outputted on my console

#

[26/Apr/2021 10:54:14] "GET /admin/login/?next=/admin/ HTTP/1.1" 500 1451

hard quail
#

If I wanted to like keep track of a list that each indivdual user has inside of Django, how would I go about doing so

#

if there a video someone has

#

or how I would do it

unique bluff
#

hey can someone please help me with my HTML coding please

inland oak
limber laurel
#

no I dont

native tide
#

@hard quail list as a python list? more commonly you'd use a database if you need to store some data permanently

#

if you were discussing a "list" on client side that will only hold objects temporary, you would likely have to use JS for that

#

"Django" as framework doesn't hold data, whatever database you use does (likely SQLite)

hard quail
#

hm ok I will look into it

#

would it be hard

#

to store data

#

i.e jimmy has 5 appels

#

and 10 bananas

shy fiber
#

I have a chat exported in file.txt I'm turning this into csv file by pandas and plotting some graphs with that csv file
Someone tell me how do I start implementing this in django

#

I have to put it on the web please help

inland oak
#

Hmm

#

can be Django model splitted into several classes?

shy fiber
#

Classes can be split so they has to

#

I don't know about django much but I know classes

#

ask others they might help you better

inland oak
#

I know, how that supposed to work with classes

#

I just not sure how it would interpret django

shy fiber
#

I'm totally newbie don't where to start

#

it's been 1 week I'm stuck with this problem

inland oak
#

web scrapping
with beautiful soup or xpath

frank lake
#

which framework can I use for sql database in aiogram(python)? I want something like in django

inland oak
#

you probably meant to say, which ORM library I could use in framework aiogram

#

the answer: SQLAlchemy, peewee, PonyORM

frank lake
#

I checked it, I think it's better to use django, how to use django with aiogram?

iron osprey
#

Can i make comment section in my website using python?

terse vapor
#

yes

iron osprey
#

Can you teach me?

#

Like when a user comments in it , it should be displayed on the website

#

Something like that

#

I just want to learn that

terse vapor
#

u can use the post id on comment model

iron osprey
#

@terse vapor dm?

terse vapor
#

sure

chilly totem
#

I have a question concern an error I encounter, what's the appropriate channel to drop that please

formal gull
#

any recommendations for this? Access to fetch at 'http://URL:8000/search?number1=2C5Z-6A666-AA&name1=&number2=&name2=&number3=&name3=&number4=&name4=&number5=&name5=' from origin 'http://URL:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. i can successfully do my search on my main computer but on another i cant.

opaque rivet
formal gull
#

yes

#

django, and react

#

if react matters for this

#

i dont think so though

chilly totem
#

Hi.
I'm back again :weary: :weary:

Error everywhere.
I am working on a project using Django, and unfortunately my python version doesn't allow me to install django-filter.

I had to uninstall the already version (3.9) to a lower version (3.7). And now I'm unable to install Django on this new version, not to talk of continue my project anymore.

Any help will be appreciated pease. Thanks house.

opaque rivet
formal gull
#

i did not. it is working on one machine which is weird to me.

opaque rivet
chilly totem
opaque rivet
formal gull
opaque rivet
formal gull
#

ill read through that though and do it ๐Ÿ‘

#

thanks

chilly totem
chilly totem
opaque rivet
#

apart from that I would just say reset your virtual environment & reinstall dependancies

chilly totem
#

I'm even more confused now, because I uninstalled the version 3.9 and installed 3.7 already. Now I'm unable to install Django less proceed on my work ๐Ÿ˜ฉ ๐Ÿคฆ

chilly totem
hallow perch
#

Any idea?

wary trench
#

guys do someone knows why selenium doesnt really work if you dont look at it (if i dont scoll down manually it doesnt work)

formal gull
#

but not on a normal browser

#

ill try and clear cookies etc. but im confused lol

#

that did it i guess

opaque rivet
formal gull
opaque rivet
formal gull
#

alright gotcha. ill do more research into that. im kind of just trying to learn everything there is and just getting through my first small project on web dev so

#

thanks ๐Ÿ™‚

past cipher
#

Does anyone know how to get live reload to work for Jinja templates? I have debug mode enabled. if I make a Python change, then it automatically reload. I am unable to get it working for Jinja templates. I know I can do the refresh myself, but I really need live reload

dawn heath
#

do I really need django-celery-beats, and results?

opaque rivet
#

in celery settings you can specify the tasks you want on the beat

#

then run a beat / worker

dawn heath
#

Django-celery-beats, results is just django backed ORM, but if I setup simple without them. Where will it save?

past cipher
fringe wyvern
#

There is a way that I can do on my site (html, css, js) login with google gmail?

wanton ridge
#

Anyone has a good javascript tutorial?

terse vapor
past cipher
#

thats python reload, it works but crashed when you modify a .py file

#

@terse vapor

hallow perch
#

Hello, i use Flask-Discord to create a connection but Firefox return me after accept the connection Firefox canโ€™t establish a connection to the server at 127.0.0.1:50000.

@app.route('/login/')
def login():
    if not discord.authorized:
        return discord.create_session()
    if discord.authorized:
        return redirect(url_for('dashboard'))


@app.route('/callback/')
def callback():
    data = discord.callback()
    redirect_to = data.get('redirect', '/')
    return redirect(redirect_to)

Any idea?

wheat wigeon
#

Hello! I just read about race conditions and how to solve them in Django using the F function.
However, since I could not summon a race condition by myself, I am not sure if I solved it right. Can someone help me check my code if I solved it properly?

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
            # Redisplay the question voting form.
            return render(request, 'polls/detail.html', {
                'question': question,
                'error_message': "You didn't select a choice.",
            })
    else:
        selected_choice.votes = F('votes') + 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
past cipher
terse vapor
#
Patient = Patient.query.first() 
        for i in Patient:
            if i.name not in i:
                a = Totalpatient() 
                a.count += 1
                db.session.add(a) 
            else:
                a.count += 0 ```
#

Why is this TypeError: argument of type 'Patient' is not iterable

past cipher
#

maybe because the model is also called Patient ?

#

maybe try a = Patient.query as a test

terse vapor
#

u mean the Totalpatient model?

past cipher
#

then try print (type(patient))

terse vapor
#

ok

past cipher
#

and i don't know, if your Totalpatient model is called that, it should be Patient = Totalpatient.query

terse vapor
#

well, patient is about patient personal info, and totalpatient is just counter

past cipher
#

try what i suggested first, I think that could be the issue

terse vapor
#

the type is a list

past cipher
#

you have a class called Patient and you also have a variable called Patient

#

change the variable to smething else, it could be trying to loop through the class

terse vapor
#

to check if the new input exist in the db

past cipher
#

Yes I understand that. But how is the code supposed to know if you're looping through a class or a variable ? Have you tried to change the variable name ?

terse vapor
#

ok, understood

#

ok, it works with your instructions๐Ÿ˜ƒ

astral pagoda
#

Anyone free to help?

#

I tried opening a help channel

slim skiff
#

ask your questions

astral pagoda
slim skiff
#

try putting it before the length validator

astral pagoda
#

I will try

#

class RegistrationForm(FlaskForm):
username = StringField('Username',validators=
[
DataRequired(message='Username is required'),
Length(min=1, max=25)
])
I did what you said. It made no difference

slim skiff
#

I'm not familiar with forms in flask, but are you sure your jinja template is correct?

#

{%for error_msg in form.username.error%}

sure it's not form.username.errors ? do you actually need to loop over this?

astral pagoda
#

I tried both ways

#

the loop and non looping method in jinja2

#

i can try errors

#

instead of error

#

Give me a sec

#

It made no difference changing the code to errors

#

Should I try reddit flask

slim skiff
#

can't help you without a minimum working example then

#

I'm not familiar with the forms

astral pagoda
#

I can link the github from the video I using

#

Give me a sec

slim skiff
#

I'll pass ๐Ÿ™‚

astral pagoda
#

Well at least I can look

#

k thanks bye

near talon
#

Hello

#

I'm looking for some help on data filtering for SQLAlchemy

#

I am designing REST APIs with FastAPI framework and I am looking for some way to filter objects in db in ascending/descending order. Unfortunately I couldn't find anything on https://fastapi.tiangolo.com/tutorial/sql-databases/. The only query method I know is db.query(models.User).filter(models.User.id == user_id).first() . anyone knows other queries and any documentation to follow?

near talon
#

Thank you~

eager bloom
#

does anyone know how to input a number with selenium in this field?

<input name="dob-month" class="step__input--date--mm" type="number" placeholder="mm" min="1" max="12" data-maxlength="2" value="" autocomplete="bday-month">
eager bloom
#

it says its not interactable

near talon
#

not interactable because you might be locating wrong element

#

imo

slim skiff
#

^ most likely

native tide
#

I forgot to put "name="

sleek coyote
#

looking for help with data-mining a website using python... I wrote a script a few years ago that worked and now doesn't and I'm not an html expert so I'm a bit lost... if someone is interested in helping, please DM me... I just had a few questions. Thanks!

native tide
#

My stylesheet isn't working

grand oriole
#

how do i have an image and make a link for it?

#

i have the image as a file on my computer

#

i use python flask

#

i don't know how to put the image in the path though

nimble dawn
#

it would like this

compact flicker
#

how can I make routines in a Django.
like if you want to send emails or update the database after a uniform interval.

inland oak
#

or just daemonized thread in background, if we aren't going for overkill

compact flicker
inland oak
#

I have one, but is not is not having clean code yet

#

if you wish to get clear code, you'll have to wait a bit

#

I thought to make it clean today

#

otherwise, you are welcome to see not clean code too ;b

compact flicker
#

Thanks.
for now I'll be using django-apscheduler
but I'd love to see you work too...

nimble dawn
#

how do i fit my website in my screen

#

i have to scroll to see the whole website

jovial zenith
#

how to activate a virtual env

true ocean
jovial zenith
#

i am learning flask

true ocean
#

you're welcome

weary dragon
#

Hello, can i put a question about graphql here?

celest lodge
#

guys in XSD why there is an attribute called schematypens

#

and not schematypes , like what does n stands for ?

covert kernel
true ocean
#

oh ok lemon_grimace

dense gorge
#

Can anyone help me how to feed an custom zoho crm module through Djnago models.Manager ?
**NB : I'm able to feed or insert data to zoho Contacts module easily ,but not my custom deposit module

#

Thanks in advance ๐Ÿ‘

tired wren
#

what are some good starter projects for a profile on freelancing site?

desert parrot
#

Okay I have a question.

I have a figure tag, inside which there is an img tag. What I want is that I wanna show a popup when the image is clicked.

nimble dawn
#

Maybe you have to create a function for it

desert parrot
#

Yeah, I figured it out. Thanksies!

tiny tundra
#

anyone here flask user ??

covert kernel
#

yeah, many here do use flask, go ahead and ask your question

idle karma
#

I have a question about Django REST Framework although it is more of a web-dev design question I think.

If I make an API using DRF what do I then do if I want to have a nice front-end that can be used for actions too?

i.e. I make a DRF API which allows CRUD operations and returns JSON data.

I now want to have nice html forms for some create/update actions and say a dashboard page which displays some tables/graphs using the data in the DB

Do I make parallel views which would presumably be very similar to some of the api endpoints for the forms?

inland oak
jade reef
#

Hello there I am new to flask and python and I am trying create a very simple flask api with json data, and this is my code.

@app.route("/data/<string:alpha_code>",  methods=["GET"])
def about(alpha_code):
    response = None
    with open(os.path.join("data.json"), "r") as jsonfile:
        file_data = json.loads(jsonfile.read())
        json_data = json.dumps(file_data)
        for item in json_data:
            for key, value in item.dict().items():
                print(key, value)
    return response

And this is my data (list of dicts)

[
    {
        "alpha_code":"US",
        "country":"United States",
        "domain":"acu.edu",
        "name":"Abilene Christian University",
        "web_page":"http://www.acu.edu/"
    }
]
# multiple dicts

And I am getting an error : AttributeError: 'str' object has no attribute 'items'

Please can anyone help me with this ??

agile stump
#

How can I open my website on mobile

remote otter
latent cosmos
#

[Q] FLASK + database:
I can retrieve successfully some data from database and show it in html document. However, in my database I have a field with TEXT, and there is a line like "Hello \nWorld \t". Problem is that it shows in html data without these new lines and tabulators. And I need them to show certain description with those new lines, new paragraphs etc. How to do it in html jinja2?
Example:

  1. Data in database:
    ("Vit C", "\tVery Healthy\nIt is important for immune system\n")
  2. HTML jinja:
    {{ data[1]|safe }}
  3. Result:
    Very Healthy It is importnant for immune system

EXPECTED:
Very Healthy
It is important for immune system

P.S: Funny thing is that in INSPECT ELEMENT mode, description is printed correctly, however in my html you cannot see these new lines, tabulators etc. wow?

inland oak
#

Django models.CharField has uselss __doc__
is it possible to override it?

#

self.__doc__ = str(self.field.__repr__())

#

with something that has better __repr__ inside of it

robust canopy
opaque rivet
opaque rivet
shy flower
#

Sorry if i am interjecting...

Is it OK to default to using

SECRET_KEY = getenv("SECRET_KEY",'<redacted>')

for production use? Asking with respect to Django. And are there any other methods to keep the SECRET_KEY out of VCS?

inland oak
#

generates random secret key every time you start your application)

#

unless you specified one in environment

shy flower
inland oak
opaque rivet
inland oak
#

mm, highly probably yes.

shy flower
#

Incase the environment variable is set then no

inland oak
#

you can specify stable key from env anyway
then it would not be a problem

shy flower
#

Thank you @inland oak !

idle karma
opaque rivet
idle karma
#

Limited in what way?

#

Would you not do something like call the DRF endpoint from within a regular django view?

opaque rivet
#

e.g. you don't have any access to JS libraries, you can't change DOM in an efficient way. You don't have as much control

idle karma
#

Right. But why do you need that is my question I guess

opaque rivet
jade reef
#

Hello there I am getting a key error in flask. Basically I sending a patch request with optional arguments.
code :

 if request.method == "PATCH":
        request_data = request.get_json()
        # alpha_code = request_data["alpha_code"]
        # country = request_data["country"]
        # domain = request_data["domain"]
        # name = request_data["name"]
        # web_page = request_data["web_page"]

        response = None
        with open(os.path.join("data.json"), "r") as jsonfile:
            universities = json.loads(jsonfile.read())
            for university in range(len(universities)):
                if universities[university]["name"].replace(" ", "").lower() == university_name.replace(" ", "").lower():
                    response = universities[university]

                    # if request_data["alpha_code"]:
                    response["alpha_code"] = request_data["alpha_code"]
                    # if request_data["country"]:
                    response["country"] = request_data["country"]
                    # if request_data["domain"]:
                    response["domain"] = request_data["domain"]
                    # if request_data["name"]:
                    response["name"] = request_data["name"]
                    # if request_data["web_page"]:
                    response["web_page"] = request_data["web_page"]

        return jsonify(response)

Python is giving me this error = response["alpha_code"] = request_data["alpha_code"]
KeyError: 'alpha_code'

Basically saying this key doesnt exist. Since I am not sending it from front end

{
        "country":"TEST"
}```
How can I make it accept optional request params ??
idle karma
#

@opaque rivet
Perhaps I'm not explaining very well. In my head I would have endpoints like so:

POST api/tasks :creates a task

mysite.com/tasks - GET lists tasks
mysite.com/tasks/create - GET displays form, POST submits form and then redirects back to mysite.com/tasks on success

And basically the stuff at mysite.com/tasks seems like it's largely just replicating the api behaviour no? So I was wondering if there is a good way to leverage that

opaque rivet
# idle karma <@!812098613450506351> Perhaps I'm not explaining very well. In my head I would...

Yeah I'm not fully understanding what the question here. They're all valid API endpoints (with the exception of mysite.com/tasks/create). There really isn't anything different than a standard view or an API endpoint, it's just that your API endpoints are should be RESTful: https://stackoverflow.blog/2020/03/02/best-practices-for-rest-api-design/

Learn how to design REST APIs to be easy to understand for anyone, future-proof, secure, and fast since they serve data to clients that may be confidential.

wispy quail
opaque rivet
#

If you don't plan on having a seperate frontend, or do not plan on making individual requests from your frontend, just use views

idle karma
#

What do you mean by "making individual requests"?

#

I'd like to be able to POST a JSON to /api/tasks OR to fill in an HTML form which would create an object

opaque rivet
opaque rivet
#
POST api/tasks :creates a task

mysite.com/tasks - GET lists tasks

These 2 can be APIs, the other one is a view

idle karma
#

I guess my question was how would you get the form page\

#

I could use a modelform with Django for example to generate an html form which had all the right fields

#

I really don't want to have to write any JS

opaque rivet
idle karma
#

Erm, for an update I guess?

#

But if you're navigating to a page to create a new task it wouldn't be pre-filled

#

It would just have empty fields right

opaque rivet
#

Yeah so your question "how would you get the form page" would just be rendering a template with a form and on submission making an API request to your endpoint

idle karma
#

Ok. And that is an acceptable way of doing things?

nimble dawn
#

What is API

opaque rivet
#

yep!

<form method="post" action="your_endpoint">...</form>
idle karma
#

Ah but now that endpoint would just return JSON...

opaque rivet
idle karma
#

But if someone is submitting a form in the browser they don't want to get JSON back haha

opaque rivet
idle karma
#

Honestly maybe I am overthinking this

#

Perhaps it is acceptable to basically have the behaviour of some of the endpoints under mysite.com/api/tasks replicated by the views serving the html pages at mysite.com/tasks?

#

I just thought that since that would mean there were two separate means of performing CRUD operations then it would be incorrect

opaque rivet
jade reef
#

Does anyone know how to create a paginated API in flask ??

terse vapor
#

how to transfer a sqlalchemy row(e.g. name) into a list in flask?

lavish prismBOT
#

Hey @whole kayak!

It looks like you tried to attach file type(s) that we do not allow (.xml). 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.

whole kayak
#

bruh .xml is not allowed

#

bruh

terse vapor
#

lol

whole kayak
#

welp to paste bin ai go

#

i get this (https://pastebin.com/du7fFEw7) as a api output
as you can see it is xml but when i pipe it into ET.fromstring(f'{xml.read()}') (xml is a output from os.popen which i use to query the api)
but i get this error Traceback (most recent call last): File "C:\Users\walke\OneDrive\Desktop\trash nation states bot\bot.py", line 24, in <module> print(NS.getIssues('password','walksanator','useragent')) File "C:\Users\walke\OneDrive\Desktop\trash nation states bot\bot.py", line 21, in getIssues xmlo = ET.fromstring(f'{xml.read()}') File "C:\Program Files\Python39\lib\xml\etree\ElementTree.py", line 1348, in XML return parser.close() xml.etree.ElementTree.ParseError: no element found: line 1, column 0

#
    def getIssues(password,nation,userAgent):
        xml = os.popen(f'powershell -Command .\\TopIssue.ps1 "{password}" "{userAgent}" "{nation}"')
        print(xml.read())
        xmlo = ET.fromstring(f'{xml.read()}')
        return(xmlo)```
here is the function
#

and here is the powershell script (incase you need it)


$url = "https://www.nationstates.net/cgi-bin/api.cgi?nation=" + $args[2] + "&q=issues"
$xml = curl -Headers @{"X-Password" = $args[0]} -UserAgent $args[1] $url -UseBasicParsing
[xml]$pxml = $xml.Content
[xml]$a = $pxml.nation.issues.OuterXml
echo $a.innerXml```
#

(i am working on a discord bot to play nation states)

#

if i can get this to parse right

#

any idea why ET is unable to parse it

jade reef
#

Is it possible to paginate json data (locally stored in a .json file) in Flask ? I am looking online and every tutorial is using a built paginate() from the database ORM. Can anyone explain the entire concept of paginated API in a nutshell ?

native tide
#

can some one explain me what does this module dou py import parse_qs and what does this mean ```py
index = parse_qs(self.path[3:])['index'][0]

whole kayak
# native tide can some one explain me what does this module dou ```py import parse_qs ``` and ...
Parse a query string given as a string argument (data of type application/x-www-form-urlencoded). Data are returned as a dictionary. The dictionary keys are the unique query variable names and the values are lists of values for each name.

The optional argument keep_blank_values is a flag indicating whether blank values in percent-encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included.

The optional argument strict_parsing is a flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception.

The optional encoding and errors parameters specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method.

The optional argument max_num_fields is the maximum number of fields to read. If set, then throws a ValueError if there are more than max_num_fields fields read.

The optional argument separator is the symbol to use for separating the query arguments. It defaults to &.

Use the urllib.parse.urlencode() function (with the doseq parameter set to True) to convert such dictionaries into query strings.

Changed in version 3.2: Add encoding and errors parameters.

Changed in version 3.8: Added max_num_fields parameter.

Changed in version 3.9.2: Added separator parameter with the default value of &. Python versions earlier than Python 3.9.2 allowed using both ; and & as query parameter separator. This has been changed to allow only a single separator key, with & as the default separator.```
native tide
#

Does anyone know how I can make a bot dashboard ?
Are there any good tutorials using Flask ?

native tide
#

@whole kayak but i dont undesrtand the parth with numbers self.path 3: index 0 what should that mean

whole kayak
distant trout
#

from 4th index to last

#

['index'][0] this accesses the element index in the list and [0] accesses the 0th element of the index

naive rock
#

How can someone tell if a website would stop/prevent you from web scrapping?

frozen abyss
frozen abyss
# native tide Does anyone know how I can make a bot dashboard ? Are there any good tutorials u...

I found this vid really useful for grasping Streamlit. https://www.youtube.com/watch?v=0ESc1bh3eIg

In this video, we build a multi-functional dashboard using Streamlit. We display Tweets about stocks from popular traders on Twitter, display all mentions of a stock symbol on StockTwits, create a simple screener for technical patterns, display a Plotly candlestick chart, count recent mentions of stocks on WallStreetBets.

โ–ถ Play video
#

What's everyone's favourite free wireframing app?

naive rock
#

Are there cases where a company would be ok if someone web scrapped them?
We work with a company. We asked them for some data. They asked us for our FTP credentials, so they can give us that data. We dont have an FTP server, so I was thinking of web scrapping their website. But I know companies dont like it when someone web scraps their website.

#

Problem is they would have our ip address and we have to login to see that data. So when I create a web crawler they would know it's us.

#

Web scrapping/crawling

terse vapor
#
for i in db.session.query(Patient.name).all():
    mylist1 = list(dict.fromkeys(i))```
#

why does this for loop function only shows one name?

formal gull
#

it looks like it is capped at 1000

naive rock
formal gull
#

i know i could get a rough list by picking out different lat/long and going around the map and getting most and getting rid of duplicates but im trying to learn if there is a better way of doing it through the API

naive rock
formal gull
naive rock
#

Yeah, this is the part where if a company has good documentation, it's fun. But if they have bad documentation, you just have to do a lot of exploration on your own.

frozen abyss
dawn heath
thorn nexus
#

Are widgets and css applied to a model/fields in forms.py (ModelForm) reapplied to those fields when a form is redisplayed after failure?

#

Form displays well when methods is GET.

#

But not after POST failure.

native tide
dawn heath
distant trout
#

what exactly is the job of a devops person?
managing aws/firebase and deployment stuff?

vestal hound
#

so basically building a good pipeline

distant trout
vestal hound
#

and that will run all your tests

#

take care of any infrastructure setup

#

notifications

#

monitoring

#

etc.

#

thatโ€™s the pipeline.

distant trout
distant trout
inland oak
#

To be automated as possible
To run every hour

Or even to run completely automated every minute, by trigger from submitted commit (in master branch for example?)

#

I have automated deploy script
In gitlab
That builds my sphinx documentation
And puts to gitlab pages

distant trout
#

lets say if there wasn't anything new being changed, would the automation still go through?

inland oak
#

And checkers, which run unit tests, lint checkers, build/dependency checkers

distant trout
#

for the automation scripts you use cron jobs?

inland oak
#

Systems like TravisCi, circle ci

distant trout
#

ohhh, so it checks for commits to your master branch, thats when the automation takes place

inland oak
#

Deploy to production is usually separated, to be triggered manually

#

Deploy to test server can be fully automated

distant trout
#

im gonna try it out and set it all up for one of my projects

inland oak
#

Useful for code reviews

distant trout
#

would you recommend gitlab or github for this

inland oak
#

Automated checkers check every pull request too

#

Easier to spot problems

inland oak
distant trout
inland oak
#

I installed gitlab runner on mine, that was easy. Quickly integrated with my online repos, removed time limits for private pipelines

#

One self hosted runner can satisfy needs for a lot of private repos.
one runner can run jobs in multiple parallelism + queue

distant trout
inland oak
# distant trout ah i see. thank you for all this info btw, really useful

U a welcome.

Btw, besides those things...
Devops should be good with docker/docker compose

Deploying with Ansible at the moment popular.

Most popular question to devops, if can they answer next question

Can someone recommend a great solution to hosting a FastAPI on multiple servers so the load can be balanced and if one goes down the other can still handle the requests?

This can be possible with Kubernetes for example

distant trout
#

oh. Yeah I have heard about Docker but haven't looked much into it. I'll research more about Docker.

terse vapor
#
@app.route("/home-for/<string:name>", methods=['POST', 'GET'])
@login_required 
def doctor_information(name): 
    current_time = datetime.now() 
    time = timedelta(weeks = 4) 
    four_weeks_ago = current_time - time 
    filter_by_month = db.session.query(Patient.name).filter(Patient.create > four_weeks_ago).all()```
#

It seems like my code will restart the counter(4 weeks) every time I refresh the page, so is there any way to prevent this happen?

nimble dawn
#
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <link rel="stylesheet" href="clock.css">
        <title>digital clock</title>
    </head>
    <body>
        <section>
            <div class="clock">
                <div class="container">
                    <h2 id="hour">00</h2>
                    <h2 class="dot">:</h2>
                    <h2 id="minute">00</h2>
                    <h2 class="dot">:</h2>
                    <h2 id="seconds">00</h2>
                    <span id="ampm">AM</span>
                </div>
            </div>
        </section>
        <script>
            function clock(){
                let hour = document.getElmentbyId('hour');
                let minute = document.getElmentbyId('minute');
                let seconds = document.getElmentbyId('second');
                let ampm = document.getElmentbyId('ampm');

                let h = new Date().gethours();
                let m = new Date().getminutes();
                let s = new Date().getseconds();
                var am = 'AM';

                if (h > 12){
                    h = h - 12;
                }
    


                hour.innerHTML = h;
                minute.innerHTML = m;
                second.innerHTML = s;
            }
            
               var interval = setInterval(clock, 1000);
        </script>
    </body>
</html>
#

i am making a clock

#

i dont know why it is not working

#

it is only showing 00

twilit needle
#

can anyone pls help with django project structure
only the structure
I want to add tornado to my project, but where would I place it
the handlers and all those stuff

nimble dawn
#

i found the error

twilit needle
native tide
#

anyone familiar with html and css in here

valid girder
#

Hi all - Iโ€™ve been building ImagineAI, a free low code platform aimed at engineers - basically, you would simply specify your backend project spec in our UI andย we instantly generate high quality, production-ready source code, including 100% unit test coverage, based on the spec (we are initially supporting Django and Node). We have no lock-in, so you can download the source code and customize as you wish.

This way you can save time on writing boilerplate code for things like ORM, APIs (in Rest or GraphQL), Auth etc and can focus on writing custom business logic.

We are releasing a closed beta version of this tool in mid-May. Are there any backend / full stack product engineers here who would be interested in this? If yes, Iโ€™d love to connect here via DM or via anusheel@imagine.ai, and can include you in our our beta release!

glad patrol
#

can someone help me regarding .net problem

#

i get this error when i open my page i am using crystal report

#
    at HTMLImageElement.<anonymous> (CivilWorkSummaryUniWise.aspx:201)
    at HTMLImageElement.dispatch (jquery2.js:5)
    at HTMLImageElement.v.handle (jquery2.js:5)```
#
    at CivilWorkSummaryUniWise.aspx:646```
supple bramble
#

start a new app for this particular tornado feature

#

python manage.py startapp tornadoapp

pseudo marsh
#

Could someone help me why my background color won't change?
I've tried this:

<head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Furniture Inventory</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
        <link rel="stylesheet" href="../../dist/css/adminlte.min.css">
        <style>body{background-color: gray !important;}</style>
    </head>
    <body>
....

I want my body's background-color to be gray, but that doesn't happen even with the !important thing
So, what am I doing wrong? (I'm using AdminLTE and Bootstrap btw but yes I want to override the background color regardless)

latent cosmos
#

maybe try to put in .css file then link rel stylesheet etc and maybe it will override more efficient

#

@pseudo marsh

#

[Q] FLASK + database:
I can retrieve successfully some data from database and show it in html document. However, in my database I have a field with TEXT, and there is a line like "Hello \nWorld \t". Problem is that it shows in html data without these new lines and tabulators. And I need them to show certain description with those new lines, new paragraphs etc. How to do it in html jinja2?
Example:

  1. Data in database:
    ("Vit C", "\tVery Healthy\nIt is important for immune system\n")

  2. HTML jinja:
    {{ data[1]|safe }}

  3. Result:
    Very Healthy It is importnant for immune system

EXPECTED:
Very Healthy
It is important for immune system

P.S: In INSPECT ELEMENT mode I can see that text is printed as it supposed to be (so new lines and tabulators appears), but in html its not displayed properly. wow?

pseudo marsh
#

Yeah that didn't work

#

Already tried that

serene prawn
#

e.g. replacing \t and \n with spaces

cloud bone
#

dear all,

#

good day,

#

i learn python langauge but i need to make web application using python anybody can suggest or help me for making this web aap...?

serene prawn
#

@cloud bone Again, it depends on what kind of web app you want to build

livid kiln
cloud bone
serene prawn
#

I would use Django if you want to render things on server side or FastAPI for api's

livid kiln
#

Streamlit is very lightweight, so depending on the complexity of your application I would perhaps go for Django

serene prawn
serene prawn
cloud bone
serene prawn
#

Yes, but it depends ๐Ÿค”

#

As i said FastAPI would be better for api's

#

You would have to learn one of them anyway

cloud bone
#

according to my research django is famous fremwork.

cloud bone
opaque rivet
#

@terse vapor has to be stored in a global variable (it will reset if the server resets)

vestal hound
#

if you want to do stuff like SSEs or async DB access you might have problems

#

shrugs

#

and in certain specific cases its ORM is lacking

nimble dawn
#

i have made a clock using css and js

#

now i want to add a timer function in it

#

i want to create a button that will change the clock to timer

#

how can i do taht

#

that

serene prawn
#

What uri paths should i use if i want to identify entity by two fields?
Say id and slug

digital hinge
#

Anyone know how to create an AD authentication page with flask without a database being needed?

serene prawn
#

Somewhere

#

Also i don't see a reason to use flask anymore

#

FastAPI is superior ๐Ÿ˜‰

digital hinge
#

I guess Iโ€™ll have to use a Php connect method before being able to show the flask app.

serene prawn
#

Wdym by "php connect"

digital hinge
#

FastAPI is relatively new, the community is small compared to other frameworks, and regardless of its detailed documentation, there is very little external educational materials.

serene prawn
#

You can use same tools you use with Flask

digital hinge
#

Php can carry out auth just from a bind no dB needed

serene prawn
#

Plus flask is much smaller compared to FastAPI

#

Wdym "no db needed"

#

How would you store user info

digital hinge
#

No database needed it just uses a lookup account and passes the authentication.

serene prawn
#

Where would it look up the accounts ๐Ÿ˜…

#

If there's no db

digital hinge
#

You donโ€™t need to, it just an auth page Iโ€™m after so only certain access group can view it

serene prawn
night agate
#

hey i had a small problem with my django here is

serene prawn
night agate
#

if any one can give me a help

serene prawn
digital hinge
#

The AD domain/LDAP server is seperate yes sorry, so authentication with the local sever in order to say yes or no to that person accessing the flask app.

serene prawn
#

Why won't you just authenticate them in flask?

#

So you would have more control over the process

#

Also making another php app seems like a bad design choice

night agate
digital hinge
night agate
#

i thing that the problem is here

inland oak
serene prawn
#

title may be None

#

If it's not present in the request

serene prawn
inland oak
#

Huh

#

Fast API better?

serene prawn
#

Imo yes

inland oak
#

Shrugs. Good to know.
I will still prefer django though
Because it can work as not API too

#

May be later, fast api then

serene prawn
#

That's why i said for api's

#

And fastapi can work with templates too

inland oak
#

Admin interface is awesome ;b
Save a time to make tool for moderators in almost zero time

serene prawn
#

You don't usually use admin interface in production though

#

But admin is good

#

It's not a killer feature whatsoever

inland oak
#

DRF has interface too...
With self forming documentation
(Not really good solution though, better to add Sphinx for documentation)

serene prawn
#

And drf docs are quite hard to make if you create any custom responses ๐Ÿ™‚

inland oak
#

Yeah

#

Already encountered this problem

night agate
#

what this Django REST

#

can do ?

serene prawn
#

In fastapi you can just specify response model and that's it ๐Ÿค”

#

Also custom input models ๐Ÿ˜…

inland oak
serene prawn
#

๐Ÿ†’

fierce wigeon
#

Hi all! Can I ask here a question about Django? I didn't found specific channel on this

serene prawn
#

Sure do

fierce wigeon
#

Thanks. I'm Linux user, Ubuntu 20.10. When I want create a Media_root path, I have not the path that almost all site show, I mean os.path.join...but BASE_DIR / 'directory'. I don't know how to convert the code for selecting a specific folder, outside from project (what usually is writes like: os.path.join(os.path.dirname(BASE_DIR), 'directory'.
Maybe something can help me solve this stupid problem? (I hope I explain good, English is not my native language)

serene prawn
fierce wigeon
#

Thanks for the help @serene prawn

dusty moon
#

any free hosting services? (asking for a friend)

terse vapor
# vestal hound what do you want to happen?

When the day pass, the for example, I add 2 patient in April 27, and the new patient in 27 should be 2, then, when it comes to April 28, it resets to 0 and starts to count again

opaque rivet
#

All this fastAPI talk... but in terms of corporate / jobs it is nowhere near the scale of django/flask.

serene prawn
terse vapor
opaque rivet
past cipher
#

I also tried: foreign_keys=['users.uuid', 'profile.id'] and db.foreign_keys=['users.uuid', 'profile.id']

grizzled mirage
#

Does someone of you have informations about falcon+restful api's in python?

native tide
native tide
#

can some one explain me what parse qs does in simple words

glass badger
#

Hello channel! Does anyone have experience serving React production build via Django?

#

I'm currently getting MIME type issues . wondering if anyone else has overcame this error

topaz widget
nimble epoch
dawn heath
#

I Have a question. do you store results in redis or postgresql for a task queue ? do I need to use the django extensions?

native tide
#

Hey i have a super quick flask-related question

nimble epoch
#

true

native tide
#
return send_from_directory(file_path.split('/')[0], file_path.split('/')[1], mimetype="application/octet-stream", as_attachment=True, attachment_filename="grabber.exe", cache_timeout=0)
#

i'm trying to send an .exe file

#

to the client

nimble epoch
#

i used to use flask

native tide
#

it works, but when I open it on my pc, it says "Windows can't run this app"

nimble epoch
#

dont remember

native tide
#

What's a better alternative

dawn heath
nimble epoch
#

so learn it

#

ive never used redis

opaque rivet
opaque rivet
#

where you store your task results is up to you, I myself haven't used it, so I'd appreciate if you let me know what you're using it for ๐Ÿ‘ I don't really see the use case

celest tundra
#

can python be used to make websites

#

im new so i want to know

#

i sorta wanted to get into python since it looked so cool and easy compared to other languages and i wanted to know if it can be used to make stuff like websites

stable hemlock
idle karma
#

Is there a current preferred user login/auth library for Flask? The login example in the tutorial seems very basic, but I suppose it may be enough

grim sorrel
#

Hi everyone. I've come across a potential project where I will have to make a request to an API, get data back in JSON, format it, and generate some graphs from it. I am thinking of using Django for the backend and React.js and Chart.js for the front end. Has anyone ever used these in tandem with eachother for a similar project? If so, I'd like to chat and get some opinions.

opaque rivet
jade lark
grim sorrel
#

also thank you as well, @opaque rivet

jade lark
#

If you haven't used React at all before I would recommend starting with that. Try making a list that you can add items to within state. I also recommend going straight for React hooks as it's easier than trying to understand classes as a beginner.

Try making a basic form that can submit data to the back end (don't do anything crazy yet).

grim sorrel
#

awesome! this will keep me busy tonight

#

thank you very much

dawn heath
# opaque rivet redis is just a key-value DB. What are you trying to do?

I still dont understand correctly the workflow of celery - redis - postgresql , but I did an example of this simple crawling process in order to understand it in a better way , but #response means what I got stored in redis database https://github.com/SkyBulk/celery/blob/main/project/orders/tasks.py . what does exactly redis store as a message broker?

in this examples people use AMQP ,and redis or AMQP and postgresql, etc

https://github.com/celery/celery/blob/master/examples/django/proj/settings.py#L10-L15
https://github.com/Parisson/TimeSide/blob/master/app/settings.py#L241-L244
https://github.com/MacroConnections/DIVE-backend/blob/master/config.py#L83-L84

GitHub

demoh. Contribute to SkyBulk/celery development by creating an account on GitHub.

GitHub

Distributed Task Queue (development branch). Contribute to celery/celery development by creating an account on GitHub.

GitHub

Scalable audio processing framework written in Python with a RESTful API - Parisson/TimeSide

GitHub

Codebase for DIVE backend (server, worker, and ORM) - MacroConnections/DIVE-backend

terse vapor
native tide
#

Other than Heroku, are there any services where I can easily deploy a Flask web application?