#web-development

2 messages Β· Page 201 of 1

native tide
#

so would this be good?

inland oak
#

every Django ORM object has unique key automatically created without any additional code lnes

#

hidden pk variable

native tide
#

ok so we dpn

#

don't need the uuidfield

inland oak
native tide
#

ok

inland oak
#

pk stands for Primary Key

native tide
#

oh I'm aware, I used pk for another feature

#

then this makes urls easier too

#

since we can just add the pk when we view the class

#

wait

#

but then how would the user add the class

#

like we don't just want them to enter by name since we want people to be able to create the same class name

inland oak
#

I thought Classes are going to be unique entities

native tide
#

no but for example let's say we have two users

inland oak
#

right

native tide
#

or like let's say we have two different class objects with the same name

#

that would cause issues right?

#

we want the user to be able to add based on a unique identifier that's static

inland oak
#

depends on if you set Name being unique or not.
But let me question you... what makes two Classes with same name, different from each other? Do they have some other param that makes them different?

inland oak
#

So... in reality we can have multiple Classes with same Names. huh. Well it will not change our Tables thankfully.
We still keep the same logic, that one student can have many classes, and one same class can have a lot of students

#

the only thing is changed, we don't set Unique (constraint) to class name then (which we did not do anyway)

vapid token
#

rip all the help channels are taken

old prawn
#

Hi All, Anyone know how to do HTML?

#

Having a really simple issue haha

#

Cant get a navbar to render proper

#

<ul> <li><a href="#home">Home</a></li> <li><a href="#news">News</a></li> <li><a href="#contact">Contact</a></li> <li><a href="#about">About</a></li> </ul>

#

However it shows :

dense slate
#

Seems to be working properly.

brisk drum
#

Someone knows a way to check when a php page gets a new content (i mean, this page posts news, when the news is posted i wanna see it from my output)
Ps: i'm not interested in web development or web scraping, i need this for a Job

dense slate
#

You'll need some kind of javascript - whether a framework or something like an ajax call with jquery or something along those lines.

brisk drum
#

If i have access to the database?

dense slate
#

Yes?

#

Either way.

#

You can do stuff client-side without a response from the server, but it still needs JS either way.

brisk drum
#

Ok so if I wanna do it automatically what i have to check from that database?

#

Uhm so JS is needed anyway

dense slate
#

Yup

brisk drum
#

Ok and what if i create some kind of loop which using web scraping checks the main news page and using some sort of data tracing i check if a new post appear to the news main page?

#

Technically for this i only need beautySoup

#

Am i right?

dense slate
#

Anything that updates your page without refreshing it will require javascript.

mild wing
#

Hey, I'm looking to make a sorting algorithm visualizer. I know some flask and a bit of js. I heard d3 would be good for animating, open to hear suggestions. I wanted to ask, is the whole process should be done with js only pretty much? Or is the "sorting" suppose to happen on server side using python? Just looking to get a general idea of the way I want to implement it

#

Never did any kind of data visualization really.. thanks

brisk drum
split snow
#

Hello is someone online to help?

native tide
#

is there any way to remove a field from a model?

#

so for example, I have a field that I set like this: uuid = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False)

#

but whenever I delete it and try to run migrations, it gives the following error:

#

so I added UUID field, but I want to go back to the standard primary key system\

inland oak
unborn badger
#

i built a web dev project using nodejs and now as im in HS theyre asking me to build a project using python since it would be too much time consuming to rewrite the project from scratch
i am thinking of mitigating the node side to python
but im not experienced in python in any way could some1 help me with some general outlook on how i should start?
becoz node uses different libraries and whenever i try to do anything in python it just throws me an error

#

plz help

#

my projects due tomorrow

inland oak
#

that sounds like a completely impossible timelines to do this task

unborn badger
#

anything might help

#

how do i create a server in python?

inland oak
unborn badger
#

i might be able to request an extension as well

inland oak
#

both instructions have answers for how to create servers too.

unborn badger
#

okay thanks

inland oak
#

Flask is more beginner friendly, but commercial choice would be Django, as it is much better and battery included

unborn badger
#

what might any other prerequisits for my system?

inland oak
#

mm

#

usually it is enough to have installed python 3.8 or 3.9

#

and matching python-venv version

unborn badger
#

wait letme explain how my project works

#

its a live news website

#

which when loaded calls an api and fetches data

#

then stores it in mongodb

#

and then iterates over it and display on the frontend using ejs

#

and nodejs as backend

#

any other prereqs for this project like some libraries or smth?

#

since tomorrow is the due date of the synopsis ill have to put the required resources in their as well

inland oak
# unborn badger any other prereqs for this project like some libraries or smth?

python 3.9
python-venv (necessary to have local node_modules analog instead of installing libraries only globally)
black as linter is good
pytest as unit testing framework is good
you would need finding and installing library for your mongodb
people often use requests library, as the most comfortable choice... (axios analog)
scratching head
I would highly recommend djangorestframework as addition https://www.django-rest-framework.org/, it makes from Django more prod ready REST API

in order to deploy you would be needed to install python prod server, use at least gunicorn, don't use dev server.
people usually wrap the result into docker container.

unborn badger
#

ooookayy thanks a lot

#

i was thinking of hosting on mongod

#

like i did for node

#

i dont wish to host globally just on a local server

#

localhost 3k

inland oak
#

docker (docker-compose) is cool to host stuff locally

unborn badger
#

ohh okay

#

thanks

#

to be fair

#

i have zero knowledge of python as of now

#

ive never made a project on it before

#

except some loops

inland oak
#

well. I am in same shoes but for frontend.
I had at least a week of time for training holidays though

#

moving boldly to Vue.js eco system)

unborn badger
#

i am pretty cool with frontend since ive made a lot of practice projects

#

but backend pyt is prettyt horrifying

#

u could learn frontend in abt a week honestly

inland oak
#

I think i am already fearing nothing.
After going through backend and DevOps, walking through frontend looks quite easily.

unborn badger
#

and the frameworks make it almost too easy

#

nothings ever vanilla

inland oak
#

I already learned all the basics to perform the tasks in frontned in just one week. I already learn middle range stuff)

#

for more advanced things

unborn badger
#

ohh

#

wait let me share a video

inland oak
#

I hate videos)

unborn badger
#

of my current state of the project

inland oak
#

oh. sure)

#

i don't like only learning from videos

#

presenting is cool

unborn badger
#

wanna join vc?

inland oak
#

nah. I am currently at job in office.

unborn badger
#

cant talk tho i dont have a mic

#

oh ok

#

@inland oak

#

how is it @inland oak

#

i dont think ill be able to move the entire framework within a day

inland oak
#

blinded with amount of spoilers. going back to work.

unborn badger
#

oka

wraith hedge
#

hey guys I'm trying to POST a file and i keep getting SuspiciousFIleOperation in the method validate_file_name() here's the traceback: https://dpaste.org/UMeQ#L12 seems to occur when I call serializer.is_valid() can anyone give me some adivce?

native tide
#

what is the file?

wraith hedge
#

just a text file

#

i'm only passing a filename instead of a full path to upload_to on the model now and the error is gone

#

so yay i guess? πŸ˜‰

stark tartan
#

Does instagram uses Django as back-end ??

buoyant geode
#

Hi can some one help me in renaming a model in django??

native tide
#

Hello I'm using django combined with Microsoft SQL Server and mssql-djangoso when I run python manage.py migrate after python manage.py makemigrations, I get the following error:

django.db.utils.IntegrityError: ('23000', "[23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot insert duplicate key row in object 'dbo.auth_permission' with unique index 'auth_permission_content_type_id_codename_01ab375a_uniq'. The duplicate key value is (4, view_user). (2601) (SQLExecDirectW)")

I know that it can be fixed removing the index associated to that column, but it's a sloppy way of solving that error and perhaps it will eventually generate new errors when django internally tries to access that particular table. Is there a better way of solving that error?
Thank you in advance, any help is very welcome

inland oak
native tide
inland oak
# native tide it's one of the default tables that django creates when running `python manage.p...

uh. Googling "django.db.utils.IntegrityError: ODBC Driver 17 for SQL Server"
https://stackoverflow.com/questions/67078278/cannot-connect-django-to-sql-server
this person has answer how to solve
https://github.com/michiya/django-pyodbc-azure/issues/50
this person has exact answer why it happens

I would recommend to be just not using microsoft SQL server.

GitHub

