#web-development

2 messages · Page 92 of 1

maiden kraken
#

even though I've:
Set buildpack to heroku/python
Set Python version to 3.8.5 with runtime.txt
Added requirements.txt
Added Procfile

cold anchor
#

what's in your procfile? and what's your project file layout?

quick cargo
#

@marble carbon pretty much yeah because its only really become production ready in recent years

#

its still rather new

maiden kraken
#

@cold anchor:
This is my structure where I am having my git repo:

cold anchor
#

where is the .git folder?

maiden kraken
#

in procfile i have:
web: gunicorn app:homepage

cold anchor
#

it looks like that's one folder deeper than the git folder might be

maiden kraken
#

hmm... it looks like my .git file is two directories higher

#

I assume I cannot create another repo inside

cold anchor
#

the Procfile and requirements.txt need to be on the same level as the .git folder

maiden kraken
#

okay thanks a lot, I will try that right now

#

man, thanks a lot, it works now!

dense slate
#

@marble carbon I meant for JS front-end stuff. Like React or Angular.

#

Wondered if there are any new favorites. Maybe Vue?

#

Or one that's more friendly with Django

native tide
#

I am trying to make migrations in django

#

py manage.py makemigrations

#

and i see this

#
You are trying to add a non-nullable field 'confirm_password' to person without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py```
#

it bothers me...

#

i might do something wrong

dense slate
#

Do you already have data in that table?

mystic wyvern
#
You are trying to add a non-nullable field 'confirm_password' to person without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py```

@native tide we are the same

#

but i give it a number

native tide
#

Do you already have data in that table?
@dense slate yes in that model

#

what number @mystic wyvern

dense slate
#

Is this a new field?

native tide
#

yes that's a new field

dense slate
#

So you either need to give it a default, so that it fills in the current data in that column, or set it to be allowed to be null.

mystic wyvern
#

bcz it at have a null value

dense slate
#

Because by default it cannot be null.

mystic wyvern
#

Because by default it cannot be null.
@dense slate yep

dense slate
#

Set default="" or just null=True

mystic wyvern
#

@dense slate yes in that model
@native tide u can give it a value

native tide
#

oh i see

#

i know what i gotta do

dense slate
#

null=True I think is typically frowned upon.

#

So I would probably set a default in this case.

mystic wyvern
#

the database can't received a none rows (:

#

this is my opininon

dark valley
#

anyone got experience with selenium?\

half bough
#

Howdy, how would I insert data into a db when I have two different models? I'm pulling in data to a form from another model but the data is not being inserted.

half bough
#

Sorry, I'm using Django

vestal hound
#

null=True I think is typically frowned upon.
@dense slate nullability is fine if you have a reason for it

dense slate
#

That seems like a weird reason. What if the reason is just so it works. 😄

vestal hound
#

it’s kind of hard to talk about this

#

without bringing up stuff like database normalisation

#

and the meaning of nullity

dense slate
#

My understanding is that if something nefarious was to be placed in there, when you expected no data, then that could be the main issue.

#

That's just anecdotal from stuff I think I read.

#

That it's better not to have null, because something COULD go wrong, but it's not inherently bad to have that set to True.

vestal hound
#

yeah, basically that

dense slate
#

@half bough You want one form to put data in two models?

vestal hound
#

I came across this a while ago and I thought it was quite a good read

dense slate
#

Thanks, @vestal hound

vestal hound
#

What are your favorite front-end libraries to use? Aiming for minimal but still covering most of the bases. I use python/django for backend if that matters.
@dense slate I use Angular with Django

#

IMO Angular is like Django and React is like Flask

#

opinionated framework vs one purpose library

#

you can also consider Ember...?

#

there was this quite comprehensive series on Medium that compared them

#

this

lethal orbit
#

Or one that's more friendly with Django
@dense slate should all be pretty equal, tbh, at least in terms of interoperability. I haven't used Angular, but Vue.js is absolutely beautiful, easy to learn, and works well, so I would recommend that. react is garbage soup, IMO.

#

My favourite stack is Django, ariadne-graphql, apollo-client, and quasar (vue.js-based CSS framework+).

#

But definitely do consider other options.

dense slate
#

What are apollo and ariadne generally for?

#

I hear a lot about Vue recently. I'll take a look.

#

@vestal hound How would you fit Vue in those comparisons?

vestal hound
#

I'm not an expert FE dev by any means, having only used React and Angular, and only Angular for any length of time

#

which is why I linked the article

#

which I think would be much more useful to you than my opinion, written as it was by someone who is an expert FE dev

dense slate
#

I'll have a read tonight.

vestal hound
#

the thing I like about Angular is that it let me build my site with the least amount of cognitive overload

#

because it is very opinionated, like Django

#

"you do things MY way and for that I'll give you a solution for every problem you might face"

dense slate
#

That sounds about right.

#

I'm playing with it recently and.. wow.

#

Like a new age of Wordpress only on steroids.

#

Albeit slightly more complicated than WP.

#

I could see a lot of SaaS type platforms doing this in the future.

vestal hound
#

I haven't used many SaaS offerings

#

but I hear the things they can do nowadays are crazy

weak chasm
#

Anyone available to help with django ? I have the website working. I'm trying to add google api authentication/authroization. I wrote that code already in 1 file. But I realized i may need to do stuff to models.py and add it's own function in views.py not just piggyback off an existing function. also maybe url.py

visual lake
#

what is a good beginner web framework?

warped timber
#

@visual lake flask is pretty simple

visual lake
#

ok I'll try it out thanks!

maiden tulip
#

Hi, I am sure somebody here also knows some JS.
I have a function with 3 arguments,

function foo(a, b = 10, c = false) {
  //baah
}

I would like to call it like this:

foo(10, c = true)
  • a bit like using keyword arguments in python, referring to them with the name of the argument. Is there a way to do this in JS?
vestal hound
#

@maiden tulip nope.

#

pass an object

#

that's the best you can do

maiden tulip
#

could you give an example for this case?

vestal hound
#
function f(params) {
  const {a, b = 10, c = false} = params
  // ...do stuff...
}

f({a: 5, c: true})
maiden tulip
#

also, I thought about using something like default so it uses the default value

foo(10, default, false)

it errors for me tho

#

but thanks, that object workaround surely has some use cases

weak chasm
#

oh shoot gm is online

#

hey gm can i ask a quick question?

vestal hound
#

?

weak chasm
#

authorization_response = flask.request.url
flow.fetch_token(authorization_response=authorization_response)
how do you get the django version of this flask code?

vestal hound
#

uh

#

what's that supposed to do?

vestal hound
#

and what do you mean "Django version"?

weak chasm
#

suppose to authenticate and authorize google api

#

like what is flask.request.url in django. b/c that's a flask function no?

vestal hound
#

hm

#

that's the URL to which the request was sent, right?

#

so if you're moving that to a Django view

#

think you could use request.build_absolute_uri()?

weak chasm
#

😮 oh

vestal hound
#

I THINK

#

I don't really use Flask

#

that's my guess

weak chasm
#

neither do i

#

i'll look into that thank you gm

vestal hound
#

yw

#

sorry I couldn't help more

wanton ridge
#

any tips where you can public your website with webservers. Maybe a tutorial for that would be nice. If someone can help me it would be cool

weak chasm
#

"public your website with webservers" you mean web hosting? @wanton ridge
maybe try https://pages.github.com/ to start

normal flint
#

does anyone have experience with Quart - apparently its an async version of Flask. With the performance increase that you get using asyncpg over psycopg2, I've been thinking about migrating.

I have a pretty massive project so if its going to be a headache and a half I'd rather just stick with my current performance.

#

I did also consider just using asyncpg with Flask and an event loop, but with all of the blueprints I am using, I feel like it would be chaos (and very impractical).

I only have so much sanity left and I didn't feel like spending it on such an outlandish approach

*pls @ me if you respond, not really active in this channel *

vestal hound
#

does anyone have experience with Quart - apparently its an async version of Flask. With the performance increase that you get using asyncpg over psycopg2, I've been thinking about migrating.

I have a pretty massive project so if its going to be a headache and a half I'd rather just stick with my current performance.
@normal flint sanic?

#

or Django?

#

okay, not Django, ignore that

#

but anyway...premature optimisation is the root of all evil

#

actually, ignore everything I just said

#

if those are your concerns, and you're facing performance problems now, why not do it?

lethal orbit
#

okay, not Django, ignore that
Django 3.2 should be getting an async ORM, so if you want async, it's not a bad choice. It already has async views.

#

But it won't be out for a few months.

#

@normal flint there may be other ways to improve performance though. Pre-calculation and memoization, caching, etc.

weak chasm
#

