#web-development

2 messages ยท Page 104 of 1

native tide
#

and product ids

#

or something

warm igloo
#

so would this item be a widget your client is selling themselves? or a website that shows a product that might be on amazon and it shows on your site but when they want to buy it it takes them to amazon?

#

so your one site might link off to dozens of other places that are actually selling?

#

more of an product aggregator?

native tide
#

Sort of

#

I'm going to have a page to add and remove items though

#

I just need a secure place to store this data

warm igloo
#

k, where are you hosting your app that also doesn't have a db for you to store said data?

native tide
#

I'm not hosting it for them haha

warm igloo
#

where are they hosting it?

native tide
#

I'm not sure

warm igloo
#

cause if you need a "free" database that doesn't have secret info in it you can actually use google sheets as a crude backend

native tide
#

They're aren't being real explicit about things

mortal mango
#

@devout coral Hey, I got a new domain for my API. I set an A record pointed at the VPS. But my VPS is only accepting http for some reason. If I do the same domain but do https://, it doesn't work. It says This site cannot be reached. But if I do http://, it works but the css says forbidden. Do you know why this happens on my new domain and not my existing domain?

native tide
#

So I kinda just have to come up with a lot of stuff

warm igloo
#

but again, I wouldn't store anything in it that is "secret" even if it is a private sheet

#

yeah I've had clients like that man it's rough ๐Ÿ™‚

native tide
#

Lol

#

Im just like

#

give me a freaking requirements docs

#

so i can actually do stuff

#

xD

#

they'll be telling me to add stuff at the most random moments

warm igloo
#

@mortal mango A record points to VPS, but is the VPS using something like Apache or nginx as the web server? They need changed too to "catch" the throw from DNS. And also to listen on the port for SSL on that IP.

#

so you may have your first domain set up on say 12.13.14.15:80 and :443, but 22.23.24.25 is only listening on 80

native tide
#

also i have sort of a noobish question

warm igloo
#

go ahead

native tide
#

how do i make an optional parameter in a route for a flask app?

mortal mango
#

@warm igloo I have apache

native tide
#

like lets say you have /x/y which could be an index, but then you could have /x/y/z

mortal mango
#

@warm igloo do you know what I need to change to make it work?

warm igloo
mortal mango
#

?

#

is that for yonderbread

warm igloo
#

Ya

#

sorry, sec

mortal mango
#

oh ok

native tide
#

haha thats the same SO post i read earlier

#

but now that i read it again

#

i realize you can specify defaults from the method parameters themselves instead of the decorator params

warm igloo
#

So, in apache, do you get to make your own changes to the vhosts? Like you can edit your httpd.conf? @mortal mango

mortal mango
#

yeah

#

I have a .conf file

warm igloo
#

@native tide Exactly. Route doesn't need to be optional, the func can.

mortal mango
#

that's my .conf

warm igloo
#

Cool. See the *:80? you need a virthost defined for 443 too

mortal mango
#

oh how do I do that?

warm igloo
#

it's nicer in nginx cause you can do both in same definition of vhost, but in apache I believe you have to have two separate ones

#

you said its working for your other domain? there should be an example in the same conf file (assuming this is same server you said it does work on)

mortal mango
#

I use the same .conf file for everything

#

do I have to create another one with 443?

warm igloo
#

no, same file is fine

mortal mango
#

oh so where do I put 443?

warm igloo
#

it's too much to type out so trying to find a good tut for you

mortal mango
#

oh ok

#

that'd be nice

warm igloo
#

cause what you'll probably want to do is reduce your :80 vhost down to "accept this traffic and redirect to 443", and the 443 vhost will have all your other directives there.

#

on my servers, cause I never want to serve over 80 but someone might still try to go to it without https, I catch the request and automatically redirect to 443 version

mortal mango
#

ok

warm igloo
#

for instance if you just changed that vhost to be *:443 it'd work

#

but 80 would stop

mortal mango
#

so what's port 80?

warm igloo
#

http

mortal mango
#

oh

warm igloo
#

and 443 is https

mortal mango
#

I'm making an api

#

so people would use http requests

#

so that would stop working right?

warm igloo
#

well, still http protocol

#

you want them to do it via the ssl version

#

no real reason to let it be plain text over 80

mortal mango
#

ok

#

I'll just change it to 443 then

warm igloo
#

you have a ssl cert installed and everything yeah?

mortal mango
#

yeah

#

from cloudflare

warm igloo
#

so yeah change that to 443

mortal mango
#

k

warm igloo
#

and if you see people trying non-ssl version, then you can add a small vhost definition to say "nah bro, go here"

mortal mango
#

oh ok

#

it's giving me the default apache ubuntu page

#

how do I make my static files to show?

