#web-development

2 messages ยท Page 80 of 1

native tide
#

im sorryyyyyy

#

try

#

python

#

from app import db

#

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)

#
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
#

Like this

#

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

manic berry
#

Is it secure and safe to use?

native tide
#

@manic berry flask-secuirty is secure to use and it will secure ur website

thorny scaffold
#

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.

manic berry
#

@native tide Yes but I'm talking about the new maintained version

#

Not the original flask-security

native tide
#

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

dapper tusk
#

Cloudflare offers something to make home hosting viable iirc

native tide
#

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

mellow tide
#

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

native tide
#

alright, thank you

native tide
#

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?

polar lantern
#

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.

untold flare
#

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

native tide
#

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.

woven spindle
#

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

native tide
#

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)

woven spindle
#

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

native tide
#

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

woven spindle
#

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

drifting elm
#

Is this channel alwayso pen for questions?

raw jolt
#

I think so but Im not sure

#

If you need help with code, you should go to help channels I assume

drifting elm
#

this is my question ^^ typical web, I guess ๐Ÿ˜„

#

I assume it's notpossible but want to double check

native tide
#

what did i do wrong

raw jolt
#

@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

drifting elm
#

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

raw jolt
#

Yeah that seems like a lazy workaround

drifting elm
#

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

raw jolt
#

Yeah doesnt happen with OAuth

#

Well idk maybe someone with more experiance will show up and suggest a proper fix, I just gonna flee

#

๐Ÿ˜‚

ornate solar
#

Can someone recommend a good tutorial on creating a scalable web structure using microservice tech (ex: docker, kubernetes, etc)?

drifting elm
#

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

ornate solar
#

i prob should not have used that wording

#

but id just use react for the front end

#

and serve it staticly

drifting elm
#

but still both scalable and using microservice tech are two diff tthings ^^

ornate solar
#

well using mircoservices makes it scalable right?

#

or do you mean creating new instances of a service to handle more traffic

distant trout
#

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

ornate solar
#

just add a <style> tags with the css

distant trout
#

oh you are right, i havent tried doing that in the html file itself

drifting elm
#

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

ornate solar
#

@drifting elm I like the idea of running express for an api gateway and then creating services with other langs like python and php

young crane
#

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)
ornate solar
#

@young crane is the users folder treated as a static folder

young crane
#

wdym static?

#

files wont be in the user folder ever, only other folder will get added

ornate solar
#

so a route is like this /users/koon/345345.png

young crane
#

yeah

ornate solar
#

is it trying to find that route or is it static like your "static" folder for getting js and css

young crane
#

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

ornate solar
#

yes but it is linking to that file

#

so when you click it it takes you to that url

young crane
#

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

ornate solar
#

no need

young crane
#

okay

ornate solar
#

remove the download tag in the anchor tag

#

and click the link and tell me what you see

young crane
#
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

ornate solar
#

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

young crane
#

like return the file object?

ornate solar
#

ive done this before in one of my projects ill try to get the code....

young crane
#

Okay, thank you very much

ornate solar
#

you're going to want to import send_from_directory from flask

young crane
#

k

ornate solar
#
@app.route('/users/<string:uid>/<string:file_name>', methods=['GET'])
def media(uid, file_name):
  return send_from_directory(f'./users/{uid}/', file_name)
quiet comet
#

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?

ornate solar
#

that might work

#

@young crane

young crane
#

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...

ornate solar
#

then include download in the achor tag

young crane
#

Thank you VERY much koon!

ornate solar
#

that will be $20

#

๐Ÿ™‚

young crane
#

๐Ÿ™‚

jaunty plover
#

Hey

#

I don't really get how oauth2 works globally

#

And how to implement it to Django

#

Could you help me please ?

modest scaffold
#
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

vestal hound
#
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?

native tide
#

How long does django take to learn? Id like to get a blogging site up

woven spindle
#

@native tide @native tide @native tide @native tide

#

hehe

#

hi FaTe

native tide
#

Hm

#

Go away

woven spindle
#

Y

#

I found you

native tide
#