@vestal hound IT WORKED. thanks. note to self if a webframework like django has a built in functionality dont try to take shortcuts and learn it lol

  1. literally write code in views.py
  2. use 2 functions: 1st function has return httpresonseredirect(external url) 2nd function has response code = httprequest.build_absolute_uri()
  3. add urls.py paths
  4. index.html write a form tag with action=function_name (views.py ones) and write method="POST"
    instead of writing functions to circumvent the views.py and thinking about celery taskschedulers and async stuff/ rabbitmq queues
    UGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH it feels so gooooood. i was stuck on this for dayssssssssssssss.
vestal hound
#

Django 3.2 should be getting an async ORM, so if you want async, it's not a bad choice. It already has async views.
@lethal orbit the reason I said "ignore that" was

#

I Googled Quart and it's apparently really meant to be a drop-in replacement for Flask

#

like

#

in terms of nomenclature and namespacing

#

so really most of what you have to do is change package names and add async/await as appropriate

#

@weak chasm good job!

normal flint
#

@vestal hound my project is gobstoppingly humongous, so I was excited when I saw the chance for find/replace imports and adding async/await

#

performance isn't a huge issue right now unless it gets more than about 3000 requests per sec (my baseline average is around 2400)

my worry is that if it gets any more popular, I will need to upgrade. If I need to rebase the code for a different framework, that would need to start now

#

that way I don't get caught with my pants down

#

I only see about a 20% increase in response time at 3000 req/s and my top 1% (4100 req/s) sees a 37% increase

versed python
#

@normal flint what tools do you use to calculate this stuff?

normal flint
#

that data is just from looking at traffic metrics for the server

#

I suppose i could simulate trafffic using a test module

versed python
#

yeah i was asking about these tests

#

do you know any libraries that can help simulate these conditions?

lethal orbit
#

locust

#

If you want something really simple, ab the apache benchmark tool.

normal flint
#

ill look into those

#

as for now, i'll probably just start the migration to Quart and hope it goes well

umbral lichen
#

Hello guys, my name is Rômulo, i've been studying python for a few months and i've got to say, i'm loving it! Its my first programming language, and i'm looking foward develop some webapp/website now. i've heard that Django can help me with this task. does anyone knows a free course or tutorials to begin with? thanks

high jacinth
#

hello people. i have a jinja2 issue

#
env = Environment(
  loader=FileSystemLoader('templates'),
  autoescape=select_autoescape(['html', 'xml'])
)
#

my files are arranged like so ```
app
-templates
-main.py

#

but jinja raises exception when i try to generate file from template

#
template = env.get_template('example.html')
#raises and exception, template not found
dense slate
#

I have a queryset of users, and I filter that based on the username that is typed into the search field. I'm getting an error that username already exists if I put the full name, but it filters correctly if I only put part of the name:

if form.cleaned_data['username']:
            try:
                gm_list = gm_list.filter(username__icontains=form.cleaned_data['username'])
                query['username'] = str(form.cleaned_data['username'])
            except:
                query['username'] = "None"```
#

thoughts on why that's happening?

#

Forms.py:
username = forms.CharField(required=False)

native tide
#

What's the best way to store an object until a user clicks "Run" to execute it?

versed python
#

what kind of object?

native tide
#

Well, the user completes a form which sends a post request with the instance arguments needed to init a class

#

I want that class to remain dormant/unused until that button click

#

in this case a prediction based on previous data which he filters in the form

versed python
#

well maybe you can achieve this via Javascript and make an api view for it

#

clicking on said button can trigger an ajax or axios request to the api view, which will respond with the required form data

#

and you can render that data in the html accordingly

native tide
#
class PersonLoginForm(forms.Form):
    username = forms.CharField(max_length=20, required=True)
    password = forms.CharField(max_length=100, required=True)

    def clean(self):
        cd = self.cleaned_data
        print(self.username)  # to debug
        actual_password = Person.objects.get(username=self.username).password
        if cd.get('password') != actual_password:
            self.add_error('password', 'That is not the correct password!')
        return cd
#

i get this error AttributeError: 'PersonLoginForm' object has no attribute 'username'

#

it clearly has a username attribute

#

but i still get that error

stable kite
marsh canyon
#

@native tide its self.cleaned_data["username"] and not self.username

tepid garden
#

is someone know Telegram bot

native tide
#

@native tide its self.cleaned_data["username"] and not self.username
@marsh canyon You were a big help. thx man!

#

I asked this on stackoverflow and look what someone answered.

#

he even demoted my question

vestal hound
#

I asked this on stackoverflow and look what someone answered.
@native tide well, the thing is

#

Stack Overflow isn't really for stuff like this

#

you're expected to do a LOT of research

#

before posting there.

marsh canyon
#

@native tide u are using the built in user model?

leaden perch
#

Who have site of django?

native tide
#

@native tide u are using the built in user model?
yes

#

you're expected to do a LOT of research
@vestal hound actually i did.

#

And these types of questions i see most of the time

vestal hound
#

they usually get downvoted

#

I've been on SO for a while

marsh canyon
#

django provides a view for login if ur using built in user model

native tide
#

and i don't see them get downvoted

vestal hound
#

I mean

marsh canyon
#

from django.contrib.auth.views import login_view

vestal hound
#

well

#

@vestal hound actually i did.
@native tide how much is "a lot"?

#

to you?

marsh canyon
vestal hound
#

like honestly there's no point arguing about this since you got your answer already

#

all I will say is that I have answered a lot of questions on SO (per unit time), and I have seen a ton of low effort ones

native tide
#

@native tide how much is "a lot"?
@vestal hound reading two whole pages of the django docs... searching related questions on stackoverflow

vestal hound
#

to illustrate, the one time I asked a question

native tide
#

from django.contrib.auth.views import login_view
ok i might use this

vestal hound
#

I more or less read the whole docs (it was a Spark question), the book written by the Spark devs, looked through the source code, etc.

#

so, yeah.

#

SO's standards are really high

#

which is why you'll probably have much better luck in more informal forums like this Discord/reddit

#

I'm not saying you were wrong

marsh canyon
vestal hound
#

but this is honestly quite a basic problem

#

that suggests that you didn't do enough research for SO.

#

just my two cents

native tide
#

well, okay

#

Am i forced to use class based views?

marsh canyon
#

the built in view is class based

native tide
#

so, yes?

marsh canyon
#

yes

#

class based views are nice

native tide
#

my whole views.py uses function based views

#

does that mean i have to convert everything to classes

#

to prevent confusion?

marsh canyon
#

u can use mixture of class and function based

#

no restriction there

#

to prevent confusion?
@native tide this depends on u

vestal hound
#

I generally prefer class-based views everywhere, but it's up to you

marsh canyon
#

yep this

vestal hound
#

Am i forced to use class based views?
@native tide for this, yes

#

in particular, if you want to support several verbs (which is typical of a more RESTful style)

#

IMO a class-based view is clearer

#

if you just want a simple RPC-style API, then class-based views kind of lose some of their advantage

native tide
#

So now that i am going to use a class based view for my login page and register page, this clean method isn't needed right?```python

class PersonLoginForm(forms.Form):
username = forms.CharField(max_length=20, required=True)
password = forms.CharField(max_length=100, required=True)

def clean(self):
    cd = self.cleaned_data
    print(cd['username'])  # to debug
    actual_password = Person.objects.get(username=cd['username']).password
    if cd.get('password') != actual_password:
        self.add_error('password', 'That is not the correct password!')
    return cd```
#

what is RPC-style API?

vestal hound
#

what is RPC-style API?
@native tide hm

#

probably something you don't need to worry about right now

#

not that important

#

you're probably writing it RPC-style anyway

#

if I simplify it a super lot

#

basically, REST-style describes what actions you're taking through HTTP verbs (GET, POST, PUT, PATCH, DELETE)

#

whereas RPC-style tends to use only GET and maybe POST and describe the action through the URL

#

it's a lot more complex than that but that's basically it

#

but you really don't need to worry about this

native tide
#

Ok. No i don't

vestal hound
#

yup

#

going back to function-based vs class-based

#

in particular, if you decide to migrate to DRF (and a lot of projects use it)

#

class-based views are a lot easier to specify authentication, permissions, serializers etc. for

native tide
#

How do i convert this function to class based then

#
def user_login(request):
    if request.method == 'POST':
        form = PersonLoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = Person.objects.get(username=username)
            if user.password == password:
                return redirect('all-users/')
    form = PersonLoginForm()
    context = {
        'form': form,
        'title': 'Login',
    }
    return render(request, 'index/login.html', context)```
#

then I will authenticate the user inside of it.

marsh canyon
#

have you complete the django tutorial on the official website?

native tide
#

The one with the polls app?

#

I completed that one

verbal obsidian
#

they showcase auth in there don't they?

native tide
#

I'm going to have to check out again then.

coarse agate
#

any flask developers able to hop over to flourine help channel?

maiden kraken
#