warm igloo
#
RewriteEngine On
RewriteRule (.*) https://yourdomain.com$1
</VirtualHost>```

That's from memory. Probably close but not *quite* right.
#

Oh, sorry, that's for the 80->443 redirect.

mortal mango
#

so that's the redirect

#

but like why aren't my static files showing?

warm igloo
#

Looks like your DocumentRoot is /var/www/html?

mortal mango
#

yeah

#

do I have to change it?

warm igloo
#

good question .. why aren't they showing

#

no, not if that's where your files are

#

is this a flask app? django? totally static?

mortal mango
#

django

warm igloo
#

I'm django-dumb, hmm.

#

You changed the port on the vhost and then restarted apache but ... now only the default ubuntu page shows?

mortal mango
#

yeah

warm igloo
#

Makes me think there is another vhost definition of 443 with its own DocumentRoot

#

can you search for DocumentRoot in that conf?

mortal mango
#

wdym

warm igloo
#

something is answer on 443 and serving that ubuntu page

#

cause your definitions look good

mortal mango
#

oh so like there's another 443 that's handling it instead of mine?

warm igloo
#

perhaps yeah

#

apache can get weird cause the conf files can include OTHER conf files too

#

er, shit, I gotta bounce man, I hope you figure this out but if not I'll be back tomorrow .. good luck though

mortal mango
#

oh ok

#

I gotta go too

#

cya tomorrow

#

hopefully we'll figure this out

trim star
#

You shouldnt use http outside of localhost

#

port 80 should redirect to port 443

#

https

vivid spear
#

hey um im kinda stuck so i was making a thing where u click the button and a database will make a random generated code which is a room.

everytime a person pressess that button. they redirect to that room ther will be a global timer in there and scraping stuff

#

but.. heres the catch. Will it be like a session or like its globally each link?

#

or i should make a new file using the built in python file manager

warped timber
#

wait why do you need to create files

#

@vivid spear

#

shouldn't your web framework have sessions

#

just use that and store the session data

#

for each room

vivid spear
#

flask? @warped timber

#

session data for the user or for the server tho?

warped timber
#

session data is stored server side per user

vivid spear
#

oh thanks. didnt knew there was something like that

#

btw

gleaming basin
#

hi need some help

vivid spear
#

is it possible to delete a session every 10 min?

gleaming basin
#

when i downloaded python 3.9.0

vivid spear
#

what modules should i use?

gleaming basin
#

it dowsn't work but for 3.8.0 it dose work

warped timber
#

session timeouts?

gleaming basin
#

so why is thta

vivid spear
#

@warped timber yeah like itll delete the room on my db

warped timber
#

not all packages support 3.9 yet

gleaming basin
#

not all packages support 3.9 yet
@warped timber ok

warped timber
#

just put a check into the view route

gleaming basin
#

what is the new runtime for 3.8.0 and 3.9.0

warped timber
#

if the current time is greater than the session start time

#

then kill the session

vivid spear
#

so i always have to check it

warped timber
#

or you could do something with a background task

#

but idt that's necessary

#

just check whenever you access it

#

if it's past the timeout then stop the room

#

and clear the appropriate session data

vivid spear
#

oh ok thanks :) i tought my work would be fixed if i just made a new html file every time someone makes a room

gleaming basin
#

guys

#

u still her ei have one more questions

#

is it pip install django

#

ot

#

or

pulsar hinge
#

Yea, but do it in Virtual environment

gleaming basin
#

pip install django===3.1.2

warped timber
#

the 2nd one just installs a specific version

gleaming basin
#

uhhh so idk whta to do tho

warped timber
#

the 1st installs the latest version compatible with your other deps

gleaming basin
#

uhm

#

so imma do dat

warped timber
#

so do the 1st unless you have a specific reason no t to

gleaming basin
#

ok

#

help

#

pls

#

my cmd is not letting me run

#

django-admin command

#

.help

#

ok

gaunt marlin
#

please don't spam put your question in a short sentence

pulsar hinge
#

Do u have django installed? Do you have created virtualenv? Are u in ur virtualenv? Redo your error, and send ss of cmd here @gleaming basin

gleaming basin
#

whhhhhhhhhhhhhaaaaaaaaaaaaaaaaaaaaaaaaaaaaaat

pulsar hinge
#

Give me screenshot of your cmd error

gaunt marlin
#

what error it raise when you type django-admin ?

neat goblet
#

Can someone help me with HTML tables?

peak meadow
#
keepalive
--keep-alive INT
2
The number of seconds to wait for requests on a Keep-Alive connection.

Generally set in the 1-5 seconds range for servers with direct connection to the client (e.g. when you donโ€™t have separate load balancer). When Gunicorn is deployed behind a load balancer, it often makes sense to set this to a higher value.

Guys, what if my request takes more than 2 minutes, it's ok to increase this value ? It's about a flask app API with gunicorn and the request sometimes has to wait for some things to complete way over around 150-200 seconds

vestal hound
#
keepalive
--keep-alive INT
2
The number of seconds to wait for requests on a Keep-Alive connection.

Generally set in the 1-5 seconds range for servers with direct connection to the client (e.g. when you donโ€™t have separate load balancer). When Gunicorn is deployed behind a load balancer, it often makes sense to set this to a higher value.

Guys, what if my request takes more than 2 minutes, it's ok to increase this value ? It's about a flask app API with gunicorn and the request sometimes has to wait for some things to complete way over around 150-200 seconds
@peak meadow that's...really long.

#

why does your request take so long?

peak meadow
#

Because

#

I'm writing some ssh commands to my raspi

#

and Waiting for the output

#

and that's how long it takes

vestal hound
#

hm.

#

that's normally not how one would do it

peak meadow
#

it will be used only by me

vestal hound
#

like

peak meadow
#

Hmm. I have no other way to wait for the output and also return something

#

because it might go wrong so I can return what's wrong

vestal hound
#

the orthodox way to do this is to return HTTP 202 with some sort of ID

#

then have the client periodically poll the server with that ID (or use server-sent events)

#

but if it's only for your personal use

#

do whatever you want

peak meadow
#

My web server will sent requests

#

and my clients

#

but for my clients

#

which is only one

#

for an api

#

it takes less than 1 minute for them

#

In the code I'm using time.wait so my ssh commands can make effect and return an actual output so I can work with it

pulsar hinge
#

Can someone help me with HTML tables?
@neat goblet Just use html table generator

neat goblet
#

okay thanks man

#

I was looking for something else

#

but got it now

limber laurel
#

Do I need the Professional edition of PyCharm to style css with suggestions etc.

swift crystal
slim beacon
#

When using templates (a base.html and a index.html) do you have the index.html css stylesheet loading in a link in the base.html, or does each html file have to load it's own css stylesheet?

#

using templates in django

twin sable
#

Hello guys

#

I really need some help with my Django project.

The login system was all fine and working, but it's no longer working again. I've gone through the code even started the project afresh the registration works alright but I can't login not even with super admin to the admin portal.

I really need some help.

Please who can help me debug this.

gaunt marlin
#

@slim beacon you would use a base.html of course, follow django princile of DRYS(Don't Repeat YourSelf)

#
{base block}
{content block your index.html}
{base block}
#

@twin sable maybe post your login implementation so we can know what wrong with it

native tide
#

I am using images in my django app but they don't show up

#

what may be the problem

gaunt marlin
#

@native tide your img path?

native tide
#

I posted my website to production

gaunt marlin
#

static you need to run different

native tide
#

/media/

gaunt marlin
#

@native tide have you run django-admin collectstatic on production environment yet? django in production mode don't use path like development

#

try to open image with the media path then see if return

native tide
#

I'll do that

slim beacon
#

@gaunt marlin My CSS loads in the base.html, but it isn't loading in the index.html. Although my other static files (imgs) load up in the index.html no problem.

gaunt marlin
#

@slim beacon you can try going to developer mode in google chrome, check console and see if any of the css path return 404 first

native tide
#

It didn't work @gaunt marlin

gaunt marlin
#

@slim beacon on your child template should also add {% load static %} at the start so it detect static template tag

slim beacon
#

@gaunt marlin I have it load static loaded, but ill check chrome to see if the CSS is returning 404

gaunt marlin
#

@native tide you tried to go to the image path in src="" yet? does it return the image?

native tide
#

this is the path to the image

gaunt marlin
#

404

native tide
#

says it doesn't exist

gaunt marlin
#

yes so the image path is wrong or the image can't be access

native tide
#

But I can do so in development

gaunt marlin
#

do you deploy django with nginx ?

native tide
#

no. What is that

gaunt marlin
#

yes but django path is different on development and production

native tide
#

oh yeah ok

gaunt marlin
#

oh you just run django runserver?

native tide
#

in development yes

gaunt marlin
#

what about production?

#

what do you run it with?

native tide
#

with pythonanywhere

#

a virtualenv

gaunt marlin
#

i haven't done pythonanywhere so sadly i don't know the process

native tide
#

yes I did do collectstatic

#

o

gaunt marlin
#

i suspect that you set up like the docs

#

if so when you run collect static it should get all static file into a directory and it should work

slim beacon
#

@gaunt marlin Hey thank you for mentioning checking the dev tools in chrome. That pointed me to figuring out what the error had been and I fixed it.

gaunt marlin
#

@slim beacon oh nice, glad i can help

slim beacon
#

It seems that there was a 404 with a missing js.map file (a sourcemap i guess its called), and i googled what was going on and it seems that this is a somewhat common problem

#

found this that spoke more about it

#

Thank you for your help!

twin sable
#

@gaunt marlin Thanks for replying

#

<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<div class="form-group icon_form comments_form">
<input type="text" class="form-control require" name="username" placeholder="Username*">
</div>
<div class="form-group icon_form comments_form">
<input type="password" class="form-control require" name="password" placeholder="Password *">
</div>
<div class="login_remember_box">
<label class="control control--checkbox">Remember me
<input type="checkbox">
<span class="control__indicator"></span>
</label>
<a href="{% url 'password_reset' %}" class="forget_password">Forgot Password</a>
</div>
<div class="about_btn login_btn float_left">
<button class="btn btn-primary p-1 form-control" type="submit" name="button"> Login </button>
</div>

#

def userLogin (request):
if request.user.is_authenticated:
return redirect('dashboard')
else:
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('dashboard')
else:
messages.info(request, 'Username OR Password is incorrect')
context = {
'title' : 'Login'
}
return render(request, 'account/login.html', context)

gaunt marlin
#

in your view can you print out password and username?

twin sable
#

this is my view above

gaunt marlin
#

put it in the code block

#

i hardly see the indent

twin sable
#

Sorry am not familiar with discord, how do I do that?

#

def userLogin (request): if request.user.is_authenticated: return redirect('dashboard') else: if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('dashboard') else: messages.info(request, 'Username OR Password is incorrect') context = { 'title' : 'Login' } return render(request, 'account/login.html', context)

gaunt marlin
#

there '`' tick and python

twin sable
#

Okay seen it

gaunt marlin
#

close with those three tick again

twin sable
#

<form method="post" action="{% url 'login' %}"> {% csrf_token %} <div class="form-group icon_form comments_form"> <input type="text" class="form-control require" name="username" placeholder="Username*"> </div> <div class="form-group icon_form comments_form"> <input type="password" class="form-control require" name="password" placeholder="Password *"> </div> <div class="login_remember_box"> <label class="control control--checkbox">Remember me <input type="checkbox"> <span class="control__indicator"></span> </label> <a href="{% url 'password_reset' %}" class="forget_password">Forgot Password</a> </div> <div class="about_btn login_btn float_left"> <button class="btn btn-primary p-1 form-control" type="submit" name="button"> Login </button> </div> </form>

fast tendon
#

```lang
code comes here
```

twin sable
#
from django.contrib.auth import views as auth_views
from . import views