No

#

I found you๐Ÿคก

vestal hound
#

How long does django take to learn? Id like to get a blogging site up
@native tide depends, how much experience do you have

native tide
#

Basic

#

Classes, subclasses

vestal hound
#

have you ever worked with Flask/Pyramid/Sanic etc.?

native tide
#

Nope

vestal hound
#

hm

#

probably a while.

native tide
#

10 hours?

vestal hound
#

if you're fairly talented, possibly

native tide
#

Hmm okay

#

Alright thanks

merry rampart
#
"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)
vestal hound
#

@merry rampart that...does not look right?

#

post the whole error

merry rampart
#

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

vestal hound
#

well

#

let me suggest this

#
  1. put your JSON in a separate dict
#

then you can just call requests.post(url2, json=json)

#
  1. when you get an error, post the whole error. (very important)
#
  1. requests.post (and indeed, all the HTTP verbs) return a Response object
#

that you cannot pass to json.loads directly, because it expects a string.

#

so, normally, you would do json.loads(response.text)...

#

...BUT

#
  1. requests has a helper for that, so response.json() will work just fine.
#

unless, of course, the request cannot be parsed as JSON, in which case it'll fail

merry rampart
#

ah okay

#

thanks for the tips lmao

vestal hound
#

np

true harness
#

whats the best way to start doing web development with pyhton?

vestal hound
#

also this is like a super small thing but in general Python variables are in snake case

#

so perhaps response_json?

merry rampart
#

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)

vestal hound
#

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

merry rampart
#

hm

#

okay

#

i'll see if I'm doing something wrong somewhere else, cus I just keep on getting more errors lol

vestal hound
#

try print(response.text)

#

to see what it looks like

#

are you sure that post returns a JSON?

merry rampart
#

no im not

#

i realized what the problem was lmao

#

sorry for wasting ur time

#

the api isnt working right or sum like that

vestal hound
#

no worries

#

hope you find something that works!

native tide
#

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")
balmy shard
#

Well

#

uhh

#

Definitely dont put it in a dictionary

native tide
#

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?

balmy shard
#

Coma something values I think

#

Kinda like an excell file

#

@native tide

#

I have no idea abt the notepad

native tide
#

ok ok

#

how do i put it in coma?

half lagoon
left jungle
#

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.

umbral blade
#

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?

flint breach
#

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

serene ice
#

anyone have knowledge about hashing for online POS systems?

magic valve
#

Mp me cause I not at my office and we talk buisness.

native tide
#

man cant even spell business

#

god muthafuckin damn

modest scaffold
#

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

vestal hound
modest scaffold
#

thx @vestal hound i appreciate it

honest sorrel
#

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.

marble carbon
#

@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

native tide
#

@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๐Ÿ˜

iron cliff
#

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')
inland moon
#

@native tide here

native tide
#

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

bleak bobcat
#

I don't wanna be mean but if CSS was too difficult you shouldn't expect to understand react at all

native tide
#

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

native tide
#

cya
@native tide
You too

native tide
#

You still need CSS with react

native tide
#

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.

native tide
#

You'll have to search jinja2 templates

#

Also if you want structured learning I'd recommend codecademy

hidden gulch
#

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?

twilit dagger
#

OK I fixed it

#

I figured it out while I was typing it out

acoustic oyster
#

cool, happy I could help xD

native tide
#

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.

left jungle
#

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

acoustic oyster
#

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

left jungle
#

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?

acoustic oyster
#

Django for backend, React front end (or just vanilla html, css, js if I am feeling lazy)

left jungle
#

Thx

acoustic oyster
#

np

#

oh and Pycharm intelligence is great, but far from a necessity.

twilit dagger
#

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

fair agate
#

Hey, what do you guys use to hide away your db config info in settings for git commit?

acoustic oyster
#

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

stoic gulch
#

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

native tide
#

How do you guys go about learning docker, etc? The documentation?

stoic gulch
#

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.

acoustic oyster
#

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

native tide
#

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

acoustic oyster
#

@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.

stoic gulch
#