Hello. Can anyone tell me wth is going with Heroku with this error? I am running django app:
2020-09-22T16:18:38.614366+00:00 app[web.1]: ModuleNotFoundError: No module named 'firstDjango' 2020-09-22T16:18:38.614556+00:00 app[web.1]: [2020-09-22 16:18:38 +0000] [10] [INFO] Worker exiting (pid: 10) 2020-09-22T16:18:38.649293+00:00 app[web.1]: [2020-09-22 16:18:38 +0000] [4] [INFO] Shutting down: Master 2020-09-22T16:18:38.649408+00:00 app[web.1]: [2020-09-22 16:18:38 +0000] [4] [INFO] Reason: Worker failed to boot. 2020-09-22T16:18:38.710259+00:00 heroku[web.1]: Process exited with status 3 2020-09-22T16:18:38.743167+00:00 heroku[web.1]: State changed from starting to crashed 2020-09-22T16:18:39.767394+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=django-test-12345.herokuapp.com request_id=1084bab6-5947-4fd2-915b-0bbdea44946c fwd="157.25.189.243" dyno= connect= service= status=503 bytes= protocol=https

#

Problem is... I don't even know what 'firstDjango' is, I am not sure why it is needed

high jacinth
#

😩

warped timber
#

@maiden kraken show your code

maiden kraken
#

to be more specific

warped timber
#

im not a django expert, but your procfile is wrong

#

i think it should be mysite.mysite.mysite.wsgi if i read the docs right

maiden kraken
#

well I was messing around it pretty hard, right now I think that there maybe is a problem because my manage.py is located below, it is not in parent directory

#

I will try your suggestion, but I also will create new repo with simpler structuture, meaning mysite/mysite will be my main directory

#

@warped timber Man, thanks a lot for your help... It wasn't exactly that but you gave me an idea. The problem was the nested structure as I worried, I found some information that heroku requires app to be at root repo, so I guess manage.py must be there

civic bluff
#

just marvel at these ingenius names...

#

how am I supposed to find literally anythng

#

class_ = "number" has 250 entries

gaunt berry
#

Whats better for dynamic web apps, PostgreSQL or MongoDB?

dusk rose
#

Hey, I guess its the best Channel to ask the following question: Is it possible to change the ip adress in A-Record by strato with python. In generall my public adress is changing everey two days and I dont want to pay 50€/per Month for a static one. Maybe somebody got an other Idea, let me know. thanks

halcyon oriole
#

@gaunt berry I find mongodb easier to work with

dusk rose
#

@gaunt berry i think mongodb is easier and you can scale it up verry much better if you need

gaunt berry
#

Thanks 😊

native tide
#

i need to deploy a flask site that works in tandem with a script that webscrapes a few sites, but im not sure how to actually deploy that

#

yall know any good ways to deploy

marble carbon
#

pythonanywhere

high jacinth
#

does anyone know how relative imports work with jinja2??

ripe shale
#

Folks I need advice again.. I want to create Django/Flask app for transfer payments (Visa/MasterCard/Paypal). Problem is I'm from Ukraine and Stripe and Braintree not available here. Do you have any other solution to create money transfer app on python?

quasi wigeon
#

hey, i am trying to build a social network web app using django.
what i need is, when a user create a post it gets updated on feed without reloading the whole page as real time database works on firebase.
do i need to use django channels for that or ajax?

cold anchor
#

either of those would work

native tide
#

this function based view

#

def profile(request, pk):
    user = Person.objects.get(id=pk)
    context = {
        'user': user,
        'title': 'Profile'
    }
    return render(request, 'index/profile.html', context)
#

i am trying to convert to a class based view

#

using DetailView

#

but i don't know where to pass pk to now

lavish plover
#

Hi, somebody knows how to redirect to a certain URL with extra arguments?

native tide
#

I have this at the moment ```python

class Profile(DetailView):
model = Person

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['user'] = Person.objects.get(id=pk)
    context['title'] = 'Profile'
    return context```
#

but pk is undefined

#

Hi, somebody knows how to redirect to a certain URL with extra arguments?
@lavish plover do you mean something like this python return redirect(f'http://localhost:8000/profile/{new_user.id}/')?

#

man, I learnt Flask and I loved it. I'm now learning Django and I love it even more... Django hype train, it really is the wave...

lavish plover
#

Well, if the user goes to a restricted url

#

Through the url bar or something

native tide
#

I learned Flask too but i don't like it as much as i like Django

lavish plover
#

I want to redirect it to index

#

But index only takes request as an argument

#

I've read that if a view has n number of args, every argument should be added to the url

#

Idk if I'm wrong

#

Basically, redirect to index to show an error message, without including that message in the url

#

And @native tide what's the difference between function based and class based views?

native tide
#

You are kinda limited with function based views, with class based you are not.

lavish plover
#

I think I'll create a 403 page smh

#

What are the advantages over function views?

native tide
#

with class based views you can inherit methods and attributes from other views. You can't do that with function based views.

lavish plover
#

damn

native tide
#

I learned about Class based views a couple of hours ago. And i told you my experiences.😀

#

So,
return redirect(f'http://localhost:8000/profile/{new_user.id}/')
would redirect to /profile/{userid}

But, wouldn't anyone be able to view that page?

#

And i think i'll be using Classbased views quite often from now on.

#

yes

#

and yes

#

In the project i am creating at least, I am allowing anyone to view anyone

#

I guess you can then use session management with Django to authenticate that, but I've not learnt that yet.

#

Ah I see.

lavish plover
#

Do you guys think Django and Flask will always be neck to neck?

native tide
#

Oh lets make a fun comparison

#

class-based views is Django. function-based views is Flask

lavish plover
#

Also, if I wanna create a 404 page
if the view is like this:
def 404_view(request, error_message):

#

fck

#

Okay anyways

#

The url must contain somewhere error_message?

native tide
#

yes

#

like so url/<str:error_message>/

lavish plover
#

It would look kinda ugly but I guess it doens't matter

#

Thank you, dude

marble carbon
#

hmm u don't have to create a view

#

for 404

golden parrot
#
@app.route("/api/launcher/<api_request>")
def LauncherAPI(api_request : str):
    if api_request.lower() == "info":
        jsonFile = open("oskarsmc-launcher.json", "r")
        string = json.loads(jsonFile.read())
        string.update({"timestamp": time.time()})
        jsonFile.close()
        return string
    else:
        return "404", 404

apparently the code above is calling a dict when i run it through gunicorn3?

quick cargo
#

@golden parrot because you're returning a string probably

#

neesd to return a string

golden parrot
#

that doesn't make sense?

#

anyway, i managed to fix it by putting ```py
str(string)

instead of ```py
string
quick cargo
#

yeah because you're returning a dict

golden parrot
#

oh lmao

quick cargo
#

you should use json.dumps() to correctly escape it though

golden parrot
#

i was confused

#

okay ima do that right now

quick cargo
#

also look at json_response() i think it is with flask

golden parrot
#

actually it doesent matter for my use case because the .json file will always be safe

#

thanks tho

#

i wonder why it didnt bug out on my windows installation but did on gunicorn on raspberry pi os

#

hmm

quick cargo
#

@golden parrot no but i mean it will fuck up the returning data by doing str() like that

golden parrot
#

oh

#

ok then

#

confuses me more

native tide
#

no @golden parrot

#

pretty sure you gotta jsonify it with jsonify()