urlpatterns = [
    path("register/", views.registration, name="register"),
    path("login/", views.userLogin, name="login"),```
#

@fast tendon thank you

gaunt marlin
#

@twin sable does it return any error while you trying to login?

fast tendon
#

you can put "py" as language there to get syntax highlightening, easier to read

twin sable
#
else:
   messages.info(request, 'Username OR Password is incorrect')
#

When I try logging in with a registered user account superuser I keep getting the else statement.

gaunt marlin
#

@twin sable can you try printing out user in your views to see what it return?

#

because it failed at the if statement so we need to know what it returned

twin sable
#

okay

gaunt marlin
#

add print('user': + str(user)) in the code and try to login- > check console what does it print out

native tide
#

Hi guys, which request method is used to update an existing model?

twin sable
#

It returns None

#

user :None

gaunt marlin
#

@twin sable ok so the authentication() return None, now we know. Next print out username and password to see if it captured from the request

twin sable
#

okay

#

username :Admin
password :admin@2020

#

it shows the username and password

gaunt marlin
#

it's correct with database?

twin sable
#

yes sir

gaunt marlin
#

you using django authenticate() method right?

twin sable
#

yes

#
user = authenticate(request, username=username, password=password)
#

the imports are there too ```py
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash

gaunt marlin
#

and in your settings included?:

#Authentication backends
AUTHENTICATION_BACKENDS = (
        'django.contrib.auth.backends.ModelBackend',
    )
#

oh btw are you using custom user model or django user model?

twin sable
#

django user model

#

and in your settings included?:

#Authentication backends
AUTHENTICATION_BACKENDS = (
        'django.contrib.auth.backends.ModelBackend',
    )

@gaunt marlin no its not included in the settings

gaunt marlin
#

try adding it and restart the server

twin sable
#
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
#

okay will do that

gaunt marlin
#

remember AUTHENTICATION_BACKENDS is not AUTH_PASSWORD_VALIDATORS, don't mix those 2 things into eachother

twin sable
#

Oh okay

#

It worked

#

You are a freaking rockstar

gaunt marlin
#

good to hear

twin sable
#

Thanks a million and one extra

twin sable
#

Taking the CS50 course

gaunt marlin
#

ah i see

unborn dust
#

cs50

#

๐Ÿ’ฏ

twin sable
#

on EDx am still finding my ground and getting used

Taking the CS50 course
@twin sable to Django

unborn dust
#

there's cs50 web as well if ur taking the regular course instead

gaunt marlin
#

it's ok since now you know, next time you will know how to fix it

#

debug is a skill

#

print every variables

twin sable
#

Yes definitely.

it's ok since now you know, next time you will know how to fix it
@gaunt marlin

#

I just learnt that now. never would have learnt that on the course

gaunt marlin
#

yeah most course don't teach you how to debug

twin sable
#

there's cs50 web as well if ur taking the regular course instead
@unborn dust CS50 Web dev by Brian Yu and Dave

gaunt marlin
#

which is sad actually

#

because when working 100% you would encounter bug

unborn dust
#

yeah that course is cool

twin sable
#

because when working 100% you would encounter bug
@gaunt marlin honestly that's true, 80% of the time I've spent working on this project was debugging error luckly solutions were on stackoverflow

#

yeah that course is cool
@unborn dust Best decision I've made this year.

wanton ridge
#

i need some help

#

after i select * from register there are empty datas in it

#

even if i fill the input fields and check the tables register there are still empty datas

#

i wanna get the datas dynamically to my database

nimble epoch
#

hi i need a little help with file uploading using flask_wtf. what does -> TypeError: object of type 'FileStorage' has no len() <- mean?

devout coral
#

@wanton ridge I am guessing that is flask?

neat shoal
#

so i'm trying to implement an API that has to support login from two OpenID Providers (Google OAuth and OpenAthens).
i'm a bit unsure as to how to implement "secured" API endpoints - for these secured API endpoints i'd need to decode a JWT token but how can I tell if the token is Google's (and then use a google token validation service) or if i'ts OpenAthens (and figure out how to decode those) - perhaps once doing the regular oauth login flow I should generate my own JWT tokens instead of using the one supplied by the OAuth provider? thoughts?

wanton ridge
#

@devout coral yes

native tide
#

For an API to update an object within a model... should I be using POST, PUT or PATCH requests?

ebon gust
#

@native tide patch

native tide
#

Ok, thanks! I don't really understand the difference between PUT or PATCH requests... Other than PUT is meant to update the whole object and PATCH just updates certain fields of an object... Is that right?

swift sky
#

im not sure why my post method is not working

ebon gust
#

@native tide exactly

#

@swift sky i guess if you don't put in at least a screenshot of your code nobody can help you ๐Ÿ˜„

swift sky
#

    @app.route("/survey", methods=["GET", "POST"])
    @login_required
    def call_survey():
        # forms and connection
        phone_survey = PhoneSurvey()
        connection = db_connection()
        cursor = connection.cursor(pymysql.cursors.DictCursor)

        # survey questions
        terminal_number = request.form.get('terminal_number')
        was_this_pandemic_related = request.form.get('was_this_a_pandemic_related_call')
        what_was_the_call_about = request.form.get('what_was_the_call')
        was_resolved = request.form.get('was_the_inquiry_resolved')


        if request.method == "POST":

            #query
            insert_sql = "INSERT INTO phone_survey (terminal_number, was_this_a_pandemic_related_call, what_was_the_call," \
                         " was_the_inquiry_resolved ) VALUES(terminal_number = %s, was_this_a_pandemic_related_call = %s," \
                         " what_was_the_call= %s, was_the_inquiry_resolved= %s)"

            #execution
            cursor.execute(insert_sql, (terminal_number, was_this_pandemic_related, what_was_the_call_about, was_resolved))
            connection.commit()
            connection.close()
            return redirect(url_for(call_survey))
        return render_template("call_form.xhtml", form=phone_survey)```
#

I get a method not allowed

#

when i try to submit my form

swift sky
#

@swift sky i guess if you don't put in at least a screenshot of your code nobody can help you ๐Ÿ˜„
@ebon gust i only wrote a small amount to see if people were interested, because it's tedious pasting code and explaining everything only to have nobody respond

#

@ebon gust but thank you for your advice ๐Ÿ™‚ i appreciate your efforts in helping.

wanton ridge
#

anyone good in sqlalchemy?

mortal mango
#

@warm igloo I'm back. Are you back?

wanton ridge
#

if someone fill the form then those datas should be direct to the database

#

that's what i want

jolly matrix
#

Im using tailwindcss alongside django.
I've tried getting downloaded custom fonts in the way tailwind css tells you to, but its not working. Do I need to do something else since Im using django?

#

The font and the css file(not the one containing the utility classes, but the file from which the output css file is made) are in a folder alongside the mainapp folder, away from static folder

stable kite
#

@jolly matrix have you downloaded your fonts the folder where you store statics?

jolly matrix
#

nope

stable kite
#

then?

jolly matrix
#

everything with with tailwind generates the output css file is in a single folder, including the fonts

stable kite
#

yes but django should know where it should look for statics

#

have done that?

jolly matrix
#

nope I'll try that out now

jolly matrix
#

thanks

stable kite
#

no problem

rancid jungle
#

Hi there im struggling finding a way to export a dash datatable in order to get it into an outlook email using win32. Anyone perhaps know a solution to this?

#

:(

pulsar hinge
#

Do you guys know how to get total price (sum of all discount prices and prices).

        return self.quantity * self.item.price
    
    def get_total_item_discount_price(self):
        return self.quantity * self.item.discount_price

    def get_end_price(self):
        pass```
If you need any code please tag me. Thanks
next needle
#

@wanton ridge try db.session.commit()
instead of

wanton ridge
#

i also tryped db.scoped_session.commit() didn't work

next needle
#

can you provide code in a bin?

#

I am much familiar with SQLALCHEMY

wanton ridge
#

can you provide code in a bin?
@next needle how to do it, never done it

next needle
wanton ridge
#

well somehow i can't save it

pulsar hinge
#

save it there, and send url to it

hollow raft
#

For those using Flask, what front ends do yall utilize? I'm fairly new to webdev stuff

bright lark
#

Heres my extremely beginner level question. Do websites built with flask or django still typically use javascript? Or is the scripting done in python?

pulsar hinge
#

For frontend u use js. Backend is done with python

wanton ridge
#

@pulsar hinge quick question why i my link empty, i paste my code there

pulsar hinge
wanton ridge
swift sky
#

should I use wtforms if i wanted to make something that a user can input text into, and that text would be loaded onto a db

hollow forum
#

Seems like it

swift sky
#

i wasn't sure if there was another way

hollow forum
#

ahh, kk.

peak meadow
#

Guys, how to make a new connection to database everytime with Gunicorn ? I'm getting this every time: MySQL Connection not available. with flask app and mysql.connector

#

It worked with uWSGI when I have specified lazy apps to true

#

Which loaded app in each worked insted of master but I know that Gunicorn already does this however I can't connect to the database

#

it works if I specify this: mydb.reconnect() after every query I have to make..

swift sky
#

uhh what i did was just place my connection info into a function

#

and reference that function in my methods

#

and code in the connect, the query, the disconnect.

#

the cursor.

#

you need to also close out the connection after every query otherwise server will force you out, since each worker will have its own connection running

#

it works if I specify this: mydb.reconnect() after every query I have to make..
@peak meadow so do that

#

idk

#

im noob

peak meadow
#

reconnect works :)) way simpler than your solution but both works

#

@swift sky

#