It's for matching students pictures

#

Many students

#

Of the entire college

#

Students I'd cards and faces really

native tide
#

@stoic gulch Is it your first time with python?

stoic gulch
#

Yes

#

Don't even have the software

#

I installed 32 bit one

#

Idk where's the 64bit one

native tide
#

I'd probably go about learning python first before attempting a big project, to make sure I understand exactly what I'm doing

acoustic oyster
#

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

stoic gulch
#

Alright I made a channel in #help-bagel and I'll try it out tomorrow

native tide
#

Do you guys do unit tests in your django / flask projects?

stoic gulch
#

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

acoustic oyster
#

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

stoic gulch
#

Do u think this is too much tho?

native tide
#

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

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

native tide
#

Because matching faces, in my opinion, I think it'll involve machine learning, which is an extra hurdle

stoic gulch
#

Actually ours was a website

acoustic oyster
#

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.

stoic gulch
#

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

native tide
#

How long do you have to do it?

stoic gulch
#

3-6 months

#

By December or something

native tide
#

In my opinion that's way too challenging, especially for a beginner

acoustic oyster
#

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)

stoic gulch
#
  • were still using C,C++ and java in college
quick cargo
#

thats a very mean challenge lol

stoic gulch
#

Damn I don't know anything about python

quick cargo
#

unless you mean just copying the image and saving it

stoic gulch
#

Any better ideas?

quick cargo
#

if you mean Using ML to match them

native tide
#

If it's ML, then its game over lol. That stuffs crazy

quick cargo
#

then thats going to be pretty much impossible unless they've given you alot of training data

acoustic oyster
#

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

stoic gulch
#

O man

native tide
#

@stoic gulch Do you have to match a user's ID to their image?

#

That will be doable

stoic gulch
#

I mean

native tide
#

Without any comparing images / machine learning

stoic gulch
#

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

acoustic oyster
#

ohhhh, you just need to match the qr code to the same qr code?

stoic gulch
#

Which I find stupid tbh

#

No

#
  1. Qr code to web database
#

If it succeeds

native tide
#

Dude reading the QR code is also gonna be cv2... and web framework... and database... and machine learning...

acoustic oyster
#

oh dang it

stoic gulch
#

Match face with database

acoustic oyster
#

this was almost easy

quick cargo
#

๐Ÿค” But surely for that face recognition it needs to have ML to make it decent

#

other wise those two images need to be IDENTICAL

stoic gulch
#

And then u get access

marble carbon
#

here

stoic gulch
#

other wise those two images need to be IDENTICAL
@quick cargo aww man

acoustic oyster
#

yeah, there are frameworks for facial recognition though haha

stoic gulch
#

Sheesh

marble carbon
#

also for face Recognition

acoustic oyster
#

this will be very difficult lol

quick cargo
#

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

marble carbon
#

nah

#

use this

#

only one image

acoustic oyster
#

it is doable though.

I believe you can use image segmentation to bypass the need for many pictures

marble carbon
#

ez

stoic gulch
#

For qr code with website is it possible

#

Scan using laptop or mobile camera

#

From Website

native tide
#

That's an awesome library @marble carbon Thanks!

marble carbon
#

ye np

acoustic oyster
#

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

marble carbon
#

ye

#

the one i posted

quick cargo
#

Keras has a pre made system for it

marble carbon
#

literally 10 lines

stoic gulch
#

So it's possible?

quick cargo
#

you just need alot of training data

acoustic oyster
quick cargo
#

pre trained models like the above can work tho

marble carbon
#

dlib

#

does the job

stoic gulch
#

So in the end can I do it or not?

#

Or its very tough

acoustic oyster
#

@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

quick cargo
#

Its gonna be Hard but its do able

marble carbon
#

smh just look at the library i posted

acoustic oyster
#

^

stoic gulch
#

Damn

marble carbon
#

lol

quick cargo
#

It is very much not gonna be simple

stoic gulch
#

Alright ima try

quick cargo
#

Its going to be even harder to make it efficient and quick

stoic gulch
#