golden parrot
native tide
#
password = forms.CharField(label="Enter a password, make it strong!", widget=forms.PasswordInput)
    confirm_password = forms.CharField(label="Confirm your awesome password", widget=forms.PasswordInput)```
#

In Flask there's a validator EqualTo which checks that confirm_password equals password. Is there any such thing in Django, or must I make the user post the request and then manually check if they are equal?

marble carbon
#

here

native tide
#

Thanks 👍

vestal hound
#

@gaunt berry i think mongodb is easier and you can scale it up verry much better if you need
@dusk rose you can horizontally scale Postgres with read replicas (read) and partitioning (write).

#

and MongoDB being "easier" is kind of like dynamic typing being "easier" - part of it is because certain errors are deferred to runtime.

#

Whats better for dynamic web apps, PostgreSQL or MongoDB?
@gaunt berry both may be applicable depending on your data.

#

in general, SQL will work.

naive oar
#

Hi All, I have a Django question that I'm having trouble with. This is the error "get() returned more than one Detail -- it returned 2!" I'm trying to use get_object_or_404 to return multiple values, is there something else that is equivalent to get_object_or_404 but for multiple objects? or what's my best option?

vestal hound
#

Hi All, I have a Django question that I'm having trouble with. This is the error "get() returned more than one Detail -- it returned 2!" I'm trying to use get_object_or_404 to return multiple values, is there something else that is equivalent to get_object_or_404 but for multiple objects? or what's my best option?
@naive oar how many objects do you want?

#

the point of get or 404 is that there should only be two possible results: one or none

naive oar
#

I thought I can pull a list from the entire table

vestal hound
#

you can, but the point is

#

get or 404 has behaviour specifically for the case where no object is found

#

it feels like what you want to do is just get a QuerySet of instances that fit some criteria

naive oar
#

this is what I'm trying to do, I want to build a parts site and depending on what vehicle brand the user picks it displays the entire table related to that brand

vestal hound
#

"entire table" = ?

#

what are your models?

naive oar
#

sorry more like everything that is linked to that specific brand

vestal hound
#

what is "everything"

#

you're going to need to be specific here

#

like I said, what are your models?

naive oar
#

class Detail(models.Model):
wheelImage = models.ImageField(upload_to='images/')
name = models.CharField(max_length=255)
name_href = models.CharField(max_length=255, default = "")
model = models.CharField(max_length=255)
sizes = models.CharField(max_length=255)

vestal hound
#

oh lord

#

please don't mix camel case and snake case

#

so where's the brand?

#

that can't be your only model

naive oar
#

I'm going off name_href

vestal hound
#

okay

#

walk me through your thought process

#

I'm not seeing what the relationship is

naive oar
#

ok

#

sorry forgot to inculde this

#

class Logo(models.Model):
brandLogo = models.ImageField(upload_to='images/')
name_href = models.CharField(max_length=255, default = "")

vestal hound
#

I'm still not seeing it

#

where's the brand

#

what is name_href meant to represent

naive oar
#

so I have the logo and using the name_href to connect with the detail model

vestal hound
#

so you're saying

#

that Logo actually represents a brand?

#

and when the user picks a Logo

#

you want to get the name_href

naive oar
#

name_href is meant to be a slug

vestal hound
#

and find all the Detail entries which have the same name_href

#

and display them?

naive oar
#

so on one page the logo is displayed with the brand logo image and the name_href so when the user selects that logo it will link to the name_href on the Detail model and display all parts associated with name_href

vestal hound
#

and find all the Detail entries which have the same name_href and display them

#

so is this correct?

#

what are the "parts" then?

naive oar
#

so it could be Toyota image with name_href=toyota on Detail it will connect with name_href=toyota and display name, model,sizes,

vestal hound
#

how are they represented?

#

with Detail, right?

naive oar
#

yes with Detail

vestal hound
#

okay, so first

#

if you're trying to describe what you're doing

#

use your model names.

#

if you keep saying "part" but show a model named Detail, everyone is going to wonder

#

what the difference is

#

whether they're two different things

#

or not

#

and it's super confusing.

#

second

#

your fields are set up wrongly, I think

naive oar
#

so sorry about the confusion

vestal hound
#

I believe what you want is actually a foreign key

#

have you heard of the concept?

#

actually, go back a bit

naive oar
#

yes I've heard of that

vestal hound
#

can a Detail be linked to multiple Logos?

#

i.e. say you have one Toyota Logo and one Honda Logo; can you have a Detail that belongs to both/

naive oar
#

No only one Logo

vestal hound
#

okay

#

so what you have is a one-to-many relationship

#

first, I suggest changing your Logo model name to Brand

#

next, in your Detail model you can have a field like this: brand = models.ForeignKey(Brand, related_name='details' on_delete=models.CASCADE)

#

if you set it up this way

#

say you have an instance of a Brand called brand

#

and you want all the Details associated with it

#

you can just do brand.details

#

and pass that to your view.

#

does everything I've said make sense?

#

or is there any part that is unclear

naive oar
#

ahh okay

#

so in the view what would be the best way to return it?

vestal hound
#

as for why not use that slug field matching approach thingy:

  1. Referential integrity. A foreign key approach guarantees that if a Detail references a Brand, that Brand always exists.
  2. Efficiency. Joining on an indexed foreign key is a lot faster than matching your entire table on a string field.
  3. Readability. Because this is the most common and idiomatic approach, it is the one that will help people reading your code understand most quickly what you want to do.
#

so in the view what would be the best way to return it?
@naive oar well, that depends on your template, right?

#

show your get_object_or_404 call

naive oar
#

okay okay

#

this is what I currently have.

#

def detail(request, name_href):
detailparts = get_object_or_404(Detail, name_href=name_href)
return render (request, 'allmanufacturers/detail.html', {'detailparts':detailparts})

#

it makes sense on using a foreign key

vestal hound
#

uh

#

no, because you want to get multiple Details, right?

#

I suggest

#

you pass the logo ID to your view instead.

naive oar
#

this is definilty growing pains

vestal hound
#

then you can do details = Detail.objects.filter(logo_id=logo_id)

#

okay I think

#

you're a bit confused

#

about how Django models work

#

have you gone through the Django tutorial?

naive oar
#

yes I have gone through the Django tutorial

vestal hound
#

okay

#

so get_object_or_404 always returns a single object.

naive oar
#

I'm still trying to get the hang of this.

vestal hound
#

but since you have multiple Detail objects associated with a Logo

#

what you need is a QuerySet

#

which is basically a collection of objects

#

that fits your criteria

#

in this case, "belonging to the same Logo that the user chose"

#

make sense?

naive oar
#

yea you mentiond that, I thought you asked me on what I have as the view?

#

sorry maybe I got confused on that part

vestal hound
#

yea you mentiond that, I thought you asked me on what I have as the view?
@naive oar yup, we need to see what you have in the view to change it

#

anyway, your original idea was "get the name_href of the Logo and match that with the Details

#

so now I'm suggesting

#

get the id instead

naive oar
#

but with a QuerySet right?

vestal hound
#

uh

#

you would return a QuerySet, yes

naive oar
#

got it

vestal hound
#

yeah

#

don't worry about not getting all this, though

#

it's a lot to take in

#

and please remember to use snake_case

naive oar
#

okay I'll clean it up to snake_case

#

Sometimes this can get really discouraging.

#

I really do appreciate your help.

#

I have a lot of reading to do and a lot of things to break in order to grow. 🤣

vestal hound
#

you're welcome

#

it's a fun journey

#

I only started on Django a while ago

#

there are a lot of things you kind of need to know to understand the whole system

#

like the theory behind RDBMS

naive oar
#

you make it sound so easy?

vestal hound
#

the request-response cycle

#

etc.

#

everything is connected

naive oar
#

yea I'm realizing that now

marble carbon
#

about the naming

#

was just talking about it a while ago

sweet mantle
#

Hello I would like to ask if some one could explain to me why my Django site isn't loading the correct page.
This is the code that is in {prokect} urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls')),
]
```It should lead to here
```Python
urlpatterns = [
    path('', views.home, name='blog-home'),
]

urlpatterns = [
    path('about/', views.about, name='blog-about'),
]
```Then this should go here and load the page
```Python
def home(request):
    return HttpResponse("<h1>You have landed at home</h1>")

def about(request):
    return HttpResponse("<h1>You have landed at about</h1>")
#

But instead it loads the 404 page

stable kite
#

@sweet mantle

urlpatterns = [
    path('about/', views.about, name='blog-about'),
    path('', views.home, name='blog-home'),
]```
versed python
#

you're overwriting your urlpatterns variable

halcyon bronze
#

I need some ideas on how to solve a small personal project

project is :

There is a site which gives training like tutorials, I want to make program in python which will visit each tutorial page and click a specific button so that I finishes the lesson and I want it to do it automatically, like automation and I should show me the last page of the tutorial page.. How can I do this? please help

stable kite
#

@halcyon bronze use selenium

halcyon bronze
#

using selenium for like web automation?

stable kite
#

yes

halcyon bronze
#

so, how should I do it like do I need to program a web crawler or something else?

#

I am new to programming learning it

stable kite
#

no it's a framework it will do the work you want

halcyon bronze
#

ok, so what I have to do in order to use selenium? is there any guide for it?

#

I don't know much of testing and all those stuff

stable kite
#

just see it's documentation

halcyon bronze
#

ok

#

thank you

stable kite
hexed zenith
#

I'm building a flask web app and I'm trying to build an infinite scroll of content. I'm getting that content from a python function but the scroll is built with js. Anyway to have the two languages communicate with each other?

warped timber
#

@hexed zenith ajax calls

#

js makes a request to an endpoint

#

then your python code responds

hexed zenith
#

oh interesting. @warped timber thanks

marsh canyon
#

u need to look at fetch() api at the js side and returning json content(mostly) with ur flask views or even flask restful can help(if not overkill) @hexed zenith

worn rapids
#

yooo if any of u are students at a uni, I've been making a Course API. I've added support for three schools with two more on the way! If anyone wants their uni supported, or wants to help out, hmu!

https://docs.coursecake.tisuela.com/

tools: FastAPI | SQLAlchemy | Beautifulsoup

tulip jasper
#

Any with Django knowledge

marsh canyon
#

u can put down ur question here and people with relevent knowledge will assist you @tulip jasper

tulip jasper
#

Ok thanks @marsh canyon

thick cove
#

Could anyone explain how I'd go about using apache2 as a reverse proxy for 2 of the subdomains to the domain apache2 is already serving?
I have a async API + cdn That I need to host on the subdomains, but apache2 does not support ASGI so I need to pass the request on to daphne then my app