I was looking for something so I don't have to use this every time

swift sky
#

i have different db that i connect to though

peak meadow
#

I'm using mysql connector

swift sky
#

like more than 1 db

peak meadow
#

Ah

#

yeah

#

still same

#

mydb1.reconnect

#

mydb2.reconnect

swift sky
#

right

#

let me know if you find somethign

peak meadow
#

I will

upbeat lynx
#

anyone have experience using "FOR JSON PATH" for sqlserver with pyodbc?

devout coral
#

Hello everyone.

fast lagoon
#

I am very new to Flask I have gotten to the point were I have and input box and in the terminal it shows a POST html. I dont understand how i can take that and use it as a var to input into my other script. Could someone help.

pale dove
#

@fast lagoon You have to use the request.form.get function and put the class of the form as the parameter

#

kind of like this

#

        # Ensure username was submitted
        if not request.form.get("username"):
            return apology("must provide username", 403)```
#

The formatting on that may not be great so don't just copy paste

devout coral
#

Time to renew my PyCharm license ๐Ÿ˜•

fast lagoon
#

@pale dove i want to take request.form.get("username") and input that into a different python script to pull from an api

#

no print it on the website

#

idk if im making sense

pale dove
#

that's fine just put what comes back from that and put it into a variable

#

you'll have whatever the user put into the form

devout coral
#

You can add the logic of your script right on that post. request.form.get("field_name") will simply return the value of the field that you passed the field name. You can set that to a variable and use the value as needed.

fast lagoon
#

I see now

#

thanks guys

pale dove
#

you got it bud

#

also @devout coral you seem pretty smart do you know of any free libraries for speech recognition that work with the python library SpeechRecognition?

devout coral
#

It is funny you ask that I was looking into starting my speech recognition project a little while back but I do not remember what the conclusion was for the research and I did not save it either...

#

May I ask what you are working on? You have caught my interest.

pale dove
#

It's a homebrewing assistant app actually

#

I'm a homebrewer and I need something to take hands free notes/set timers etc so that's what I've made

#

only problem is the speech function has to run in the background to get woken up or else it's not really hands free

#

I've got the logic to work but google only gives 50 requests/day

#

and it requests once about every 10 seconds

devout coral
#

Oh, well I know there are some free libraries

#

The application makes requests even on idle?

pale dove
#

yeah it's similar to how alexa and siri work

#

so they don't really ever stop running they just keep processing your voice and wait for the "Hey siri" phrase to wake up

devout coral
#

Yeah, but why not use a module that is not great but runs locally to process the wake up command?

#

Then once it hears it anything after that gets sent to Google

pale dove
#

that's definitely an option that I'm open to

#

i don't really mind if the background one is on board or via the web

#

but the options are limited for on board ones

#

and I do plan on having this available to the public when I'm done

#

so using the web based one does seem more attractive

devout coral
#

Well you would only need it to recognize one phrase pretty accurately and that is all

pale dove
#

yeah that's it

devout coral
#

And use the web based for everything else

pale dove
#

I'm down for that haha

#

any libraries you'd suggest for that

devout coral
#

Ok, I am currently taking a break from my project cause itโ€™s Friday so let me see if I can help you out.

pale dove
#

thanks bud

devout coral
#

Also, out of curiosity why are you on the web deck one of you are working on something that is not related to web dev?

#

Not that I mind. Just wondering.

pale dove
#

I wanted to help out UrgentCashew and you seemed knowledgeable so i figured I'd ask you haha

#

I already opened two rooms for my issue I'm in neon if you wanna switch to that

devout coral
#

sure

silver shell
#

Hi - is it possible to somehow add custom forms to admin site? I need to make a form where i enter some data which causes 3 model instances to be created in the right order with some constraints....so instead of having to remember that order and constraints and use default forms it would be very beneficial to make a custom form for that

bitter trail
#

I hosted a site year back on zeit (now called vercel).
I can't find my project anymore on my pc.
So I am trying to download the project I hosted but unable to find an option.
Can someone provide a solution ?

silver shell
#

@bitter trail use scp or rsync?

bitter trail
#

No idea what you talking about.

silver shell
topaz widget
#

@silver shell rsync is faster

silver shell
#

@topaz widget that depends...

topaz widget
#

for big recursive copies, I think rsync is faster.

cold haven
#

I changed my mind on trying to use a webscraper in django. It just seems that it works best as a plugin to a browser. Wouldn't really be any use in a web app.

topaz widget
#

Sure it would.

cold haven
#

maybe

topaz widget
#

I can think of plenty of uses.

cold haven
#

doesn't seem logical unless you use inter-process communication, because protractor is a separate instance of a program.

topaz widget
#

i have no idea what protractor is.

cold haven
#

you would have to run a separate script for it.

#

same with other webscrapers

topaz widget
#

I don't see why that's a problem.

cold haven
#

seems like too much work when you can just get the job done in a web browser client.

topaz widget
#

And your web app could totally run the scraping internally.

cold haven
#

no, it needs a separate instance.

topaz widget
#

Not necessarily.

cold haven
#

i'm using protractor to build it.

#

it does.

topaz widget
#

I don't know what protractor is, but there are other ways to do scraping that could be incorporated directly into your web application's logic.

#

completely synchronously.

cold haven
#

most webscrapers are built from selenium internally and you need to plug into a browser driver

#

like chromedriver

topaz widget
#

yeah, there are headless browsers.

cold haven
#

wdym?

topaz widget
#

but there are also simpler web scrapers that don't need a browser.

#

They just use pure http requests.

cold haven
#

you know of any with an API I could use?

topaz widget
#

What I mean is that there are browsers that don't need a gui to run and can run on a server.

cold haven
#

name one.

topaz widget
#

BeautifulSoup

cold haven
#

ok

topaz widget
#

not a browser

#

That's a library for scraping.

#

You would use Python urllib for the scraping.

#

to make the requests*

cold haven
#

how do I know the difference between something like selenium and beautiful soup?

#

where would be the determining factors?

topaz widget
#

Selenium can run JavaScript, beautifulSoup can only parse static html.

#

So BeautifulSoup is limited in what it can do compared to Selenium.

cold haven
#

so, does it use spiders or something and read elements like a search engine would?

#

in static html?

topaz widget
#

BeautifulSoup is more of an html/xml parser.

#

It's not really used for making requiests.

#

That's done with Python's urllib.

cold haven
#

why did you say you could make requests with it then?

topaz widget
#

I didn't

cold haven
#

so you use one in combo with the other.

topaz widget
cold haven
#

i don't want to read that , but I get you.

topaz widget
#

yes, you need to use beautifulsoup with urllib

cold haven
#

ok thanks

#

my question wasn't if selenium works on a server.

#

it's a question of what is better to use.

#

and hooking into a chromedriver is not what I want to do

native tide
#

Hey, so I want to create a new field to my object, and that field will contain several users, how can I do that?
I would like to add a button to users' pages and that button will add them to that specific object field. (Django)

cold haven
#

or running a separate script

topaz widget
#

Here's a somewhat trivial example of using BeautifulSoup:

import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter - ')
html = urllib.request.urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, 'html.parser')

# Retrieve all of the anchor tags
tags = soup('body')
for tag in tags:
    # Look at the parts of a tag
    print('TAG:', tag)
    #print('URL:', tag.get('href', None))
    print('Contents:', tag.contents[0])
    #print('Attrs:', tag.attrs)
cold haven
#

yeah it looks like that's what I would want. It's the tool I have been looking for

#

๐Ÿ™‚

topaz widget
#

Be forewarned, though, you probably shouldn't be using web scraping for some kind of web application in most cases.
If a website wants you to programmatically access their data, they will almost always have an API for that sort of thing.

cold haven
#

yeah that's true.

#

some websites don't come with an API

topaz widget
#

If you plan on doing this ethically--even being able to use BeautifulSoup completely synchronously in your website's code--I would recommend doing the web scraping asynchronously since you can't control how long it will take a website to respond to a request.

cold haven
#

sure

#

that's the route I was going anyway

devout coral
#

Anyone here have experience setting up celery?

topaz widget
#

I might just use AJAX if I were going to use something like this and de-couple the web scraping functions from my website's "views".

devout coral
#

With django that it.

cold haven
#

i'm just using a browser plugin for now.

#

it's working fine

topaz widget
#

AJAX would send a request to the server, which would then handle the scraping and return a response to the user in JSON.

cold haven
#

yes, AJAX is nice.

topaz widget
#

I have not used any server-side asynchronicity yet.

cold haven
#

I suppose I can run it in django and connect to sites on the backend and box the data into a database.

topaz widget
#

Yes, you could. I'm not sure how to handle asynchonous views or endpoints on the backend, though.

cold haven
#

I want to create a controller logic that calls it

#

works as an intermediary between the view and model logic

#

well, you wouldn't need to use AJAX in django

topaz widget
#

no, not ajax

#

asynchronous python

cold haven
#

oh

topaz widget
#

Not sure if it would be necessary or if all that stuff is just handled under the hood in Django.

cold haven
#

there is an async python library I bet.

topaz widget
#

there 100% is.

#

I just don't know if you need to use it or if views are called asynchronously innately by Django.

cold haven
#

yeah that would be the next step in my learning of Django

#

how to build the logic on the backend and send a view to the client

#

shouldn't be a big issue

topaz widget
#

Usually it's pretty straightforward, but communicating with a server controlled by a third party is another matter.

cold haven
#

which is why I just want to use a browser plugin for it.

topaz widget
#

I might just be overcomplicating things.

#

If you're the only person using your application, you can use the browser plug-in, but if it's an application that will be used by other users, you can't really expect people to download a browser plugin to use your web app.

cold haven
#

depends on how big your company is really, but generally a company has its own software.

topaz widget
#

If this is just going to be used internally to some organization, then yes, I suppose you could.

cold haven
#

you could have a bunch of people using browser plugins on different clients

topaz widget
#

I was thinking more for mass consumer market.

cold haven
#

yeah

topaz widget
#

Joe Schmoe should not have to download a plugin to use your website.

cold haven
#

something that is client based would definitely need to be defined as that.

topaz widget
#

You might even just do the scraping on the front-end.

#

I've thought about this issue.

cold haven
#

but you are overcomplicating things.

topaz widget
#

Here's why I might do it on the front-end...

#

not overcomplicating, may even be simpler.

cold haven
#

it is

topaz widget
#

There is a good reason to do it from the browser.

devout coral
#

Django does not work asynchronously you need something like celery for that.

#

Which is what I am trying to set up but setting it up on windows is a pain and I do not feel like putting it on the server to test that functionality atm.

topaz widget
#

Distribute the requests so that

  1. you don't have to worry about server resources
  2. spread the IP addresses of the requests to avoid getting IP banned due to excessive request volume from one source
devout coral
#

Wait what are you trying to do?

topaz widget
#

Box is trying to do web scraping within a web app.

#

The web application does web scraping.

#

web-ception

cold haven
#

it really depends on the application you are trying to make as to doing it front or back end.

topaz widget
#

true, but if all the data is just going to the user, the client can just do the scraping and then save whatever needs to be saved to the back-end when done.

cold haven
#

the bigger issue is security

topaz widget
#

It would distribute the requests and resources better by having the front-end do the scraping.

#

Seems to me like JavaScript would have decent libraries for this sort of thing.

#

It really depends on your use case.

#

If you just want a server continuously analyzing certain web pages, then yes, better to do it on the back-end.

#

But if the scraping is initiated by a user's whim, it might be better to do it on the front-end.

cold haven
#

i didn't really want advice on how to make an MVC app, so you are over-thinking

topaz widget
#

It's relevant to what you asked, though.

cold haven
#

and it's straightforward

topaz widget
#

Like, I said, it really depends on your use case.

cold haven
#

I said that before you did.

warm igloo
#

be nice y'all

topaz widget
#

lol

#

I don't understand the anger but it doesn't bother me.

warm igloo
#

also, front end scraping is gonna hit CORS issues amongst other things that limit js's reach

topaz widget
#

good point

warm igloo
#

If you want to scrape with js, it won't be in browser, it'll be nodejs and you'll back to backend at that point. nodejs does have scraping libs, but they're not gonna run in browser.

cold haven
#

that's why i'm in this channel, because I know it's back to back end.

topaz widget
#

That's a good point and a big oversight on my part.

cold haven
#

it's silly to think you can run this on the front end.

warm igloo
#

and if you're worried about being banned, you're building a scraper that is against TOS and that means we should NOT discuss that on this discord server

#

its against the rules

topaz widget
#

web scraping isn't 100% against the rules.

#

not all web pages disallow it.

warm igloo
#

I know. But getting banned for doing it was mentioned, which then means the target has limits, which likely means some TOS setup, which IS against the rules to violate ANY tos on any site

topaz widget
#

Search engines use scraping though.

warm igloo
#

And Box, no need to be condescending, they worked through it, had a discussion, and now they see there would be a lot of limits to make it not a good choice

#

yes, and people like good bots and hate bad bots .. don't build a bad bot

cold haven
#

wdym

#

i'm not even in this convo

warm igloo
#

er, my misread then cause it totally seemed like you were in the convo and being snarky .. my bad

#

chat is fun

#

so easy to misconstrue tone

topaz widget
#

I don't think you were misconstruing anything.

cold haven
#

yeah, i'm not bothered by it.

warm igloo
#

hey, look, a squirrel! back to web dev talk? ๐Ÿ˜‰

topaz widget
#

lol. I need to hit the weight room actually...

cold haven
#

I didn't think you needed to connect to another server in urilib

#

it just let's you connect to endpoints

#

not any specific server but it's a feature of the api.

#

it doesn't even matter and you can connect from client or server.

#

it's just a built in web browser basically

#

kind of like what you would see in React Native.

#

this guy went on a rant about MVC but it's fine.

#

i'm not upset about it, so let's just drop it.

#

Trolls like that wouldn't land a job very well or find it hard to land a job.

#

that's why there is Karma for Trolls.

devout coral
#

Lol

#

This whole conversation was jus interesting.

cold haven
#

try that at a job interview...just saying

#

gg'd

topaz widget
#

wtf are you talking about?

cold haven
#

lol no worries

topaz widget
#

If anyone's trolling here, it's you.

#

mental

cold haven
#

plz.

topaz widget
#

absolutely mental. i was trying to help you. jesus.

cold haven
#

how many job interviews have you had?

quick cargo
#

wtf are you two arguing about

topaz widget
#

I'm done talking to you psycho

cold haven
#

this is epistemological

topaz widget
#

@warm igloo I was going to ask you a question, but this chat has been poisoned.

cold haven
#

just ignore me

warm igloo
#

"i'm not bothered by it" has to make sure to replay the conversation in a summary just to prove some point

#

lol

cold haven
#

no, i'm done

#

:/

warm igloo
#

time to step away and paint some toy soldiers, peace y'all

cold haven
#

pz

quick cargo
#

Reading through everything that you lot have gone through is mind boggling

cold haven
#

it's an interesting topic, but I do think implementing a webscraper on the front-end is a waste

#

you need a data store if you are going to go that route I believe.

#

I know that webscrapers are frowned upon because they can be used for evil things, but I would be using it for legitimate business purposes.

quick cargo
#

The only reason todo it as if it was a actual 'client' would be to make use of the JS enabled system and testing

topaz widget
#

I blocked that other guy. He was being insane.

quick cargo
#

which does exist for the record

cold haven
#

yeah you would use it for protractor

quick cargo
#

For example Selenium is a multi-language set of packages that completely automate the browser

topaz widget
#

I was trying to help him and then he just started going psycho on me.

cold haven
#

front end testing for endpoints and that's it.

quick cargo
#

you generally wouldnt use the front end directly with a manual client on it because it causes all sorts of issues

#

but browser automation is not uncommon for testing

#

and entire systems are built around that

cold haven
#

and it leads to security issues.

#

as I was saying earlier

quick cargo
#

What do you mean by security issues though and in what context

cold haven
#

you can make requests behind a reverse proxy on a cloud service for example instead of making it client specific

quick cargo
#

make what client specific though lol

cold haven
#

so it's nice to give someone advice up to the point that they want it is my point. If you tried to give your boss advice you would get fired pretty quick.

#

Just a word of advice.

#

I think I have said enough and that includes advice for trolling.

quick cargo
#

i mean coming from someone viewing this outside of that conversation it looks like none of you really knew either what you were talking about or what the actual topic was, Just looks like a mess of one person talking about one thing and the other on another trail of thought

cold haven
#

because you are in a different perspective.

#

how could you get what we are talking about

#

just like i didn't know what he was saying.

#

it works both ways

quick cargo
#

because i have eyes and a brain, I can scroll up and read through the conversation

#

:P

cold haven
#

yeah right...give me one good point about it

quick cargo
#

It just looks like you two trying to one up each other every time tbh

cold haven
#

you can't really speak paint with a broad brush and expect results either.

#

which is what you are doing right now...

quick cargo
#

๐Ÿคฃ Im starting to see who caused this original issue now

cold haven
#

I'm the one who asked the question originally.

#

So yes, and what reading skills and brain if it took you that long.

#

Constructive Criticism.

quick cargo
#

That's not constructive criticism that's picking fights with people who originally were trying to help you Altho i think discuss would be a better word for this lmao

cold haven
#

๐Ÿ™‚

#

well, I don't think anyone likes an over explanation of a topic.

#

I know this from experience.

#

you end up cheating yourself and making yourself look bad.

#

I was just trying to save him from embarassment.

quick cargo
#

๐Ÿคฃ Im gonna resist the temptation of opening this can of worms

cold haven
#

whatever, I'm glad someone has a sense of humor in here.

#

I admit I don't know it all.

#

I know pythagorean theorem and that's enough for me.

#

you need petabytes of storage to be the best troll.

#

at that point you may as well be A.I.

#

troll bot 2.0

native tide
#

I'm making an API request with a username field which is less than 4 characters long. It is responding with "Ensure this field has at least 4 characters." but I don't know why.

This is my model, I added MinLengthValidator to the username field, but my message is different to that being shown on the API response. Does anyone know why?

class Users(models.Model):
    username = models.CharField(max_length=20, unique=True, validators=[
        MinLengthValidator(4, message={"error": "Username must be at least 4 characters in length."})])

    email = models.EmailField(validators=[EmailValidator()], unique=True)
    # Email validator similar to that within a form.

    password = models.CharField(max_length=100, null=False)
cold haven
#

lmao

native tide
cold haven
#

MinLengthValidator has a param of 4 in it that's probably why ๐Ÿ™‚

native tide
#

The 4 specifies the minimum length of the passed value

cold haven
#

you asked why is it giving you an error of minimum of 4 characters

#

I think that's it

#

idk

native tide
#

I didn't ask that

cold haven
#

ok idk then

#

๐Ÿ™‚

native tide
#

I think I've found my solution anyway. It's just that I specified the message="something" in my validator which should be the message shown in a ValidationError (I think?) but I can just write a custom validator with my desired message which does the same thing

cold haven
#

if the issue I specified isn't the effect then it's certainly the cause.

quick cargo
#

Does message actually take a dictionary

cold haven
#

i like sets

quick cargo
#

Looking at le docs it takes a normal string

native tide
#

I don't know. Probably not. But I have tried a string also and it doesn't work so idk

cold haven
#

bleh...

#

idk either

quick cargo
#

I take it you're using this as a model form not just saving it after making it

native tide
#

Naw I ain't using forms

#

Can validators be used for models?

quick cargo
#

Yeah but they're not automatically ran technicall6

#

Though further reading validator Litterally just does

#

If X > nunber

cold haven
#

wow

#

trollbot 2.0

#

yeah i'm happy knowing pythagorean theorem

quick cargo
#

No idea what you're going on about but okay

native tide
#

lmao

cold haven
#

this wasn't the college course we were looking for.

native tide
#

I'll keep the main validation on the backend and the minor stuff (like making sure username > 4 characters) on the Frontend. Using react so might as well

#

Cant give a scooby doo to work out why django does what it does

#

but it is what it is

quick cargo
#

It's a weird issue I'll give you that

#

Most likely it'll be something random throwing it off

native tide
#

This is the validator itself

class MinLengthValidator(BaseValidator):
    message = ngettext_lazy(
        'Ensure this value has at least %(limit_value)d character (it has %(show_value)d).',
        'Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).',
        'limit_value')
    code = 'min_length'

    def compare(self, a, b):
        return a < b

    def clean(self, x):
        return len(x)```