But if u have any better ideas feel free to dm me

#

Better ideas for mini projects

marble carbon
#

๐Ÿคทโ€โ™‚๏ธ

stoic gulch
#

For a comp sci student

acoustic oyster
#

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

stoic gulch
#

And something that sounds awesome cuz our teachers are stupid

quick cargo
#

ive done some Facial rec stuff but they're a pain to train

acoustic oyster
#

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

stoic gulch
#

Yikes

#

Any better ideas/suggestions for a project

acoustic oyster
#

I mean, I think this is a great idea

quick cargo
#

i'd probably abstract the issues out first

native tide
#

Some image recognition project would be cool

quick cargo
#

you're trying todo essentially 3 Fairl BIG projects in one

acoustic oyster
#

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

native tide
#

And all you'd really need to know is cv2

acoustic oyster
#

you're trying todo essentially 3 Fairl BIG projects in one
yeah, that is the main problem

stoic gulch
#

oof

#

also another question

#

The website will be made in django?

#

Or HTML CSS etc will do

#

Since django is python framework do django

quick cargo
#

Django is backenfd

stoic gulch
#

O

quick cargo
#

Html css and Js are gonna be needed for front

stoic gulch
#

I've never used it in my life

acoustic oyster
#

@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.

stoic gulch
#

We're 4 of us

#

But 2 are useless

acoustic oyster
#

that is how it goes

stoic gulch
#

And I am lazy kinda

acoustic oyster
#

LOL

#

my god

stoic gulch
#

But yeah I can try

acoustic oyster
#

maybe the image analysis idea is a bit much then xD

marble carbon
#

Just make a basic crud app

acoustic oyster
#

^^^

stoic gulch
#

So what all do I need then?

marble carbon
#

you're biting more than you can chew

stoic gulch
#

Html css js django opencv python

fair agate
#

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

stoic gulch
#
  • the problem is we have classes etc
#

How many hours dedication is required for this?

acoustic oyster
#

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

marble carbon
#

try to build an MVP first

stoic gulch
#

MVP?

marble carbon
#

minimum viable product

stoic gulch
#

Wait wait this website is a simple one

acoustic oyster
#

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

stoic gulch
#

For me website is no problem

acoustic oyster
#

minimum viable product
yeah, exactly this

stoic gulch
#

Just the python part

marble carbon
#

coz u don't know Django yet

stoic gulch
#

Yes

acoustic oyster
#

yeah, django will take some time to learn

#

on top of learning python

marble carbon
#

yea

stoic gulch
#

Damn

#

And is open cv of python?

acoustic oyster
#

and django is not necessarily super beginner friendly, it uses a lot of data structures and classes

stoic gulch
#

Like if ik python do ik open cv?

marble carbon
#

open cv is like another step ahead of django

#

so more steep learning curve

stoic gulch
#

But you guys are here to help right :)

acoustic oyster
#

yeah haha

stoic gulch
#

Yeah ty

acoustic oyster
#

we wont do your work for you though

marble carbon
#

^^

acoustic oyster
#

you need to learn it

stoic gulch
#

Alright ima start it with full speed tomorrow

#

Yeah

#

I'll try

#

Cya and gn

acoustic oyster
#

Corey Schafer on youtube for django

marble carbon
#

^

acoustic oyster
#

it should be pinned tbh

fair agate
#

Corey Schafer is amazing

stoic gulch
#

Ty

acoustic oyster
#

Oh, and vote for him, he is up for an award for teaching

fair agate
#

@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

marble carbon
#

oooh

sturdy patrol
#

anyone here good with Selenium?

fair agate
#

Pretty Printed is also quite good

stoic gulch
#

How is programming with mosh?

native tide
#

Pretty Printed is the bomb

marble carbon
#

nice list

#

I know most of them x)

#

would be hard to choose one lol

native tide
#

Btw, does web development count as software engineering?

marble carbon
#

yea

#

imo

stoic gulch
#

@acoustic oyster btw do I start one at a time or all together

native tide
#

I find it as such a broad term, I don't really know what the main part of it is.