native tide
#

Hi, is there anyone with experience on selenium and python? I need to scrape Instagram

thick cove
#

Scraping instagram is against their TOS, use their API

lavish prismBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious/inappropriate or be for graded coursework/exams.

native tide
#

I knew with Selenium it was kind of possible...

#

there also on git hub some repos about it. Can you tell me more?

versed python
#

they're illegal

#

obviously

#

I don't think any small operations will land you in trouble. But that being said, see rule 5 above.

native tide
#

Thanks @versed python for the info 🙂

weak chasm
versed python
#

TIL. Is this robots.txt present for all websites? @weak chasm

vestal hound
#

TIL. Is this robots.txt present for all websites? @weak chasm
@versed python not necessarily

#

but most big sites will include it

#

it's more a convention thing

weak chasm
#

[django]
can someone explain what this regex(?) is doing? found in urls.py

        name='complete'),```
vestal hound
#

can someone explain what this regex(?) is doing? found in urls.py

        name='complete'),```

@weak chasm "match any URL that starts with complete/ and a string (call this backend) that does not contain a slash, followed by the string contained in extra. make backend available as a captured group.

#

at least, that's how I read it

#
>>> import re
>>> extra = 'something'
>>> regex = re.compile(r'^complete/(?P<backend>[^/]+){0}$'.format(extra))
>>> regex.search('complete/goes_into_backendsomething')
<re.Match object; span=(0, 35), match='complete/goes_into_backendsomething'>
>>> regex.search('complete/goes_into_backendsomething').group('backend')
'goes_into_backend'
#

if you mean why, I'm not very sure

weak chasm
#

okay...i'm thinking i might have to use it. trying to figure out why my urls.py changes the url path before i can grab the url in the url box from a httpresponseredirect.

native tide
#

How can I have error handling in my django form?

sullen basalt
#

Hi, I'm using Django and am trying to make an API call but when i print r It returns 'None' can anyone help me?

    def get(self, request):
      r = request.GET.get('https://www.reddit.com/r/terraria/about.json')
      print(r)```
quick cargo
#

@sullen basalt you know that's for url args

#

Not for fetching data from a url

versed python
#

Also, it seems like you're using the django request object. This object can only communicate with the django server, not outside it. @sullen basalt

#

Looks into requests module which can do this for you

sullen basalt
#

Well that fixed my issue, thank you!

heady scroll
#

Any thoughts of the justdjango.com site for familiarizing oneself with Django?

I’m enjoying what I’m learning so far and the lessons look pretty extensive

Was wondering if anyone else had any thoughts from trying it

#

Asking because my free trial has or will expire (I just know it’s sometime this week)

wide sphinx
#

hey

keen summit
#

i need some guidance in finding a django package for my need

versed python
#

need for description

keen summit
#

i am looking for a django package that let me add social accounts per object rather than user himself.

example i am a userX, in my app i have model company, each company have there own social accounts, so i am looking for this behaviour that userX can attach social accounts to companies object.

#

any thoughts ?

jovial storm
#

How do I make not plain text for GET request in flask?

#

sorry im stupid

#

help me

versed python
#

your question makes no sense. Elaborate

lethal orbit
#

You mean return a template render?

#

Use the rendering function.

warped timber
#

or do you mean using a different mime type, like for images?

#

return Response(resp. mimetype="image/png")

lethal leaf
#

Anyone good with Heroku? I'm having some weird issues that I can't figure out.

coarse agate
dense slate
#

Is there a reason why my form, when searching/filtering a queryset, throws an "already exists" error if they type the exact username they are searching for but not if they only put part of the name?

#

I'm not sure why it's doing a check to see if the field exists.

heady scroll
marble carbon
#

they have a youtube channel as well

#

p good

solar ridge
#

Is there a way to change the django.contrib.auth.models.User __str__ function ?

#

I want to return the first_name field, instead of the default username

versed python
solar ridge
#

Thank you, i'll have look into this method

uncut spire
#

i have a tricky session problem if someone is keen: let's say i use auth0 to manage sessions for people logged into my site, but then i have another service managing some 3rd party external session. a user's auth0 session goes stale, but they are still logged in via the aforementioned service to the 3rd party platform. right now my idea is to just pass the auth0 token to the service each time while caching the issue date from the session, check if current_auth0_token_issue_date > previously_cached_issue_date + configured_auth0_staleness_TTL and revoke the 3rd party token--can anybody think of a cleaner way of doing this? seems pretty jank but i'm struggling with finding a better method

native tide
#

Does anybody know why Django is not finding my css file, with this code?

#

This is the error:

[23/Sep/2020 16:32:07] "GET /static/register.css HTTP/1.1" 404 1662```
honest dock
#
{% load static %} 

you need this

#

and to load static files you will need to do this:

#
href="{% static 'path of css' %}"
native tide
#

@honest dock Is the path of the css, relative to the HTML file, or from the project directory?

honest dock
#

You should use the settings.py in the main folder and define where is the static file for the project

#
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    os.path.join(BASE_DIR, "media"),
]

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn ')

I use this

native tide
#

what is the best library for managing and deploying hundreds of databases for distributed workload?

our arsenal right now:

  • flask
  • sqlalchemy
  • pscopycog2
  • pygal
  • jinja2
  • flask-caching
honest dock
#

and if you're in development mode, add this to your urls.py file in main as well:

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
quick cargo
#

@native tide you're only mentioned 1 db driver sooooo

native tide
#

all is postgres

#

@honest dock Thanks 🙂 This solved it for me:

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    os.path.join(BASE_DIR, "media"),
]```
honest dock
#

so in your project, you will have later on a directory called static, inside of it should be a directory called css

coarse agate
#

I'm running a Flask app on an Ubuntu 16.04 VPS using Apache, nginx & Gunicorn.
When I run the same Flask app on my local machine (just using python website.py) it runs fine, but when on the VPS it fails at the 4th & final API POST request.

API I'm calling: Roblox
Response code: 429
Response headers:

{'content-length': '51', 'expires': '-1', 'roblox-machine-id': 'CHI1-WEB5027', 'pragma': 'no-cache', 'cache-control': 'no-cache', 'date': 'Wed, 23 Sep 2020 12:29:48 GMT', 'x-frame-options': 'SAMEORIGIN', 'content-type': 'application/json', 'p3p': 'CP="CAO DSP COR CURa ADMa DEVa OUR IND PHY ONL UNI COM NAV INT DEM PRE"'}

Cannot find ratelimit documentation online, nor anything about why that response doesn't contain a Retry_After

honest dock
#
<img src="{% static 'img/apple_logo.png' %}"

And here is an example of how you will use it later on

quick cargo
#

@native tide i mean if you want performance you dont use flask or psycopg2

#

asgi's and asyncpg™️

native tide
#

aight

coarse agate
#

Anyone? ^^^

native tide
#

Is there any way to assign the label a class, in Django?

brittle basin
#

Hello, I'm trying to deploy a simple flask app I made to Heroku. When I deploy, the logs at Heroku say it cannot find a user nginx

#

This is my dockerfile - as you can see I've added user nginx, but no effect

#

Any idea why?

uncut spire
#

the USER command does not add a user to the container, i believe. i think what you want is RUN useradd -ms /bin/bash nginx or to run it as an existing user

#

CMIIW

#

***then you need USER nginx, after running useradd @brittle basin

brittle basin
#

***then you need USER nginx, after running useradd @brittle basin
@uncut spire Like that?

uncut spire
#

assuming ubuntu and a valid bash in that location then yes i think that's right

#

post the output if not and i'll help you

brittle basin
#

post the output if not and i'll help you
@uncut spire Thank you mate 🙂 I added the line, but it says it is already added

uncut spire
#

uh

#

and previously it said user not found thinkmon

brittle basin
#

and previously it said user not found thinkmon
@uncut spire This happens in later point

#

The already exists message appears sooner

uncut spire
#

it's just one container yeah?

brittle basin
#

Yep

uncut spire
#

how are you running nginx in there

native tide
#

Hi guys this is my form. Could you guys lead me into a direction to help authenticate the username, to make sure it is unique? Should I check if the username exists in my DB on every post request, or is there an alternative option?

#

Django btw

brittle basin
#

how are you running nginx in there
@uncut spire Well basically I call "heroku container:push web -a <app_name>" to create the container and "heroku container:release web -a ourtale" to start it. The nginx starts in the entrypoint script which is inside that image

sleek pecan
#

Is anyone here familiar with using DataTables?

uncut spire
#

so the user nginx seems to exist within the container, but not on the deploy target which i would guess is the source of that mix up

#

do you wish the container itself to host nginx?

#

so I've only used heroku once many years ago, i believe it's difficult to run images as root, is that still true?

#

i'd try following up there @brittle basin or changing your deployment strategy, as it looks like what you're trying to do is run an nginx image as root on heroku

atomic hill
#

Getting a 'Syntax Error' anyone can help??

wide leaf
#

i want to get value of cashamount where user = FrenchFries#8854
how do i do it?
mysql

quiet solstice
#
SELECT cash_amount FROM tablename WHERE USER = FrenchFries#8854```
#