And somehow it is returning this??
#

I don't even see how that validator is creating that message

#

I am using a serializer so maybe it's doing something

quick cargo
#

If you remove the validator does it give the same message out of curiosity

native tide
#

That message only came up when I added the validator to the model

quick cargo
#

Is this DRF?

native tide
#

So no

#

Yes

quick cargo
#

Looking at their docs they have a bit of a diffrent system todo validator with the serializers

#

Then again this is probably going beyond my experience with django

native tide
#

Ooh that is probably the problem. The validation error in the docs is eerily similar to my one

#

Lol changing the message that the validator itself returns changes nothing. So it must be a serializer thing

#

This is definitely above me... gonna shove this behind the counter

vestal hound
#

Lol changing the message that the validator itself returns changes nothing. So it must be a serializer thing
@native tide it is

#

validation is a serializer-level operation

#

in DRF

native tide
#

HOLY SHIT NOW IT WORKS

#

yesssiiirrrrr

#

Thanks @vestal hound

#

So, the serializer does the validation. If I .save() a serializer object, will the model I already have also do its validation on the data?

vestal hound
#

So, the serializer does the validation. If I .save() a serializer object, will the model I already have also do its validation on the data?
@native tide nope

#

basically Django model validators are tied to Django forms

native tide
#

Oh okay, so any validation I have in a model's field is only for its forms?

