#web-development
2 messages Β· Page 201 of 1
every Django ORM object has unique key automatically created without any additional code lnes
hidden pk variable
yup
ok
pk stands for Primary Key
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
err? Why would you wish them creating multiple same class names?
I thought Classes are going to be unique entities
no but for example let's say we have two users
right
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
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?
Well, it would be possible, sure.
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)
rip all the help channels are taken
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 :
That's just a list.
Seems to be working properly.
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
You'll need some kind of javascript - whether a framework or something like an ajax call with jquery or something along those lines.
If i have access to the database?
Yes?
Either way.
You can do stuff client-side without a response from the server, but it still needs JS either way.
Ok so if I wanna do it automatically what i have to check from that database?
Uhm so JS is needed anyway
Yup
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?
Anything that updates your page without refreshing it will require javascript.
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
In that loop i will refresh, every tot mins i refresh the page, get the link which i'm interested in and check if there is something new
Ok
Hello is someone online to help?
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\
if you don't need to be migrating prod data with it, which I assume you don't
I would advice just deleting manually all migrations from the folder, except for the file __init__.py, keep it.
and dropping database
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
rewriting from node.js to python frameworks in one day? Well, I think there is nothing in the world to help you with that
that sounds like a completely impossible timelines to do this task
how to get started with Flask framework
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
how to get started with Django framework
https://docs.djangoproject.com/en/3.2/
i might be able to request an extension as well
both instructions have answers for how to create servers too.
okay thanks
Flask is more beginner friendly, but commercial choice would be Django, as it is much better and battery included
what might any other prerequisits for my system?
mm
usually it is enough to have installed python 3.8 or 3.9
and matching python-venv version
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
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.
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
docker (docker-compose) is cool to host stuff locally
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
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)
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
I think i am already fearing nothing.
After going through backend and DevOps, walking through frontend looks quite easily.
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
I hate videos)
of my current state of the project
wanna join vc?
nah. I am currently at job in office.
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
blinded with amount of spoilers. going back to work.
oka
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?
what is the file?
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? π
Does instagram uses Django as back-end ??
Hi can some one help me in renaming a model in django??
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
auth_permission is your own table, or is it one of default auth tables?
it's one of the default tables that django creates when running python manage.py migrate
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.
this is my first thread here so forgive me if something is wrong.
I'm creating a CRM sorta application in Django and trying to connect to a MSSQL database using pyodbc. I manage to connect and Django
how about using good old PostgreSQL, or at least Maria DB?
PostgreSQL has the best Django compatibility i think
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...π
short story told, due to incorrect SQL implementation in Microsoft SQL server, Django highly likely will never work correctly there π€·ββοΈ
I downgraded django and it works for now, let's see if the bandage worksπ
Maybe I get another error sooner or later...
there is alternative in using different ORM also, like SQLAlchemy, but then you will not use even 10% of Django abilities
considering incorrect SQL implementation of Microsoft SQL server, I would have avoided Microsoft servers though.
not the best thing to use for ORM ;b
Me too
Thank you!
u a welcome. Other people would say though, that I am supposed to avoid ORMs π
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
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 followed numerous threads recommending multiple variations of these snippets like this thread with no dice https://stackoverflow.com/questions/19794695/flask-python-buttons
I've been stuck here for the past hour with no resolution in sight
cheers in advance
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..
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
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.
I would say websockets
I found this on stackoverflow too:
https://stackoverflow.com/a/12236019
I will look furder in these things if i get there. I was just wondering... π€·ββοΈ
Further*
@inland oak hey sir
whats wrong with this?
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.
Just the key idea is to use time stamp instead of refreshing to see if the server allows incoming data or not.
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
doing render_template("zzz.html", xxx=yyy) will make the variable xxx be available in the template zzz.html
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
*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
xxx=yyy becomes kwargs={'xxx': yyy} inside the function.
with jinja, you would reference the variable via {{ xxx }}
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
i must have to say, this kwags and args thing is quite confusing
think of them as extra arguments.
oh wait, i can just do current_user.name?
Ohh I see, okay. Thanks!
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?
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
I got it
The variable needs to be lowercase and I'm pretty sure naming it Class is going to conflict
that's not the issue I believe, if you name it a keyword, you have to access it's id using two underscores rather than .
so using Class__id=pk worked
Class = models.ForeignKey worked? π€
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
Which kind of picture you have used in pp and asking for help
Reported you
yes
it wouldn't work if it was lower case
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.
no class is a keyword
so we wouldn't be able to name the field that at all
lowercase class is a keyword
Right, it's reserved.
but uppercase Class isn't
Well, use whatever you want but I would recommend finding better variable names.
I have a model, when creating an instance of a model, is there any way to check if that object has already been created
oh I know now
Check it exists in the database?
yeah
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?
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?
const click?
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
I dunno, does it do what you need it to?
no, a new classesandstudents object is created
even when the user and the class are the same
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.
This
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.
Going to need some more info. What fields exist? What's the full error.
utilisateur is the field that exists
Full error is: 400 bad request {"utilisateur": {"username": ["an user already exists with this name"]}}
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?
Yes
Yes
It is my login credential but its not the only field with this same error
Ok well you'll need to find where and why it cares that it needs a unique value.
What i want is: posting data and if data already exists fill it with the existen data
Yes
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?
How do i update
Get the object, set the variables to whatever you want, and .save() it.
Good opportunity to lookup how to update an object
Still same error
I tried this:
user = User.objects.get(username=validated_data['utilisateur']['username'])
user.save()
Dossier.objects.create(
utilisateur=user
)
show the whole code
@dense slate
Yes i added this
Ok one sec
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
So where's your if statement...
i just want to it to insert with the existen user instead of creating a new user
But then you return with creating a new object right after.
What should i do?
I want to create the Dossier object
I did mention to try a conditional statement.
Its the utilisateur thats making the error
Based on whether the object exists.
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^^
It finally worked omg
Wasted a day on this bug
What did you end up doing?
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?
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
is es6 like pep8 or am i lost
Es6 is version 6 of JavaScript
so like a es6 tutorial = up to date js tutorial
The latest version of node supports esnext
now what is esnext π©
Which is the next version of JavaScript
Not to be confused with next
Yes.
like tkinter in py?
Yes
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
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.
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.
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
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
Yeah, so look at rpyc and build it. Looks like that lets you set up a server easy and then you can just write the calls to it to a file or whatever.
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.
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
Hlo guys
Does anyone have experience with agora and django
A guide for how to ask good questions in our community.
Django is one of the most used frameworks.
I'm hitting an API for text information and it is slow! Any thoughts on polite ways of sending more/faster requests?
Yes, but I found a github repo it's not performing well on my side
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
This means that a comma was expected in between your form.email() like (id=..., class=...)
Can someone help me establish a connection between a Flask Server running inside PyCharm Prof., ngrok and AWS?
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?
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['name', 'email', 'body']
HOW TO put a class on this fields\
@native tidewhat do you mean by put class on fields ?
if you wanna style it you should use front-ends like css bootstrap
@native tide if you agree i dm you to help you much better
okay
have any1 used agora ft django?
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
does anybody know how wiremock works for django?
Just some messaging or live chat?
Live chat will require some kind of websockets or polling.
anybody good at ajax
Iβm okay with Ajax whatβs up?
can someone explain current_user to me in flask? what does it access
I don't know flask well, but I'm assuming maybe the logged in user if there's a user session in the request header?
so, this current_user access the sql database? im honestly not sure aswell
It would probably be the user object of the logged in user.
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
Is this the same thing from yesterday?
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.
ok so I can just do model.objects.get(id=x, user=request.user) and then edit that
how long does it take for the average to be comfortable with getting data from sql and stuff incorporating everything into a webpage?
not too long, just watch some tutorials, then you'll be able to do what you want with it
is sql pretty much the same for flask sql?
yes
I need help making a bot yβall want them ps5s this how many u can get plus more
anyone here know peewee?
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']```
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
Maybe it gets hashed to a string longer than that?
how can I get current object in view
Django Channels modification is made to make it
https://channels.readthedocs.io/en/stable/tutorial/index.html
https://channels.readthedocs.io/en/stable/index.html
Chat feature like Facebook for example in peronal inbox....
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
how can I import models from another app in django
It sounds like some sort of iframe, check available Facebook integrations
- Flask with Rich logging: https://github.com/BD103/Flask-Rich
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.
https://www.google.com/search?q=how+to+fetch+data+with+javascript
what about these search results does not work for you?
You can use axios or fetch to get the data, then manipulate the DOM either imperatively or declaratively
Hello, did anyone experience having certain fields missing from a form model??
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
how are you logging them in?
Just run a sql query using their user id to look for it no?
yeah i figured it out, i just did if email == 'test@gmail.com' then run some code, how secure is that compared to auth tokens? because thats all backend so i can imagine its pretty secure? and if email != 'test@gmail.com' i just have it return "unauthorized"
Your security depends on if u a having sanitized input.
And on having important stuff hashed
And on having strict SSL
And unnecessary ports closed
And a lot more things
Also auth tokens complement it with helping to prevent additional reauths, not replace it
could you please elaborate this in my dms?
im new to web development and would like some extra help π
I would not mind speaking in voice in around ten hours. At the moment I have to go to work.
no worries thank you! could you please accept my friend request?
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?
Guys is socket okay for building a messaging app for a flask website?
If it's a website you can use urllib
It already has the protocols HTTP/S and functions to use them
I'll take a look on that. Thanks Roie!
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...
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
And If I start building project which projects should i start and move fwd as learning + experience...
I don't know if this is an efficient approach, but why not just add required in the html input field?
Do you have a github account?
well html is generated by swagger i believe and it is not just input field, it is also a form in which you can try a request so it is important for me to set this thing how it is supposed to be set
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
You can use regex to extract the 1.90
but it varies
Should i use int for that
This might help https://stackoverflow.com/questions/60951520/python-selenium-can-not-extract-innertext
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
yes..
I would advice to be NOT using the hostinger. As far as I remember it is a fake, not a real cloud hosting (in terms of service quality)
I would recommend starting from beginner friendly providers like Hetzner, Digital Ocean, Vultr, Linode
or if u want more advanced ones then: AWS, GCP, Azure.
the difference between quality providers (like the ones which I mentioned), and the shitty providers (everything the rest usually) is 10-100 times.
i bought it
4 daysback
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
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
wha
ok but theres a 30 day money return back garuantee
βοΈ then run while u can
uh
@inland oak
u making me confused lil bit
? wdym
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.
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?
Celery keeps its tasks in NoSQL backend databases like RabbitMQ or Redis
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
Wait
Everything can be done much simpler and more gracefully
https://docs.celeryproject.org/en/stable/userguide/workers.html
Process Signals
The workerβs main process overrides the following signals:
- TERM Warm shutdown, wait for tasks to complete.
- QUIT Cold shutdown, terminate ASAP
- USR1 Dump traceback for all active threads.
- USR2 Remote debug, see celery.contrib.rdb.
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
well
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
When my stuff is too slow it's 99 times out of 100 I who wrote shitty queries/back-end code
i read that there is some solution with the help of docker by splitting multiple processes
it really depends
show code as text
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
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))
the "file" is just a variable and the columns are Year, Industry_aggregation_NZSIOC in parquet file
but query = self.db.AQLQuery(aql, bindVars=bind) actually sends a query
doesn't it?
yes
yeah so you're sending one query per row in the dataframe
which is why I said this
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
good observation now i will try to change that
I got the right answer to the question but it doesn't randomize the question
site hosted
Did someone already used PyZoom ?
Never heard of that
Hello
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())
Omg. The Hecker.
Are you the one?
nope
π
Daisy: This is awful!
Roseluck: The horror, the horror!
its pretty much self-explaining too.
this moment from My Little Pony: Friendship is Magic. season 5, episode 9, slice of life.
How about starting using jinja2?
thats no fun
Or even better... Frontend framework, fully weaponized with SASS, JavaScript, Babel and e.t.c. stuff which makes easy development
jokes aside, how is it awful?
sorry to disappoint you but I am not interested in front end dev
I just wrote this for my school bc im too lazy to actually write html
Heavily. It is the worst thing I saw in quite a while. Half of a year at least.
With jinja2 it will be much better. At least ten times
I code for fun
using ready made code is no fun
Worthy enough to post in memes basically
Equally funny to Hecker level
The problem with readability.
In one week u aren't going to remember what was written there and how to change it
lies
I always remember my code
Jinja will make a clear separation between python and html code
Spare your future self, use jinja
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
I could even help you a bit later in rewriting it to Jinja
I want to save you!
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
U just aren't having installed proper syntax highlighting
U a missing the hell above it
cause that is not meant to be in ur code, you import it
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
Reinventing wheels is silly.
When we make web site, we don't write web servers from zero every time. And especially operating systems and hardware drivers
As I freaking said
I am doing this for fun
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
Perhaps. Perhaps. As an one time thing to be never used again, it will serve sufficiently enough.
This code is not to be developed later.
it is final code, there are no improvements to make
maybe adding properties as a dictionary
but thats all
you just said no for the sake of saying no?
nah it isn't ugly
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?
lmao
correction: 28K lines of code
imagine copy pasting that in ur code instead of importing
what would be "uglier" for you? @inland oak
guys, is it possible to create an online server like Google using python?
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
ohk thanks a lot dude!
google is actually made in python
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
but, its core, searching stuff was made initially fully in python ;b at least crawlers
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
Hii!!
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?
It's reddit (old) that was written in python
Flask calls that a flash
though the ui element is called a banner
or a toast
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
in flask, you create it by using the flash() function
You still have to render it in your function.
example of a toast: https://getbootstrap.com/docs/5.0/components/toasts/
I think this is what you were originally wanting: https://getbootstrap.com/docs/5.0/components/alerts/
wait, so i have to connect this alert to my python too?
just your html
bootstrap makes it easy, but you can do it manually if you like.
in your template, call get_flashes()
wait, so how do i connect it to after i logged in? there must be python code right?
!d flask.get_flashed_messages
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:
!d flask.flash
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.
i think i might have to experiment with this, im super confused lol
experimentation is good.
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?
list = form.save(commit=False)
Anyone knows why this cause the following error:
AttributeError at /en/sell_page
'dict' object has no attribute '_committed'
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
Anyone here know to enable cloud recording in agora vuejs
Bulma or Bootstrap
which one is better?
Bootstrap ig
ty
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,)```
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')
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!
No. Don't do that on this server. Read the #rules please.
Can you explain further?
where do i go then for help
any django experenced
folks here ?
needs some advices suggestions regarding scalablilty
To hire someone? Find a job site I suppose. Or Fiverr? Or Reddit?
Just not here, as per the rules.
Just go ahead and ask instead of asking to ask or asking for an expert. Shoot your shot and see who answers. π
cool, following so far .. single vps?
dedi
well i'm aware that i could optimize the queries allot
planing to do that in near future
dedi?
okay, you have a vm .. is the app and db on same vm?
@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
clusterinz APP services, or clustering DB
sorry, still wanting to find out what you are asking and want
ah thebouv
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
do you cluster the web apps ( django, uwsgi, nginx ) or the clustering DB
for preformance
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
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)
yea
you want the db to have good backup and easy to recover though
I mean, what is the nature of your app?
if it is microsecond ecommerce transactions where you can't tolerate a single failure, that's more expensive to plan for
there are certain functions in the webapp, which steal allot of time and
i'd like to talk about that : )
haha
hmm
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.
yea
thats why we are planing up front
i guess we gonna have a big explostion in next year
congrats if that works out
get yourself an infrastructure person soon π
well i'm pretty skilled
Cool.
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
Suggestions: make sure your app is 12 factor. Think in regards to ephemeral and immutable infrastructure.
whats a 12 factor
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
A methodology for building modern, scalable, maintainable software-as-a-service apps.
good idea
sure, sounds good
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
so your vm works now with django and uwsgi yeah?
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
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)
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
and build a separate front end and use django as api backend?
yep
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.
np
i've only used django debug toolbar
gotta give thumbs up for those folks
they did a good job
Nice. I actually have never built out a django app. I prefer Flask or FastAPI for most of my web work.
ah i started working in it long time ago
then stoped now got back into it
its easy
big up for the community
I prefer slim frameworks
django is heavy, but I get its purpose
tough
I actually need to cookie-cutter my last Flask site out to make it easier to spin up something similar
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
what does youtube use
which is true
If you started out building a dating site and instead ended up building a video sharing site (...
true
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 ?
python is usable for blockchain developer?
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?
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
that's so broad to answer question... which we can't even begin to answer since we don't know how is your website working
is it just bunch of html/css/js files, or is it requiring python web server
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
Hold on, if it's that static https://pages.github.com/ should work I think
Websites for you and your projects, hosted directly from your GitHub repository. Just edit, push, and your changes are live.
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
This may help https://jekyllrb.com
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
I don't know shit, but I just got heroku working for my flask app
What's your problem?
Should I create my project after creating a virtual env or can I create it after finishing the project. For deploying in heroku
these are both independent of each other. you usually want to use a virtual environment for your development to have all of your dependencies as you expect them in a fresh environment
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
You do need to create the virtual environment and have an updated version of requirements.txt for heroku to work. So get that up and going whenever most convenient
Is this a good channel to ask about web scraping in?
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
What do you mean by an "api further"
And which json has the cookie in?
What code do you have so far and what problems are you running into?
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 ?
Sorry I'm not sure what you mean, what sort of API are you looking to read?
rest api
What problem are you running into here? What's the output you have? Where do you need to pass the sessionid?
i need to pass the sessionid to the an api further but i dont know how to get the sessionid out
Please try to answer all three of my questions, it will help me help you
@haughty isle Found my error it was some pytest error...nevermind..thanks for replying
???
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
A new version of what?
Of a software I'm using
the cur_version.json
I'm pretty sure you need to provision a database to store state between invocations of chron apps
i'm using the free plan on heroku, with github connected
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
fine man..you good with django? i am getting an error after deploying it..i can share my code and error here if you can help me
oh got it
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
sorta :D do share it here
just a min
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
Oh you mean gitscraping? You don't even need heroku for that
This is so exciting! Git scraping is now an officially supported pattern at GitHub, and they've released a flurry of neat new tools that help people take advantage of the technique https://t.co/ILeqSPRVcQ
339
did you run migrations?
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
I ran it in localhost. How do I run it for heroku server?
https://help.heroku.com/GDQ74SU2/django-migrations I think this should help
haven't used heroku myself
Thanks for the explanation man
noticed it later that day, thanks for the response doe c:
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.
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.
Hm, I upgraded Flask to 2.x in a new branch and it seems to have started up without issues and responds to requests.
What is you coding theme
I like it
Which is best package or you recommend for 3rd party django rest framework for authication
something oidc.
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
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
Is the time shorter
Than sending it to my server via API and then uploading it to S3
or does django-storages static file where I store a file as FileField do this same thing in the background
Your first problem solution:
import os
os.environ.get("ENV_NAME")```
your second problem:
import
from ..wherever.script import x```
Check if the env has set properly
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*
anyone can help?
hi guys
im relatively new to python and building backend using flask
how do i call an api and store the data that gets sent using flask? i searched on the web and stumbled on a module named requests but when i call r = requests.get('https://api.openweathermap.org/data/2.5/weather?q=ACITY&appid={notgonnashowthekey}')
i just get status 200 in return
how do i get json or any form of data that i can use
if I'm not mistaken, you can use .json() on the response
yup
Okay ill try
Ah damn the powr got cut off
Ill try in the morning its time to slep anyway thanks @trail hearth
No problem!
Careful with that .. make sure you get the response, check that it is 200 (and not 500 or 404 for example) and THEN use .json() to be safer.
eh, html css seem fine imho
understand thank bro
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
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.
Lots of fun things you can do: https://wtforms.readthedocs.io/en/3.0.x/
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 π
{{ 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!
I'm here https://wtforms.readthedocs.io/en/3.0.x/fields/#wtforms.fields.Label but I can't find anything on how to implement a label to this variable field
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?
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
Can someone help me with django?
please
i have created two classes in my script.py
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.
Yeah i did thanks man it worked.
@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
@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
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?
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.
!rule 9
ok
how so ?
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?
Do you have a Traceback?
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
anyone contributing to Django open source?
it's ok...resolved it. I just needed to change algorithm
Algorithm?!
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
Which error specifically?
Did you try putting the server somewhere else?
It might be because you're putting the server rather than posting it?
who knows how u can transfer audio stream through aiohttp websockets?
if i just enter the server i get Not Found