You should probably change your system to use id's, since usernames can be changed.

versed python
#

@atomic hill everything looks fine. Maybe vscode added some tabs or spaces randomly?

#

pip install autopep8 and autopep8 -ri . in the project root will take care of formatting issues if any

brittle basin
#

i'd try following up there @brittle basin or changing your deployment strategy, as it looks like what you're trying to do is run an nginx image as root on heroku
@uncut spire Thanks! I'll try that

neon elbow
#

Would this be the right channel to talk about web scraping?

#

I'm curious if anyone familiar with Scrapy has used google cache for scraping before. I was surprised to see there wasn't an extension to make scrapy use it. So, I'd like to write one so you can easily set a setting like "GOOGLE_CACHE_ENABLE": True

atomic hill
#

it was a problem with the enviroment

neon elbow
#

Not sure if an extension can modify the URLs to be scraped though.

marble carbon
#

heroku can run docker containers too what

wide leaf
#
            @bot.command(pass_context=True)
            @commands.has_role(680261746707267593)
            async def addcash(self, usercash: discord.Member, amountcashadd: int):
                # TODO actually code this command
                cashamountdownload = MySQLConnection.mycursor.execute("SELECT cash_amount FROM Money WHERE USER" == str(usercash))
                MySQLConnection.mycursor.execute("UPDATE Money SET cash_amount = %s WHERE USER == %s", (cashamountdownload + amountcashadd, str(usercash)))
                MySQLConnection.db.commit()
                cashprnt = int(cashamountdownload) + amountcashadd
                add_cash_embed = discord.Embed(
                    title="Adding of Cash Successful",
                    description=":white_check_mark: Added **$" + str(amountcashadd) + "** to " + str(usercash) + "'s cash balance \
                    \n cash balance is now **$" + str(cashprnt) + "**",
                    colour=discord.colour.Color.green()
                )
                add_cash_embed.set_author(name=str(usercash), icon_url=usercash.avatar_url)
                await self.send(embed=amountcashadd)

it says

raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
#

how do i fix?

native tide
#

hi
i have some buttons on a page and i want to add a new class tp each of them with jquery one by one when clicked but what i ve tried isnt working, any idea why?

.turnred{
  height: 100px;
  width: 100px;
  text-align: center;
  border: 5px solid black;
  border-radius: 50%;
  background-color: red;
}


var cells=document.querySelectorAll('button');

for (var i = 0; i < cells.length; i++) {
  $('cells[i]').on("click",function() {
    $('cells[i]').this.addClass('turnred');
  })

}
past cipher
#

do you think sending a youtube channel with videos of me coding, and explaining how I'm doing things to an employer would benefit me? I've been making videos, and I've realised when I am talking it through on video and explaining it, I find writing the code so easy. When there is a bug, because I am explaining it on video, and fixing shit real quick. Just wondering if an employer would even take the time to watch these videos ?

wide leaf
#
            @bot.command(pass_context=True)
            @commands.has_role(680261746707267593)
            async def addcash(self, usercash: discord.Member, amountcashadd: int):
                # TODO actually code this command
                cashamountdownload = MySQLConnection.mycursor.execute("SELECT cash_amount FROM Money WHERE USER" == str(usercash))
                MySQLConnection.mycursor.execute("UPDATE Money SET cash_amount = %s WHERE USER == %s", (cashamountdownload + amountcashadd, str(usercash)))
                MySQLConnection.db.commit()
                cashprnt = int(cashamountdownload) + amountcashadd
                add_cash_embed = discord.Embed(
                    title="Adding of Cash Successful",
                    description=":white_check_mark: Added **$" + str(amountcashadd) + "** to " + str(usercash) + "'s cash balance \
                    \n cash balance is now **$" + str(cashprnt) + "**",
                    colour=discord.colour.Color.green()
                )
                add_cash_embed.set_author(name=str(usercash), icon_url=usercash.avatar_url)
                await self.send(embed=amountcashadd)

it says

raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
#

how would i fix this?

native tide
#

How can I check if a username is already taken? This doesn't work.

#

User.objects.filter(username=username) doesn't return None when a random username is passed

#

oh nevermind found the docs for it

#

if the queryset is empty .exists() returns False

marble carbon
#

yeah

native tide
#

But now... the RegexValidator...

#

How tf does that even work

#

Maybe it was a bad idea making my own django forms after all

marble carbon
#

Regex Validator?

#

for username?

#

why don't u just use UserCreationForm instead

wide leaf
#