vestal hound
#

uh...

#

okay maybe I didn't explain that properly

#

let me rephrase

#

in DRF, validation is run solely by the serializer

#

BUT if you use a ModelSerializer, then it pulls the validators from the (model) fields and uses appropriate substitutes when creating the serializer fields, as a convenience

#

With ModelForm the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class.
...
When you're using ModelSerializer all of this is handled automatically for you. If you want to drop down to using Serializer classes instead, then you need to define the validation rules explicitly.
(emphasis mine)

native tide
#

Ahhh. That explains a lot. I was using ModelSerializer and I didn't know where my validation message was coming from, so I guess it did it automatically for me. That was the thing I wanted to change

vestal hound
#

yeah, you can change it by manually defining the field in question

native tide
#

And is that only achievable by making it a Serializer Class?
If I have a modelSerializer like this...

#

Is there a way to manually define each field and add their validators?

vestal hound
#

And is that only achievable by making it a Serializer Class?
If I have a modelSerializer like this...
@native tide just like

#

title = serializers.CharField()

#

for example

native tide
#

Am I doing this right? I tried to define each field explicitly but for the ModelSerializer I need the class Meta and fields = [] defined... So I ended up with this:

class UserSerializer(ModelSerializer):
    class Meta:
        model = Users
        fields = ["username", "email", "password"]
        username = CharField(max_length=20,
                             validators=[MinLengthValidator(4, message="Usernames must be at least 4 characters long")])
        email = EmailField()
        password = CharField(max_length=100)```

This is just using the fields in the fields variable and not the others. 

Doing it with Serializer, not ModelSerializer, works just fine.
vestal hound
#

@native tide no outside Meta

native tide
#

Awesome! Thanks @vestal hound that gave me a great practical understanding of validation with serializers. I'm new to DRF so I'm yet to understand all the theory but that's made what I want to do much more easier and understandable

#

Really appreciate it

vestal hound
#

yw

quiet comet
#

in django i need to save my email to a .log file. Should i just open and write to the file everytime the email is sent? Or is that a bad idea because if i sent a lot of email then i would have to open the file, write, etc everytime

vestal hound
#

in django i need to save my email to a .log file. Should i just open and write to the file everytime the email is sent? Or is that a bad idea because if i sent a lot of email then i would have to open the file, write, etc everytime
@quiet comet depends on how many emails you're sending

quiet comet
#

its just for testing

vestal hound
#

I'd suggest just using the simplest implementation

#

then if it's slow you can worry about it

#

premature optimisation is the root of all evil

quiet comet
#

so whenever i send a email i open the file and append the email? k, i was just wondering if there was something better

vestal hound
#

so whenever i send a email i open the file and append the email? k, i was just wondering if there was something better
@quiet comet well I mean

#

it's not a very complex problem so the number of alternatives is limited

#

open file every time you want to write

#

buffer and open file once in a while

#

hold file open constantly and write

quiet comet
#

well ty anyway for calming my paranoia

vestal hound
#

np

#

don't worry about this kinda thing

#

until it becomes a problem

limber dew
#

Anybody familiar with saleor ??

swift crystal
near bison
#

Why is an SPA considered non-ideal for an ecom website?

vestal hound
#

Why is an SPA considered non-ideal for an ecom website?
@near bison according to whom

near bison
#

That isn't true? i read it somewhere and stuck in my mind. Someone was saying that amazon has never even looked into SPAs because of the capping of scalability, which isn't good for an ecom venture

native tide
#

so I am using flask to make a website and I need this if statement to work inside the html code but it does not want to work everything has been defined correctly as far as I am aware and yet it still does not work any help would be greatly appreciated thanks: [https://paste.pythondiscord.com/uyorunomor.xml] Line 24 {% if server.get('owner_id') == owner %}

full steppe
#

hi
someone told mwe we can use django for frontend
he is using it is this true

wanton tulip
#

Hello #web-development! I am working on a web platform, currently working on some different authentication methods. I am seeking for your input. What authentication method should I use, when I want the best ease for my clients/users? I have worked with a passwordless method and jwt token based method. "My end goal would be to let the client only have to enter an e-mail adres where a verification link would be send to the clients e-mail adres, where if they click on it, it would ask for there information." If someone could give me somewhat information to reach my endgoal I would love to know that." Thanks in advance! ๐Ÿ˜„

vivid spear
native tide
#

hi
someone told mwe we can use django for frontend
he is using it is this true
@full steppe frontend is the elements that the user interacts with like buttons and pictures and stuff like that so front end would be html and css. html is used to display data and css is used to stylize that and customize your website further and as far as i am aware django does not do that.

wanton ridge
#

anyone familiar with sqlalchemy. I need help to get my datas dynamically to my database when a user fill the input fields

swift crystal
rancid jungle
#

Can anyone help me find out how i can send a styled dash datatable in an email? Or is this a problem that nobody can solve in python?

#

Looks like i found the problem that broke the python internet

next needle
#

I was busy..

wanton ridge
#

it's fine. No need hurry

next needle
#

try upgrading your SQLALCHEMY

#

pip install --upgrade Flask-SQLAlchemy

#

@wanton ridge ^

wanton ridge
#

still same @next needle

next needle
wanton ridge
#

yeah i tried and it says no db is defined and then i define db, then it says scoped sesseion has no attribute execute

jolly matrix
#

Does anyone use tailwindcss here?
Im having a problem with customization. The changes I make in the tailwind config file does not take effect after building. Im trying to enable the active variant for the backgroundColors.
SOLVED

peak meadow
#

This is not related to Python but maybe some of you might know. Why this isn't working ?

#

so with sudo and same path the app is not found..

quick cargo
#

You haven't given it any cli arguments

native tide
#

@wanton ridge
Have you initialized your db

#

Also, wouldn't it be better to not use raw SQL? You could have a model Users and then say user = Users(username="x", password...) and then do db.session.add(user) then db.commit()

wanton ridge
#

@native tide yes i do

#

but still nothing

#

i installed flask_mysql too

native tide
#

Was your code snippet in a different file to main.py (or whereever your DB is intiailized)?

wanton ridge
#

no different file, same

native tide
#

Without seeing the rest of the code I don't know what else it could be.

But one thing I would recommend is using the ORM without raw sql, then just do db.session.add(object) then db.commit(), you know what I mean? @wanton ridge

wanton ridge
#

wait i will send you whole code

#

yes i know

native tide
#

Is there any reason as to why you can't use the ORM that way?

wanton ridge
#

i have this

#

it works but it doesn't send the datas to the database

native tide
#

Does your route '/' add data to the db

wanton ridge
#

after i check my database i am getting this

#

empty datas

#

i talking about the /register

native tide
#

So why in the '/' route do you have db.execute and in '/register/' do you have session.execute

wanton ridge
#

ahh yeah let me change it

#

but do you know why i am gettting empty datas in my database wheen i go to my register site and fill datas in then click on submit

true falcon
#

Hey i am trying to deploy a web app in heruko and i am getting this error at log
at=error code=H14 desc="No web processes running" method=GET path="/" host=mouse-position-tool.herokuapp.com request_id=91c3aeb6-399a-4c82-be2a-8b24f096d720 fwd="183.83.152.226" dyno= connect= service= status=503 bytes= protocol=https
Here is the link to my project https://github.com/Prasanna-Natarajan-3595/Mouse-postion-tool if anying wrong please help me

native tide
#
name = request.form["Name"]
email = request.form["Email"]
password = request.form["Password"]
session.execute("INSERT INTO antworten13 (Name, Email, Password) VALUES(?, ?, ?)", (name, email, password))
#

@wanton ridge try this

#

@wanton ridge Did it work?

wanton ridge
native tide
#

@wanton ridge Yeah but isn't that a different error

#

See where the error lies

#

Also dude @wanton ridge why can't you just use ORM? Why raw sql?

wanton ridge
#

for learning raw sql is better for me first

native tide
#

If you insist... if you just use ORM it wouldn't have been a problem. I think the sql complicates it

#

But anyways where is the new error

wanton ridge
#

i have no keys

#

i have another question @native tide

#

if i use ORM i dont need to create a table in my .py right? i can just create a table via terminal mysql right?

native tide
#

@wanton ridge You create a model in Python... say you create a model called Users, then in your '/register/' you can just do:

user = Users(username="something".....)
db.session.add(user)
db.commit()
and the user object is added to the db

#

Read the docs on it

wanton ridge
#

ahh thanks

native tide
#

It's much better to use models rather than raw SQL because with raw SQL you will be repeating yourself often e.g. if you want to validate userinfo and overall it's much easier

manic grail
#

Hi there, which db would you use if you had to choose, PostgreSQL or MySQL, and why?

peak meadow
#

This is somehow related to Python. Does any of you have any ideea ?
The path is the same but when using sudo and the path, it's not working

limber dew
#

Anybody familiar with saleor platform ???

#

just ping me

twin sable
#

Hello, has anyone integrated any crypto currency (Blockchain preferred) payment and receiving API with Django?

Please don't ignore if you have.

native tide
#

I want to have a React frontend with a Django backend. Can anyone let me know how I should do session management or auth?

fervent vortex
native tide
#

@fervent vortex When you make a request to a URL, your Django app will have a view which is a Python function which will run. For example, rendering a .html page for the user to see. In Django you can set which URLs you want your website to have and you can assign views to them. So, if I make a request to mywebsite.com/register/ my view renders a sign-up page. If I make a request to mywebsite.com/pricing/, another view will render a pricing page.

fervent vortex
#

hm OK

#

makes sense

native tide
#

Are JWTs a good option for React-Django combo?

fervent vortex
#

but why do i have to have 2 urls.py, one in mysite/, the other in polls/

native tide
#

The urls.py in your root directory will contain the urls for your apps. So if you have apps polls and pricing, it will contain the urls for them.

Then in your apps if you want any leading urls, like /pricing/new/, you will add the new/ there

#

You don't need to have 2 urls.py but seperating it by app makes it nicer

fervent vortex
#

hm ok

silver shell
#

I am using django session based auth and i want to be able to test my endpoint via url using python manage.py test. How do I do that?

#

@native tide "Are JWTs a good option for React-Django combo?" use session based auth

native tide
#

Is that possible if I have a React frontend with a Django backend? They only communicate via APIs @silver shell

silver shell
#

@native tide of course its possible - why shouldn't it be?

native tide
#

I'm not saying it isn't, I've not worked with Django auth yet so I'm just unsure on what to do.

silver shell
#

then use session based auth ๐Ÿ™‚

native tide
#

Ok. Thanks I'll look into it

#

Session based auth with DRF

silver shell
native tide
#

Thanks, much appreciated! @silver shell

silver shell
#

yw

native tide
#

Just setup a signup API and currently I'm making a React signup form to try to test it out. I'll be back with some questions when I get to that point haha

silver shell
#

ok. have fun'

icy fog
#

Hi guys, anyone knows why I'm getting a 403 when I'm trying to run a test against a Django REST Framework API endpoint on my own localhost server?

#
class RegisterAccountTest(APITestCase):
    def test_register_user(self):
        url = '/users/'
        data = {
            "username": "testuser",
            "email": "testuser@gmail.com",
            "password": "password321",
            "is_staff": 'false',
            "is_active": 'true',
        }
        # Use APIClient provided by Django REST Framework
        client = APIClient()
        client.login(username='pidgeon-admin', password='[insert password here]')
        response = client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(User.objects.count(), 3)
        self.assertEqual(User.objects.get().username, 'bobdoe')
        client.logout()```