marble carbon
#

you're essentially building a software

stoic gulch
#

Yes

#

Oh another question

#

Would an app or website be easier

#

To do my project

marble carbon
#

yk java?

#

or kotlin?

stoic gulch
#

Well learning it

#

Learning java

#

But it's hard

marble carbon
#

then go for python

acoustic oyster
#

@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
}
}
stoic gulch
#

kk ty

marble carbon
#

wait

#

@acoustic oyster WHAT

#

๐Ÿ˜

acoustic oyster
#

lol

marble carbon
#

heard of environment variables??

#

they're a thing

acoustic oyster
#

This is from the corey schafer vid, I know now xD
I use docker nowadays

marble carbon
#

lol never got to that part

acoustic oyster
#

but yeah, I agree env variables are better

marble carbon
#

yeah

acoustic oyster
#

this is just simpler to me (when learning) because I already used json and was familiar

fair agate
#

how do you use env variables in this case?

acoustic oyster
#

that depends on your OS

marble carbon
#

ur new to django?

fair agate
#

not new, have some experience now but newer

acoustic oyster
#

os.environ.get(my_env_variable_name)

marble carbon
#

ye but

#

how u set them depends on OS

acoustic oyster
#

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

marble carbon
#

ah yes lol

acoustic oyster
#

I sent you my noobie code from corey schafer

marble carbon
#

pls don't judge

#

๐Ÿ˜

acoustic oyster
#

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

marble carbon
#

sqlite is real db ๐Ÿ˜ 

acoustic oyster
#

lolol

#

I use MySQL so I cant judge

marble carbon
#

sqlite is not bad

#

it is quite good

acoustic oyster
#

I will probably be following the trend and moving to postgres in the future, in some juicy docker containers

marble carbon
#

ye PostgreSQL is what I use in production

acoustic oyster
#

but for now my db is MySQL and I am NOT messing that up ๐Ÿ™ƒ

#

I accidentally deleted my entire db once, never again

marble carbon
#

lol how

native tide
#

Are you guys fullstack engineers?

acoustic oyster
#

Hobbyist

fair agate
#

How do I properly add new attributes to a model without causing db errors?

native tide
#

have a development dB and a production

#

if no errors add to the production

fair agate
#

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

acoustic oyster
#

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

fair agate
#

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

acoustic oyster
#

ohh, are you adding fields to the production db?

fair agate
#

yeah I'd like to figure out how to do that without breaking things

#

for context I am using mongodb via Djongo

acoustic oyster
#

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

fair agate
#

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

timber prawn
#

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?

marble carbon
#

well there's trees

#

watch this video, it discusses various packages for implementing trees

timber prawn
#

i understand. thank you @marble carbon

#

if you need help with nodejs, lemme know

marble carbon
#

ah

#

nice

timber prawn
#

unless you're good at that too lol

marble carbon
#

is there a

#

beginner tutorial for it

#

that you'd recommend

timber prawn
marble carbon
#

yea that's what I thought

#

lol alright ty

timber prawn
#

it's actually how i learnt nodejs two years back

marble carbon
#

is there a framework similar to Django in nodejs?

timber prawn
#

hmm afaik no. if there is, it's not famous

marble carbon
#

hapi?

timber prawn
#

strapi?

marble carbon
#

strapi is different

timber prawn
#

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

marble carbon
#

yeah so express is the most popular thing

timber prawn
#

pretty much yeah

marble carbon
#

wait you have experience with both

#

so if given the choice would you go with Django or express?

timber prawn
#

i haven't used django much

marble carbon
#

yeah but ur aware of its power

timber prawn
#

ayy i've heard stuff bout it

#

that's why im making an open source reddit api

marble carbon
#

this migrations stuff

timber prawn
#

just the backend

marble carbon
#

is it there in express?

timber prawn
#

ORM?

marble carbon
#

nah the migrations

#

migration files

#

and its management

honest current
#
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.

timber prawn
#

@honest current didn't know that would've worked. tytytytytyty!!!!!

marble carbon
#

orm

timber prawn
#