i have this ```python
cashamountdownload = MySQLConnection.mycursor.execute("SELECT cash_amount FROM Money WHERE moneyuser =" + str(usercash))
print(cashamountdownload)
MySQLConnection.mycursor.execute("UPDATE Money SET cash_amount = %s WHERE moneyuser = %s", (cashamountdownload + amountcashadd, str(usercash)))
MySQLConnection.db.commit()

#

but it says

#

Command raised an exception: ProgrammingError: 1054 (42S22): Unknown column 'FrenchFries' in 'where clause'

hexed zenith
#

trying to use the fetch() api to GET a json from a flask function. Is that possible?

warped timber
#

check your server logs for exceptions

#

@hexed zenith

wide leaf
#

i need help

#

look above

warped timber
#

@wide leaf don't use string concatenation; use parametrized queries

#

what's usercash?

#

also

#

!traceback

lavish prismBOT
#

Please provide a full traceback to your exception in order for us to identify your issue.

A full traceback could look like:

Traceback (most recent call last):
    File "tiny", line 3, in
        do_something()
    File "tiny", line 2, in do_something
        a = 6 / 0
ZeroDivisionError: integer division or modulo by zero

The best way to read your traceback is bottom to top.

• Identify the exception raised (e.g. ZeroDivisionError)
• Make note of the line number, and navigate there in your program.
• Try to understand why the error occurred.

To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.

wide leaf
#

how do i do that? @warped timber

vestal hound
#

trying to use the fetch() api to GET a json from a flask function. Is that possible?
@hexed zenith you mean a route?

#

do you think sending a youtube channel with videos of me coding, and explaining how I'm doing things to an employer would benefit me? I've been making videos, and I've realised when I am talking it through on video and explaining it, I find writing the code so easy. When there is a bug, because I am explaining it on video, and fixing shit real quick. Just wondering if an employer would even take the time to watch these videos ?
@past cipher try #career-advice, but I would say make your videos for a wider audience; your channel can be one of the things in your portfolio.

native tide
#

a

#

a

#

a

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @native tide until 2020-09-23 21:57 (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

hexed zenith
#

@vestal hound yeah but I think i got it

warm nymph
#

hey guys, HEROKU QUESTION: I have a problem with updating the requirements.txt file when deploying, it simply doesn't update from local

vestal hound
#

hey guys, HEROKU QUESTION: I have a problem with updating the requirements.txt file when deploying, it simply doesn't update from local
@warm nymph are you sure you modified the right file?

warm nymph
#

i'll send a few screenshots to show what I mean, btw i'm new to heroku, so please bare with me

vestal hound
#

i'll send a few screenshots to show what I mean, btw i'm new to heroku, so please bare with me
@warm nymph please send stuff as text

warm nymph
#

it seems to be more of a hassle for the channel, since it has a long output

#

are you sure?

vestal hound
#

what do you wanna send?

#

I mean

warm nymph
#

showing requirements.txt on local, and on the server

vestal hound
#

once you push

#

it should reinstall everything

warm nymph
#

yeah but it doesn't for some reason, idk. the requirements,txt file doesn't update

vestal hound
#

so you mean

#

the file on the server is different from the one on your local?

warm nymph
#

yes

vestal hound
#

ah, okay

warm nymph
#

i connected github to heroku and tried again, heroku still doesn't update, even though github did

vestal hound
#

how do you know what's on the server?

warm nymph
#

heroku run "cat requirements.txt"

vestal hound
#

okay, fair enough

#

hm.

#

you checked the git commits?

warm nymph
#

I checked github commits to verify requirements.txt updated as I intended

#

i just checked and the build didn't succeed, i'll try to fix it and come back if I need any help

#

it did succeed in previous times though, it didn't because I changed the python version

vestal hound
#

i just checked and the build didn't succeed, i'll try to fix it and come back if I need any help
@warm nymph yup, that must be why

#

it would be a truly horrific thing if your code updated but requirements.txt didn't 😉

warm nymph
#

i only updated the requrements.txt file to fix the problem

vestal hound
#

hm

#

why are you using 3.6?

#

any reason?

warm nymph
#

it raised an error when i used 3.8

#

I thought that might be it, so i downgraded

vestal hound
#

ah, I see...

#

hm

#

it's generally better to use newer versions unless you have a specific reason

#

but yeah, anyway, I think you found the answer to your original problem

warm nymph
#

I probably need to give runtime.txt as 3.8.x to resolve it maybe'

#

thank you for the help 🙂

vestal hound
#

beats me

native tide
#

Django or flask? 👀

vestal hound
#

about the 3.6 thing

#

Django or flask? 👀
@native tide depends on nature of project and your level of experience

warm nymph
#

Django or flask? 👀
@native tide flask

native tide
#

I actually started with django not too long ago and I really like it

warm nymph
#

it depends on what you want to do, I just want to create a simple api

vestal hound
#

if you have to do anything with a database

#

Django starts to look more attractive

#

until you are experienced enough with SQLAlchemy or something similar

#

to make it worth it

warm nymph
#

it's a small app, i wanna start with something simple to minimize variables

#

is a rest api with authentication a thing? I don't want everyone being able to access the api, just authenticated users

native tide
#

I heard people say django is difficult, and it really isn’t.
I knew nothing about it and just by building one project I learned a lot

vestal hound
#

is a rest api with authentication a thing? I don't want everyone being able to access the api, just authenticated users
@warm nymph yes

#

wait

#

what do you mean by "a thing"

#

it's a small app, i wanna start with something simple to minimize variables
@warm nymph IMO Django is actually simpler

#

because it's opinionated

native tide
#

I fell in love with it lol ^^

warm nymph
#

you may be right idk, I just have a bad experience from when I was a noob

@warm nymph IMO Django is actually simpler
@vestal hound

#

what do you mean by "a thing"
@vestal hound I haven't looked it up yet, I was just wondering if it's not too complicated to implement

#

it doesn't sound too hard for a simple application, checking http headers and such right ?

vestal hound
#

for Flask?

warm nymph
#

yes\

vestal hound
#

I have no idea, I don't use it

#

but for Django it's more or less built-in

warm nymph
#

and for django?

vestal hound
#

okay so the thing about Django is

#

yes, it is pretty complex

#

so it's best (IMO) for people who are experienced with Python

#

but new to web dev

#

Flask is probably easier for people who are new to both

warm nymph
#

I see

#

what about light weight api, why django over flask? opinionated? how is it opinionated in that regard

vestal hound
#

what about light weight api, why django over flask? opinionated? how is it opinionated in that regard
@warm nymph well, it has its own ORM

#

and templating system

#

and authentication methods

#

it handles some aspects of security

#

it has its own method of testing

#

etc. etc. etc.

#

in short, the answer to many questions like "how do I do <x> in Django" is "Django's way"

#

on the other hand, for Flask it's more like "find another library to do it"

#

what about light weight api, why django over flask? opinionated? how is it opinionated in that regard
@warm nymph what is "lightweight" to you?

#

requests/s?

warm nymph
#

I see.

#

wouldn't flask teach you more maybe in that regard? different libraries, probably more elaborate syntax? but a larger headache of course

vestal hound
#

wouldn't flask teach you more maybe in that regard? different libraries, probably more elaborate syntax? but a larger headache of course
@warm nymph depends on what you wanna learn...?

#

Flask does more or less one thing: routing URLs to functions

warm nymph
#

right

#

I want to learn how to structure an application, unit test it and so on

vestal hound
#

Django imposes its own structure

warm nymph
#

thank you for the input, good night 🙂

honest dock
#

picking_sites/?q=y

{% url 'picking_sites' q as picking_sites %}
{% url 'picking_sites' as picking_sites %}

Heya, I was wondering how I can use the url picking_sites with a query as variable in django template

timid bluff
#

hi guys! im new in Django. i got problem when i use postgresql. (createdb: could not connect to database template1: FATAL: Peer authentication failed for user "username"
). i tried to change the pg_hba.conf file and restarted but it didnt work. can you guys help me(i'm using Debian).Thanks! Have a good day!

nimble birch
#

why does a website need a backend, why not just talk directly to the database from the front end?

proper hinge
#

One reason is security

#

If the database was accessible via the front end directly, then users could perform arbitrary queries.

#

Any any client-side checks you put in place to prevent that could easily be patched out and circumvented.

marble carbon
#

if only all that backend did was communicating with the database

#

our jobs would be much more easier

stable kite
#

which is best ui framework for react?

thorn parcel
#

is that a python question?

warped timber
#

@thorn parcel this channel isn't only for python

thorn parcel
#

well then

versed python
#

see sidebar for more info

marble carbon
#

is there a Frontend channel?

#

or offtopic is the suitable channel for this? 🤔

versed python
#

This channel IS the frontend channel

#

Help with web technologies such as Flask, Django, HTML, CSS, and JS.

vestal hound
#

yeah

#

I mean if you wanna ask about, say, how to fix a Redux problem

#

maybe it would be off-topic

#

but in general frontend stuff goes here IME?

native tide
#

ELI5 time:
What is Gunicorn?

marble carbon
#

wsgi server

#

watch this, sums it up real nice

native tide
#

Thank you 🙂

jovial storm
#

and to make get request return

requestdata.var1
>>> value1

requestdata.var2
>>> value2
shell heath
#

oh ye*************

#

***oh ***

native tide
#

Does anyone know how to pass data from a React form to django?

vestal hound
#

Does anyone know how to pass data from a React form to django?
@native tide POST

#

to your Django route

native tide
#

Thanks. So they'll send a POST request to my route... and I'll validate through their info. Is it possible to send a request from Django -> React for this?

vestal hound
#

??

#

why would you send a request the other way

#

that would mean that the user is the server

indigo moth
#

.topic

fallow cairnBOT
#
**How has Python helped you in web development?**

Suggest more topics here!

native tide
#

Django lol

bright spindle
#

Whats the best possible way to allow users to create their own "custom address"

#

e.g. gofven leads to my profile page

#

putting it into the user class would generate heaps of null columns, not ideal for something that will be queried for search results

vestal hound
#

@bright spindle can you elaborate more

bright spindle
#

custom address would be optional

versed python
#

@bright spindle look into a python package. it's called faker. Might be what you want

bright spindle
#

could i make it myself

#

it doesnt seem that hard

versed python
#

faker is pretty extensive and can be used fpr other stuff

vestal hound
#

as in

#

you mean on your own domain, right?

#

like www.example.com is your domain?

versed python
#

but yeah you could create your own and or actually work on what you need to

bright spindle
#

no i mean i would want to know whats the best way to make a model for custom user address

#

within my domain

versed python
#

your domain name, you can prepend

bright spindle
#

e.g. people can set their address to, baconlover

#

and for people who havent set they will access it trough their userid

versed python
#

something like url = my_domain + fake.url()

bright spindle
#

eg. users/id/8592

#

nooooouu this is django

#

its not about the domain

#

its about models

#

i can make the domain

#

what would be the most ideal way to store it

#

cus if i put it in the usermodel it would generate ALOT of NULL values

versed python
#

maybe JSONField is what you need?

warped timber
#

make a new table called aliases or something and you only need 2 columns

versed python
#

or use postgresql ArrayFields

warped timber
#

or just add a column to your existing table for a username

bright spindle
#

JSONField would be pathetic,

#

aliases maybe

#

if i do an onetoonefield for the userclass and link it to the alias

#

that would work

versed python
#

yeah whatever works, works

bright spindle
#

well not quite

#

i mean yes

#

but u need performance

#

searching trough jsonfields and arrayfields is slow

#

making a dedicated table for it is alot quicker

#

and i dont need many NULL values

versed python
#

yeah that sounds like a better idea

vestal hound
#

perhaps I am missing something

#

but I don't really see

#

what the problem is

#

have a view bound to that route with a parameter

fickle fox
#

@native tide you can share it in here as well 😄

livid warren
#

I have created a registration page, and I need a unique id in it
This is the requirement -
Unique Id :- it would be a six digit alpha numeric combination unique if it isn’t entered by the
user it would be auto generated from backend.

native tide
#

is this the right area for django related stuff?

#

i used the blog option to start my django project. and i wonder why there is a urls.py in the main directory and an urls.py in the blog subdirectory

#

could somebody explain that, please?

#

sorry, i am wrong. the urls.py in the subdirectory was created by a tutorial

livid warren
#

I'm not really sure someone commented that I should look into this chat

#

Yes this is related to Django and I'm really confused in the unique id part

native tide
#

2 seperate topics

livid warren
#

Sorry?

native tide
#

my posting is independant from yours

native tide
#

I don't know if this is right channel to put this on but im trying to login to heroku in the VS code terminal and I get this error 'heroku : The term 'heroku' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1'

#

and i have check that the path is right

versed python
#

have you installed heroku?

lethal orbit
#

Whats the best possible way to allow users to create their own "custom address"
@bright spindle What framework? in Django, I would make it a SlugField ... verify that it is unique on save.

#

If users can have zero or one addresses, make it part of the user model and nullable.

#

If you can have more, make it with a foreign key to user.

vague mango
#

What's the standard design choice for displaying a success or an error response to the user from an api call on JS? Ideally the UI displays some sort of a loading screen or a loading message until receiving the response.

native tide
#

I'm having issues with Django's RegexValidator... Do you guys know why this won't work?

#
username = models.CharField(max_length=20, unique=True, validators=[RegexValidator(regex="^[a-zA-Z0-9]+([._]?[""a-zA-Z0-9]+)*$")])
#

I can still create users with forbidden characters...

versed python
#

did you makemigrations?

native tide
#

Yes I did

#

Makemigrations and then migrate

versed python
#

everything looks correct

#

did you check if you can input a string thats actually correct?

native tide
#

Yes... It adds users regardless of their name.

#

I'll send over the Django view, and the html.

#
def register(request):
    if request.method == "POST":  # If the form is submitted, giving a POST request but there is a validation error...
        form = registerform(request.POST)  # The form will re-appear, with the info from POST request shown in fields.

        if form.is_valid():
            username = form.cleaned_data.get("username")
            email = form.cleaned_data.get("email")
            password = form.cleaned_data.get("password")
            confirmed_password = form.cleaned_data.get("confirm_password")
            if models.User.objects.filter(username=username).exists() is True:
                messages.warning(request, "Username has already been taken")

            elif models.User.objects.filter(email=email).exists() is True:
                messages.warning(request, "Email already used to sign up.")

            else:
                user = models.User(username=username, email=email, hashed_password=confirmed_password)
                user.save()
                messages.success(request, "Your account has been created. Yay!")
                return redirect('/register')
    else:
        form = registerform()

    return render(request, 'users/register.html', {"form": form})
#

Well the HTML is just the form.

#

Btw, am I correct in saying if the Username goes against the RegexValidator - it will create a ValidationError?

#

Do you know if I can view the message of the ValidationError? That will help me troubleshoot it.

versed python
#

Do you know if I can view the message of the ValidationError? That will help me troubleshoot it.
@native tide {{ form.username.errors }}

native tide
#

Thanks @versed python , for the first message, do you think I should just write my own Regex validator in that case?

versed python
#

I have never used inbuilt validators myself, but thats just because I never needed them. Custom validators have always worked for me. If you wanna write them, see link above.

native tide
#

{{ form.username.errors }} isn't showing me anything, so I don't think the validator is working. So yeah, I think I will write my own validator. Thanks @versed python 🙂

versed python
#

@native tide {{ form.username.errors }}
@versed python This will generate a list, so you can loop using {% for error in form.username.errors %}

#

{{ form.username.errors }} isn't showing me anything, so I don't think the validator is working. So yeah, I think I will write my own validator. Thanks @versed python 🙂
@native tide I am not very sure about this, you might want to check how to output form errors in Django template lang.

native tide
#

Yeah... no errors being shown. Ok - I'll go ahead in trying to make my own regex validator.

#

I'll make a regex string such as "*$ ^%#" and loop over every character in their username, if any characters are in the regex string I'll raise a ValidationError and an error message

#

We'll see how it goes, thank you very much for your help 🙂

native tide
#
def CustomRegexValidator(string):
    regex = ["$ @!#%^&*()-+[]{}\/:;',.|`~£"]

    for characters in string:
        if characters in regex:
            raise ValidationError(message="Your username contains forbidden characters")
        break