#

This is my code so far for my test case

wanton ridge
#

am getting this error after i click on submit

#

i also started mysql

native tide
#

Hello, guys

#

I was working in Docker python web

#

I have got this error

#

Docker version: 19.0.12, python: 3.7.9 , Os: Mac Os (Catalina)

native tide
#

Trying to make an API call with axios. But I'm getting this error right after I submit my form:

#

This is my JS (React)

handleSubmit(){
        if (this.state["password"] === this.state["confirm-password"]){
            axios.defaults.xsrfCookieName = 'csrftoken'
            axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"
            axios.POST("localhost:5000/api/register/", {
                "username": "ReactUser",
                "email": "ReactEmail@gmail.com",
                "password": "React",
                "confirm-password": "React"
            }).then(res => {console.log(res)})
        }
    }```
#

And my API view if that will help...

#
@api_view(["POST"])  # API view for POST requests
def register(request):  # This will register a user from their POST request.

    if request.method == "POST":
        if "username" and "email" and "password" and "confirm_password" in request.data:

            if request.data["confirm_password"] == request.data["password"]:  # Checks that password is confirmed.
                hashed_password = make_password(str(request.data["password"]))  # Hashes password
                request.data["password"] = hashed_password
            else:
                return Response(data={"password": "Passwords do not match"}, status=status.HTTP_400_BAD_REQUEST)

            serializer = UserSerializer(data=request.data)

            if serializer.is_valid():
                serializer.save()
                return Response(data=serializer.data, status=status.HTTP_201_CREATED)

            else:
                return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        else:
            return Response(data={"error": "Model fields not satisfied"}, status=status.HTTP_400_BAD_REQUEST)```
