#web-development
2 messages ยท Page 80 of 1
try
python
from app import db
what do i change
what was worng
just line 2?
db = SQLAlchemy(app)
waiiiitt i didnt save it
also
let me re try
also
db = SQLAlchemy(app)
do i type that in the python before or after from app import db
yes
python
after that from app import db
can i reset the terminal
like clear it out
don't
idk how to clear
oh
type cls
in terminal
cleaar everything
ok
ok cleared
first step
pyhton
yes
check
next step
from app import db
bro
what
db should be this db = SQLAlchemy(app)
not db = SQLALchemy(app)
what the difference
i dont see
change db to this SQLAlchemy(app)
no cap L second L
tell me the line its on
if u don't change db = SQLALchemy(app) to db = SQLAlchemy(app) U will keep getting error
i fixed it
Now
try
python
OH
Model
i did that and did the import app thing
not model
capital
?
capital M
not lower m
Integer not integer
Capital I not i
so i suck ass at spellling lol
oh wait
capital
capitl String not string
something wrong with my primary
oh i spelled it wrong
primary_key=True
@native tide I'll fix ur code now
fixed nullable spelling\
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
class todo(db.Model):
id = db.column(db.Integer, primary_key=True)
content = db.column(db.String(200), nullable=False)
data_created = db.column(db.DateTime, default=datetime.estnow)
def __repr__(self):
return '<Task %r>' % self.id
@app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)```
class todo(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200), nullable=False)
data_created = db.Column(db.DateTime, default=datetime.estnow)
def __repr__(self):
return '<Task %r>' % self.id
Fixed it
thank you
uh it that all
ahhh replacec the class
Column should be Captial C not column
now
try
python
from app import db
i got to cut the grass soon once i fix this little part
don't worry
that is not a error
if u wanna fix that
oh it isnt
so what do i do with it
am i good?
copy that error and paste here
SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning.
warnings.warn(FSADeprecationWarning(
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
after app = Flask(name)
replace line 6?
nonooo
just copy and paste this code and put after app = Flask(name)
here?
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
Like this
now were cooking
python
from app import db
after that
db.create_all()
then database created , good to go
test.db???
i think it worked
yayayaay worked
thank you so much sir, gotta go cut the grass
continue with tutorial now
yay
I'm currently using flask-login
Should I use flask-security? (the new maintained version) (https://github.com/Flask-Middleware/flask-security)
Is it secure and safe to use?
@manic berry flask-secuirty is secure to use and it will secure ur website
I am trying to play a video via <video> stored in the /media/. But as soon as the page loads I get this error in the console: ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
How to fix this?
I researched and found out that it might be due to the development serevr limitations
But I needed confirmation from someone who knows about this.
this is a part of my final year college project and hence it is necessary for me to figure this out somehow.
Any suggestions or alternatives for playing/'streaming' video stored in /media/ are appreciated.
@native tide Yes but I'm talking about the new maintained version
Not the original flask-security
hey y'all, i have a question: how do certain websites check if the user is using mobile or desktop? Some sites I go to redirect me to their mobile subdomain (m.domain.com) instead of their regular one. Do they do this by checking the user agent? or is there some other magic happening there?
the reason why i am asking is, i have a flask website that is responsive, but i also have a mobile version that feels like a PWA. I would like to send mobile users to the PWA like website
Cloudflare offers something to make home hosting viable iirc
okay, i also looked at flask-mobility. did you ever heard of this by any chance?
But as far as i can see they also "just" check the user agent.
my question is if there is some other viable way of doing this
it is usually header based (that is why you can "request desktop version" on mobile -- it ultimately just sends a request with the primary user agent)
as far as reactive sites though, most of what I see in use now is just a display size/orientation (see bootstrap)
but if you want to do some real mobile optimization, then yeah, UA detection and redirection is the way to go
alright, thank you
Hey guys, is there any way to make an itsdangerous token a single-use token?
Alternatively, is there any way I can remove all the data from the token to then make it unusable after a request?
I am developing an API which downloads something from a given url and then saves it in a database for being retrieved later. Whats the best way of doing something like this? The easiest way I imagine would be blocking the thread until the download is completed and then saving it either directly in the database as binary data or saving the path to the db.
In a django project does it make sense to have an app for the home screen?
and then different apps for each seperate part of the site
What is the best flask plugins for security and cookies?
This is gonna sound really dumb. I heard django is really good, so i decided to use django with my website, but i don't really understand why. What do i use python for in my website. It feels like it took so long to setup and all that shows on my website is html and css and django was just a big waste of time i feel like. What do i do with django, why is it recommended.
Python is a good language for data science and backend web development
also saves time so you don't have to learn a whole new language just for frontend development
Django is a backend framework via Python. If you're new Flask is easier to learn. Frontend is done via HTML CSS and JS (/react)
Django is frontend and backend
Flask - Simple and lightweight. Good for projects that aren't very complex or don't require too much functionality
Django - More complex and offers more functionality than Flask
so how do i do things with my html and python. Like how do i connect them to do something. Like with js you can make an image slider. you have to connect your javascript to your html though. How do i go about connecting python to my html
the frameworks have functions to allow that
where you can link the HTML with your python
you can also call python code directly from the HTML
they work pretty well together
Is this channel alwayso pen for questions?
I think so but Im not sure
If you need help with code, you should go to help channels I assume
Is there a way to disable the prompt for windows authentication when using basic authentication in your API?
https://media.discordapp.net/attachments/599377007754870839/745699889949966406/unknown.png
This vibe. If the password provided is incorrect, the browser will automatically prompt again (but with the standard authentication form) and retry
I know you can question the use of basic authentication here, but it's for good reasons
this is my question ^^ typical web, I guess ๐
I assume it's notpossible but want to double check
hey, when i say run flask in my cmd, i want a address but i dont get it
what did i do wrong
@drifting elm well, not python, but I was doing log in with laravel not long ago and it never touched standart form
So you should be able to avoid it here aswell
This mustn't have anything to do with the language ^^
it's quite agnostic in this sense, the browser sees a 401 on a basic auth request
and prompts to retry
Highly there's something in the response headers you can provide for it to not have this behavior
or NOT return a 401
but that's quite bad practice.. especially since the main use of this API is not the webpage
Yeah that seems like a lazy workaround
I bet you can disable this in the browser settings but also that is not the solution im looking for
I feel like I'm forced to support OAuth
Yeah doesnt happen with OAuth
Well idk maybe someone with more experiance will show up and suggest a proper fix, I just gonna flee
๐
Can someone recommend a good tutorial on creating a scalable web structure using microservice tech (ex: docker, kubernetes, etc)?
those two things are completely different
scalable website = frontend, microservice tech = backend
you won't find a good tutorial for both at the same time
oh sorry web structure
i prob should not have used that wording
but id just use react for the front end
and serve it staticly
but still both scalable and using microservice tech are two diff tthings ^^
well using mircoservices makes it scalable right?
or do you mean creating new instances of a service to handle more traffic
is there anyway I can pass a flask variable link to css?
so I have a image url from an API call and I want to show it as a background on one of my pages
just add a <style> tags with the css
oh you are right, i havent tried doing that in the html file itself
well using mircoservices makes it scalable right? honestly I wouldn't say so, it makes it somewhat compatible but not really, epsecially docker is more of a pain.
docker promises compatibility but docker installation is not available on all systems XD
its quite ironic
@drifting elm I like the idea of running express for an api gateway and then creating services with other langs like python and php
So, I am trying to make a very basic web server where i can upload files to and then download them later. Currently you can upload a file and view each file you upload, but you can not download the file after. When you click the link to download it fails and says Failed - No File Any help is much appreciated
This is how I am trying rn
{% for file in allFiles %}
<a href="./users/{{ session[NAME_KEY] }}/{{ file }}" download target="_blank">{{ file }}<br></a>
{% endfor %}
Here is the view for the HTML page
import os
from os import curdir
from flask import Flask, redirect, session, request, url_for, render_template
@app.route('/uploads', methods=['GET'])
def uploads():
if request.method == 'GET': # I have it check incase I add in the POST method later
if not os.path.exists(f'{curdir}/users/{session[NAME_KEY]}'): # Creates a folder with their login name if it does not exist
os.makedirs(f'{curdir}/users/{session[NAME_KEY]}')
allFiles = os.listdir(f'{curdir}/users/{session[NAME_KEY]}')[::-1] # Gets every file in that list, then reverses it, return a list like ['File.txt', 'WebPage.html', 'Audio.wav']
return render_template('stored_files.html', session=session, NAME_KEY=NAME_KEY, allFiles=allFiles, open=open, user=session[NAME_KEY])
This is the file tree I have
- Web-Server (Project folder)
- static (folder)
- templates (folder; contains html files)
- users (Folder; contains folders of each user that makes an account)
- Drew (My user folder)
- WebServer.py (The main file)
@young crane is the users folder treated as a static folder
wdym static?
files wont be in the user folder ever, only other folder will get added
so a route is like this /users/koon/345345.png
yeah
is it trying to find that route or is it static like your "static" folder for getting js and css
In the html it finds that file
./users/{{ session[NAME_KEY] }}/{{ file }}
so, if you did it it would look like this
./users/koon/48573985.jpg
I dont think so, thats the issue. When you click download it brings up the download box and the name of the file it is downloading is 48573985.htm
not .html, just .htm
then if you hit download it just fails
i can send you my entire project if you would like
no need
okay
remove the download tag in the anchor tag
and click the link and tell me what you see
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
http://127.0.0.1:8080/users/Drew/Test.txt
ok
youre going to need to create a route called /users/<string:uid>/<string:file_name>
and when it gets that it will need to return the contents of the file
like return the file object?
ive done this before in one of my projects ill try to get the code....
Okay, thank you very much
you're going to want to import send_from_directory from flask
k
@app.route('/users/<string:uid>/<string:file_name>', methods=['GET'])
def media(uid, file_name):
return send_from_directory(f'./users/{uid}/', file_name)
in django_filters if i use this "lookup_expr='lte'" in the template it shows .. is less than or equal to. Is there anyway to hide that part?
kinda?
1 sec ill show you
Okay well
for text files
it just opens a new page with the text
for other things, it downloads them
is there a way to make the file get downloaded if it is text? if not its fine because you can just hit Save As...
then include download in the achor tag
Thank you VERY much koon!
๐
Hey
I don't really get how oauth2 works globally
And how to implement it to Django
Could you help me please ?
TypeError: path() missing 1 required positional argument: 'self'```
im getting this error using the storage class in django
i dont know why this error is being thrown can someone help
TypeError: path() missing 1 required positional argument: 'self'```
@modest scaffold try Storage()
does anyone here know how Django's ordering works?
like is it implemented at a database level, or does it just add ORDER BY implicitly to queries?
How long does django take to learn? Id like to get a blogging site up
How long does django take to learn? Id like to get a blogging site up
@native tide depends, how much experience do you have
have you ever worked with Flask/Pyramid/Sanic etc.?
Nope
10 hours?
if you're fairly talented, possibly
"name": "Minecraft", "version": 1}, "username": emails[count], "password": passwords[count]})
parsedJSON = json.loads(responseJSON)```
Whenever I run this, I keep on getting the error "(File Location), Line 136 (parsedJSON), in <module>, parsedJSON = json.loads(responseJSON)
(Sorry this probably isnt the right place, I just don't know where else to put this lmao)
Traceback (most recent call last):
File "path", line 136, in <module>
parsedJSON = json.loads(responseJSON)
File "path", line 341, in loads
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not Response
i have to delete the path since it has my name in it
well
let me suggest this
- put your JSON in a separate
dict
then you can just call requests.post(url2, json=json)
- when you get an error, post the whole error. (very important)
requests.post(and indeed, all the HTTP verbs) return aResponseobject
that you cannot pass to json.loads directly, because it expects a string.
so, normally, you would do json.loads(response.text)...
...BUT
requestshas a helper for that, soresponse.json()will work just fine.
unless, of course, the request cannot be parsed as JSON, in which case it'll fail
np
whats the best way to start doing web development with pyhton?
also this is like a super small thing but in general Python variables are in snake case
so perhaps response_json?
alright
so where do i put the response.json? lol
sorry im new to coding in python
parsed_json = json.loads(response_json.text)```
This is what my code is now, and I'm getting the error:
File "path", line 136, in <module>
parsed_json = json.loads(response_json.text)
File "path", line 357, in loads
return _default_decoder.decode(s)
File "path", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "path", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I think you want
response = requests.post(...)
parsed = response.json()
but you're getting an error, which suggests to me that your response doesn't contain what you think it does
hm
okay
i'll see if I'm doing something wrong somewhere else, cus I just keep on getting more errors lol
try print(response.text)
to see what it looks like
are you sure that post returns a JSON?
no im not
i realized what the problem was lmao
sorry for wasting ur time
the api isnt working right or sum like that
hey how do i create a csv file to see the user's username and pw's
import csv
login = False
while login == False:
data=[]
with open("login.csv") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
data.append(row)
print(data)
un = input("Please Enter Username: ")
pw = input("Please Enter Password: ")
col0 = [x[0] for x in data]
col1 = [x[1] for x in data]
if un in col0:
for k in range (0, len(col0)):
if col0[k] == un and col1[k] == pw:
print("You are logged in")
login = True
else:
print("Wrong username or password")
i just dont know what a csv file is
orrr is there a way to translate the code to put it in a normal .txt notepad file?
Coma something values I think
Kinda like an excell file
@native tide
I have no idea abt the notepad
Guys, I'd appreciate it if anyone with some spare time and knowledge in Flask dev can take a look at https://stackoverflow.com/questions/63498127/flask-email-link-prefixed-with-link
I have a Flask backend. I'm sending a registration link to users. The link that arrives in the email (I'm sending it to my personal hotmail email address) is as follows:
[staging.site.com/#/sign-up...
whats the best way to start doing web development with pyhton?
@true harness You have to have a basic experience and understanding of python, the you choose some framework, I recommend using Flask, because it is easy. Then you read Flask documentation or watch some tutorials.
Hi, i know this is a python server, but hear me out
am torn between learning node.js or django for my backend. Ive started learning django which i enjoy but it seems like there arent a lot of dev jobs looking for django devs and i see node.js more often. Which is better? Which of the two kinds of developers have more hirings/opportunities?
I honestly like django more, am just worried about the job opportunities if people are hiring junior django devs..
Or is full stack dev mostly for freelancing?
anyone ever used selenium for download a file, do you happen to know if there's an option in there somewhere, to actually choose the filename when downloading it?
because you can't really directly interact with the popup meant for user interacion
anyone have knowledge about hashing for online POS systems?
Who can disgn me a imge for a discord bot ?
If I have all information it'm will me more easy to do cards for make a display like this
Mp me cause I not at my office and we talk buisness.
how would i convert a string into html to be displayed by the broswer e.g. post = <p>hello <strong>everyone</strong><p>
whenever i put post is a template it doesn't process it like html e.g. {{post}} leads to <p>hello <strong>everyone</strong><p> being display on the webpage
how would i convert a string into html to be displayed by the broswer e.g.
post = <p>hello <strong>everyone</strong><p>
@modest scaffold https://stackoverflow.com/questions/4848611/rendering-a-template-variable-as-html
thx @vestal hound i appreciate it
I've got a Flask based web server (using development one currently) and it streams a live video feed from my RPI camera. However, Chrome shows that the webpage is still loading while I'm on it - presumably due to the while true loop used for the video feed.
Any idea how I could stop it showing infinite loading?
class Camera(object):
thread = None
frame = None
last_access = 0
def initialise(self):
if Camera.thread is None:
# Start background frame thread
Camera.thread = threading.Thread(target=self._thread)
Camera.thread.start()
# Wait until frames start to be available
while self.frame is None:
time.sleep(0)
def get_frame(self):
Camera.last_access = time.time()
self.initialise()
return self.frame
@classmethod
def _thread(cls):
with picamera.PiCamera() as camera:
# PiCamera setup
camera.resolution = (320, 240)
# camera.hflip = True
# camera.vflip = True
# Giving time for the camera to warm up
camera.start_preview()
time.sleep(2)
stream = io.BytesIO()
for foo in camera.capture_continuous(stream, "jpeg", use_video_port=True):
# Store current frame
stream.seek(0)
cls.frame = stream.read()
stream.seek(0)
stream.truncate()
if time.time() - cls.last_access > 10:
break
cls.thread = None
def generator(cam):
while True:
yield (b"--frame\r\n"
b"Content-Type: image/jpeg\r\n\r\n" + cam.get_frame() + b"\r\n")
@web_app.route("/")
def main_page():
return Response(generator(Camera()), mimetype="multipart/x-mixed-replace; boundary=frame")
if __name__ == "__main__":
web_app.run("0.0.0.0", threaded=True)
I believe it's due to the infinite loop in the generator function but don't know how to fix that.
@umbral blade well if you're hoping to learn web development for the purpose of applying to jobs, I'd say take a look at the openings, if the market share of Javascript jobs is more then it would be better to learn that
@umbral blade I was also having a problem like you, and I made my decision to learn Django and when I find the time I will learn Node๐
I'm trying to see which value is assigned to a variable inside settings.file but I couldn't debug it, how can I do that. the variable is:
SENDGRID_API_KEY = env.str('SENDGRID_API_KEY')
@native tide here
nice
I have a lot of time to spare, should I learn JS.
I was learning CSS from FCC .but I dropped it yesterday
@native tide
I am currently learning Javascript and CSS, but I advise you to learn JavaScript React, but you will find it a little difficult.
ohk
I will learn JS React
Good luck
๐
Learn it from freecodecamp
ohk
I tried learning CSS from FCC but failed
let's hope it's good for React
and others.
cya
I tried learning CSS from FCC but failed
@native tide
We all failed at something๐
๐
bye
time to code
let's hope it's good for React
@native tide
You should download it, you will find some problems but never give up
I don't wanna be mean but if CSS was too difficult you shouldn't expect to understand react at all
ohk
I mean I can understand a CSS code (by googling it ofc)
but when it came to building a project, I forgot everything.
You should download it, you will find some problems but never give up
@native tide download?
we can download a full certification from FCC?
@native tide download?
@native tide
I thought it was a mistake
ohk
have a nice day
cya
cya
@native tide
You too
You still need CSS with react
How can i for example post something then it shows? What should i use?
Flask jinja2 templates
With a form
I'm using Flask but i don't know how to make posts just show by putting information into them.
@native tide
Let's say you had a list, in your function you had list = [x,y,z]
Then in your html template you can say:
{% for things in list %}
{{ things}}
{% endfor %}
You should look up the docs on jinja2 templates
Link?
Just google it man
What should i google what is the concept?
Thanks though.
You'll have to search jinja2 templates
Also if you want structured learning I'd recommend codecademy
Helllo , we're trying to have a portal to host challenges over the portal all year long , does anyone have suggestions for the cheapest and easily scalable web services that we can use?
cool, happy I could help xD
is intellij python plugin good? since im learning django, and i am already familiar with intellij and dont want to switch ide specifically for python. i will use both python and kotlin/js in my projects.
is intellij python plugin good? since im learning django, and i am already familiar with intellij and dont want to switch ide specifically for python. i will use both python and kotlin/js in my projects.
@native tide I tried for similar reason, if you do not need, that much inteligence and help when you are writing code, like in PyCharm it's great
it is probably just as good as any other ide. I use pycharm though, I imagine the plugin should work like a plugin for vscode or other ide
I use multiple IDEs though. Pycharm for python, vscode for front end web dev
I use multiple IDEs though. Pycharm for python, vscode for front end web dev
@acoustic oyster Just a question, I assumed that you are doing full stack, what framework are you using?
Django for backend, React front end (or just vanilla html, css, js if I am feeling lazy)
Thx
Hello now I actually have a question about Django, how can I have a model which can only be created with someone with admin access?
On the frontend
Like there is a LoginRequiredMixin is there an AdminMixin
Hey, what do you guys use to hide away your db config info in settings for git commit?
my db stuff is in a separate file for deployment.
I keep my info in a JSON file and store it in a different dir, then have the site import that setup info.
The better choice is to use docker and use a .env file
I usually use the default local db for dev
Hi guys, I'm absolutely new to python and web development
I need someone to guide me to make a wesbite with python for my mini project
And here's what I'm supposed to do
How do you guys go about learning docker, etc? The documentation?
Make a website which takes a pic of a qr code connects to a data base to check if it matches. Next step is a face scan and check if it matches. All within the website.
Lol, I struggled so much, I had people on the server hold my hand through it
The docs for docker are pretty good if you are willing to dig through them. I looked up some guides for examples of syntax as well as referencing the docs, then asking for help on this server when I was really stuck.
I am very new to docker, but I can use it semi effectively now
Thanks! I had a quick browse, and there's lots of terminology that I've still to learn, but at least I know where to continue looking
@stoic gulch That sounds like maybe just doing some python stuff.
In django I would create a model for a picture with whatever info you need and store that in something like a /media dir. Then use whatever searching algorithms you need to in order to search through all the DB items, compare your image to the image at the url in your model, then return the object that matches.
It's for matching students pictures
Many students
Of the entire college
Students I'd cards and faces really
@stoic gulch Is it your first time with python?
Yes
Don't even have the software
I installed 32 bit one
Idk where's the 64bit one
I'd probably go about learning python first before attempting a big project, to make sure I understand exactly what I'm doing
an example (psuedo code) would be:
class TestImage(models.Model):
name = models.CharField()
image = models.ImageField()
and then your search algorithm could do something like this (this is horribly inefficient):
def check_image(current_image, test_image):
return current_image == test_image
test_image = # the image to test
for student in TestImage.objects.all():
if check_image(student.image.url, test_image):
return student
you would need to come up with a better search than this, but I think it could be done similarly^
But I agree, this is a very advanced project for a beginner in programming. Definitely doable if you have a decent background in another language
Alright I made a channel in #help-bagel and I'll try it out tomorrow
Do you guys do unit tests in your django / flask projects?
But ty
Do you guys do unit tests in your django / flask projects?
@native tide not unit test or anything
It's the syllabus change and we have a mini project to do
And our teachers are wonderful and want difficult projects
I use the django built in testing. I have been trying out pytest as well as it ends up much more readable imo
but def use testing, it saves a lot of manual testing xD
Do u think this is too much tho?
I probably should, but honestly I don't know where. I'm trying to learn good software practices and software like docker to better apply to fullstack jobs. Man it's a journey
Did you make the project idea? Or did the teachers assign it? @stoic gulch
And anything to improve upon it
Did you make the project idea? Or did the teachers assign it? @stoic gulch
@native tide teachers idea kinda and ours too
Because matching faces, in my opinion, I think it'll involve machine learning, which is an extra hurdle
Actually ours was a website
Do u think this is too much tho?
your project? learning a framework (like django) AND python AND image analysis is a very big and challenging project. Whether it is too much depends on your willingness to learn, time commitment, team size, time limits, etc.
I have been programming and doing django for years and I would consider that project challenging as I do not know any efficient algorithms for image searching and am not very experienced in image segmentation.
Then they said to make a notepad or something with face scan etc
And then they said make an app for events for scanning students faces and id
For college fests
How long do you have to do it?
In my opinion that's way too challenging, especially for a beginner
You will likely need to learn several frameworks as well as python. This would require a decent understanding of python classes, algorithm complexities, as well as either machine learning or pre-existing knowledge of image search algorithms (or finding a framework)
- were still using C,C++ and java in college
thats a very mean challenge lol
Damn I don't know anything about python
unless you mean just copying the image and saving it
Any better ideas?
if you mean Using ML to match them
If it's ML, then its game over lol. That stuffs crazy
then thats going to be pretty much impossible unless they've given you alot of training data
Personally I could see completing that project as a solo project in 1-2 months if I devoted time to it almost every day, I would say I am an intermediate at python, django, and ML
O man
I mean
Without any comparing images / machine learning
Here's what it is
Ur a student
And u have a qr code at the back of ur id
First u scan the QR code on website
And then if it matches u go to round 2
And match the face with database
ohhhh, you just need to match the qr code to the same qr code?
Dude reading the QR code is also gonna be cv2... and web framework... and database... and machine learning...
oh dang it
Match face with database
this was almost easy
๐ค But surely for that face recognition it needs to have ML to make it decent
other wise those two images need to be IDENTICAL
And then u get access
here
other wise those two images need to be IDENTICAL
@quick cargo aww man
yeah, there are frameworks for facial recognition though haha
Sheesh
also for face Recognition
this will be very difficult lol
if you're going to use ML you need hundreds if not thousands of images for image rec
to make it accurate in any way
it is doable though.
I believe you can use image segmentation to bypass the need for many pictures
ez
For qr code with website is it possible
Scan using laptop or mobile camera
From Website
That's an awesome library @marble carbon Thanks!
ye np
in fact (I have never done it fully, mind you) I think with the right frameworks, facial recognition could be done in 20 lines of code or less
Keras has a pre made system for it
So it's possible?
you just need alot of training data

pre trained models like the above can work tho
@stoic gulch it is definitely possible
It is not easy. The success would entirely depend on your own motivation and ability to teach yourself new concepts
Its gonna be Hard but its do able
smh just look at the library i posted
^
Damn
lol
It is very much not gonna be simple
Alright ima try
Its going to be even harder to make it efficient and quick
๐คทโโ๏ธ
For a comp sci student
Like, personally I have never done facial recognition or qr code stuff, but I could probably have this mostly prototyped in like two weeks. Then another month or so to make sure it all works.
But I have been doing this a little while
And something that sounds awesome cuz our teachers are stupid
ive done some Facial rec stuff but they're a pain to train
it is more based on your motivation to learn and trouble shoot.
This is the type of project that is easy to be "bit off more than you could chew"
it is possible, but it is huge and it may become dissuasive when you have trouble getting it to work. If your motivation and willingness to learn is high enough, then it will not be a problem, just time consuming
I mean, I think this is a great idea
i'd probably abstract the issues out first
Some image recognition project would be cool
you're trying todo essentially 3 Fairl BIG projects in one
Perhaps you can break it into smaller goals/features?
Start by just making a website where you can look up students by name? then if you still have time and motivation you can start adding the additional features
And all you'd really need to know is cv2
you're trying todo essentially 3 Fairl BIG projects in one
yeah, that is the main problem
oof
also another question
The website will be made in django?
Or HTML CSS etc will do
Since django is python framework do django
Django is backenfd
O
Html css and Js are gonna be needed for front
I've never used it in my life
@stoic gulch If you want to do this project, I say go for it, just break it down into more "bite-sized" features so if you decide any feature is too much at the time, you still have a fully functional project.
I use django for backend, flask is an option too.
that is how it goes
And I am lazy kinda
But yeah I can try
maybe the image analysis idea is a bit much then xD
Just make a basic crud app
^^^
So what all do I need then?
you're biting more than you can chew
Html css js django opencv python
Non, how do you import the db info from that file? I made a txt as a simple form to test but I'm not sure how to get it to actually execute the code properly
yeah, for the code jam that just passed, since we had a deadline we were unsure we could meet, we started off with a very basic concept that was scalable.
Once we met our initial goals (create a fully functioning website with users, login, logout etc) we then added full features such as: adding experience points for using the site, adding a chat room, adding a weather app, adding a search engine, adding profile management, etc.
These were all things we knew we wanted but we were unable to predict the time it would take to do these
try to build an MVP first
MVP?
minimum viable product
Wait wait this website is a simple one
In a team of four in 8 days we were able to create a fully functioning website, I contributed about 2 hours a day average, some team members contributed more, some less
For me website is no problem
minimum viable product
yeah, exactly this
Just the python part
coz u don't know Django yet
Yes
yea
and django is not necessarily super beginner friendly, it uses a lot of data structures and classes
Like if ik python do ik open cv?
But you guys are here to help right :)
yeah haha
Yeah ty
we wont do your work for you though
^^
you need to learn it
Corey Schafer on youtube for django
^
it should be pinned tbh
Corey Schafer is amazing
Ty
Oh, and vote for him, he is up for an award for teaching
@acoustic oyster with regards to your use of json for database info, how do you pull it in and execute it properly?
100% voting for him
oooh
anyone here good with Selenium?
Pretty Printed is also quite good
How is programming with mosh?
Pretty Printed is the bomb
Btw, does web development count as software engineering?
@acoustic oyster btw do I start one at a time or all together
I find it as such a broad term, I don't really know what the main part of it is.
you're essentially building a software
then go for python
@fair agate i have a file called "<website_name>.JSON" in a directory on my linux server.
Then I load in these settings into django as such:
with open(my_file_path, "r") as f:
config = json.load(f)
DATABASES = {
'default': {
"ENGINE": "django.db.backends.mysql",
"NAME": config["db_name"],
# etc etc etc
}
}
kk ty
lol
This is from the corey schafer vid, I know now xD
I use docker nowadays
lol never got to that part
but yeah, I agree env variables are better
yeah
this is just simpler to me (when learning) because I already used json and was familiar
how do you use env variables in this case?
that depends on your OS
ur new to django?
not new, have some experience now but newer
os.environ.get(my_env_variable_name)
instead of the json stuff I did, just replace with an os.environ.get
and the json stuff should use .get as well anyway LOL
ah yes lol
I sent you my noobie code from corey schafer
for dev you can use the local, default db if you would like.
I did not create the db info until I deployed the site.
However I know many, maybe most, prefer to have a real db for testing
sqlite is real db ๐
I will probably be following the trend and moving to postgres in the future, in some juicy docker containers
ye PostgreSQL is what I use in production
but for now my db is MySQL and I am NOT messing that up ๐
I accidentally deleted my entire db once, never again
lol how
Are you guys fullstack engineers?
Hobbyist
How do I properly add new attributes to a model without causing db errors?
what if you need to add fields to an existing model in an existing production DB?
say in the future we need a new stat to track
in django?
You should be able to add a new field, run python manage.py makemigrations
Then python manage.py migrate
if it fails to migrate, then you may have done something wrong previously.
The solution may be to migrate back to zero, then delete migrations.
I have previously deleted the db file and deleted migrations because I did not feel like fixing everything
you should be able to add fields no problem, just make sure to give them a default or one-off default when prompted
I wasn't prompted, it just threw a db error
I am just thinking in the future if we need to add fields which no doubt we will
it'd be catastrophic to lose the db over that, so I'd like to learn means of adding fields while the stakes are comparatively nonexistent
ohh, are you adding fields to the production db?
yeah I'd like to figure out how to do that without breaking things
for context I am using mongodb via Djongo
you should only every makemigrations in the dev environment, if all your migrations work, in theory they should be able to migrate to the production db
So what, when it is in dev environment I just use a local sqlite3 db as an example and when it is ready for production I connect to the mongodb?
I deleted the old migrations and it looks like it worked actually
oh wow we're discussing django? great i had a question.
i'm making an open source reddit api for fun to learn more about django
You've got a Post model that's abstract. It has two child models: Submission and Comment
One Post can have Many Comments
class Post(models.Model):
created_gmt = models.DateTimeField(default=timezone.now)
class Meta:
abstract = True
class Submission(Post):
textpost = models.TextField(blank=True, max_length=2000)
linkpost = models.URLField(blank=True, max_length=1000)
title = models.CharField(max_length=120)
def __str__(self):
return self.title
def is_text(self):
return len(str(self.textpost)) > 0
def is_link(self):
return len(str(self.linkpost)) > 0
class Comment(Post):
parent_submission = models.ForeignKey(
'Submission', on_delete=models.CASCADE)
parent_comment = models.ForeignKey(
'Comment', on_delete=models.CASCADE)
def __str__(self):
return "Comment"
Question: instead of having parent_submission and parent_comment in Comment, is there any way to directly store that in Post as a list of foreign keys of Comment?
well there's trees
watch this video, it discusses various packages for implementing trees
unless you're good at that too lol
this guy's channel is solid for it https://www.youtube.com/channel/UCW5YeuERMmlnqo4oq8vwUpg
it's actually how i learnt nodejs two years back
is there a framework similar to Django in nodejs?
hmm afaik no. if there is, it's not famous
hapi?
strapi?
hmm
never used it
or even heard of it
afaik people usually install the exact feature they desire and run it with express
eg. graphql vs rest (kinda inbuilt), sessions, tokens, etc
yeah so express is the most popular thing
pretty much yeah
wait you have experience with both
so if given the choice would you go with Django or express?
i haven't used django much
yeah but ur aware of its power
this migrations stuff
just the backend
is it there in express?
ORM?
class Post(models.Model): created_gmt = models.DateTimeField(default=timezone.now) class Meta: abstract = True class Submission(Post): textpost = models.TextField(blank=True, max_length=2000) linkpost = models.URLField(blank=True, max_length=1000) title = models.CharField(max_length=120) def __str__(self): return self.title def is_text(self): return len(str(self.textpost)) > 0 def is_link(self): return len(str(self.linkpost)) > 0 class Comment(Post): parent_submission = models.ForeignKey( 'Submission', on_delete=models.CASCADE) parent_comment = models.ForeignKey( 'Comment', on_delete=models.CASCADE) def __str__(self): return "Comment"
@timber prawn Just add post as a ForeignKey to Comments.
@honest current didn't know that would've worked. tytytytytyty!!!!!
@marble carbon kinda? https://sequelize.org/master/manual/migrations.html
An easy-to-use multi SQL dialect ORM for Node.js
orm
sequelize comes with it's own migrations manager
ohh
sequelize is a nodejs package/library
afaik mongoose (ORM for mongodb) doesn't have an inbuilt one but u can install it from another package
I see
how do I best adjust a value of some field from a model? For example, I have ratings, how would I adjust those ratings? Where/how would I invoke that?
like, say one is a float field, say I want to add or subtract some number from/to the value
and adjust the individual entry in the db
how would I make that happen in Django?
I have a script to do the mathematical operation I want written in Python but I'm not sure how to get it to take the elements from each user and read it correctly if that makes sense
there's update method?
you wanna add an integer to all values?
let's say they're 1.2, 1.4, .1.5, 1.7 and you want to add 4 to all?
is that what u wanna do?
Entry.objects.all().update(number_of_pingbacks=F('number_of_pingbacks') + 1)
no a specific value
say take id 4 specifically, get their current rating, then pass that into my ELO equation and adjust the rating accordingly
say take id 4 specifically, get their current rating, then pass that into my ELO equation and adjust the rating accordingly
@fair agate
To get a particular id:
entry = Entry.objects.get(id=<id>)
#pick rating
rating = entry.rating
#add whatever
rating + random_value #eg. 1.5, 50000 etc
#save updated entry
entry.save()
I will experiment with that, appreciate it ๐
ValueError: badly formed hexadecimal UUID string
keep this value error
i switched from slugs to uuid
and deleted the migrations folder
before migrating again
django
anyone have any solutions or explanations
@wild thunder this is a python server
so im using flask and trying to get my css to work and its not working
html
<link rel="stylesheet" href="{{url_for('static', filename='styles\main.css')}}" type="text/css">``` css
```css
body {
margin: 0;
padding: 0;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #54c026;
}```
@acoustic oyster gm
So about my website project is it ok if I use SQL database and not django?
But how do I put in the python stuff
eh
Or is django needed
u could say it is
easier
but only to get started
but integrating auth and database
is another thing
while Django comes with these two
have you never done web dev before?
Nope
hmm
Ty
also go with Django 2.2
@marble carbon Out of curiosity, why Django 2.2? The latest stable version is 3.1, after all..
Noob question, but what's wrong with ASGI?
As for the LTS versions, https://www.djangoproject.com/download/#supported-versions shows that 3.2 is the next LTS, and it'll be out before 3.1's extended support ends.. Do you think it'll be easier to switch from 3.1 to 3.2 rather than 2.2 to 3.2?
they would both do the job, I like django
asgi is great
I just used it in my most recent project
setting up asgi isn't the easiest
By the way, TIL that Django has LTS versions as well. Haha, thanks @marble carbon ๐
It does add extra steps, I found it fairly streamlined though
@stoic gulch django is a good backend as it provides ORM and all the web stuff that would allow you to use html for a front end.
It is very possible to write your own backend by making database queries and I encourage it for learning, it may actually be simpler than using django, but django is very feature rich and provides you a lot of what you need out-of-the box.
I mean most of it will remain backward compatible
If someone is comfortable with 2.2, then it makes sense to wait for 3.2 before jumping over.
For a new learner, perhaps it makes sense to start learning 3.1 and hop over to 3.2 when it's released.
There will be less backwards incompatible changes and code refactoring needed that way..
I mean most of it will remain backward compatible
@marble carbon Oh, haha that invalidates my point
@stoic gulch django is a good backend as it provides ORM and all the web stuff that would allow you to use html for a front end.
It is very possible to write your own backend by making database queries and I encourage it for learning, it may actually be simpler than using django, but django is very feature rich and provides you a lot of what you need out-of-the box.
@acoustic oyster this is only for a one time show
The website
The same thing for bots?
bot?
async
what about bots?
websockets use async, discord bots use websockets
async โ asyncio in Python, or is it?@acoustic oyster
@stoic gulch bruhh you're obviously going to be using an SQL database with django
for storing your data
Kk ty
And not django
@stoic gulch Django and SQL are different things. Django is where you write logic for handling HTTP requests. An SQL database is where you will store your data. Django integrates with SQL databases. You'll have to use both.
Things will become clearer as you go through the tutorial @marble carbon sent.
Ok so django is for connecting to database
And SQL is database
async creates a coroutine
Ok so django is for connecting to database
@stoic gulch Simply speaking, yes. But it can do a lot more than that.
Kk
idk much about async yet
not in Python yet
will learn more when I get into Django 3.2

Things will become clearer as you go through the tutorial @marble carbon sent.
@scenic apex what tutorial did he send?
Oh that
Django
if you want async practice in python I do recommend discord bots.
Django is nice too.
I used websockets in my last django project, was pretty fun
https://docs.djangoproject.com/en/stable/intro/tutorial01/
@marble carbon @stoic gulch This one
Ty
Hey guys, I am absolutely new to web development with Python and I want to know which web framework I should start learning, Flask or Django?
Some of those "expert" friends of mine have suggested learning django because it is more scalable? Is this true and if so, how is it better than flask?
yeah, that would help thanks ๐
@native tide here found one
I've used Flask and now I'm learning Django. I've also used Starlette (FastAPI is built on this) on a larger personal project. What I've noticed through using Flask and Starlette and now learning Django is that in some cases I've almost reinvented the wheel in implementing features that are provided out-of-the-box and battle-tested by Django. In short, Flask focusses on offering a selection of features which is sufficient for smaller applications. It can be extended with other packages. For larger production-ready apps Django can save you time and offer you reliability in providing features like database migration and in-built security (I'm still learning Django so I'm sure people can add to this list)
there's the admin feature as well, and good support for creating APIs with DRF as well
learn Flask first
yeah coz Django has a bit of a learning curve
then the why behind Django is much nicer
if you come from Flask it'll be easier to understand why Django has this file structure and project structure defined
Django has some assumptions baked in too
what do you mean you don't have a users table that's unthinkable
nice, thanks guys!
I have an app with SSO and permissions based on LDAP membership attributes from another source and Django doesn't like it
So Flask it is
yeah sometimes
Django's baked in assumptions
don't allow much customisation
if you're looking for customisation go with flask, don't bother hacking your way around Django
don't allow much customisation
@marble carbon So you're saying its not too flexible?
it'll be tedious
It depends on your use really
For an app that's mostly glue for other apis it's tedious
80% of web development use cases should be covered with Django
the rest is where u have just different sort of web app with weird dependencies and logic
80% of web development use cases should be covered with Django
@marble carbon now this sounds promising
Are you talking to a DB or LDAP and PeopleSoft
like they're adding async support in Django too

I think that another plus point of learning Django is that you will easily understand other technologies which use MVC architecture (I am currently learning Java EE)
I started with django and do not know flask.
I also have been programming for a few years though, so I understood the concepts relatively easily.
I find the forced file structure is a great learning tool as well
Any Django people know how to solve a
ValueError: badly formed hexadecimal UUID string
hello can someone help me with this flask query problem? I want the code below to collect data from a form and send a GET request to an external api. It's working fine, but the search query is being broken into two words instead of being treated as one search term. This is returning unreliable results. The code below sends search queries that look like this: search/bill?search-form-input=gun+reform, but what I need for my searches to work correctly is for the search query to be treated as one phrase. For this the api says to wrap your words in quotes to make it phrase search. Can someone please help me adjust my code to make sure my form data is being passed correctly?
@app.route('/search/bill')
def get_bill_info():
"""Retrieve all bill information"""
search_term = request.args['search-form-input']
res = requests.get(f"{BILL_API}?query={search_term}", headers={
'X-API-key': key})
data = res.json()
# return data
bill_data = data['results'][0]['bills']
return render_template('search/bill-voting.html', bill_data=bill_data)
Does storing data in the session pose any risk of the user being able to view the data? Should I tokenise the data?
Any data in the session is viewable for the user
I need to somehow update the content of a webpage
like the contents of a <p></p> element
but have it based on a word document or something
so basically... I'm building a webpage that will need to be updated daily with new content
and ideally this content would be user submitted in a word document
Can you use redis for messages and a regular sql database for other things?
I mean, Sure
@bleak bobcat So how could I protect the cookies? Encrypt the data stored in session?
You shouldn't send sensitive data to the user
Well, I'm saving the user's ID and their email in the session so that their data persists during account verification. But I wouldn't like that data compromised if they can see the data
Ooh, I can encrypt the session data or use flask-session. Cool
Or use redis
Has anyone used dhango-channels?
I don't think that's risky data @native tide the user should know his email anyway, and could probably find his id somewhere in a form anyway
^
The best practice to know if a user form is working, you should query the whole database with raw passwords and show it in the template, so you know it works.
BassSpleen, whole reason not to put that information in a cookie is if users cookie is stolen
Yeah, I'd rather not have the user's cookies stolen. They do that with stolen paypal accounts, they include the useragent
Hello Fellow Developers.
actually I am creating a e-commerce site for my city and using Django rest framework as backend and react as frontend and react-native as mobile application. Is it a good idea to use react native for mobile app for e-commerce app
hey there!
just dropped at an update on an application I've been working on.
DomeCode is a platform that simplifies your process to learn code and provides you with other tools as well to help you learn to code. Get more, with less hassle.
The feature called Fusion is a real-time disposable editor using which you can start learning front-end technology including HTML, CSS, JS with any YouTube tutorial of your choice in a single tab instead of a code editor and two browser windows like a memory hog.
Loading failed for the <script> with source Why do i get this i use firefox?
lol i have no idea, I've tested this on safari and chrome and didn't face any issues.
just tried it on firefox as well, idk it's an individual issue i suppose.
@native tide is the link above still accurate? if so, the obvious issue I see is the little , (comma) right before the "action" where there should be a space instead
Thanks.
@willow iron Bruh ! I think you are processing the code after each keystroke, don't do that.
That leads to problem with JS code, I just did alert('Hi') and it was alerting me everytime I press a key
what am I doing wrong at the moment to pass the new_password2 ? this gives me None in django , but I can catch the value in console.log ? why? https://dpaste.org/ZekF
Howdy, friends. Using JWT and django, I found a nifty module that handles most the JWT stuff for me.
With that said, it makes it so that I can make a post request with a username and password, then I am returned a JWT. I believe it returns a new JWT with every request from the same user. Once the user has a token, every request header needs to provide the token.
And the token itself does not appear to be actually tied to a user. Is this how it is supposed to work? Due to our stack, I am unable to find a tried-and-true module for JWT auth.
@willow iron Bruh ! I think you are processing the code after each keystroke, don't do that.
That leads to problem with JS code, I just did
alert('Hi')and it was alerting me everytime I press a key
@upper swift ah okay got it!
guys i need help with the redirect. i keep getting this message ValueError at /register/ The view account.views.registration_view didn't return an HttpResponse object. It returned None instead.
but my views and my redirect url looks perfectly fine ive tried debugging it alot
def registration_view(request):
form = RegistrationForm(request.POST)
context = {}
if request.method == 'POST':
if form.is_valid():
form = RegistrationForm(request.POST)
form.save()
Torn_ID = form.cleaned_data.get('Torn_ID')
raw_password = form.cleaned_data.get('password1')
account = authenticate(Torn_ID=Torn_ID, password=raw_password)
login(request, account)
return redirect('rgs')
else:
context['form'] = form
else:
form = RegistrationForm()
context['form'] = form
return render(request, 'register.html', context)``` this is my views for reguistration but it wont budge
If your form isn't valid it won't return anything
@tepid lark i made the form not valid on purpose to display error message
but isnt working
Hi everyone,
I have the classic Django vs Flask question..
I've used both the frameworks a little and know the basic difference between them.
My question is specific to creating JSON APIs (not web apps) which can be used commonly by different client front ends (Android, iOS, Web).
Which framework will be better for this case?
I'm inclined towards Flask since it has good extensions to work with SQL and NoSQL databases, whereas the Django ORM works only with SQL databases.
But my questions are about the design patterns.
Django is designed to build apps which follow the MVT (Model-View-Template) design pattern.
What I want to create is more of an MVC with a clear separation between the "data" (the database and the API) and the "UI" (which will be different for different clients). My API shouldn't know anything about the front ends (hence no HTML templates).
Does Django enforce MVT at any point?
If I use Django to implement my design, will I get any friction?
Will Django's out of the box features create problems?
Thanks!
(I know even Flask supports MVT. But it's less opinionated and seems to give me more flexibility)
How would I upload a .json file to a flask webserver?
I want to make a web app with a Flask back-end with a React front-end. Is there any way to do this without a Flask REST API?
@scenic apex
I use django rest framework for some apps where front end is entirely in react.js
So I use djsngo models and mysql to serve the rest api without use of templates. I have also recently (today) been using graphql with djsngo and it works great.
I've never used flask though tbh
Oh
@full pagoda you could always use graphql if you are opposed to REST itself.
How do you install it?
The normal way to pass data would be with some sort of api though.
So is it like a query language?
I use django, the module we use is ariadne for djsngo. Im sure there are similar modules for flask.
Yeas, graphql is a query language.
@acoustic oyster Thanks! I'll try it out!
Np, I highly recommend if you do not like rest itself
The row in table 'main_post' with primary key '3' has an invalid foreign key: main_post.username_id contains a value 'Luke' that does not have a corresponding value in auth_user.id.
Whats Wrong with my Django Error?
from django.contrib.auth.models import User
# Create your models here.
class post(models.Model):
"""
Non-Admin's Posts here
"""
username = models.ForeignKey(User, default=1, on_delete=models.SET_DEFAULT)
title = models.CharField(max_length=50)
description = models.CharField(max_length=200)
def __str__(self):
return self.title
main_post.username_id must be integer
or main_post.username = <user object>
You can add to_field parameter to ForeigKey, but I'm not recomment to do it.
Just use main_post.username.username when you need to retrieve "Username" and main_post.username = User.objects.get(id=<id>) if you need to set user
Thanks Man!
I removed the foreign key and this happened
django.db.utils.IntegrityError: The row in table 'main_post' with primary key '3' has an invalid foreign key: main_post.username_id contains a value 'Luke' that does not have a corresponding value in auth_user.id.
i really dont understand this
If you're in development and your database is quite small, you can try deleting the database and migrations, and migrate once again. Again I don't recommend doing this, this is like the last resort.
Also I would suggest you to check the field values of this particular user in the Django shell.
Did you change the primary key field in your User model?
hey, newbie here, does anyone know what basically is an api?
Yes
It means Application Interface.
So like
You can have a Google Sign in API in your Website
you didn't build it
but you called api request to add it into your web
its hard to explain
@somber aurora I see. I guess you have set your own field to primary key, instead of the default Auto Field in the User. And that's causing an error.
oh hmm...I think i'm getting it