#

This is my validator

#

but it still doesn't work.

quick cargo
#

because thats now how that works?

#

you need to actually use the regex module

native tide
#

@quick cargo but wouldn't my custom validator still work for anything which contained forbidden characters such as $, etc?

quick cargo
#

look through the link i sent

#

or actually why are you even calling this a regex?

#

its just a string with what i assume is the characters that arnt allowed?

native tide
#

Yeah, I see. I can implement that but I don't think it's an issue with the actual validator but its implementation

#

Maybe it's not a regex. It checks if a passed string has fordbidden characters

quick cargo
#

i mean atm you're doing if char in list not if char in string

native tide
#

Ok I changed it, to a string.

quick cargo
#

you need to remove that [] wrapping the string

fickle fox
#

guys is there anyone who knows hoiw to uplaod images in flask webapp

native tide
#

Yeah that's what I did. I actually made a really really stupid and blatant mistake, which I won't talk about 🙂 Thank you for the help

#

Let's just say I was stuck on that validation error for 1hr+ because I was writing the code in my models.py file and not my forms.py file 😂 oh lord

uncut spire
#

@fickle fox create a POST endpoint that extracts the image file using flask.request.files, make a curl like curl localhost:8080/upload' -F 'file=@images_directory/pic.png'

plucky tapir
#

With flask can I just use get for now as a base and then switch to post when I know a little more?

uncut spire
#

you can theoretically make a GET with a json body payload, so yes

#

note that they are primarily words for your (a human's) benefit, you can again theoretically (dont do this.) make an API entirely out of GET

#

but a POST has server semantics behind it that you'd be best off understanding first, the labels are only scary until you learn why they're there

native tide
#

hello i have a question

#

is there a counter code to count no of times a page has been reloaded

#

like it should end the cookies count if the url is changed and start over again

versed python
#

You could easily create a table for it

plucky tapir
#

Flask newbie here, how soon should I go from doing things “locally” to working on an actual web page
Also is there a big process to go from one to the other?

versed python
#

As soon as you can. The more you try, the more you learn.

plucky tapir
#

Should testing continue to be done locally? Can updating your flask python go directly to a webpage?

versed python
#

wdym?

#

You should test your webapp preferably with automated ones

native tide
#

ok i have past a cookies test case, i can clear the first 4 but las one throws error

#

because the response is now "you visited site 4 times" instead of 1

#

here's app code

#

what should i do??

#

it's a simple site visit counter

plucky tapir
#

I suppose I meant develop rather than test. I’m creating a webpage that someone else will using to create a database, currently using the local address to see my results/progress. That should be done on an actual webpage instead of local? Can I do my development locally until I am ready to push something periodically I n increments? @versed python

versed python
#

Yeah, version control is a thing. Idk if you know about it? git, github?

topaz widget
#

@plucky tapir Most things can be done locally. There is some stuff that can only be done on the server itself.

#

You should keep your server version synced with your local copy as much as possible.

#

What I mean by that is don't change your server files unless necessary--always just upload from local to change server files.

#

Hey does anyone know much about cookies with Django? I'm specifically wondering if all I use are the basic session cookies if I need to put a cookie notice on my website to comply with EU regulations.

plucky tapir
#

@versed python just going to start using it, but I have the idea of what you’re saying regarding there being branches used for stages.
But sounds good. I was wondering if there was like a big difference from developing locally in comparison to a webpage, but it seems like you can just push your code directly to the server and it should be the same

topaz widget
#

branches are not used for stages @plucky tapir

native tide
#

am disappointed

topaz widget
#

You would create a branch if you are "forking" your project @plucky tapir

versed python
#

yep you should keep your actual working code on master branch and develop on development branch

#

that way even if you fuck up development branch, you still have a working master

topaz widget
#

Hm, I thought the point of git is that if you fuck up you just return to a previous revision, not needing a wholly separate branch for development.

versed python
#

i prefer that method since I don't have to deal with git resets and all, since they mess up commit history sometimes, and cause conflicts too

native tide
#

i just set the counter to 0 for setcookie

versed python
#

but your method is valid too yeah

native tide
#

and it worked ....booom babay

#

ignore me please

topaz widget
#

Speaking of cookies, I need to figure out what to do about a cookie notice or if it's even necessary.

native tide
#

am just happy i solved it on my own

#

thanks anyways

topaz widget
#

Does anyone know how critical it is to have a cookie notice when all you're using cookies for is managing sessions?

native tide
#

you mean like permission to use cookies???

#

to notify user

topaz widget
#

Complying with EU regulations

#

yes

plucky tapir
#

@native tide good job

topaz widget
#

So I don't get fined.

native tide
#

idk .... am not making anything that big to care

topaz widget
#

Well, you never know. Someone could try to fuck with you.

#

And if you're operating outside of the law, you're easy to fuck with.

native tide
#

ordinary coders never get in trouble, it's only for big corporations

topaz widget
#

But if the law applies to small websites, too, you should really try to be compliant.

native tide
#

ok

topaz widget
#

Someone could have an axe to grind, so giving them the ability to bury that axe in you is not a good idea.

dark valley
#

whats javascript used for?

native tide
#

Any way to validate POST requests with flask?
I mean, my frontend is in react so it's fine but if someone sends a request using postman or the like, how do I validate that it doesn't have extra fields, wrong inputs etc?

#

from what I saw, flask_wtf and WTForms only work if you put {{ on your html }}

uncut spire
#

@native tide there's a few strategies there, note that the @spare ridge.route decorator allows you to specify methods=['POST']

#

another common idea is to use marshmallow to do validation