#

I'm getting a 404 error and my API view does not return them. So the request is not reaching the API

silver shell
#

@native tide POST should be lowercase

#

p.s. use intellisense

native tide
#

The same issue occurs with post being lowercase

#

apparently it's something to do with csrf

silver shell
#

you should check if you have a session token

native tide
#

I haven't added any session auth yet

#

Just trying to make a plain POST call to the API view to sign up a user

silver shell
#

You should try to clone that repo and see if you can make it work there first....that would be easier to debug for you

native tide
#

I think it's something to do with the form itself. not the axios call (but idk)

return(
            <div className="container-fluid">
                <form method="get" onSubmit={this.handleSubmit}>
                    <div className="form-group">
                        <label className="text-muted">Username</label>
                        <input type="text" id="username" />
                    </div>
                    <div className="form-group">
                        <label className='text-muted'>Email</label>
                        <input type="text" id="email" />
                    </div>
                    <div className="form-group">
                        <label className="text-muted">Password</label>
                        <input type="text" id="password" />
                    </div>
                    <div className="form-group">
                        <label className="text-muted">Confirm Password</label>
                        <input type="text" id="confirm-password" />
                    </div>
                    <div className="form-group">
                        <button className="btn-lg btn btn-block" type="submit">Submit</button>
                    </div>```
#

When I switch the form method from post to get the error message disappears

#

but if I switch the method on the axios request nothing changes

#

so it leads me to think it's somethin to do with the form

silver shell
#

hehe ok...looks like you didnt read that blog at all

native tide
#

but how can I implement a cookie for a user if they don't even have an account?

silver shell
#

everything is written in the blog

#

just read it?

zealous tusk
#

what is the best place to learn django?

silver shell
#

@native tide you are posting json which is totally wrong for django session auth

#

and which quite clearly shows you did not read the blog at all

native tide
#

@silver shell but the first API view in the blog checks if a user has an account. I need the user to actually create an account first, by doing this signup form -> api

silver shell
#
const data = new FormData()
data.append('username', username);
data.append('password', password);
#

from the blog

native tide
#

honestly I don't understand what they're doing in that paragraph

silver shell
#

In which paragraph?

native tide
#
const user;
document.querySelector('#login-form').addEventListener('submit', async ev => {
  ev.preventDefault();
  const data = new FormData(ev.target);
  const resp = await fetch('/user/', {
    method: 'POST',
    body: data,
    credentials: 'same-origin'
    headers: { 'X-CSRFToken': csrf_token },
  })
  if (resp.ok) {
    user = await resp.json();
  } else {
    errors = await resp.json();
  }
})```
#

And to me it seems like that blog only covers the fact that a user has already created an account. But I have not gotten to that stage yet...

#
from django import http
from django.views.generic import View

class UserView(View):
    def get(self, request):
        if not request.user.is_authenticated:
          return http.HttpResponseForbidden()
        return http.JsonResponse({
          "id": request.user.pk,
          "username": request.user.get_username(),
        })```
silver shell
#

@native tide then i can tell you that you are wrong

#

@native tide it covers sign up, validation and sign out

native tide
#

Could you kindly explain how it covers sign up? Because that's the part which I can't see

silver shell
#

You have it right there. You just pasted the javascript part of the sign up code

native tide
#

Ok... so you're making a POST request with these lines:

fetch('/user/', {
    method: 'POST',
    body: data,
    credentials: 'same-origin'
    headers: { 'X-CSRFToken': csrf_token }```

where the data is FormData(ev.target) (idk what this is but I assume it's just a dict with username/password etc)

and then that request is handled by this view?
```py
from django import http
from django.views.generic import View

class UserView(View):
    def get(self, request):
        if not request.user.is_authenticated:
          return http.HttpResponseForbidden()
        return http.JsonResponse({
          "id": request.user.pk,
          "username": request.user.get_username(),
        })

def post(self, request):
        form = AuthenticationForm(request, request.POST)
        if form.is_valid():
          login(request, form.get_user())
          return self.get(request)

        return http.JsonResponse(form.errors.get_json_data(), status=400)
        })```
#

and the user data is passed here?

if form.is_valid():
          login(request, form.get_user())
          return self.get(request)```
#

Is that the signup route?

silver shell
#

const resp = await fetch('/user/', { is the signup route

native tide
#

and why is that?

silver shell
#

mmm because thats how its built i guess ๐Ÿ™‚ I am not sure i understand your question

#

user data is passed here const data = new FormData(ev.target);

native tide
#

Well as a beginner to Django session auth and having a react frontend I don't think that blog does any favors in teaching why

#

And yes I did read it

silver shell
#

why what?

#

why data is passed?

native tide
#

e.g. why this is signup:
fetch('/user/', {
method: 'POST',
body: data,
credentials: 'same-origin'
headers: { 'X-CSRFToken': csrf_token }

silver shell
#

Because /user/ handles sign up and data contains signup data

random karma
#

Hi Iโ€™m new this would be to know or can I best learn web-development**

silver shell
#

@random karma its good to learn web-development** yes ๐Ÿ™‚

random karma
#

I am in school but the web development courses are not good enough and it is difficult to learn well

#

@silver shell Do you know where I can learn more on my own?

silver shell
native tide
#

Ok. So that that was what I'm trying to do. But in the line headers: { 'X-CSRFToken': csrf_token } where is csrf_token defined?

silver shell
random karma
#

Thanks ^^

patent badger
#

how do i run some code every time someone connects to my website?

#

its flask

#

like i want to print something like
{ip} connected
or if they are signed in
{username}/{ip} connected

spark parcel
#

@patent badger I assume you are using templates of some kind? Just print their IP address/username into your template.

#

return render_template('welcome.html', ip=request.remote_addr, username=username)

patent badger
#

what?

#

i wanted to print it using print()

spark parcel
#

then print() it

patent badger
#

i wanted one function that would run on every request so i don't have to add it to every page.

spark parcel
#

so.. gunicorn/your proxy should do apache style logging of the IP address right?

#

if not..

#

you can setup logging that includes the IP address/username

#
    '[%(asctime)s] %(remote_addr)s requested %(url)s\n'
    '%(levelname)s in %(module)s: %(message)s'
)```
patent badger
#

I mean, this is what it logs rn

127.0.0.1 - - [24/Oct/2020 17:37:33] "GET /gallery/kausbrai/ HTTP/1.1" 200 -
127.0.0.1 - - [24/Oct/2020 17:37:34] "GET /gallery/kausbrai/cat-1.png HTTP/1.1" 200 -
127.0.0.1 - - [24/Oct/2020 17:37:34] "GET /gallery/kausbrai/static/bootstrap.min.css HTTP/1.1" 200 -
127.0.0.1 - - [24/Oct/2020 17:37:35] "GET /favicon.ico HTTP/1.1" 200 -
spark parcel
#

read that link on flask logging, it should help

patent badger
#

also, it says 127.0.0.1 because im using ngrok

#

i think i have a way around that

quiet comet
#

in django, how to check if contract_date exists?
customer/4/
customer/4/?contract_date=&contract_end_date

so if i do a get request i want to check if it have the contract_date in the url, tried my_param = request.GET.get('contract_date ') but when contract_date have nothing it returns none

spark parcel
#

@patent badger Im pretty sure that page talks about getting t he proxy IP address

steady cypress
#

hehehe

#
setTimeout(() => {window.location.replace("https://www.youtube.com/watch?v=dQw4w9WgXcQ");}, 3000);

add this to make your website 1000 times better

#

is shitposting allowed?

vestal hound
#

in django, how to check if contract_date exists?
customer/4/
customer/4/?contract_date=&contract_end_date

so if i do a get request i want to check if it have the contract_date in the url, tried my_param = request.GET.get('contract_date ') but when contract_date have nothing it returns none
@quiet comet so what do you expect to happen if contract_date is not passed?

vivid spear
#

can someone identify why this is not working?

steady cypress
#

it says there's no module named random_words @vivid spear

#

where is it supposed to be located?

vivid spear
#

replit is having issues i just open shell and pip install it

#

@steady cypress im just gonna install rnadom words wait

steady cypress
#

its a pip package?

rare zinc
#

hehehe
@steady cypress hmmm u tryna rick roll me if i timeout?