Sorry, back again! Still same setup as last time: Django on a Windows Server 2012, MS SQL Server. Working with djangoCMS and having the above issue when creating new pages. Full traceback: (&#3...

#

how about using good old PostgreSQL, or at least Maria DB?

#

PostgreSQL has the best Django compatibility i think

native tide
#

Yeah I will highly consider swapping from Microsoft SQLServer to another DBMS after reading those docs you provided above

#

The thing is that it's an ongoing project and it's almost everything done using Microsoft SQL Server. I recently join the project and I don't have the experience to propose that we should use another DBMS...πŸ˜…

inland oak
#

short story told, due to incorrect SQL implementation in Microsoft SQL server, Django highly likely will never work correctly there πŸ€·β€β™‚οΈ

native tide
#

Maybe I get another error sooner or later...

inland oak
#

considering incorrect SQL implementation of Microsoft SQL server, I would have avoided Microsoft servers though.

#

not the best thing to use for ORM ;b

inland oak
#

and I think some people would say that both things should be avoided (ORM and Microsoft SQL servers ;b)

#

but lets less listen them, and code faster and more comfortable with awesome ORMs

sour epoch
#

hey folks! I need some help with a simple flask webapp that I can't get buttons to execute scripts on

#

if it matters, I am using ajax to dynamically display the status of a machine(if they are online or offline)
web.py

@app.route('/update', methods=['POST'])
def checkVMStatus():
    ...
        return jsonify('', render_template('status.html', x=vmStatus))
    ...
        return jsonify('', render_template('status.html', x=vmStatus))


@app.route('/', methods=['POST', 'GET'])
def index():
    if request.method == 'POST':
        if request.form.get('submit_button') == 'Turn On':
            print("Turning On")
        elif  request.form.get('submit_button') == 'Turn Off':
            print("Turning Off")
    return render_template('index.html', x=vmStatus)

index.html

<form method="post" action="/"> 
        <input type="submit" name="submit_button" value="Turn On">
        <input type="submit" name="submit_button" value="Turn Off">
</form>
#

I've been stuck here for the past hour with no resolution in sight

#

cheers in advance

sour epoch
#

fixed. frankly I have no clue how that happened but I came back to it after a break and it automagically worked

#

god I hate it when this happens..

dusk portal
#

hey

#

how can i create screen sharing

#

video sharing

#

platform at django

native tide
#

i guess you need to check out in the internet about WebRTC, cause as i know, it's the main method for creating applications with stream video

unreal pier
#

I am just wondering...If like there would be a webapp, what is loaded in on a users browser and another user edits something in that web app...I want that to the page update automatically.
If my explanation is not clear here is an example:
A student writes a test on a webapp but the teacher closes the test, so the student can't write the test anymore...it refreshed automatically.
So we can say the server pushed data to the loaded in site.
How would I achive this with flask?
I would send like a AJAX type request at every X sec to check if anythin changed...
OR
I shouls use somehow web sockets, and just listen to the socket and get data from there, and if update is there then update the web app
?
Or other thoughts? Maybe can anyone send a link for a video or article what explains something like this?
Thanks for the answers.

unreal pier
#

I will look furder in these things if i get there. I was just wondering... πŸ€·β€β™‚οΈ

#

Further*

dusk portal
#

@inland oak hey sir

steep pier
# unreal pier I am just wondering...If like there would be a webapp, what is loaded in on a us...

One idea: Synchronize the clients PC with internet clock as well as hosts PC. Now Everytime user updates the input, let the program on client side add time stamp to the data.
Client PC might check after some long time to see if server has closed or not.
In any case it will send the data within acceptable time range. i.e. when the connection closes.
This will save bandwidth as compared to refreshing every 100 Ms.

steep pier
spiral blaze
#

hi guys, i want to pass usernames from my python file to html, can someone teach me how to do that in flask?

@app.route('/')
def home_page():
    return render_template('home.html',) ```
#

i know its something after home.html but im not really sure what to pass in there

frank shoal
#

doing render_template("zzz.html", xxx=yyy) will make the variable xxx be available in the template zzz.html

spiral blaze
#

do i just pass my class in there?

#

like ```@app.route('/homepage')
@app.route('/')
def home_page():
return render_template('home.html', User=user)

#

sorry for the friend request by the way, felt like you were the most reliable person for flask

frank shoal
#

xxx=yyy is what is known as a kwarg

#

!kwarg

lavish prismBOT
#

*args and **kwargs

These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.

Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.

Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.

Use cases
β€’ Decorators (see !tags decorators)
β€’ Inheritance (overriding methods)
β€’ Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
β€’ Flexibility (writing functions that behave like dict() or print())

See !tags positional-keyword for information about positional and keyword arguments

frank shoal
#

xxx=yyy becomes kwargs={'xxx': yyy} inside the function.

#

with jinja, you would reference the variable via {{ xxx }}

dusk portal
#

we're building screen share n video share part of an web-app but it seems django wont handle these me n @dapper rapids r trying from last 3-4 hours + we have used WebRTC also but seems it wont help

spiral blaze
#

i must have to say, this kwags and args thing is quite confusing

frank shoal
#

think of them as extra arguments.

spiral blaze
#

oh wait, i can just do current_user.name?

gleaming tiger
#

hey. im using an Application Factory in Flask and i keep finding my self bumping into the problem of needing access to the app instance. first it was the database. now its logging. im using blueprints, wtforms, and peewee. at first i refactored the database so that the Application Factory could handle initialization of the database as the docs recommend. the docs state that i should not need access to flask.Flask.app_context, flask.current_app, or flask.current_app._get_current_object. I know that current_app is a werkzeug.local.LocalProxy instance and that interacting with it in any way raises an exception in Flask. I know that importing an app is discouraged to prevent recursive imports. how do i access logging in other parts of my web app? what am i missing here?

native tide
#
def viewClass(request, pk):
    classes=ClassesAndStudents.objects.filter(Class.id=pk)
    return render(request, 'class/viewClass.html', {'classes': classes})
#
from django.db import models
from django.contrib.auth.models import User


# Create your models here.

class Class(models.Model):
    name = models.CharField(max_length=255)
    upload = models.ImageField(null=True)
class ClassesAndStudents(models.Model):
    student = models.ForeignKey(User,null=True, on_delete=models.DO_NOTHING)
    Class = models.ForeignKey(Class,null=True, on_delete=models.DO_NOTHING)
#

I have this view and these models, I want to filter by the primary key of the class object within classes and students

#

how do I do that?

#

when I run the code that I have currently, it outputs: keyword can't be an expression

#

like I want to get all classesandstudents objects which have a class id of pk

native tide
#

I got it

dense slate
#

The variable needs to be lowercase and I'm pretty sure naming it Class is going to conflict

native tide
#

so using Class__id=pk worked

dense slate
#

Class = models.ForeignKey worked? πŸ€”

native tide
#

anyone familiar with django rest framework?

#
class DossierSerializer(serializers.ModelSerializer):
    utilisateur = UserSerializer()
    agent_de_terrain = UserSerializer()
    agent_de_bureau = UserSerializer()

    def create(self, validated_data):
        return Dossier.objects.create(
            utilisateur=User.objects.get(username=validated_data['utilisateur']['username']),
            etat=validated_data['etat'],
            agent_de_terrain=User.objects.get(username=validated_data['agent_de_terrain']['username']),
            agent_de_bureau=User.objects.get(username=validated_data['agent_de_bureau']['username']),
            date_de_envoie=validated_data['date_de_envoie'],
            date_de_recepisse=validated_data['date_de_recepisse']
        ).save()

    class Meta:
        model = Dossier
        fields = [
            'id',
            'utilisateur',
            'etat',
            'agent_de_terrain',
            'agent_de_bureau',
            'date_de_envoie',
            'date_de_recepisse',
            'ajoute_le',
            'modifie_le'
        ]

im posting data but it returns 400 bad request as some fields already exists. i dont want to create those

shut bloom
#

Which kind of picture you have used in pp and asking for help

Reported you

native tide
#

it wouldn't work if it was lower case

dense slate
#

That doesn't make any sense.

#

Generally in Python, variables are lowercase. If it doesn't work as lowercase, there's something wrong with the name.

native tide
#

no class is a keyword

#

so we wouldn't be able to name the field that at all

#

lowercase class is a keyword

dense slate
#

Right, it's reserved.

native tide
#

but uppercase Class isn't

dense slate
#

Well, use whatever you want but I would recommend finding better variable names.

native tide
#

I have a model, when creating an instance of a model, is there any way to check if that object has already been created

dense slate
native tide
dense slate
#

You can use .exists()

#

Just lookup how to use it

#

Or you can try to .get() it, and if it fails you know it doesn't exist.

#

and handle it in the exception.

#

what's the error?

native tide
#
def addClass(request):
    classes=Class.objects.all()
    if(request.POST):
        check=ClassesAndStudents.objects.all()
        data=request.POST
        for i in check:
            if(i.student==request.user and i.Class==data['class']):
                return redirect('classes')
        userandclass = ClassesAndStudents.objects.create(
            student=request.user,
            Class=Class.objects.get(id=data['class'])
        )
        return redirect('classes')
    ctx={'classes': classes}
    return render(request, 'class/addClass.html', ctx)
#

this is how I'm doing it right now, would this not work?

dense slate
#

const click?

native tide
#

so I'm trying to see if there's a classesandstudents object that has the same student and class that we just got and redirect otherwise and it's not working

dense slate
native tide
#

even when the user and the class are the same

dense slate
#

Right, so see how .exists() is used.

#

And work it in.

#

Probably needs to be declared as a const or function.

#

Like I wrote above, const click

#

or function click

#

You need to declare it.

dense slate
#

so doesn't it need to be var click, function, click, or const click?

#

My JS is not as strong and I generally work in React, but anytime I see that error, I forgot to put const or whatever in front of the function name.

dense slate
native tide
#

Full error is: 400 bad request {"utilisateur": {"username": ["an user already exists with this name"]}}

dense slate
#

So it looks like you have a user with the username you are trying to use in the form.

#

You don't want it to care?

native tide
#

Yes

native tide
dense slate
#

Is username your projects login credential?

#

It's likely set to unique=True

native tide
#

It is my login credential but its not the only field with this same error

dense slate
#

Ok well you'll need to find where and why it cares that it needs a unique value.

native tide
#

What i want is: posting data and if data already exists fill it with the existen data

dense slate
#

Ah

#

But if it doesn't exist, create new?

native tide
#

Yes

dense slate
#

Ok then you need a conditional statement that basically checks if the user exists, then, if so update and save, if not do then create the new one.

#

what was it?

dense slate
#

Good opportunity to lookup how to update an object

native tide
#

I tried this:

user = User.objects.get(username=validated_data['utilisateur']['username'])
user.save()

Dossier.objects.create(
    utilisateur=user
)
dense slate
#

show the whole code

dense slate
#

So did you change anything?

#

I saw that code already.

dense slate
#

That's the whole code?

#

Show the whole new code.

native tide
#

Ok one sec

native tide
# dense slate That's the whole code?
class DossierSerializer(serializers.ModelSerializer):
    utilisateur = UserSerializer()
    agent_de_terrain = UserSerializer()
    agent_de_bureau = UserSerializer()

    def create(self, validated_data):
        user = User.objects.get(username=validated_data['utilisateur']['username'])
        user.save(force_update=True)
        return Dossier.objects.create(
            utilisateur=user,
            etat=validated_data['etat'],
            agent_de_terrain=User.objects.get(username=validated_data['agent_de_terrain']['username']),
            agent_de_bureau=User.objects.get(username=validated_data['agent_de_bureau']['username']),
            date_de_envoie=validated_data['date_de_envoie'],
            date_de_recepisse=validated_data['date_de_recepisse']
        ).save()

    class Meta:
        model = Dossier
        fields = [
            'id',
            'utilisateur',
            'etat',
            'agent_de_terrain',
            'agent_de_bureau',
            'date_de_envoie',
            'date_de_recepisse',
            'ajoute_le',
            'modifie_le'
        ]
#

it tries to create an user instead of getting and inserting with the existen user

dense slate
#

So where's your if statement...

native tide
dense slate
#

But then you return with creating a new object right after.

native tide
#

I want to create the Dossier object

dense slate
#

I did mention to try a conditional statement.

native tide
#

Its the utilisateur thats making the error

dense slate
#

Based on whether the object exists.

jaunty kelp
#

hey i need some help, cause my html (with flask) script do not send a post request when i press a button but i dont know how, pls dm for script^^

native tide
#

Wasted a day on this bug

dense slate
#

What did you end up doing?

finite wagon
#

ive started to learn js
but im not sure the path i shld take while learning
like do i have to learn es6 after learning basics? or node? and then what
wb uh stuff like angular or react native?
what even are they
like i kinda know but i dont know
and should i learn ts?

frank shoal
#

They're nice to know. es6 is important, but most tools will warn you when you do something wrong.

#

Yes, learn ts

#

Ts makes you aware of the types. You can even use ts in regular js via jsdoc

finite wagon
#

is es6 like pep8 or am i lost

frank shoal
#

Es6 is version 6 of JavaScript

finite wagon
#

so like a es6 tutorial = up to date js tutorial

frank shoal
#

Formally ECMA6

#

Yes.

finite wagon
#

ohhhhhhhhhhhhhhhh

#

ty

#

wb node?

frank shoal
#

The latest version of node supports esnext

finite wagon
#

now what is esnext 😩

frank shoal
#

Which is the next version of JavaScript

finite wagon
#

oh

#

oh wait i meant

frank shoal
#

Not to be confused with next

finite wagon
#

uh

#

πŸ‘

#

are stuff like react like packages?

#

or libraries

#

or modules

frank shoal
#

Yes.

finite wagon
#

like tkinter in py?

frank shoal
#

Yes

finite wagon
#

ohhhhhhhhhhhhhhhhhh

#

tysm

jaunty depot
#

hey guys
I've been learning WTForms in order to implement a user logging function into my site
I created the site before I got into WTForms, that's why I created my own input forms etc
following every tutorial on that I see people do "{{ forms.field }}" in html file when they don't have any form tags in their html files

I have mine which I wouldn't like to erase, I just need to link the corresponding fields to the ones in routes
how do I do that?
what I mean is:

I have this snippet in my index.py file

    class LoginForm(FlaskForm):
    email = StringField(validators=[InputRequired(), Email()])
    password = PasswordField(validators=[InputRequired(), Length(min=6, max=20)])
    submit = SubmitField()

@app.route("/login", methods=['GET', 'POST'])
def login():
    form = LoginForm()
    return render_template('login.html', form=form)```

and this in login.html
```Html
  <form class="formentry" method="POST" autocomplete="off">
    <!-- {{ form.hidden_tag() }} -->
    <div>
        <div class="greenthingytop"></div>
        <input id="useremail" class="inputentry" name="email" type="email" placeholder=" " />
        <label style="top: 20%" class="labelentry" for="useremail">Enter email address</label>
    </div>
</form>```

how do I link them without erasing my form tag and putting instead {{ form.email }} etc?
#

I have already css file styling this form and all inputs and labels in it, I wouldn't like to lose it

#

I read on WTForms docu that puttin "form.field(class_="text_blob")" would render "<input type="text" name="field_name" value="blah" class="text_blob" id="field_name" />" in return

#

so I made Python {{ form.email(id_="useremail" class_="inputentry" name_="email" type_="email" placeholder_=" ") }} but it didn't work

#

my site crashed and the error it gave me was "jinja2.exceptions.TemplateSyntaxError: expected token ',', got 'class_'"

after checking various issues like mine I couldn't find a solution to my problem. Others had error caused by typos, I almost sure I don't have those

digital hinge
#

Anyone know of a RPC listener, I need to setup a server that will capture ANY RPC calls and save them. At the moment, I am trying to work out an API but i have no idea what the calls are. Anyone have any tips here? New to this stuff.

warm igloo
#

Uh .. what do you mean @digital hinge ?

You want to create an RPC server of your own to capture calls and save them?

Certainly not that you want to create something that listens to all RPC calls on a network even if it isn't the target of them, right?

Have you looked at rpyc? Seems like it'd have everything you'd want.

digital hinge
#

There is an application that sends this unique API everytime it saves, I need to capture that information so i can work out how to then continue to write the programs. Unfortunately they dont provide much information beyond that they just say have a server that

native tide
#

I have html where I can add an event, but I want to be able to delete and edit that event, how can I structure the html so that the fields when I click to edit the event are automatically filled in when the user clicks on it

#

also is there a way to edit model instances in django

warm igloo
#

Well, you for instance could have a React front end that makes calls to your backend api. That's a common pattern. React (or vue or whatever) on the front, and your backend is an api for CRUD operations for instance.

And the alternative is that your backend generates your front end code and sends it along to the client. Think a default django or basic Flask app (in most examples).

Note: you can do both or either of these with Django, Flask, etc.

native tide
#

can I edit model instances in django

#

like fetch an instance using get and then edit that or do I have to fetch it, then delete it, and then add an edited version back to the database

dapper rapids
#

Hlo guys
Does anyone have experience with agora and django

inland oak
orchid dragon
#

I'm hitting an API for text information and it is slow! Any thoughts on polite ways of sending more/faster requests?

dapper rapids
pallid lily
#

Got to admit Django is seriously the best back end framework exists

#

you can make Angular and Flutter and React apps under same roof (Django) and will work just fine

jovial cloud
thorn sage
#

Can someone help me establish a connection between a Flask Server running inside PyCharm Prof., ngrok and AWS?

native tide
#

Hey, I want to get some information from the source code of a webpage. The problem is, the information I want is suppsedly only available (so I was told), when the javascript on the page is executed. So I rendered the javascript on the page with Python but nevertheless, the information I seek is not available, only when I inspect element the page, I can see the text I want to have. Could anyone help me with solving that problem?

native tide
#
class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['name', 'email', 'body']

HOW TO put a class on this fields\

quasi tapir
#

@native tidewhat do you mean by put class on fields ?

native tide
#

to add style

#

to the fields

#

want to add style here

#

@quasi tapir

quasi tapir
#

if you wanna style it you should use front-ends like css bootstrap

native tide
#

yp i know how to add class to i can style it

#

i dont have a input

quasi tapir
#

@native tide if you agree i dm you to help you much better

native tide
#

okay

dusk portal
#

have any1 used agora ft django?

regal fossil
#

I am workign on web project in django where patients can make appointments with doctors I want to add a chat feature in it so doctors can chat with there patients when they attend/make appointments but I dont know how to implement chat features looking for some guidance here

dusk portal
native tide
#

hi

#

@dusk portal

indigo gale
#

does anybody know how wiremock works for django?

dense slate
#

Live chat will require some kind of websockets or polling.

dusk portal
#

anybody good at ajax

digital hinge
#

I’m okay with Ajax what’s up?

spiral blaze
#

can someone explain current_user to me in flask? what does it access

dense slate
spiral blaze
#

so, this current_user access the sql database? im honestly not sure aswell

dense slate
#

It would probably be the user object of the logged in user.

native tide
#

is there any way to fetch and edit a model instance

#

or do I have to fetch it, delete it, and then add in the edited version

dense slate
#

You just get the object from the DB, then update the field, like user.name = "whatever", then user.save() to save it to the DB.

native tide
#

ok so I can just do model.objects.get(id=x, user=request.user) and then edit that

dense slate
#

You only need one of those variables to get it.

#

But yes.

spiral blaze
#

how long does it take for the average to be comfortable with getting data from sql and stuff incorporating everything into a webpage?

native tide
spiral blaze
#

is sql pretty much the same for flask sql?

native tide
#

yes

sharp valley
#

I need help making a bot y’all want them ps5s this how many u can get plus more

gleaming tiger
#

anyone here know peewee?

manic crane
#

i keep getting this error => django.db.utils.DataError: value too long for type character varying(59) when my password are only like 8 letters long here is my code =>

#
    email = models.EmailField(verbose_name='email',max_length=59, unique=True)
    username = models.CharField(max_length=30,unique=True)
    occupations = models.CharField(max_length=200,null=False) #amount of occupations user does
    #cliques = models.ForeignKey(Clique,null=True,on_delete=models.CASCADE) #cliques user is in 
    date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
    last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    dob = models.DateField(blank=True, null=True,unique=True)
    password = models.CharField(unique=True, max_length=59)

    objects = OccupierManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username','occupations','password','dob']```
native tide
#

so I have my models structured by this:

#
class Class(models.Model):
    name = models.CharField(max_length=255)
    upload = models.ImageField(null=True)
class ClassesAndStudents(models.Model):
    student = models.ForeignKey(User,null=True, on_delete=models.DO_NOTHING)
    Class = models.ForeignKey(Class,null=True, on_delete=models.DO_NOTHING)
class PDF(models.Model):
    description=models.TextField(max_length=500, null=False, blank=False)
    PDF=models.FileField(null=False)
    category=models.ForeignKey(Class, on_delete=models.SET_NULL, null=True, blank=True)

    def __str__(self):
        return self.description
#

as you can see the PDF has a foreign key with type Class, I have html to view a class by the primary key

#

to this class html, I want add an "add pdf" button which submitted will automatically get the class from where they clicked it

#

how would I do this

dense slate
native tide
#

how can I get current object in view

regal fossil
regal fossil
inland oak
# regal fossil Is there a way to do it without using these packages?

Everything is possible.
But that it the fastest way to make it production ready and handling a lot of users in your own infrastructure.
If it is not the goal..
...u can just make it with just default rest API calls

Or using iframe from Facebook, or whether the way it integrates, if u don't mind dependency to them

Or just finding chat to web sites handling customers as service, basically SaaS

native tide
#

how can I import models from another app in django

inland oak
wispy quail
dawn shard
#

Guys, any idea how I can fetch data from a URL through Javascript? Preferably, the way in which it will be possible to manipulate the DOM. I searched a lot but couldn't find anything.

indigo kettle
wooden ruin
honest dock
#

Hello, did anyone experience having certain fields missing from a form model??

devout aurora
#

hey im making a website in flask and i need to retrieve the "name" of the person who is currently logged in

#

the name is stored in the database and they registered with it

mild wing
#

Just run a sql query using their user id to look for it no?

devout aurora
inland oak
devout aurora
#

im new to web development and would like some extra help πŸ˜„

inland oak
devout aurora
lucid marsh
#

i have a page with scroll snapping, and a css animation.
the scroll snapping works fine, except with a css animation playing.
when css animation isn't playing, the scroll snapping scrolls smoothly, but when it plays, it scrolls instantly isn't smooth. anybody knows why this happens?

fickle saddle
#

Guys is socket okay for building a messaging app for a flask website?

tiny snow
#

If it's a website you can use urllib

#

It already has the protocols HTTP/S and functions to use them

fickle saddle
#

I'll take a look on that. Thanks Roie!

lusty wigeon
#

I am Python developer since 1 year.. I am Intermediate level at python.. Have worked in PyQt5.. Also watched Django Videos as well and built some projects under supervision of Videos.. So I want to move forward in django field.. What is your advice for me? Whether I should further study django (watch videos or reading books or blogs) or should i be able to make projects live on django without any supervision.. Kindly if you suggest me anyone of them then kindly provide some best resources so far to move forward quick (I will give upto 4 hrs per day along with my job)..Thanks...

thick sinew
#

Hey guys, I am working with drf-yasg and I'm unable to make field required in post method. My model is

class Comment(models.Model):
    id = models.AutoField(primary_key=True)
    author = models.ForeignKey(Guest, on_delete=models.CASCADE)  # set null?
    text = models.TextField()
    publication_date = models.DateTimeField(auto_now_add=True)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    child_comments = models.ManyToManyField('Comment')

serlializer:

class CommentSerializer(ModelSerializer):
    post = StringRelatedField()
    author = SlugRelatedField(
        read_only=True,
        slug_field='name'
    )

    class Meta:
        model = Comment
        fields = '__all__'
        depth = 3

in swagger post comment only requires text but i also need it to make post field required

lusty wigeon
fickle saddle
fickle saddle
thick sinew
sinful jetty
#

I am trying webscraping using beautiful soup

<div class="trn-defstat__value">1.90</div>

This is what i want to scrape but i only want to get the 1.90

How do i do that

fickle saddle
sinful jetty
#

Should i use int for that

fickle saddle
sinful jetty
#

hmm

#

thx

native tide
#

could someone help me extract text from a webpage with Python which is not shown in the source code and also not shown in the source code after you execute the javascript with a chromedriver. I try to do this now for days and I cannot get it done

lusty wigeon
marsh girder
#

hi

#

can i know how i must host site on hostinger cloud hosting?

inland oak
#

the difference between quality providers (like the ones which I mentioned), and the shitty providers (everything the rest usually) is 10-100 times.

marsh girder
inland oak
# marsh girder dont worry im trying it for 20 days

let me start with telling you that in normal providers u get your server within 30 seconds, and you can destroy it within same 30 seconds.
you don't pay there for a month in advance, or for setup fee.
the payments are calculated based on hourly usage very precisely, and charged at the end of the month

inland oak
# marsh girder wdym

I mean what I mean.
normal providers don't charge monthly fees or initial setup fees for their servers/resources

#

they charge hourly payments based on how many hours u used their resource

marsh girder
#

ok but theres a 30 day money return back garuantee

inland oak
marsh girder
#

@inland oak

#

u making me confused lil bit

inland oak
marsh girder
inland oak
# marsh girder u sure hostinger bad for cloud hosting?

i am 100% sure.
providers outside of quality range, can be interesting only because they provide more resources for cheaper price (sometimes)
if you don't plan to grow outside of one server, DevOps, CI/CD are alien words for you which u don't wish to have, and you don't mind getting service in quality outdated by 10-20 years, then sure, hostinger(and similar to it providers) will be fine.

karmic star
#

How to update celery image for an api server without losing track of already running background tasks?

We have a flask api server which is deployed on kubernetes cluster as a service, it is interacting with celery service for executing any background task.
Now let say we want to update our celery image, but doing so if any background task is still in processing state won't be processed because when we update the image it will remove the old celery container as soon as new container is up.
What are best approach to update celery image without losing the already running background task in that celery container?

inland oak
#

don't wipe them when you update Celery, and... as long as forward compatibility works, u'll be fine

#

How to make sure that no running tasks gets lost, I am a bit less sure though

#

because taken tasks will be changing their status to STARTED

#

a bit more knowledge is required in how celery keeps track of tasks

#

and just checking all tasks and fixing them back to be not started yet perhaps

#

tasks in progress are surely still kept though

inland oak
#

Everything can be done much simpler and more gracefully

thin lance
#

Greeting,
Is there a way to speed up writing to the database?
example:
I have a parquet file and it takes me 70-75 seconds to write it, which is not much, but if I had a bigger file, it would take longer.
I use FastAPI, ArangoDB, docker and pandas

vestal hound
#

that depends on a lot of things.

#

hard to say why it's slow

#

it could be that that's near the theoretical limit

#

or the connection is slow

#

or you might have some inefficient serialisation logic

#

lots of moving parts in that

thin lance
#

could a docker help?

last scaffold
#

When my stuff is too slow it's 99 times out of 100 I who wrote shitty queries/back-end code

thin lance
#

i read that there is some solution with the help of docker by splitting multiple processes

vestal hound
vestal hound
#

not as images

#

hard to read

#

but what I see right now

#

is that you're sending one query per document

#

which is generally not a thing you want to do

#

you want to batch your queries

thin lance
# vestal hound show code as text
def insert_parquet(self):
        time_start = time.time()
        file = pq.read_pandas("Industry").to_pandas()
        k = len(file['Year'])
        for i in range(k):
            docs = {
                "year": file['Year'][i],
                "industry_aggregation_NZSIOC": file['Industry_aggregation_NZSIOC'][i], 
                "industry_code_NZSIOC": file['Industry_code_NZSIOC'][i],
                "industry_name_NZSIOC": file['Industry_name_NZSIOC'][i],
                "units": file['Units'][i],
                "variable_code": file['Variable_code'][i],
                "variable_name": file['Variable_name'][i],
                "variable_category": file['Variable_category'][i],
                "value": file['Value'][i],
                "industry_code_ANZSIC06": file['Industry_code_ANZSIC06'][i]
                }
            bind = {"docs": docs}
            aql = "INSERT @docs INTO Industry LET newDoc = NEW RETURN newDoc"
            query = self.db.AQLQuery(aql, bindVars=bind)
            print(query)
        print((time.time() - time_start))
thin lance
vestal hound
#

doesn't it?

vestal hound
vestal hound
#

I'm not familiar with AQL so I don't know how you'd express that

#

or if it's even possible

#

but if it is

#

that'd be a good place to start

thin lance
#

good observation now i will try to change that

quasi tangle
#

can someone help me?

#

uh I got it right but it doesn't randomize the question

quasi tangle
marsh girder
#

site hosted

quasi tangle
#

oh

#

wdym?

inner pumice
#

Did someone already used PyZoom ?

fickle saddle
#

Never heard of that

loud shore
#

Hello

minor pike
#

writing html like a pro:

from typing import List

class MissmatchedRowsAndCols(Exception):
    pass


class HtmlTableBuilder:
    classes: List[str] = []
    identifier: str = ""
    rows: List[str] = []
    cols: List[list] = []

    def add_row(self, name: str):
        self.rows.append(name)
        return self

    def add_col(self, fields: list):
        if len(self.rows) != len(fields):
            raise MissmatchedRowsAndCols(
                "The given fields are not matched 1:1 with the rows.")
        self.cols.append(fields)
        return self

    def build(self, indent: int = 4) -> str:
        html = "<table border=\"2px\""
        if len(self.identifier) > 0:
            html += ' id="' + self.identifier + '"'
        if len(self.classes) > 0:
            html += ' class"' + (" ".join(self.classes)) + '"'
        html += ">\n"

        html += (" "*indent) + "<thead>\n"
        for row in self.rows:
            html += (" "*(indent*2)) + "<th>" + row + "</th>\n"
        html += (" "*indent) + "</thead>\n"

        html += (" "*indent) + "<tbody>\n"
        for col in self.cols:
            html += (" "*(indent*2)) + "<tr>\n"

            for field in col:
                html += (" "*(indent*3)) + "<td>\n"
                html += (" "*(indent*4)) + str(field) + "\n"
                html += (" "*(indent*3)) + "</td>\n"

            html += (" "*(indent*2)) + "</tr>\n"
        html += (" "*indent) + "</tbody>\n"
        html += "</table>"

        return html


builder = HtmlTableBuilder()
builder.add_row("index").add_row("language")
builder.add_col([0, "Python"]).add_col([1, "Kotlin"])

print(builder.build())
inland oak
#

Are you the one?

minor pike
#

nope

inland oak
#

πŸ™

inland oak
#

How about starting using jinja2?

minor pike
#

thats no fun

inland oak
#

Or even better... Frontend framework, fully weaponized with SASS, JavaScript, Babel and e.t.c. stuff which makes easy development

minor pike
minor pike
inland oak
#

With jinja2 it will be much better. At least ten times

minor pike
#

I code for fun
using ready made code is no fun

inland oak
#

Equally funny to Hecker level

inland oak
#

In one week u aren't going to remember what was written there and how to change it

minor pike
#

I always remember my code

inland oak
#

Jinja will make a clear separation between python and html code

#

Spare your future self, use jinja

minor pike
#

first of all, I made it clear that this wasn't for actual use
it was a way to automate my homework

second of all, I said that using ready made stuff is no fun for me

and lastly my aim was to make it so that you just add stuff to the class and it generates html w/o you knowing html

inland oak
#

I want to save you!

minor pike
#

and btw jinja2 is way too ugly

#

how is my code ugly?

#
builder = HtmlTableBuilder()
builder.add_row("index").add_row("language")
builder.add_col([0, "Python"]).add_col([1, "Kotlin"])

print(builder.build())
#

this is way too pretty compared to jinja

inland oak
minor pike
#

ah yes, installing syntax highlighting in my browser

#

very possible

minor pike
#

jinja is more than 2K lines of code

#

copy paste that in the same file as ur code

#

thats the dumb thing you are comparing

#

my 50 lines of source code

#

vs 2K+ lines of source code

inland oak
minor pike
#

stop being blind

#

and actually read my messages

#

i dont want to make a website

#

i want to mess around with code

#

thats the difference

inland oak
minor pike
#

it is final code, there are no improvements to make
maybe adding properties as a dictionary
but thats all

minor pike
#

you just said no for the sake of saying no?

opaque token
#

nah it isn't ugly

minor pike
#

it is compared to the usage of the class I made

#

its not ugly overall

#

but why write html
when you can exclusively write python?

opaque token
minor pike
#

imagine copy pasting that in ur code instead of importing

#

what would be "uglier" for you? @inland oak

jovial kayak
#

guys, is it possible to create an online server like Google using python?

minor pike
#

is it possible? yes
is it recommended? no
why? because google is way too big for python to run

I mean...we all know how slow python is
Writing the server in Go, Rust or C++ is better speed wise

#

whilst you can do it in python, if you are dealing with the whole population on earth, it would most likely either crash or be slow as hell

jovial kayak
#

ohk thanks a lot dude!

inland oak
minor pike
#

no, it uses python

#

and a lot of other languages

#

not just python

#

c++ is mainly used for the search, and some python along with it

inland oak
minor pike
#

yeah

#

and then bc of a lot of issues the crawlers were rewritten in c++

strange charm
#

Can someone help me with django

#

i have one form field data, which i don't want to save in database and process that data directly to my script

unborn badger
#

Hii!!

spiral blaze
#

guys i want to make something say You logged in! on top when you logged in, then you can click to close it, does anyone know what its called?

frank shoal
#

It's reddit (old) that was written in python

frank shoal
#

though the ui element is called a banner

#

or a toast

spiral blaze
#

wait its just a flash? i thought its like something in html

#

are there like a docs of it? im kinda confused on this one

frank shoal
#

in flask, you create it by using the flash() function

#

You still have to render it in your function.

spiral blaze
#

wait, so i have to connect this alert to my python too?

frank shoal
#

just your html

#

bootstrap makes it easy, but you can do it manually if you like.

#

in your template, call get_flashes()

spiral blaze
#

wait, so how do i connect it to after i logged in? there must be python code right?

frank shoal
#

!d flask.get_flashed_messages

lavish prismBOT
#

flask.get_flashed_messages(with_categories=False, category_filter=())```
Pulls all flashed messages from the session and returns them. Further calls in the same request to the function will return the same messages. By default just the messages are returned, but when with\_categories is set to `True`, the return value will be a list of tuples in the form `(category, message)` instead.

Filter the flashed messages to one or more categories by providing those categories in category\_filter. This allows rendering categories in separate html blocks. The with\_categories and category\_filter arguments are distinct:
frank shoal
#

!d flask.flash

lavish prismBOT
#

flask.flash(message, category='message')```
Flashes a message to the next request. In order to remove the flashed message from the session and to display it to the user, the template has to call [`get_flashed_messages()`](https://flask.palletsprojects.com/en/2.0.x/api/#flask.get_flashed_messages "flask.get_flashed_messages").

Changelog Changed in version 0.3: category parameter added.
spiral blaze
#

i think i might have to experiment with this, im super confused lol

frank shoal
#

experimentation is good.

spiral blaze
#

the solution that i can think of is just make another webpage that says You logged in! after you log in but that wouldn't be super satisfying

#

like this one that i have currently, will definitely have to change it

#

do you think i should make a base.html so i dont have to copy my code everytime?

honest dock
#
list = form.save(commit=False)

Anyone knows why this cause the following error:

AttributeError at /en/sell_page
'dict' object has no attribute '_committed'
native tide
#
class Event(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()
    author = models.ForeignKey(User,null=True,on_delete=models.DO_NOTHING) #2
    @property
    def get_html_url(self):
        url = reverse('oauth_app:event_edit', args=(self.id,))
        return f'<a href="{url}"> {self.title} </a>'
#

I have a model event which has two DateTime Fields, I am making something to edit the event where I have to load the start_time and end_time into two html local date time input fields

#

it can put in the title and description but can't input the date time fields

#
2021-11-17 16:54:00+00:00
#

this is what the console outputs when the start_time is called from views.py

#

why is it not automatically inputting the start date and end date

#
 <div class="form-group m-3">
                              <label for="birthdaytime">Start Date (date and time):</label>
                              <input type="datetime-local" id="birthdaytime" name="starttime" value="{{event.start_time}}">
                            </div>
                            <div class="form-group m-3">
                              <label for="birthdaytime">End Date (date and time):</label>
                              <input type="datetime" id="birthdaytime" name="endtime" value="{{event.end_time}}">
                            </div>
#

this is the html

dapper rapids
#

Anyone here know to enable cloud recording in agora vuejs

oak lion
#

Bulma or Bootstrap
which one is better?

native tide
oak lion
finite schooner
#

getting this error from flask "raise ValueError("urls must start with a leading slash")
ValueError: urls must start with a leading slash" googled it and it it said when you define your link make sure to put / before it, only problem is my code already has slash so im confused here's the code

from flask import Flask, render_template
app = Flask('site', __name__, template_folder='templates')

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

if __name__ == '__main__':
    app.run(debug=True,)```
bright spindle
#

havin 'Meta.fields' must not contain non-model field names error in Django, because of inheriting parent model i guess

#
class NotificationBase:
    class Type(models.TextChoices):
        GROUP_POLL = 'GROUP', _('group')
        POLL = 'POLL', _('poll')
        PROPOSAL = 'PROPOSAL', _('proposal')

    type = models.CharField(choices=Type.choices, max_length=255)
    target = models.IntegerField()


# All notifications goes in Notification model
class Notification(TimeStampedUUIDModel, NotificationBase):
    link_type = models.CharField(choices=NotificationBase.Type.choices, max_length=255)  # The target link
    link_target = models.IntegerField()  # The link target id
    message = models.TextField()  # The notification itself
    date = models.DateTimeField()  # When to notify the subscribers
#

link type and link target is accesible somehow

#
class UserNotificationFilter(django_filters.FilterSet):

    class Meta:
        model = UserNotifications
        fields = ('id', 'notification__id', 'notification__link_type', 'notification__target', 'read')
devout aurora
#

looking for a "full stack engineer" just need some help with security measures for my webapp, this website is coded in flask for the backend. willing to pay dm me!

sharp tree
#

does get method need a forms.py to call the data off ?

warm igloo
warm igloo
devout aurora
native tide
#

any django experenced

#

folks here ?

#

needs some advices suggestions regarding scalablilty

warm igloo
warm igloo
native tide
#

sure

#

my current setup on vps is nginx + uwsgi + mariadb

warm igloo
#

cool, following so far .. single vps?

native tide
#

dedi

#

well i'm aware that i could optimize the queries allot

#

planing to do that in near future

warm igloo
#

dedi?

native tide
#

dedicated server

#

its a vps, you just get the entire hw

warm igloo
#

okay, you have a vm .. is the app and db on same vm?

native tide
#

haha

#

yea

warm igloo
#

cool

#

def want to split that in future but go on

native tide
#

ok

#

thats why im here

#

ah my question is more

#

is the practice

indigo kettle
#

@bright spindle I think you want

class NotificationBase(models.Model):
    class Type(models.TextChoices):
        GROUP_POLL = 'GROUP', _('group')
        POLL = 'POLL', _('poll')
        PROPOSAL = 'PROPOSAL', _('proposal')

    type = models.CharField(choices=Type.choices, max_length=255)
    target = models.IntegerField()

    class Meta:
        abstract = True
native tide
#

clusterinz APP services, or clustering DB

warm igloo
#

sorry, still wanting to find out what you are asking and want

native tide
#

ah thebouv

warm igloo
#

I mean there are tons of things you can do to make it more scalable. For instance, low hanging fruit is to put in a LB, have it in front of multiple vms running your app, and to isolate your db to its own private-access-only vm

#

or to use a dbaas

native tide
#

do you cluster the web apps ( django, uwsgi, nginx ) or the clustering DB

#

for preformance

warm igloo
#

big question but you can go very very far with a load balancer, a couple vms for the app, and a db server that gets a backup for disaster recovery

#

if you want to mature to "the next stage" beyond just a single vm

native tide
#

so you cluster the web app and services

#

not the db firstly

warm igloo
#

depends on what tolerance you have for downtime, how big your audience is, and some other factors

#

yeah, I wouldn't worry much about the db EXCEPT to get it off the same machine .. that's never a good idea (Except as a proof of concept, personal project, etc)

native tide
#

yea

warm igloo
#

you want the db to have good backup and easy to recover though

#

I mean, what is the nature of your app?

native tide
#

we have some cronjobs

#

that do daily backups

#

etc..

warm igloo
#

if it is microsecond ecommerce transactions where you can't tolerate a single failure, that's more expensive to plan for

native tide
#

there are certain functions in the webapp, which steal allot of time and

#

i'd like to talk about that : )

#

haha

warm igloo
#

you can remove a LOT of headache by looking at DBaaS like AWS Aurora

#

or RDS

native tide
#

hmm

warm igloo
#

also, you don't have to build what you need in a year .. its best to iterate on it. And the more you can automate, the easier it'll be to grow.

native tide
#

yea

#

thats why we are planing up front

#

i guess we gonna have a big explostion in next year

warm igloo
#

congrats if that works out

native tide
#

so tryna get ready for the chalanges

#

amen

#

thanks

warm igloo
#

get yourself an infrastructure person soon πŸ˜‰

native tide
#

well i'm pretty skilled

warm igloo
#

Cool.

native tide
#

its just the enterprise tools

#

im not fimiliar ha

#

haha

#

i'd rather create my own custom dns and handle it my self

#

but...

#

seens DigitalOcean gives a simple load balancing

#

method

#

for cheap

#

like $10

warm igloo
#

Suggestions: make sure your app is 12 factor. Think in regards to ephemeral and immutable infrastructure.

native tide
#

whats a 12 factor

warm igloo
#

I mean if you want really cheap you don't even need an actual LB but you can do round-robin DNS as a poor man's load balancer

native tide
#

hmm

#

well i'd prolly go with LB

warm igloo
#

good idea

native tide
#

which costs like 10$ on do

#

which is extremelly cheap

#

if it does the work

warm igloo
#

sure, sounds good

native tide
#

but im more interesting

#

in how scaling django works

#

like anyone has any docs on how reddit

#

scales infrastructure

#

or any of the mayor sites that use django

#

i feel like im missing something with the django + uwsgi part

warm igloo
#

so your vm works now with django and uwsgi yeah?

native tide
#

this is my setup

#

Nginx as web Server, ( proxy pass to ) uwsgi which runs django ( uwsgi started via systemd )

#

I have mysql-server installed on the same vm

warm igloo
#

imagine you save an image of the vm as it is now, duplicate it, and put an lb in front of it, and move that DB to its own place (that doesn't accept open web connections, only from your app vms)

native tide
#

the load is fine for now

#

except on certain

#

actions which require for loop which will update certain rows

#

this can take up to few seconds

#

i need to optimize the query

#

well my plan is to

#

stop using django as renderer

#

since it steals allot of time

#

so we'll go from Class based views, to API's

#

and now comes the lb part

#

i need to debug is django orm slow

#

or mysql query

warm igloo
#

and build a separate front end and use django as api backend?

native tide
#

yep

warm igloo
#

I suggest you look into using application performance monitoring tools that allow you to pinpoint slowness down to the query being executed or line of code errors are happening on. NewRelic, Datadog, AppOptics, etc.

native tide
#

nice

#

ty for that

warm igloo
#

np

native tide
#

i've only used django debug toolbar

#

gotta give thumbs up for those folks

#

they did a good job

warm igloo
#

Nice. I actually have never built out a django app. I prefer Flask or FastAPI for most of my web work.

native tide
#

ah i started working in it long time ago

#

then stoped now got back into it

#

its easy

#

big up for the community

warm igloo
#

I prefer slim frameworks

native tide
#

haha

#

m2 depending on the project

warm igloo
#

django is heavy, but I get its purpose

native tide
#

tough

warm igloo
#

I actually need to cookie-cutter my last Flask site out to make it easier to spin up something similar

native tide
#

anyone knows what reddit uses as frontend ?

#

or instagram

warm igloo
#

the ig app is react native I believe so I'd assume the web front end co-opts some of those react components and uses those as well

#

but the web interface is always behind the app interface and with less features so dunno

native tide
#

what does youtube use

warm igloo
#

handy website

native tide
#

hmm

#

lol it says php

warm igloo
#

which is true

native tide
#

really ?

#

i tought it uses django

warm igloo
#

php is friggin everywhere dude

#

likely the use a lot of tech

native tide
warm igloo
#

cool that article is also from 2012

#

πŸ˜‰

native tide
#

true

warm igloo
#

and it could be php but be Hack like FB uses

#

or that site could be wrong

#

it's harder to get a tech sig on backend unless it leaves telltale signs in the front end somehow

#

likely what you'll find at the "big boys" is a heavily customized stack that isn't just a bunch of off the shelf things

#

don't worry about them though to be honest

#

build what you can with what you know

#

if you explode, refactor/rebuild

#

when you have the money to do so heh

#

So you good on your near term plan @native tide ?

native tide
#

yea

#

we could prolly be good for better near term

cobalt badge
#

python is usable for blockchain developer?

vapid stag
#

Guys, I have had this question for some time.

Let's suppose Ive a forum and a submit button. When I hit submit, it might send a POST to my flaskapp /hello endpoint and what's typed in forum get stored in db. Can I aslo use GET here?

I don't understand the difference between the two. I read some theories but didn't get the difference. I feel it's the same except GET will have the url param at url bar. That's the only difference. I could use GET instead of POST as well?

inland oak
# vapid stag Guys, I have had this question for some time. Let's suppose Ive a forum and a ...

most of the difference is semantic.
GET we use to request things which DON"T change server data (Get existing users / msgs)
POST we usually use to Create new object, Submit newdata (Create user, Create new msg, Create auth session(submitting login/password))
DELETE to delete objects
UPDATE... to update those objects partially for example. and in bulks.
(CRUD acronym stands for this pattern: Create, Read, Update, Delete)

#

Additionally there is difference that
GET request can accept only Query Parameters as its input data, while POST request can accept additionally JSON input in its data body

#

which makes GET requests vulnerable to attacks a bit, because hackers can insert GET requests into <script> fields for self invocation, that makes POST requests a bit safer

#

but at the same time, since GET requests have all its requested data in Query parameters, which is basically url like http://localhost?blablabla=123&another_data=fdgk
it makes it perfect target for caching mechanisms to speed up your web site! because it allows easily having separate caching copies in web accelerators for GET requests with different query parameters

past dove
#

hi, can anyone tell me how to publish a website that i made online

#

?

inland oak
#

is it just bunch of html/css/js files, or is it requiring python web server

past dove
#

It's just html, java and css

#

@inland oak

inland oak
# past dove <@370435997974134785>

Urgh. I know only the hard way.
which involves, renting VPS server, installing there web server (nginx or apache), and serving its content. (preferably with CDN ;b)
Additionally people usually like to buy domain names, and installing ssl certificates for https protected connection

#

In theory, in theory, some hosting providers resolve all those problems for you, which would be easier way

#

all you need to acquire their web hosting space, and drop your folder with website to them

#

they will handle setting up web server / domain and e.t.c.

#

basically you have option to go full way on your own and having complete control, or to find hosting provider that resolves those problems for you

frozen wadi
#

Hold on, if it's that static https://pages.github.com/ should work I think

#

I haven't used it before but it's free!

#

Definitely give that a shot before renting your own digitalocean droplet, that should be way overkill for a static site

digital hinge
chilly mesa
#

heyy!!!1

#

I am trying to deploy my blog in heroku

#

its running properly in localhost

#

but im getting an error while i am deploying in heroku

#

could any of you help me ? it would be really helpfu;

#

btw i used django

native tide
#

why when i change the debug to False

#

all my images not showen

#

help plz

native tide
#

???

#

i fix it thx for me hhhh

lime pecan
#

What's your problem?

chilly mesa
#

Should I create my project after creating a virtual env or can I create it after finishing the project. For deploying in heroku

meager anchor
#

but if you already have your host system set up the way the project needs, you don't need to create a virtual env

#

it's good practice to use one, but nothing forces you to use one

lime pecan
fallen prairie
#

Is this a good channel to ask about web scraping in?

orchid mural
#

Hi guys, needed some help with apis in python, im trying to login to an api and dont have much knowledge about requests and session.I have made a username and password file as constant at the moment.Can anyone suggest me a good resource for this.I plan to take cookie and sessionid from json and pass to an api further

haughty isle
haughty isle
#

What code do you have so far and what problems are you running into?

orchid mural
#

so far i have done response =s.get(url) print(response.json)

#

new to the api part hence

#

my bad not the cookie the sessionid needs to be passed

#

@haughty isle are there any resources where i can read more api in python and how to work with them ?

haughty isle
orchid mural
#

rest api

haughty isle
orchid mural
#

i need to pass the sessionid to the an api further but i dont know how to get the sessionid out

haughty isle
#

Please try to answer all three of my questions, it will help me help you

orchid mural
#

@haughty isle Found my error it was some pytest error...nevermind..thanks for replying

haughty isle
#

???

young zealot
#

Hello! I've a simple update checker hosted on heroku. When a new version get released, i get a mail and it should update the current version. But i still get mails as the file still be the old one! Had to make a commit on github to fix it.

                if res.status_code == 200:
                    logger.info("Success.")
                    with open(file="cur_version.json", mode="w+", encoding="utf-8") as f:
                        json.dump(remote_version, f)

Can heroku update version hosted or there is something I'm missing? Thanks

young zealot
#

Of a software I'm using

haughty isle
#

Which file still be the old one?

#

Are you using heroku chron?

young zealot
#

the cur_version.json

haughty isle
#

I'm pretty sure you need to provision a database to store state between invocations of chron apps

young zealot
#

i'm using the free plan on heroku, with github connected

haughty isle
#

You know 12-factor apps and all that

#

You want to know when you release a new version of your app or when some website changes?

#

Generally heroku apps are supposed to be stateless

#

And store state in other services

chilly mesa
young zealot
#

is it possible, in your opinion doing an automatic commit to my repo ?

#

to update the cur_version file

#

that script used to be located on my raspberry, wanted to try heroku but had this problem

#

maybe i just get out the part where i save to a file, and just store the version in a variable?

#

that should work, if the heroku server doesn't reboot

chilly mesa
#

this is the code for that. this is the actually the code for homepage

#

this is the error

#

it is working properly in the localhost and i am getting this error only after deploying

haughty isle
hybrid lotus
#

Hi I'm working on chartJS for python

#

but I wonder where the 'twitterChart' should be called?

#

this is my ajax

#

all in same file

chilly mesa
meager anchor
#

haven't used heroku myself

vapid stag
bright spindle
iron magnet
#

Hi,
I created an API backend for my iOS app with Flask. It works fine, but it's not yet live. I used Flask 1.1.2 and started thinking whether I should really port to 2.x before launching it. However I can't seem to find any info on how much 2.x has changed from 1.1. The 1.1 docs have a page https://flask.palletsprojects.com/en/1.1.x/upgrading/, but it only covers upgrading to 1.x and 2.x doesn't have anything similar it seems.

high hemlock
#

guys in Django, why is the manage.py outside the project?
this is the command i ran django-admin startproject backend .
it looks ugly now, I have the backend folder and the frontend folder. But this manage.py is sticking out like a sore thumb.

iron magnet
#

Hm, I upgraded Flask to 2.x in a new branch and it seems to have started up without issues and responds to requests.

stark tartan
#

I like it

#

Which is best package or you recommend for 3rd party django rest framework for authication

frank shoal
#

something oidc.

fallen spoke
#

Hey, I want to work on a project that is basically an online notepad, just a very basic text editor. I'm wondering how would I go about doing this? do I just store each file's content in a text field? do I create a folder for every user and store their notes on it? I have no idea how this app would work and I would appreciate any help

signal fjord
#

Hi. I'm currently using flask to create a dashboard for my discord bot. I've set up everything correctly so far, however I'm running into a small issue.

I've checked the docs and it seems what I've done should be correct, so I might be missing something small.

I'm using discords oAuth2 verification and I'm trying to access the username and discrim.
Upon routing to my redirect after login, it should return the username and discrim, however it's returning this.

#

Here's my oAuth checks

#

And here's my routing

graceful flax
#

Hi

#

Django static files if stored on S3

#

and I upload it through my API

strange charm
#

Can someone help
i have one seprate file in django called script.py
how can i import .env variable inside script.yp
and how can i use script.py functions in views.py?
please help

graceful flax
#

Than sending it to my server via API and then uploading it to S3

graceful flax
graceful flax
strange charm
#

i tried but not working

#

it is saying none

graceful flax
#

your second problem:


import 
from ..wherever.script import x```
graceful flax
strange charm
#

@graceful flax i'm able to load value in views.py

graceful flax
#

That's weird

#

Are you running the script separately?

strange charm
#

yes

#

and i put my script inside my app.

sharp tree
#

hello

#

can i get help

#

the blue one i want to attach it to an image

#

mean when i press the blue one it will lead me to a picture but should i connect them

#

how*

sharp tree
#

anyone can help?

unborn badger
#

hi guys

#

im relatively new to python and building backend using flask

#

i just get status 200 in return

#

how do i get json or any form of data that i can use

trail hearth
unborn badger
#

Can u plz give an example?

#

Like requests.get().json()?

trail hearth
#

yup

unborn badger
#

Okay ill try

#

Ah damn the powr got cut off

#

Ill try in the morning its time to slep anyway thanks @trail hearth

warm igloo
native tide
#

this channel only python?

#

or html css...

warm igloo
#

eh, html css seem fine imho

native tide
#

understand thank bro

jaunty depot
#

hey guys
could you please tell me how do I stylize wtf forms variable in html file? I designed my site in figma and only then moved to the code. I first made templates with forms and inputs and fields

now I'm learning about wtforms and thanks to the way they work I will have to erase my inputs and labels and put the variables in their places, but when I do that, the fields look ugly. How could I make them look like my designed input fields?

initially I have this:

<form class="formentry" method="POST" autocomplete="off">
    <div>
        <div class="greenthingytop"></div>
        <input id="useremail" class="inputentry" name="email" type="email" placeholder=" " />
        <label style="top: 20%" class="labelentry" for="useremail">Enter email address</label>
    </div>
    <div>
        <input id="password" class="inputentry" name="password" type="password" placeholder=" " />
        <label style="top: 38%" class="labelentry" for="password">Enter password</label>
    </div>
    <div>
        <input id="passwordc" class="inputentry" name="confirmpassword" type="password" placeholder=" " />
        <label style="top: 56%" class="labelentry" for="passwordc">Confirm password</label>
    </div>```
#

and it looks like this:

#

but when I change to

<div>
        <div class="greenthingytop"></div>
        <div id="useremail" class="inputentry" name="email"> {{form.email}}</div>
        <!-- <input id="useremail" class="inputentry" name="email" type="email" placeholder=" "></input> -->
        <label style="top: 20%" class="labelentry" for="useremail">Enter email address</label>
    </div>
    <div>
        <input id="password" class="inputentry" name="password" type="password" placeholder=" " />
        <label style="top: 38%" class="labelentry" for="password">Enter password</label>
    </div>
    <div>
        <input id="passwordc" class="inputentry" name="confirmpassword" type="password" placeholder=" " />
        <label style="top: 56%" class="labelentry" for="passwordc">Confirm password</label>
    </div>
#

it looks like this

warm igloo
#

You add classes and id's when you call the form element like so:

        {{form.email(class_="inputentry", placeholder=" ", madeupattribute="hello")}}

No need to wrap it in a div since your original template didn't have that either.

#

Note that adding class looks weird cause "class" is a reserved word in python and lots of its templating langs like jinja, so here it has to be class_ but literally any other attribute you would want can be entered in.

#

@jaunty depot πŸ‘†

jaunty depot
#
{{ form.email(id_="useremail" class_="inputentry" name_="email" type_="email" placeholder_=" ") }}```

a couple of days ago I was trying exactly this, but my site crashed and the error it gave me was "jinja2.exceptions.TemplateSyntaxError: expected token ',', got 'class_'"
#

I thought that I had to add _ after every attribute that was used in input tag

#

even after I added "," I received some other error, I thought that it won't work

#

I have some styling related to labels of those inputs, now that I changed it, the labels do not work. How could I implement them to this {{form.email(class_="inputentry", placeholder=" ", madeupattribute="hello")}} ?

#

btw, you are a champ, I changed the code and now it looks like this:

#

exactly how I wanted, so thank you very much for that!

jaunty depot
#

hah, alrighty I found the issue

at first my form looked like this

#

with this code:

</div>
        {{form.email(class_="inputentry")}}
        <!--  -->
        {{form.email.label(class_='labelentry')}}
    </div>
#

and I could not find anything on how to get to the label, so that I can customize it in css file or something, even WTF docu does not say much about it

but then I was mendling with the code, trying to somehow add or remove various attributes

then by accident I added "placeholder" attribute to the form.email and then I saw this:

#

those two labels look weird and I couldn't get why I have two of those, I didn't even specify this "Email", not even in my python code

then I left the space in a placeholder in form.email and I was left with only this "Email" label near the top of the cell
it even acts just like I specified it in my css file, so that is great that I finally got to the point where I wanted to manipulate this attribute

I just don't know how could I center this label? It looks liks it's implemented automatically by FlaskForm/WTForm, so I'm not sure if it's possible?
but I guess it should, since it moves to the left just as I specified
but I also specified the center and margin parameters, yet it still sticks to the top of the cell

does anyone know if this can be changed?

jaunty depot
#

alrighty, I found the answer to my question
this:

#

is because of the code:

class RegisterForm(FlaskForm):
    email = StringField(validators=[InputRequired(), Email()])
    password = PasswordField(validators=[InputRequired(), Length(min=6, max=20)])
    confirm_password = PasswordField(validators=[InputRequired(), Length(min=6, max=20), EqualTo(password)])
    submit = SubmitField()

I had no idea that WTF capitalizes all of those specified fields + it erases underscores apparently and makes spaces between words

strange charm
#

Can someone help me with django?

#

please

#

in dashboard i want to create and delete button

#

in view i have dashboard function already. Now i want to create a button in dashboard called create and deleted button.

#

if i send get request it will create my object and delete my object.

unborn badger
unborn badger
#

@warm igloo i got it working but i got into a problem

#

{"coord":{"lon":77.4,"lat":23.2667},"weather":[{"id":701,"main":"Mist","description":"mist","icon":"50d"}],"base":"stations","main":{"temp":22.13,"feels_like":21.86,"temp_min":22.13,"temp_max":22.13,"pressure":1014,"humidity":56},"visibility":2000,"wind":{"speed":4.12,"deg":10},"clouds":{"all":75},"dt":1637382628,"sys":{"type":1,"id":9063,"country":"UK","sunrise":1637370460,"sunset":1637409879},"timezone":19800,"id":1275841,"name":"London","cod":200}

#

this is the data i got but i dont know how to index and use specific parts for ex. the temp field in this jason

#

json*

#

Anybody help plz

dense cloak
#
@app.route('/db', methods=["GET", "POST", "DELETE"])
def database():
  if request.method == "GET":
    return f"""
      <iframe src='https://db.infinityiron.xyz/api/pass/list?file=demo'></iframe>
        <h4>Set a key.</h4>
          <form method='post'>
            <input type='text' name='key'>
            <input type='text' name='value'>
            <button type='submit'>Send!</button>
        <h4>Delete a key</h4>
          <form method='delete'>
          <input type='text' name='key'>
          <button type='submit'>Delete!</button>
  """
  elif request.method == "POST":
    db.store(k=request.form['key'], v=request.form['value'], f="demo")
    return redirect('/db')
  
  elif request.method == "DELETE":

    db.delete(request.form['key'])
    return redirect('/db')

only uses the POST method creating a blank entry on the db

native tide
#

Is there a way to dynamically change the flask_env like it is available for JavaScript like the CONST_DEBUG? If I am running it on my local machine it should automatically switch to the development server is there some way to achieve this?

tight agate
#

Hi all I'm building the OpenSea of Real Estate and hiring a graphic designer in the next 48 hours to get started. If anyone knows any great web3 designers that can handle a logo, branding and identity package from start to finish in a tight deadline, please link me. The creative brief is extremely precise, and the process will be smoothe and fun.

haughty isle
#

!rule 9

lavish prismBOT
#

9. Do not offer or ask for paid work of any kind.

digital thorn
manic crane
hybrid lotus
#

Hi can sb help me please I get this nonetype error but I'm trying to interate values from pymongo

#

but the user["uid"] is not iterable when it becomes none... so how do I get the "uid" then?

haughty isle
#

Also it's best to write your code top to bottom, rather than allow it to drift over to the right

#

If you return in an if branch, you don't need an elif or else branch

sonic island
#

anyone contributing to Django open source?

hybrid lotus
haughty isle
hybrid lotus
#

I meant my methods in other files

#

the mongodb backend files

stuck narwhal
#

Hello

#

I need some help with flask

#
from flask import Flask, request
app = Flask(__name__)

@app.route('/api',methods=['POST'])
def makecalc():
    #data=request.get_json()
    return "hello"

# def hello():
#     return "welcome"

if __name__ == '__main__':
    app.run(debug=True)
#

when i run this i dont get the endpoint in the outout

#

and when i put the server in the browser it throws an error

haughty isle
#

Did you try putting the server somewhere else?

#

It might be because you're putting the server rather than posting it?

bitter basin
#

who knows how u can transfer audio stream through aiohttp websockets?

stuck narwhal
stuck narwhal
haughty isle
#

Yeah if you're putting the server you need to use methods=["PUT"]

#

You need to post the server instead or change the methods=

#

In your screenshot you're getting the server rather than putting it, as you initially said

jaunty depot
#

@app.route("/", methods=["POST"])

#

something like that

#

oh sorry, you already have this, didn't notice