sequelize comes with it's own migrations manager

marble carbon
#

ohh

timber prawn
#

sequelize is a nodejs package/library

fair agate
#

@acoustic oyster appreciate your help before btw ๐Ÿ™‚

#

thank you for that

timber prawn
#

afaik mongoose (ORM for mongodb) doesn't have an inbuilt one but u can install it from another package

marble carbon
#

I see

fair agate
#

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?

marble carbon
#

adjust?? elaborate

#

wdym by adjust

fair agate
#

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

marble carbon
#

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)
fair agate
#

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

marble carbon
#

I haven't tried it but

#

nah

#

you gotta loop through em

#

no other option

honest current
#

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()

fair agate
#

I will experiment with that, appreciate it ๐Ÿ™‚

keen lily
#

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

mellow tide
#

@wild thunder this is a python server

wild thunder
#

yeah i know

#

started php 2 days ago

#

but alright, sorry

timber token
#

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;
}```
stoic gulch
#

@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

marble carbon
#

wdym

#

django is not database

#

database is obv SQL database mostly

stoic gulch
#

So what to make backend with? @marble carbon

#

For face scanning and qr code scanning

marble carbon
#

a web framework??

#

like Django or Flask

stoic gulch
#

O

#

So flask is easier?

marble carbon
#

eh

stoic gulch
#

Or is django needed

marble carbon
#

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?

stoic gulch
#

Nope

marble carbon
#

hmm

stoic gulch
#

Everything is new

#

Nothing was even taught

stoic gulch
#

Ty

scenic apex
#

also go with Django 2.2
@marble carbon Out of curiosity, why Django 2.2? The latest stable version is 3.1, after all..

marble carbon
#

well that's the LTS version

#

and there's asgi in 3

scenic apex
#

Noob question, but what's wrong with ASGI?

acoustic oyster
#

they would both do the job, I like django

#

asgi is great

#

I just used it in my most recent project

marble carbon
#

setting up asgi isn't the easiest

scenic apex
#

By the way, TIL that Django has LTS versions as well. Haha, thanks @marble carbon ๐Ÿ˜„

acoustic oyster
#

It does add extra steps, I found it fairly streamlined though

marble carbon
#

lol, you didn't onoe

#

know*

#

I'm waiting for 3.2 before making the jump tho

acoustic oyster
#

@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.

marble carbon
#

I mean most of it will remain backward compatible

scenic apex
#

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
#

@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

marble carbon
#

There's mainly this async stuff in 3.2

#

@stoic gulch then go with django

stoic gulch
#

The same thing for bots?

marble carbon
#

bot?

stoic gulch
#

async

marble carbon
#

what about bots?

stoic gulch
#

Discord bots u use the async thingy

#

In python

acoustic oyster
#

websockets use async, discord bots use websockets

marble carbon
#

oh

#

maybe idk

#

wait

stoic gulch
#

And what is the problem if I use SQL database?

#

And not django

marble carbon
#

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

stoic gulch
#

Kk ty

scenic apex
#

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.

stoic gulch
#

Ok so django is for connecting to database

acoustic oyster
#

they are not the same

#

asyncio is a context manager

stoic gulch
#

And SQL is database

acoustic oyster
#

async creates a coroutine

scenic apex
#

Ok so django is for connecting to database
@stoic gulch Simply speaking, yes. But it can do a lot more than that.

stoic gulch
#

Kk

marble carbon
#

idk much about async yet

#

not in Python yet

#

will learn more when I get into Django 3.2

stoic gulch
#

Things will become clearer as you go through the tutorial @marble carbon sent.
@scenic apex what tutorial did he send?

#

Oh that

#

Django

marble carbon
#

๐Ÿ™‚

#

yea scroll up

acoustic oyster
#

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

marble carbon
#

ahhh

#

remove the tag from quote

#

pls

#

don't ping if not meant for me

stoic gulch
#

Ty

native tide
#

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?

marble carbon
#

lol

#

this question again ๐Ÿ˜†

#

someone pin an answer to this

native tide
#

yeah, that would help thanks ๐Ÿ™‚

marble carbon
#

@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

tepid lark
#

learn Flask first

marble carbon
#

yeah coz Django has a bit of a learning curve

tepid lark
#

then the why behind Django is much nicer

marble carbon
#

if you come from Flask it'll be easier to understand why Django has this file structure and project structure defined

tepid lark
#

Django has some assumptions baked in too

#

what do you mean you don't have a users table that's unthinkable

native tide
#

nice, thanks guys!

tepid lark
#

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

marble carbon
#

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

native tide
#

don't allow much customisation
@marble carbon So you're saying its not too flexible?

marble carbon
#

it'll be tedious

tepid lark
#

It depends on your use really

marble carbon
#

I mean it depends

#

yea

tepid lark
#

For an app that's mostly glue for other apis it's tedious

marble carbon
#

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

native tide
#

80% of web development use cases should be covered with Django
@marble carbon now this sounds promising

tepid lark
#

Are you talking to a DB or LDAP and PeopleSoft

marble carbon
#

like they're adding async support in Django too

tepid lark
marble carbon
#

eel?

#

:pogfish:

#

heh

thorny scaffold
#

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)

acoustic oyster
#

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

keen lily
#

Any Django people know how to solve a

#

ValueError: badly formed hexadecimal UUID string

zealous cloud
#

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)
native tide
#

Does storing data in the session pose any risk of the user being able to view the data? Should I tokenise the data?

bleak bobcat
#

Any data in the session is viewable for the user

swift sky
#

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

limber laurel
#

Can you use redis for messages and a regular sql database for other things?

zealous siren
#

I mean, Sure

native tide
#

@bleak bobcat So how could I protect the cookies? Encrypt the data stored in session?

bleak bobcat
#

You shouldn't send sensitive data to the user

native tide
#

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

limber laurel
#

Has anyone used dhango-channels?

bleak bobcat
#

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

marble carbon
#

yeah lol

#

saving their password in cookie on other hand...

bleak bobcat
#

^

limber laurel
#

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.

zealous siren
#

BassSpleen, whole reason not to put that information in a cookie is if users cookie is stolen

native tide
#

How can i add to this to show the post on the same page?

native tide
#

Yeah, I'd rather not have the user's cookies stolen. They do that with stolen paypal accounts, they include the useragent

broken basin
#

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

willow iron
#

hey there!

#

just dropped at an update on an application I've been working on.

#

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.

native tide
#

Loading failed for the <script> with source Why do i get this i use firefox?

willow iron
#

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.

versed lotus
#

@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

native tide
#

Thanks.

upper swift
#

@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

dawn heath
#

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

acoustic oyster
#

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
#

@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!

native tide
#

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
tepid lark
#

If your form isn't valid it won't return anything

native tide
#

@tepid lark i made the form not valid on purpose to display error message

#

but isnt working

scenic apex
#

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)

versed tangle
#

How would I upload a .json file to a flask webserver?

full pagoda
#

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?

acoustic oyster
#

@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

full pagoda
#

Oh

acoustic oyster
#

@full pagoda you could always use graphql if you are opposed to REST itself.

full pagoda
#

How do you install it?

acoustic oyster
#

The normal way to pass data would be with some sort of api though.

full pagoda
#

So is it like a query language?

acoustic oyster
#

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.

full pagoda
#

@acoustic oyster Thanks! I'll try it out!

acoustic oyster
#

Np, I highly recommend if you do not like rest itself

somber aurora
#

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
warm bobcat
#

main_post.username_id must be integer
or main_post.username = <user object>

somber aurora
#

Oh ok thanks!

#

@warm bobcat How to make it a string

warm bobcat
#

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

somber aurora
#

Thanks Man!

somber aurora
#

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

tame onyx
#

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?

somber aurora
#

Yeah

#

I set the Primary Key to true

#

I passed it into the Foreign Key

solar pecan
#

hey, newbie here, does anyone know what basically is an api?

somber aurora
#

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

tame onyx
#

@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.

solar pecan
#

oh hmm...I think i'm getting it