#web-development

2 messages ยท Page 75 of 1

fossil bay
#

But what you said makes sense, a single string probably won't convert to JSON well..

rigid laurel
#

test = request.json.get('name')

#

replace it with thta

#

the python bit

#

or in fact - just do print(request.json)

fossil bay
#

No error, but it printed None haha

#

127.0.0.1 - - [31/Jul/2020 15:18:38] "POST / HTTP/1.1" 405 - None 127.0.0.1 - - [31/Jul/2020 15:18:38] "POST /extract/ HTTP/1.1" 200 -

#

I'm thinking it's an issue with post

rigid laurel
#

hmmmm - I don't know enough jquery to be of any help I think. The last thing I can think to suggest is $.post( "/", { name: "John", time: "2pm" }, dataType="json" );. My only other suggestion would be ditching jquery and using the default JS fetch API

#
const data = { username: 'example' };

fetch('https://example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
  console.log('Success:', data);
})
.catch((error) => {
  console.error('Error:', error);
});
#

There's an example of posting some data with the fetch API

fossil bay
#

I'll give fetch a go! I've been trying this method for three days and can't for the life of me figure it out, haha. Thanks for the help, though!

rigid laurel
#

If you're having trouble with the fetch stuff. Ping me and I'll set up a minimum example to show the two parts working together

hallow parrot
#

Hello, everybody,
I recently finished a book on "Flask Web Development", it was very enriching. So I was able to familiarize myself with Flask and SQLAlchemy to build a small REST API.

I would now like to do a more consistent project, so I turned to OpenAPI to do the specification of my future API. So I generated the backend code in Flask with Swagger Editor but I'm having difficulties to make the link with SQLAlchemy. The generated models should not be touched in case of code regeneration, which is logical, but how can I define my columns for my database? I was thinking of inheriting this model or maybe creating a model only for the database, but in this case I don't see the interest of this code generator.
I have difficulties to define an interesting workflow. Has anyone ever built an API from the code generated with Swagger Editor and implemented persistence with SQLAlchemy?
I hope my question isn't too general...Thanks for the help

fossil bay
#

I FIGURED IT OUT!

#

So the route needed to be '/extract'

#

$.post( "/extract", { name: "John", time: "2pm" }, dataType="json" );

#

Which makes a ton of sense lol

rigid laurel
#

oh - haha. It's always a simpler problem than it seems to be

fossil bay
#

Honestly. I'll tell you what though, never gonna make that mistake again haha

rustic pebble
#

Hi, so I have the following function:

def get_user():
    data = get_cookie_data()
    if not data:
        return None
    else:
        discord_id = data['discord_id']
        print(discord_id)
        current_user = User.get(int(discord_id))
        print(current_user.username)
        return current_user
#

get_cookie_data() is this:

def get_cookie_data():
    try:
        token = request.cookies.get('user')
        return jwt.decode(token, read_file('./assets/public.pem'))
    except Exception as e:
        print(str(e))
        return None

I am using Stripe with sessions api, which basically lets you pay and redirects you back to the main website along with a code. When I am trying to register the user to the database I am calling the get_user() function, which occasionally returns None, meaning that there is not user logged in. In order for the user to pay it is obligatory for them to be logged in.
This is the route in which the error is being generated:

#
@app.route('/success')
def payment_success():
    session_id = request.args['session_id']
    customer_session = stripe.checkout.Session.retrieve(session_id)
    customer = stripe.Customer.retrieve(customer_session['customer'])
    stripe_response = requests.get(url=f'https://api.stripe.com{customer["subscriptions"]["url"]}',
                                   headers={'Authorization': f'Bearer {stripe_keys["secret_key"]}'}).json()
    resp = make_response(redirect('/dashboard'))
    if 'data' in stripe_response.keys():
        if customer['id'] == stripe_response['data'][0]['customer']:
            user = get_user()
            user.stripe_id = customer['id']
            user.cancelled = 0
            db.session.add(user)
            db.session.commit()
            user_to_guild_handler(BOT_TOKEN, GUILD_ID)
            requests.post(f'http://{DISCORD_SERVER_URL}/new_member_alert',
                          data=json.dumps({'user_id': user.discord_id, 'email': user.email}))
            try:
                coupon_key = request.cookies.get('coupon')
                coupon = Coupon.get(key=coupon_key)
                coupon.uses -= 1
                coupon.update()
                resp.set_cookie('coupon', 'USED', expires=0)
            except Exception as e:
                pass
    return resp
#

Does anyone have any idea on why that thing could happen"
Exception details:

#
AttributeError: 'NoneType' object has no attribute 'stripe_id'
  File "flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "flask/_compat.py", line 39, in reraise
    raise value
  File "flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "app.py", line 251, in payment_success
    user.stripe_id = customer['id']

NoneType is referring to the None user object

#

Basically my question is: How can I solve this issue? What is causing it? Cookie expiration is set to one week

#

One possible answer I have is that they use incognito mode

#

But they wouldn't be able to login in the first place

plain zealot
#

Anybody familiar with node.js?

balmy shard
#

@plain zealot I can help with syntax and discord.js, idk about anything else

upbeat forge
#

For the user accounts database, do you want make a different table explicitly for users only or do you create a custom User Model?

#

Using django

#

I dont want to use the default login/signup form of django so what should i do?

balmy shard
#

Does django let you use html?

upbeat forge
#

yes

balmy shard
#

Learn How To Make Signup Form Using HTML And CSS | Create Sign Up Form In HTML CSS
โค๏ธ SUBSCRIBE: https://goo.gl/tTFmPb

โค๏ธ Complete website Using HTML and CSS
โœ”๏ธ 8 Complete website step by step
โœ”๏ธ Source Code Download
โœ”๏ธ 76 Lectures, 12 Hours Video
โœ”๏ธ Course Completion certifi...

โ–ถ Play video
#

Idk how good it is

#

I went with the first thing I found

#

Swap out the background with whatever, shouldn't be too hard

upbeat forge
#

Actually django has a inbuilt way of dealing with forms, and i want to create a custom form but to do that should i use the default Users model or create a new one?

plain zealot
#

It is not about syntax though

upbeat forge
#

backend stuffs

balmy shard
#

@upbeat forge
Make a database with table called logins (or whatever you wanna call it) with an id, username, and password column

Definitely not the most secure, but it works for development

#

It is not about syntax though
@plain zealot wait til someones online I guess

lone galleon
#

hi, it's possible to start http.server (SimpleHTTPRequestHandler) and close him after one request? or after N request?

ripe goblet
#

@upbeat forge i usually create a new one.

upbeat forge
#

@upbeat forge i usually create a new one.
@ripe goblet ohh and can i use all the default functions lile login or logout with that self created model?

ripe goblet
#

yup

#

it inherits the modelForm class according from django docs

upbeat forge
#

Okayyy

wind walrus
#

If I want to let the user upload a thumbnail image for a post and I want to be able to use it in different sizes, how should I do that?

#

I can save it in a small size like 125px by 125px but then quality will be super low when I need to enlarge it

#

So do I just save it as the original file and scale it down in the HTML as needed?

scenic dove
#

Hi, for DRF, is it okay if I only have JWT Authentication under DEFAULT_AUTHENTICATION_CLASSES or will I not work with sessions?

The problem I'm facing right now with sessions enabled is whenever the server restarts, it deletes all sessions and it doesn't seem to check if there's an existing JWT token so it just throws an Unauthorized error.

granite loom
#

who knows how to use django

native tide
#

not me, I'm also trying to learn it

#

I want to make a comment web app, where you can select a user and give them a suggestion

granite loom
#

for we

#

web javascript

native tide
#

is it a bad idea to host web server on localhost? I'm thinking of getting some of the new raspberry pi 4gb ram and making a cluster server

granite loom
#

would be better

native tide
#

yeah idk I'm new to Web apps

#

would NodeJS be better than django or flask?

wind walrus
#

I'm a high schooler just making a blog with Flask for fun

#

In that case is it possible to use Google Drive instead of S3 to store my images?

vague ibex
#

would NodeJS be better than django or flask?
@native tide Both are powerfull when used properly . The one you know how to use properly, can be a great asset for you.

rigid laurel
#

In that case is it possible to use Google Drive instead of S3 to store my images?
@wind walrus
You don't have to use s3, but Google drive won't work

wind walrus
#

Are there any free alternatives?

rigid laurel
#

Well. S3 gives you 5gb for free

#

So

#

S3

#

I'm not sure on what, but there probably are free ways to host or

vague ibex
#

is S3 free?

rigid laurel
#

It

#

S3 gives you some storage for free

wind walrus
#

5GB is permanently free? Or like just 1 year or sth?

#

That's nice cos I won't be using that much GB anyway

rigid laurel
#

Permanent

#

I think

#

Not 100%sure

wind walrus
#

As part of the AWS Free Tier, you can get started with Amazon S3 for free. Upon sign-up, new AWS customers receive 5GB of Amazon S3 storage in the S3 Standard storage class; 20,000 GET Requests; 2,000 PUT, COPY, POST, or LIST Requests; and 15GB of Data Transfer Out each month for one year.

#

Sorry my English is not my first language does that mean it's "for one year" only?

vague ibex
#

There is not any limit i suppose

#

I mean you can use those requests and 15gb data each month for one year

rigid laurel
#

Oh. Apparently so. It's very cheap though, every after that one year

vague ibex
#

so yeah, its for one year

wind walrus
#

True, would've been great if it was permanent but

vague ibex
#

Everyone company tries its best to provide the service but there's always a catch lol

#

Technically, I mean there won't actually be any company that will provide you unlimited cool features forever.

late fjord
#

what is the difference between react and django

vague ibex
#

React is a Javascript Framework whereas Django is a Python framework

late fjord
#

I know that

vague ibex
#

React is used for Front-end whereas Django is used for back-end

#

That's it

late fjord
#

that is what I don't understand

vague ibex
#

You don't understand front-end and back-end?

late fjord
#

yes

#

I know what is back-end

#

what is the role of react on making webistes

vague ibex
#

then what do you not understand?

#

You use HTML, CSS for front end right?

late fjord
#

yeah

vague ibex
#

React is a Javascript framework which proves to be a powerful alternative

late fjord
#

we can not do like django, i mean templates and urls ...

vague ibex
#

Django is a back-end framework and React is a front-end framework.

#

That's why you cannot use React like Django

late fjord
#

Imagine I wanna build an instagram clone what do I use?
if react what is it's job
django
or both

vague ibex
#

alright

#

Listen up and if you have any doubt, ask me

late fjord
#

yeah

vague ibex
#

For instagram clone, you need a client and a server.

late fjord
#

yeah

vague ibex
#

I hope you understand what they mean?

#

good.

#

For the Client side, You would use React

late fjord
#

why

#

???

vague ibex
#

Client side == Front end

late fjord
#

got it

vague ibex
#

cool

#

shall I explain further?

late fjord
#

yes please

vague ibex
#

alright.

#

Now after you have designed the client side, you will require it to send requests to the server side for retrieving data

#

For that, you will require a server to process the requests and send back reports

late fjord
#

for the client side do I use react to bring data from the server and display it

vague ibex
#

For a server to work, you need to do server-side scripting using any backend language

#

@late fjord , the front-end part is a large concept.

#

Let me explain to you what the front-end actually is.

late fjord
#

please

vague ibex
#

yep.

#

Whenever you go to a website, like say spotify

late fjord
#

yeah

vague ibex
#

you've visited spotify right?

late fjord
#

no, but I know how it works

vague ibex
#

oh cool

#

Now, it will have a user-interface.

late fjord
#

yes

vague ibex
#

Like the new releases, the new songs , etc. etc.

#

This is the front - end

#

Now, whenever I click on any of the song

late fjord
#

you send a request to the server

vague ibex
#

it will shift to the back end

#

The front end requests the server aka back-end

#

the server sends back the required code and the front end runs it.

#

That's it.

late fjord
#

got it

vague ibex
#

Now, the backend consists of server and a database too

#

For a database included server, the server , after receiving the request from client will check into the database(ofc through a piece of code) and then retrieve the data and send it to the client.

#

That's how it works ๐Ÿ˜„

#

I hope you understand, do you?

late fjord
#

I reading the message

#

I am

#

Got it

vague ibex
#

No doubt?

late fjord
#

but I have seen some people building react clone with react and firebase

vague ibex
#

react clone of what?

late fjord
#

I mean facebook spotify instagram ...

vague ibex
#

React is capable of making API calls (send request to backend), which deals with the data. React cannot deal with database or any datasource itself.

#

btw React is a library and not a framework.

late fjord
#

got it

#

so firebase is a backend framework or what

vague ibex
#

I would suggest you to check it out.

#

It has a good explaination about firebase.

#

If you do not understand , just ping me ๐Ÿ˜„

late fjord
#

but can you give me a quick idea about it in just a message only one

#

please

vague ibex
#

Firebase is a mobile-backend-as-a-service that provides powerful features for building mobile apps. Firebase has three core services: a realtime database, user authentication and hosting.

#

^ there.

#

It is the first line the webpage says.

late fjord
#

thank you

vague ibex
#

basically, firebase is a mobile-based-backend

#

no problem!

#

It's my pleasure to help you :D.. If you need further help, feel free to ping me up! ๐Ÿ˜„

late fjord
#

So we cannot use only react to build a website

#

the last question

vague ibex
#

We surely can.

#

If the website has a client and a server that works, then we cannot.

#

React is only a front-end library.

#

got it? @late fjord

wind walrus
#

Btw a quick question - why would something like Imgur or Google Drive not work to store images? You can upload/retrieve files with Python right?

#

Imgur or Google Drive as opposed to S3 that is

late fjord
#

yes, but can u give me an example of a website without server

vague ibex
#

sure

#

@late fjord btw do not use the words - "without a server"

#

Every website is hosted on a server which keeps it alive

wind walrus
#

Lol my first website was just HTML and CSS no backend at all

vague ibex
#

you can ask that "can a website exist without backend"

#

The answer is yes.

late fjord
#

yeah got it, so, can a website exist without backend

wind walrus
#

Like a simple <h1> Hello world </h1>

vague ibex
#

Let me grab a link asap.

#

yeah got it, so, can a website exist without backend
@late fjord yup!

#

It is a gaming blog.

#

It only has a front-end and a CMS by blogger (if that really counts lol)

late fjord
#

thank you so much you helped me a lot I'll check it, btw, can I send you a friend request

vague ibex
#

sure ๐Ÿ˜„

#

It's my pleasure to help people clear their doubts.

#

I do myself have a lot of doubts in general.

#

A quick tip: "Always try to clear your basic concepts when progressing further"

wind walrus
#

can I ask a quick question as well

vague ibex
#

It really helps

#

sure xTryhard

wind walrus
#

why would something like Imgur or Google Drive not work to store images? You can upload/retrieve files with Python right?

late fjord
#

don't forget to accept it ๐Ÿฅบ ๐Ÿฅบ

#

thank you

vague ibex
#

I've accepted it.

wind walrus
#

I'm just a high schooler coding for fun, so this website won't be important or anything

#

Imgur or Google Drive as opposed to S3 that is

vague ibex
#

why would something like Imgur or Google Drive not work to store images? You can upload/retrieve files with Python right?
@wind walrus Google drive stores images?

wind walrus
#

Yeah you can upload any file to Google Drive

vague ibex
#

yea?

wind walrus
#

can't we just use Google drive or Imgur instead of paying for S3?

#

It's just a website for fun so it's not serious or important or anything just a blog

merry geode
#

For simply displaying images, you can use Imgur probably. I have not tried. Google drive might be difficult though, it may not allow embedding the image in another site. Worth a try though,

wind walrus
#

So what can S3 do that Imgur wont be able to do?

rigid laurel
#

be interacted with programmatically

unique hill
#

Does anybody know how to use file feilds in django

late fjord
#

just ping brunckek he know a lot of stuffs he might help you @unique hill

unique hill
#

@flint breach i have a doubt regarding file feilds in django

#

can you help me

#

@late fjord thanks

late fjord
#

you are welcome

#

this is my forms.py:

from django import forms
from .models import *


class AskQuestion(forms.ModelForm):
    class Meta:
        fields = "__all__"
        model = Question
unique hill
#

what is happening when you submit the form

#

does the page reload??

late fjord
#

and this is my views.py:

@login_required(login_url='/user/register/')
def ask_question(request):
    form = AskQuestion(request.POST, initial={'asker':request.user})
    if form.is_valid():
        form.save()
        return redirect('/questions/')
    return render(request, 'questions/askquestion.html', {'form':form, })
#

yes it does

#

@unique hill

unique hill
#

then checkout if the form has the appropriate action

#

and also if the button is of the type submit

late fjord
#

I didn't set the action

unique hill
#

that's why i believe its reloading

late fjord
#
<form method="POST">
    {% csrf_token %}
    {{form.title.label}}
    {{form.title}}
    {{form.text.label}}
    {{form.text}}
    {{form.tags.label}}
    {{form.tags}}


    <input type="submit" value="Ask">
</form>```
unique hill
#

put a action

late fjord
#

what is the role of the action

unique hill
#

to check whether that is the problem

late fjord
#

do I set it to ""

unique hill
#

action means your form knows where to go when this form is submitted

#

if there is no action than it will keep on reloading the current page

late fjord
#

so what do I do

unique hill
#

what do you want to do after the ask button is pressed

late fjord
#

I want them to be redirected the page of the question

unique hill
#

so you can write

#

action = {% url 'whatever name it is' %}

late fjord
#

but I did redirect in my view

#

and it doesn't save to the database

unique hill
#

try using action for this ask_question function

#

what is the name in urls.py for ask_question function

late fjord
#

I didn't give it a name

#

now I gave it one

unique hill
#

than first give it a name

#

so now add action for it

late fjord
#

it is 'askquestion'

#

how

unique hill
#

action={% url 'askquestion' %}

late fjord
#

just {% url 'askquestion' %}

unique hill
#

yes

#

but in double quotes

#

action = "overhere"

late fjord
#

the same problem

#

the page is still reloading

#

and not saving to the database

unique hill
#

show what changes you made

late fjord
#

maybe because the form is not valid

unique hill
#

in the html file

late fjord
#
<form method="POST" action="{% url 'askquestion' %}">
    {% csrf_token %}
    {{form.title.label}}
    {{form.title}}
    {{form.text.label}}
    {{form.text}}
    {{form.tags.label}}
    {{form.tags}}


    <input type="submit" value="Ask">
</form>
unique hill
#

this looks fine

#

put a breakpoint at form

#

wait a sec

#

what is the name of your table in models

#

where you want to save this data

late fjord
#

and my urls.py:

urlpatterns = [
    path('', questions, name='questions'),
    path('ask_question/', ask_question, name='askquestion'),
    

]```
#

where breakpoint

unique hill
#

what does form.save() do

#

??

late fjord
#

it saves the data to the database

#

maybe because the form is not valid

unique hill
#

at form.is_valid()

#

and also at form

late fjord
#

I don't get you

unique hill
#

do you know how to debug

late fjord
#

no

unique hill
#

very good

#

so search on youtube

#

how to debug a django code

#

do u use vs code or pycharm

late fjord
#

I use vs code

#

I actually removed the instance and it is saving

#

do you know how to the instance correctly

#

please tell me that you do

#

@unique hill

unique hill
#

your code is working now??

late fjord
#

after changing python form = AskQuestion(request.POST, instance={'asker':request.user})
to:

form = AskQuestion(request.POST)```
unique hill
#

but overhere it says initial

#

i am actually not familiar with this instance thing

#

this might help

subtle crest
#

Hey, hope I'm in the right channel. I'm looking to build some API for an ELO system (specifically using Docker, but that shouldn't change much from the python side). I've been looking at Flask to build the API. What I'm not sure about is how to build that API. I want some private routes for registering that a match has happened and should update the ELO. But I also want some public API at some point for other services to be able to read the data. Is there a way to do this in Flask, or would it be better to separate the two into two different apps?

late fjord
#

thank you @unique hill

native tide
#

Anyone using apscheduler for flask scheduling ?

late fjord
#

I am now having trouble with django I don't know what is happenning ```bash
if request.method=="POST":
^
SyntaxError: invalid syntax

#

can anyone help me

#

@native tide please help me, you're the only one online

native tide
#

Well you are having synax error if you dont have any code after : just add pass

#

error should dissapoear

late fjord
#

Sorry to bother you I found where the problem is, it is because I forgot to close ()

native tide
#

if u want to use js in django does it have to go in the static folder?

glass sandal
#

It can go in your html code too

#

@native tide

native tide
#

also is there a way to pip install pyjs or do i have to clone the repo

nova escarp
#

Hi, does anyone know if it is possible to have the user be able to "change" the queryset filter on Django? I want to make a field on my site that allows the user to type in a date and hit enter, then it will show them a list of objects that match that date. is this possible within Django?

quick cargo
#

@native tide if its only a small 1 off bit of JS it can just go in <script></script> tags in the html

acoustic oyster
#

@native tide pip install git+https://github.com/pyjs/pyjs.git#egg=pyjs

native tide
#

oh ic tx

#

i was wondering y my pip install pyjamas was failing the whole time lol

brave elbow
#

Can someone help me. I have completed a 'register' page and form in Flask. It redirects to /login. I want to flash a success message when i reach /login from my completed /register form. How can i do this? I assume there is someway under the @login route to determine where the user came from... but i dont know

balmy shard
#

Bois

#

I need to know if a pi zero could run a basic flask app

#

The app only takes input, saves it to a database, then displays it

#

@ me if anyone knows

quick cargo
#

Yes a pi could run a flask app

#

@balmy shard

balmy shard
#

I mean a zero (the small one with a 1gb ram)

#

@quick cargo

quick cargo
#

it should still

#

Like flask is light weight

#

and a small server wont use much

#

A small Django app i run uses about 100MB RAM total and a unnoticeable amount of CPU

balmy shard
#

Oh

#

Great

vapid oasis
balmy shard
#

im cheap ok

acoustic oyster
#

does anyone know any search engines that allow crawling/scraping? Or free apis for web search results? (Must abide by TOS and of course laws)

native tide
#

Does anybody know if you can add a name to a URL path in Django when using the include object? or can you only add a name with returning a view from the url path?

native tide
#

wonder if the path seperators in html differ for windows and linux systems

silent shore
#

How do I put my logo on my navbar?

#

And links?

dapper falcon
#

I've forked a project on codepen to use as an animation for my site nav, but I can't seem to get it to work. Consists of three files, but testing it through my flask app fails

#

anyone have a sec to tell me how I'm an idiot?

edgy marsh
#

So im trying to web scrape using bs4 and im following an old tutorial. This is my current code: ```from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'https://www.retailmenot.com/view/shopdisney.com'

#opening connection, grabbing page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

#html parsing
page_soup = soup(page_html, "html.parser")``` but i keep getting an error

#

am i missing any dependencies ?

polar lantern
#

Error 403 Forbidden

#

The page is blocking your request

edgy marsh
#

oh

#

so can i just not scrape it then

polar lantern
#

Not that easily

edgy marsh
#

hmm is there a work around

polar lantern
#

They use Cloudflare which detects your bot and forces you to solve a captcha which you can not do that easily

edgy marsh
#

ok

#

what if i use selenium

polar lantern
#

That should work

#

But they may still ask for a captcha

#

but there are apis to solve them

edgy marsh
#

ok

#

what apis

polar lantern
#

captcha solver services

quiet lily
#

I'm just wondering can i really incorporate Google Material design to a Dango project? I have used Materialize CSS but i prefer MD

#

I have been search for quite sometime now but haven't found any example on how to achieve this

glass sandal
#

Guys what is the point of name in url definition in my urls.py?

#

Like :

#
path("".views.function,name="something") #What does the name do?
quiet lily
#

You can easily refer to that view in your template

dapper tusk
#

when in a template, you can link that url with {% url 'something' %}

#

and I think redirect can also use those

glass sandal
#

Oh

#

So I can do a href like :

<a href="{% url 'something' %}">Goto something</a>

And this will point to the main page right?

#

Since something's url is "" in this case

dapper tusk
#

that seems correct

glass sandal
#

Oh I see

#

Thanks for info anyways

balmy shard
#

@edgy marsh use selenium

edgy marsh
#

i am

#

it still gives me a capatcha tho

wind walrus
#

What kind of database would I use for an email subscription list?

#

I'm using Flask with Flask-SQLAlchemy and deploying it to Heroku with Heroku Postgres

balmy shard
#

Idk

#

@edgy marsh do the captcha manually ig

wind walrus
#

Would I store a mailing list in SQLAlchemy database?

rancid lintel
#

mailing database doesn't seem to be a huge deal i guess choose whatever you're comfortable with. you should be more focus on the content than which database to choose.

ember pecan
#

Hello people,
Does someone have a good tutorial to help me setup a Flask app with Apache WSGI without using virtualenvs?
I tried it myself but I keep having a ImportError: No module named flask in the Apache logs (of course the Flask app works fine if I run the standalone server, and I already tried making sys.path.appends in the wsgi file)

dapper tusk
#

Maybe print out sys.executable to see what python Apache is running from

ember pecan
#

How can I do that? Trying to write to a file in the wsgi file does not seem to work

dapper tusk
#

Print should appear in the log, or you could raise an exception, which you already know how to see

native tide
#

How do I put my logo on my navbar?
@silent shore <img src="image link">

ember pecan
#

ah, looks like my WSGI is running python 2.7 instead of 3.5

unique hill
#

does anybody know how to upload multiple images in django

ember pecan
#

Managed to fix it. Discovered at the same time that wsgi module for Apache is only compiled for a specific version of Python... that sucks.

#

Thank you btw

native tide
#

Im using Django and I need to make requests from POSTMAN with the csrftoken, however I noticed the token is only generated and returned when I visit the /admin route, but is there some way I can get this to work with guest endpoints, such as a /register route?

rigid laurel
#

the answer to your question is probably on that page

native tide
#

thx, the csrf_exempt decorator works

west wren
#

I'm having a lot of trouble reading Flask data for my frontend. I have a React frontend and a Flask backend which serves as the REST api. When I serve it locally with npm start, the two can communicate seamlessly. However, if I try to host them on Heroku, I'm unable to do so with the error (index):1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0.

I've spent the entire day fruitlessly trying to solve this issue. Any advice?

Stack Overflow question with more details: https://stackoverflow.com/questions/63215903/cannot-get-data-from-flask-from-react-when-deployed-on-heroku-but-works-locally

Current website, trying to GET data made with Flask from /api/test: https://test-mandarin-web-app.herokuapp.com

native tide
#

Does Django support OAuth2 Login with Discord? I know OAuth2 is platform agnostic, but the resources I've found mostly stresses on how to create your own OAuth2 system so other people can create clients to use it as a third party service, I just want to have my Django app allow OAuth2 login

dapper tusk
#

Ye, afaik that supports it

native tide
#

thx

native tide
#

Is BaseBackend not a class anymore from the module django.contrib.auth.backends?

#

When i import it, it doesnt appear in intellisense, and it also throws an error saying BaseBackend cannot be found

#
from django.contrib.auth.backends import BaseBackend

class DiscordAuth(BaseBackend):
  def authenticate(self, request, token=None):
    print("Hi")
#

I checked my django version ```
"django": {

        "index": "pypi",
        "version": "==3.0.8"
    },``` just incase
tall bobcat
#

AWS EC2 Django help needed.

my django backend has function wherein a file is created with :
f = open("xyz.txt", "w")
when i run it with runserver command on ec2 aws it runs fine.
but when i run it with apache it says permission denied and give me an error

upbeat forge
#

Yelp

weak lynx
#

Hi! Im have been studing the most basic of python this entire week, i know loops, functions, classes, objects, data types, lists and all that stuff... And i want to start learning web development, i have been asking and some say... look for Django or flask... so i will do it but i dont really understand which is better and what the are for... so if some one is able to help me with a recommendation about How to enter into web development it will be great.... Thank you

dark agate
#

flask it will be nice if you are a beginner

#

but before flask you should learn html & css

weak lynx
#

@dark agate do you know where can i learn those? and its completely necesary?

dark agate
#

there is a lot of resources in youtube

#

a lot of people recommend the html & css crash course by Traversy Media

coral wind
#
D:\programs 2.0\python\webdev\python-getting-started>heroku local
[OKAY] Loaded ENV .env File as KEY=VALUE Format
6:49:09 PM web.1 |  Traceback (most recent call last):
6:49:09 PM web.1 |    File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1520.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 194, in _run_module_as_main
6:49:09 PM web.1 |      return _run_code(code, main_globals, None,
6:49:09 PM web.1 |    File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1520.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 87, in _run_code
6:49:09 PM web.1 |      exec(code, run_globals)
6:49:09 PM web.1 |    File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\Scripts\gunicorn.exe\__main__.py", line 4, in <module>
6:49:09 PM web.1 |    File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\gunicorn\app\wsgiapp.py", line 9, in <module>
6:49:09 PM web.1 |      from gunicorn.app.base import Application
6:49:09 PM web.1 |    File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\gunicorn\app\base.py", line 11, in <module>
6:49:09 PM web.1 |      from gunicorn import util
6:49:09 PM web.1 |    File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\gunicorn\util.py", line 9, in <module>
6:49:09 PM web.1 |      import fcntl
6:49:09 PM web.1 |  ModuleNotFoundError: No module named 'fcntl'
[DONE] Killing all processes with signal  SIGINT
6:49:09 PM web.1 Exited with exit code null
#

how do i fix this and what even happened in thefirst place

polar lantern
#

import fcntl
6:49:09 PM web.1 | ModuleNotFoundError: No module named 'fcntl'

#

pip install -r requirements.txt

#

Did installing the requirements work?

glass sandal
#

Guys what could I do to profit with Django or Flask excluding Freelancing and Making an online shop?

#

(As a teenager)

fickle fox
glass sandal
#

But it's related to web dev too

fickle fox
#

well ads, donations

#

paying services

glass sandal
fickle fox
#

seems they mtued it

#

muted*

glass sandal
#

So

#

what could I do now :/

fickle fox
#

monetize site

#

example

glass sandal
#

You mean affiliate marketing? Or like adsense

#

?

fickle fox
#

like adsense

glass sandal
#

Oh... But it's blocked in our country . Isn't there like another way?

fickle fox
#

there are other services for that

#

just google them

glass sandal
#

Ok lemme check it our . Thanks for the info tho!

fickle fox
#

tho affiliate marketing is good idea as well

glass sandal
#

Yeah . But still , almost the same

fickle fox
#

not same

#

u gain income from different things

glass sandal
#

ik , but they have similarities

#

Like you advertise something in both

#

As far as I know*

fickle fox
#

well yea just u promote ur self as affiliate

glass sandal
#

yep

#

Or I could just sell my website I guess?

limber laurel
#

I am having an issue using djangos LoginRequiredMixin, I get a circular imports error if I set login_url to reverse('test') for example, also even if I hardcode the url, it redirects me to some iwerd non existing url, could anyone help me with this?

uncut rover
#

is there anything else i can use flask for?

#

except backend

zealous siren
#

you can build front ends with it

uncut rover
#

yeah, html is better

native tide
#

Is there someone who know about MYSQL and displaying data in a table with flask?

fickle fox
#

Ask what u want to know

#

!ask

lavish prismBOT
#

Asking good questions will yield a much higher chance of a quick response:

โ€ข Don't ask to ask your question, just go ahead and tell us your problem.
โ€ข Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
โ€ข Try to solve the problem on your own first, we're not going to write code for you.
โ€ข Show us the code you've tried and any errors or unexpected results it's giving.
โ€ข Be patient while we're helping you.

You can find a much more detailed explanation on our website.

sudden grail
#

Hey guys, i really need your helps.

#

Im making a project and im confused about design

#

so,

#

what i got:

#

the layout matters

#

as you can see, there are threads on the right

#

what you say, where should they open up?

#

if you click on a thread then it should move into the middle

#

upon the base chat

#

or stay in the right panel?

#

which is more comfortable?

#

this is it if you click on a thread

#

the right side changes

#

but is it okay to see the chat there? or would it be more intuitive to see just one chat in the middle,

#

base or a threaded chat

#

What do you say? Any response would be helpful :/

glass sandal
#

I'm not a UI designer but I'd rather the text input to be in the chat's div

#

Or the chat should be centered on the screen

sudden grail
#

@glass sandal yees-yes, this is just the layout. On the right side there will be a chat panel like in the middle if i choose this way.

#

But should it be there?

#

or open in the middle

glass sandal
#

I mean , I am not a UI designer as I said :(

sudden grail
#

yeah, i know ๐Ÿ™‚ but thanks
I am not as well, just thinking about best approaches. If it'd open in the middle, then you cant make mistakes and send messages to the wrong chat(because you might send if you see two chat opened)

#

but if you need to search for some infos, then you have to go back, search in the base chat or wherever

#

and open up the thread again

#

both has pros and cons

#

but which one's pros are bigger and cons are smaller? thats the question

#

personally you, @glass sandal , what would you use with more "passion", which one?

glass sandal
#

Uhhhh...Ummmm... I would say remove the div that is on the right side , and move the chat to the center

#

And you can do another chat in the dashboard

#

Like the left side

sudden grail
#

and then on the right u can see the list of threads, and if you open one, then it shows up in the middle. Otherwise you see the base/"main" chat of the channel in the middle

glass sandal
#

Oh I see

sudden grail
#

Threads are meant to organize the main chat into topics

#

you know

#

and organizing infos

#

around topics

#

to catch up later if you go on holiday or something

glass sandal
#

I mean , it's 00:21 here and I'm being a lil dumb . I may not be able to answer rn

sudden grail
#

easier than scrolling up

#

yeah, i get it ๐Ÿ™‚

#

i hope, others will answer too ๐Ÿ˜•

glass sandal
#

They will

uncut rover
#

wait, so can u use flask as backend?

sudden grail
#

?

fickle fox
#

flask is backend framework @uncut rover

weak lynx
#

Hi i just instaled sublime text 3... can someone say me how to put there flask?

strong oyster
#

Hey

fickle fox
#

what u mean by put flask??

#

with pip install flask create something u want and run in terminal

weak lynx
#

@fickle fox Im new and i dont understand what is a virtual enviroment and i dont know how to download it and put there flask... can you help me?

fickle fox
#

pip install flask

weak lynx
#

I use phyton 3.5

fickle fox
#

then import it code what you want

#

to stun it

#

flask run

weak lynx
#

where do i copy pip install flask?

dark agate
#

theres thousand of videos in youtube

#

look it up

weak lynx
#

ok, thank you

fickle fox
#

terminal

weak lynx
#

And if i understand well a Virtual Enviroment is a place where you run a project like in a closed room?

dark agate
#

yes

weak lynx
#

Okkk i got it

#

sorry for this ultra dummy question but Idle python is the terminal?

fickle fox
#

no

#

its cmd

weak lynx
#

ok, so i will go for it, thanks

uncut rover
#

@fickle fox thx for the conformation, wanted to hear it from a non-crappy coder

silent shore
#

@silent shore <img src="image link">
@native tide @native tide it stays under it, I used a png image for nav bar

native tide
#

wdym

#

send ss

#

@silent shore

silent shore
#

Look at the left where the text is

#

@native tide

native tide
#

ok

#

can you show me the full html code of this section

balmy shard
#

bois i have a question abt gunicorn

#

ive been getting
index() takes 0 positional arguments but 2 were given

#

and idk why

#

pls @ or dm if anyone knows

cobalt oyster
#

can someone help me with mock testing? I wrote this code but it dosen't work. Let me know what I am doing wrong. Thank you```python
class PrivateHomePageTests(TestCase):
"""Here we will check homepage for logged in user"""
def setUp(self):
"""Lets create a user and log him in"""
# Lets set up some user obj
self.user = get_user_model().objects.create_user(
first_name='test',
email='testman@testmail.com',
last_name='man',
mobile_number='9999999999',
)
self.user.country = 'Wakanda'
self.user.city = 'Gotham'
self.user.state = 'Metropolis'
self.user.country_iso = 'India'
self.user.longitude = '25.0000N'
self.user.latitude = '71.0000W'
self.user.save()
self.client.force_login(self.user)

 @mock.patch("geoip2.database.Reader", mock.MagicMock(return_value="123.201.248.48"))
 def test_that_logout_button_is_present(self):
     """Lets do a get req to home page with loggedIn user"""
     res = self.client.get(HOME_PAGE_URL)
     # now lets check is logout button is present in the home page

     self.assertIn(b'<button class="btn btn-outline-danger"><a href="""{% url "accounts:logout" %}"""> Logout </a></button>',
                  res.content)```
#

so here the geoip won't work in TestCase so I am trying to mock it's response.

cobalt oyster
#

or if someone can tell me how to use geoip in tests that would help me too

last ginkgo
#

need help with django

#

main.models.ToDoList.DoesNotExist: ToDoList matching query does not exist.

snow dragon
distant olive
#

i have already started making a website

using css and html
but

should i need to install pycharm for it

or

can i make a seperate page on vs code {main.py} and i can make???

which is the correct way
plz anyone tell

silent shore
limber laurel
#

Is there something opposite of LoginRequiredMixin or should I make custom logic for that?

keen nebula
#

Pls anyone who can make some simple calculator with 1 parameter

native walrus
native walrus
#

@native walrus Please help me xD
@native walrus SOLVED

native tide
#

hey is there any django help discord server

native tide
#

guys i need help i inserted an image using static the cod works but i cant see the image

late fjord
#

@native tide can you show me your html file where you are trying to insert the image

modest scaffold
#

can someone help me my regex url isnt working

#

here is the code re_path(r'^tic-tac-toc/pos(\d{1})/$', views.tictactoePos),

feral loom
twilit zenith
#

hey, i have seen underscore used quite often in django docs, can anyone explain what it means? py role = models.CharField(max_length=1, choices=[('A', _('Author')), ('E', _('Editor'))])

#
('A', _('Author'))
``` `underscore before ('Author")`
cold anchor
#

that's usually used as the "no name" function for localization/i18n

nova crest
#

Simple Flask question: do users see any print('something') commands that are run in the code?

#

I have quite a few print() commands for development and bug fixing purposes, but I don't want my users to see those, even when they go looking

twilit zenith
#

by users do you mean other developers? or webapp users? @nova crest

mellow tide
#

@nova crest prints go to the console, so unless you are doing something strange, generally, your user won't see print statements (unless they are running said server)

nova crest
#

I was talking about Web App users

#

I figured the prints would only go to the server console, and not reach client side

#

thanks for the confirmation!

mellow tide
#

@nova crest fwiw, generally, when running a server, you don't want a bunch of prints to console though because daemons typically don't run in an active console (they are usually background jobs) so you usually want to do logging to a file rather than to a console... but for dev purposes, that is fine

#

not to mention, administrators typically have a set number of places to go hunting for logs

nova crest
#

@mellow tide Fair point. I will eliminate the prints when I'm ready for prodution

mellow tide
#

TODO: ftw ๐Ÿ˜„

formal shell
#

Hey guys. I created a boolean field in my models, and I wanted to set to True this specific field, from my settings.py in Django. Is it possible to do that? If anyone could help me to sort this out, it would help a lot

mellow tide
#

I don't really know Django, so I'm of no help here this

uncut rover
#

I figured it out, (its flask btw), in the app.run() you put debug=True

digital kayak
#

Hey guys. Is there any datastructure in js to implement a queue with O(1) time operations?

#

List's shift() operation has O(n) time complexity

vestal hound
#

which operations?

digital kayak
#

enqueue and dequeue

rigid laurel
#

An array

#

Popping and insertion are o(1)

#

Oh wait

#

That's a stack

#

No. An array will work

vestal hound
#

I'm sure there're tons of implementations, but it's trivial to roll your own

rigid laurel
#

You just need to use shift instead of pop

#

An array implements the methods you need

vestal hound
#

You just need to use shift instead of pop
@rigid laurel p sure that's O(n)

rigid laurel
#

Reading about it, it's engine dependant

vestal hound
#

I think common implementations would leave it O(n)

#

it is possible to have constant time shifting but I don't think that's what most common use cases require

rigid laurel
#

Yeah. You can't rely on it. I'm surprised js doesn't set out these requirements the way python does

digital kayak
#

something like a linked list would do it

#

As it doesn't need to shift everything

rigid laurel
#

I can't find a decent source for time complexity of operations in JS anywhere. Shift/Unshift seem to be pretty much always O(N), but I'd like to see a reasonable place have done the research

cold anchor
#

JS is just a spec, so the time complexity will depend on the underlying implementation of the JS engine, which varies between browsers

rigid laurel
#

Sure. But python specifies time complexities

#

And is also just a spec

#

Although it does have one main implementation

past cipher
#

User submits a link, it adds the link to the database with a timestamp. I want to remove this row once 30 days has passed. I want to know the best way to check if a record is older than 30 days and remove it ?

rigid laurel
#

delete from table where condition

cold anchor
native tide
#

hey ik this is a python server but

#

Im having some trouble making my image full size in css

#
body{
    margin:0;
    padding:0;
    display:flex;
    justify-content:center;
    align-items:center;
    height:100vh;
    background: url('https://cdn.wallpapersafari.com/1/88/L6Aojc.jpg');
    background-repeat: no-repeat;
    font-family:cursive;
}
#

this is what i have so far

#

ive tried many things but nothing works

#

please ping me if you could help

past cipher
#

delete from table where condition
@rigid laurel but how can I run this automatically once a day without restarting server ?

rigid laurel
#

Cron job or built in python scheduler

past cipher
#

thanks will check out a cron job

rigid laurel
#

or hook it into some unrelated process

hollow linden
#

@native tide What do you mean by Full size?

native tide
#

take up the whole screen

hollow linden
#

The full size of the Image, or fill the size of the container?

native tide
#

container

hollow linden
#

Background-size:cover

native tide
#

thanks!!

#

i tried so many things and that was the answer lolll

hollow linden
#

If you want to make things correctly use this:

#

background-size: cover;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;

native tide
#

thank you

hollow linden
#

You're welcome

native tide
#

Hi y'all, I'm not quite familiar with JavaScript and the legacy code of the Flask App that i have here, but maybe you can help me to figure this one out:

I have a Slider with control buttons that lets you cycle through a few pictures. I want to automate this slider so that it executes the function for the next image on click or does it automatically if no click is received within 3 seconds. I think I identified the relevant function:

$(".hero-wrap-text-slider-holder a.next-slide").on("click", function() {
    $(this).closest(".hero-wrap-text-slider-holder").find(sync2).trigger("next.owl.carousel");
    return false;
});
$(".hero-wrap-text-slider-holder a.prev-slide").on("click", function() {
    $(this).closest(".hero-wrap-text-slider-holder").find(sync2).trigger("prev.owl.carousel");
    return false;
});

How can I add something like an OR Operator to wait three seconds before triggering the next slide?
I guess this is some sort of Boostrap Carousel deviant if that helps

#

if this is the wrong place to ask, since this is a python place, please just ignore the above

twilit zenith
#

correct me if im wrong but isn't that jquery?

wild thunder
#

how to fix it

#

i tried width 100% and height auto but it's not working

lapis stratus
#

Can I see your code @wild thunder

wild thunder
#

yes

lapis stratus
#

Cool dm me

wild thunder
#

NP, i'll send it here

.card-profile-img {
    width: 100%;
    height: 100%;
    margin: 10 auto;
    border-radius: 50% 50% 50% 50%;
    background-position: 50% 50%;    
}
<img class="card-profile-img border-2px" src="{{url_for('static', filename='images/profile.jpg')}}">
#

i'm just testing some stuff, i have a game in mind i would enjoy to do, but i'm stuck with this

#

@lapis stratus

lapis stratus
#

Alright try to change the background position to center

wild thunder
#

nothing happens, stills the same

lapis stratus
#

background-size:cover;

wild thunder
#

same*

#

with square images it works

#

but wide images get it streched

lapis stratus
#

Hmm

#

You're trying to make it circle?

wild thunder
#

yes

lapis stratus
#

Just try to use border-radius:50%;

wild thunder
#

it is already

#

border-radius: 50% 50% 50% 50%;

lapis stratus
#

Use one value

#

one 50% only not 4 of them

wild thunder
#

oh

#

i made one thing

#

my container is 19rem

#

i put this as 18rem x 18 rem

#

width and height

#

worked

lapis stratus
#

Really nice keep working on that man!

wild thunder
lapis stratus
#

Maybe your container is too large

wild thunder
#

yeah sure, i'll fix it

#

but it's good enough

#

thanks @lapis stratus !

lapis stratus
#

No problem @wild thunder

wild thunder
#

now that it's working, please rate it

#

hahaha

uncut spire
#

anybody have experience with taking an existing Flask-via-gunicorn-on-Ubuntu app and integrating datadog for monitoring? is it as simple as preempting the entrypoint with ddtrace-run or is it preferable to ddtrace.patch_all()? or some third option i'm not considering?

mellow tide
#

I think the patchall is the way to go

#

I think they are working on some auto instrumentation though

uncut spire
#

10-4, thank you @mellow tide

fickle basin
#

can anyone tell me why i got '''path('store/', store_views.store.as_view(template_name='store/store.html'), name='store'),
AttributeError: 'function' object has no attribute 'as_view''''

#

the path is a views from the store app

remote jacinth
#

Howdy. I'm extremely new to coding (my only experience is really making interactive stories in Twine! ) and I just played around with making some code for a "random character generator".

#

I'm trying to figure out a way to host my short code (all it does is spit out some info on this random character) on a place that isn't repl.it

Been trying to use Flask on Glitch and I'm a little out of my depth ๐Ÿ˜… https://glitch.com/edit/#!/great-lavender-bonnet

I can't even figure out where to put my code - total newbie. If anyone was able to just give me the 10-second explanation of where to place the various dumb print commands, let me know.

radiant garden
#

What's a good choice of asynchronous web framework nowadays? Tornado seems to be the only option when I started my previous project, but there seems to have been a lot of movement in that area (with ASGI etc)

#

I have a very simple Flask app and I want to break out the long processing (to something like Celery) but I need to request to wait and return when the task is done

quick cargo
#

The most performant are Starlette and fastAPI, the most flask like is Quart, Aiohttp and Sanic are also two common ASGIs

elfin peak
#

Hello, if anyone knows flask, heres my code and the error.

from flask import flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Hello, welcome to the Lumber Legend's main page!"


if __name__ == "__main__":
    app.run()
Traceback (most recent call last):
  File "D:/codyk/Coding/.Aprojects/Website/website.py", line 1, in <module>
    from flask import flask
ImportError: cannot import name 'flask' from 'flask' (D:\codyk\Coding\.Aprojects\PythonMain\venv\lib\site-packages\flask\__init__.py)

Process finished with exit code 1

#

Any help is appreciated

quick cargo
#

caps

#

from flask import Flask

elfin peak
#

What

quick cargo
#

wow that did not do what i wanted it todo

elfin peak
#

from Flask import Flask?

quick cargo
#

lower case f the first time

#

you are importing the class Flask from the module flask

elfin peak
#

Ah

#

wow people are so smart here

#

i love you bro

#

wow.

#

holy crap dude thanks omg

hollow glacier
#

I only want certain users to have access to the moderation app in my project. Would I do that with user groups and permissions?

elfin peak
#

can i ask, is it always lower cse first then capital?

quick cargo
#

nop

#

you just need to pay attention to case sensitivity with modules

elfin peak
#

thanks so much

quick cargo
#

if they follow Pep8 All classes should be CaseLikeThis any things like modules or files are lower case setc...

elfin peak
#

Thanks bro

#

You are so awesome omg thank you so muich

modest scaffold
#

hi guys im just here asking why this get_or_create() won't work

#

it gives this error

#

games.models.gameMoves.DoesNotExist: gameMoves matching query does not exist.

#

and in the handling of that error gets this one TypeError: cannot convert dictionary update sequence element #0 to a sequence

late gale
#

what's the best hosting server for django Pythonanywhere or Google Cloud Platform and why ?

balmy shard
#

Google

#

Because probably has better bandwidth etc

#

Because of how many requests they get

#

And because its google

#

But pythonanywhere might be better because its specifically for python

thick inlet
#

i have an html which loads and play an audio file in program directory... from the html page i use js recorder to record realtime and replace the audio file in program directory.....but when i play the audio file again i get the old audio from cache memmory, not the replaced one..i want my html page to update frequently when i play the audio.... (refreshing doesnt work, but closing and opening the tab again works..., but i wanna update the audio without refreshing nor closing the tab) any solutions?

balmy shard
#

window.reload()

#

Stick that in the Javascript and see if it works

#

It should be obvious that it reloads the page

#

And might fix it since it's being reloaded by the page and not the person

#

Idk tho

#

@thick inlet

native tide
#

so one of my apps looks like this:
`app

  • static
    -----css
    -----icons
    -----js
    -templates
    ------base.html`
    and it seems nothing under my static folder seems to load in my html after i {% load static %}
thick inlet
#

iam playing the audio in html, refreshing js doent work @balmy shard

balmy shard
#

Idk then

#

@thick inlet

balmy shard
#

What?

serene agate
#

anyone knows flask?

twin sable
#

anyone knows flask?
@serene agate yes

nova crest
#

I know some Flask too

limber laurel
#

@classmethod
def create(cls, name, c_goal, user):
plan = cls.objects.create(name=name, c_goal=c_goal, user=user)
plan.save()
Is this syntax valid?

wind walrus
#

If I want to create a mailing list, what sort of database would I use?
It needs to contain a name and an email column, at the very least

#

MySQL? This isn't the job for SQLAlchemy right?

limber laurel
#

Im pretty sure you can use SQLAlchemy with MySQL @wind walrus

queen sinew
#

sqlalchemy is an ORM that works with many databases, it's not a database itself

#

MySQL being one of them

wind walrus
#
class SubscribedUser(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20))
    email = db.Column(db.String(120), unique=True, nullable=False)
#

could I just do this?

#

then to send an email I just SubscribedUser.query.all() and get their emails

limber laurel
#

yes

wind walrus
#

I made an AJAX post request to send the name/email data from the HTML forms to Python backend via JavaScript

#

and this is my Python to add the user to the mailing list

#
@main.route("/email_confirm", methods=['POST'])
def email_confirm():
    email_data = request.form["email"]
    name_data = request.form["name"]

    user = SubscribedUser(name=name_data, email=email_data)
    db.session.add(user)
    db.session.commit()
    send_confirmation_email(name=name_data, email=email_data)
    return "<h1>" + email_data + "</h1>"
#

Here, what should I return? I'm not rendering a template or anything...

solar hatch
#

what is the use of SECRET_KEY in flask ?

ashen anchor
late fjord
#

I am new to djnago do you think it is goood to moove from djangooo to flutter

solar hatch
#

flutter is a framework which use dart similar to C# which is kinda low level language if your starting out(on your programer journey) I recommend useing django or flask

bleak bobcat
#

It's just not the same purpose

solar hatch
#

flutter can be used make website

bleak bobcat
#

Looking at the docs it uses canvas mostly, so no, not the same purpose

solar hatch
#

but i think only flutter for frontend

#

django is for backend

#

Looking at the docs it uses canvas mostly, so no, not the same purpose
@bleak bobcat flutter mostly use "widgets"

lusty kernel
#

hi guys i needed some help... so like i was trying to make a django project and i had deleted the pip for django some time back now ive successfully reinstalled it however usually to start a django project we use execute django-admin startproject (name of file) however it seems to not work can anyone help?
im using vsc btw

hollow linden
#

@lusty kernel Are you using a Virtual Env?

lusty kernel
#

no

#

ill give trhe error one sec

#
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
#

this is the error @hollow linden

hollow linden
#

Use this

#

python C:\Users\blufl\AppData\Roaming\Python\Python38\Scripts\django-admin.py startproject (name of file)

lusty kernel
#

oh ok

hollow linden
#

This is not a solution but I just wanna see if it will work ^^

lusty kernel
#

but will the files be installed in the directory i want them in ?

hollow linden
#

I'll gave you the correct solution after ^^

lusty kernel
#

oh ok

#

kk

#

it worked

#

@hollow linden

#

thx mate

hollow linden
#

You can add: "C:\Users\blufl\AppData\Roaming\Python\Python38\Scripts" to you Path environment on windows

lusty kernel
#

ok cool

hollow linden
#

Like that you can use the command you mentioned before

lusty kernel
#

ok

#

thx mate init

hollow linden
#

You're welcome

lusty kernel
#

welp new problem

#

python3 manage.py runserver

#

this is the command i used and the error i get is

#

C:\Program Files (x86)\Python38-32\python.exe: can't open file 'manage.py': [Errno 2] No such file or directory

#

is it another file location problem

#

?

hollow linden
#

The script manage.py didn't exist on that path

lusty kernel
#

so if i write python (xyz path)

#

would it work?

hollow linden
#

Hmm let me clarify my words

#

If you wanna run a Script

#

You should be in the same folder where the script is

#

Or run python3 'the absolute Path of the script ' run server

#

That can be a little hard to understand ^^

#

Do you know the path where your script 'manage.py' is?

lusty kernel
#

its in my project folder

#

@hollow linden

hollow linden
#

Can you copy paste the whole path of your project folder?

lusty kernel
#

C:\Users\blufl\Desktop\dexbotx\pyshop/manage.py

hollow linden
#

Use python3 C:\Users\blufl\Desktop\dexbotx\pyshop\manage.py runserver

lusty kernel
#

i legit just did that

#

but like nothing happened

#

tho lemme try it again

#

it shdu give me a webadress to go to right @hollow linden ?

hollow linden
#

I don't know what the script did ^^

lusty kernel
#

i mean nothing happened

hollow linden
#

That's another problem ^^

lusty kernel
#

hmmmm

hollow linden
#

Let me see

#

First do that

#

cd pyshop

#

If it not work us this dir pyshop

lusty kernel
#

it worked

#

the cd one

hollow linden
#

Your path changed now?

lusty kernel
#

yes

#

it did

hollow linden
lusty kernel
#

ok lemme try

#

nothing happened even so

#

@hollow linden

hollow linden
#

Do you know the name of your app?

lusty kernel
#

its called pyshop

hollow linden
#

Try this command : python manage.py pyshop

#

python3*

lusty kernel
#

ok

hollow linden
#

Can you open manage.py on your editor and show me the first line?

lusty kernel
#

ok

#

@hollow linden

hollow linden
#

It's not recommanded but try to delete line number 1

#

#!/user ... python

#

Save and try to run the script

lusty kernel
#

ok

hollow linden
#

If not use : django-admin runserver

modest scaffold
#

does anybody know how to solve this error in djano Forbidden (CSRF token missing or incorrect.):

wind walrus
#

Add {{ form.hidden_tag() }}?

#

to your HTML

hollow linden
#

It's more like a warning, not and error ^^

wind walrus
#

first thing inside <form>

valid cypress
#

Anyone who know React, how to solve this:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `Header`.

Here is header

import React from 'react';

import { Navbar } from 'react-bootstrap';

export class Header extends React.Component {
    render() {
        return (
            <Navbar>
                <Navbar.Header>
                    <Navbar.Brand>
                        <a href="/">My site</a>
                    </Navbar.Brand>
                </Navbar.Header>
            </Navbar>
        );
    }
}

and importing

import { Header } from '../Header/Header';
modest scaffold
#

@wind walrus what does that do

#

@hollow linden how do i solve it

#

btw addin form.hdden tag stuff didnt work

hollow linden
#

I'm here, let me see ^^

#

@valid cypress You don't need you need quote inside the return? ^^

#

You don't think *

modest scaffold
#

@hollow linden that does not help

#

the strange thing is its working for my other forms

valid cypress
#

@hollow linden What quote?

hollow linden
#
            <Navbar>
                <Navbar.Header>
                    <Navbar.Brand>
                        <a href="/">My site</a>
                    </Navbar.Brand>
                </Navbar.Header>
            </Navbar>
        ");```
valid cypress
#

No, this is JSX syntax, so no quotes

hollow linden
#

@modest scaffold Strange

modest scaffold
#

should i share more code

#
            {% csrf_token %}
            <button name="reset" value="True">Reset</button>
        </form>``` here is the html
#

corresponding view ```def tictactoe(request):
newGame, created = liveGame.objects.get_or_create(id=0,gameId="yes")

movesModel, created2 = gameMoves.objects.get_or_create(game=newGame)
moves = list(movesModel.moves)
if "reset" in request.POST:
    return render(request, 'tic-tac-toe.html', {"boardSetup":[0,1,2,3,4,5,6,7,8],"error":"hi there"})
else:
    return render(request, 'tic-tac-toe.html', {"boardSetup":[0,1,2,3,4,5,6,7,8],"error":"hi there"})```
hollow linden
#

@valid cypress Try to add default after export export default class ...

valid cypress
#

Still not working

hollow linden
#

@modest scaffold Something is missing! are you using Jinja?

#

@modest scaffold is you website https?

#

That will help

modest scaffold
#

@hollow linden its not https i dont think so anyway

#

@hollow linden what is missing

hollow linden
#

I don't know ^^

quick cargo
#

Is this flaswk

#

flask*

modest scaffold
#

no django

quick cargo
#

okay Django

modest scaffold
#

missing crsf token for some reason

#

even though i have it in the html and im returning a render object

quick cargo
#

You seem to need to get the template object then pass it the context first then the request

valid cypress
#

This is still not working when I changed this to default

modest scaffold
#

@quick cargo cant i use a render() function though

#
In the corresponding view functions, ensure that RequestContext is used to render the response so that {% csrf_token %} will work properly. If youโ€™re using the render() function, generic views, or contrib apps, you are covered already since these all use RequestContext.```
#

nvm its working now

#

i think it was somthing to do with broswer cache

hollow linden
#

All fine ^^

modest scaffold
#

in django can you have variables inside template tags like this {% if apples|slice:"{{x}}" %} where x would be a variable

bleak bobcat
#

Yes you can but you'd remove the " and {{}}. However don't put logic inside templates

feral owl
#

anyone know how to run a java program using subprocess in django?

native tide
#

HEy guys

#

I have an issue

#
@app.route("/")  #Homepage
@app.route("/home")
def home():
    return render_template("home.html", posts=posts)  #Use render_template to return html files containing the code for the pages.


@app.route("/about")   #About Page.
def about():
    return render_template("about.html", title='About')

@app.route("/register", methods=['GET', 'POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        flash(f'Account created for {form.username.data}!', 'success')
        return redirect(url_for('home'))
    return render_template('register.html', title='Register', form=form)

@app.route("/login")
def login():
    form = LoginForm()
    return render_template('login.html', title='Login', form=form)

if __name__ == "__main__":  #__name__ is __main__ if we run this directly.
    app.run(debug=True) ```
#

so this is a small snippet of code

#

but when it should redirect it doesn't it just reloads the page

dapper tusk
#

redirections do not always work on all browsers afaik

#

so you have the fallback link

#

if the redirection does not redirect, the user can still click the link

limber laurel
#

too many values to unpack (expected 2)

I get a value error and it points to my ChoiceFields
gender = forms.ChoiceField(choices=('male', 'female'), label='Gender')

This is one of my choice fields

wind walrus
#

I have an Instagram account and I may change its username in the future

#

But I want to link it to my websites

#

Is it possible to get a link to the account with the account ID or something instead of the username so that I wonโ€™t have to go change the code for my website every time I change my username?

native tide
#

Web scraping?

#

idk

#

Or just add a clickable instagram logo?

wind walrus
#

But wouldnโ€™t that still need to have a link that points somewhere?

#

And in the link will be the account username so...

native tide
#

The best I could do would be to have a clickable instagram logo

#

but I am still new to this web dev stuff so yeah.

wind walrus
#

Yeah, I canโ€™t find a better solution, thanks for your time

native tide
#

Oh no worries sorry for not being able to help more.

modest scaffold
#

how do i only slice one element from a list in django templates

native tide
#
class SignUpForm(FlaskForm):
    field1 = StringField('Field1:', validators=[DataRequired()])
    field2 = StringField('Field2:', validators=[DataRequired(), EqualTo(field1, message='Fields not equal')])
    submit = SubmitField()

@app.route('/signup', methods=['GET', 'POST'])
def signup():
    form1 = SignUpForm()
    return render_template('signup.html', form=form1)```

Would anybody know as to why EqualTo() validator is not working (not showing the message)?
crimson yarrow
#

ive got this html form with text input boxes

#

this is what the form looks like
lets say i want to retrieve the value "hello"
shouldnt request.form['MB_IDLE_TIME'] get it for me?

native tide
#

Try request.form.get(x)

#
    field1 = StringField('Field1:', validators=[InputRequired(), EqualTo('field2', message='Fields not equal')])
    field2 = StringField('field2')
    submit = SubmitField()

@app.route('/signup', methods=['GET', 'POST'])
def signup():
    form1 = SignUpForm()
    return render_template('signup.html', form=form1)```
#

None of the validators except InputRequired() give me any feedback. Even though both fields are not equal, the message isn't showing.

#
    {{ form.hidden_tag() }}
    {{ form.field1.label }}
    {{ form.field1() }}
    {{ form.field2.label }}
    {{ form.field2() }}
    {{ form.submit() }}
</form>```
#

This is the form

#

Flask btw

strong oriole
#

which one is easier to learn
django or flask?

void leaf
#

Flask

#

Does anyone know if thereโ€™s a way to import a variable defined outside of the webpage function into the html template in flask?

native tide
#

With the delimiter {{ }} or am I misunderstanding

void leaf
#

So Iโ€™m making a function that web scrapes and grabs a value, I want to show that value on the flask webpage.

#

@native tide doesnโ€™t using the delimiter {{}} require the variable to be defined in the page function

mellow tide
#

you could assing the scaped value to a global variable and then use that variable in your page function @void leaf

#

but now you are taking the risk of blocking on a scrape

void leaf
#

Thatโ€™s what I did. The scraped value is x . Do I need to put x in the page function arguments

mellow tide
#

@strong oriole flask by a long shot lol ... but that is because django includes EVERYTHING you need. Flask you have to lego it together

#

Thatโ€™s what I did. The scraped value is x . Do I need to put x in the page function arguments
@void leaf either as an argument, or defined as a global variable

strong oriole
#

wdym lego it together

void leaf
#

Thanks Iโ€™ll let you know if it works @mellow tide

mellow tide
#

puzzle-piece it, you have to find and build functionality outside of the original intent of flask

native tide
#

Sorry bro I'm not that experienced to answer

mellow tide
#

flask is great for hosting sites, but doesn't include user auth, a database, it's not really that great for APIs unless you use another plugin

#

basically, you have to find the plugins you want with flask, whereas, Django is "batteries included" and they all exist, but you have to learn all the parts

#

it's ultimately more work to use flask, but you get to break it up a bit

native tide
#

Guys if you have a DataRequired() validator, if the form is empty, it will show you a box saying 'Field empty' right?

#

Is that the same for other validators such as Length()?

mellow tide
#

i would assume, but without looking at it, i don't know lol

strong oriole
#

soo django is more noob friendly as it has everything but flask is just some bits i need to use to create something big did i get you guys right?

native tide
#

I think flask is more user friendly but there are plugins for stuff such as authenticating users instead of it being included in django

strong oriole
#

so final decision flask or django is easier to learn while being good enough to do something useful

#

xD

dark agate
#

flask is more friendly for beginners

native tide
#

Yea I'm a beginner I'm having a good time with flask

#

Except for the validators :(( still unsolved

late gale
#

Does anyone here familiar with pythonanywhere please

mellow tide
#

i've used it in a pinch, why do you ask @late gale

uncut spire
#

if i have a flask application that is beginning to accrue a lot of routes/the main application file is getting pretty long, is splitting it into blueprints a decent improvement?

mellow tide
#

yeah, that is what blueprints are for ๐Ÿคท thats typically how i do it anyway

#

granted, i don't do much with Flask anymore

uncut spire
#

awesome, thanks!

late gale
#

@mellow tide I have made translation in django like i made a button to change from english to arabic and vice versa it works very well on local host but it doesn't work on pythonanywhere is there any problem how to solve this

mellow tide
#

oy, yeah i18n is not my strongest area lol

late gale
#

=,=

#

i have added the local files on the url of pythonanywhere but still not working

#

what shall i do then

#

i added all the urls
/locale/
/ar/
/LC_MESSAGES/

#

and nothing has worked

#

does anyone know a solution for this i searched alot on google but seem most people doesn't use localization /django translation

#

please i was trying to search for a fix since july

bold elbow
#

hey so rn i have this view where i post a message in a forum:

class NewMessage(LoginRequiredMixin, CreateView):
    model = Message
    fields = ['content']

    def form_valid(self, form):
        form.instance.author = self.request.user
        thread_path = self.request.path.replace('/new', '')
        form.instance.thread = Thread.objects.filter(pk=int(thread_path[thread_path.rfind('/') + 1:])).first()
        return super().form_valid(form)
```and i have the middle two lines in `form_valid` to get the current forum
the thing is, would there be a more efficient way to do this? (ping plz)
native tide
#

If I give some flask code can you guys try to run it and see if it works? Because I'm getting no errors the code matches documentation and it's not working for me

gentle hornet
#

you can send the code

native tide
#
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, PasswordField
from wtforms.validators import DataRequired, EqualTo, Length, InputRequired
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'CSRF_PROTECTION'

class SignUpForm(FlaskForm):
    username = StringField('Username:', validators=[DataRequired()])
    password = PasswordField('Password:', validators=[InputRequired(), EqualTo('password1', message='Passwords do not match')])
    password1 = PasswordField('Confirm Password:', validators=[InputRequired(), EqualTo('password2', message='Passwords do not match')])
    submit = SubmitField()
@app.route('/')
def hello_world():
    return 'Hello World!'

@app.route('/signup', methods=['POST','GET'])
def signup():
    form = SignUpForm()
    return render_template('signup.html', form=form)


if __name__ == '__main__':
    app.run()```
#

This is the form

#
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sign Up</title>
</head>
<form method="post">
    {{ form.username.label }}
    {{ form.username() }}
    {{ form.password.label }}
    {{ form.password() }}
    {{ form.password1.label }}
    {{ form.password1() }}
    {{ form.submit() }}
</form>
</body>
</html>```
#

signup.html

#

So, the issue I am having is that EqualTo() is not showing errors when the password fields do not match. Can you possibly see if it is showing you anything, if the password fields are different?

#

Thanks so much btw

#

Oh, this is on /signup page btw

lucid vine
#

sqlite3.DatabaseError: file is not a database, what the hell does this mean? It is for a fact a database ๐Ÿ˜…

#

fun fact is that identical files work fine on another pc...

#

also if I run the function directly, not through flask it updates the values as it should

wild thunder
#

guys, what is the best way to schedule tasks in flask?

cold anchor
wild thunder
#

oh it seems very easy to use

#

thanks @cold anchor ๐Ÿ˜„

rustic pebble
#

@cold anchor what are the disadvantages of using crontab?

cold anchor
#

the most granular time is 1 minute

#

you need to make sure the user running the command has permissions to do so

#

and you're limited to the health of the server it runs on

native tide
#

I have a question involving security with Django. A project I'm working on with it is going to be using React components in some places, for instance a private message window commonly seen in a lot of forums. For the inbox for example, the component will simply make an API call to the server of the user's ID, and get back a paginated list of messages. The necessary data for JS is fed in through the template as context, simple enough right?

This is the part that loses me though... can't this functionality be easily manipulated, or if not, what is preventing it? For example, someone locally changing their html data, running it, and then getting someone else's inbox messages (provided they have another person's primary key), or doing the same with a POST request, changing data that isn't theirs. Any nudge in the right direction would be much appreciated.

cold anchor
#

only give load the messages of the currently authenticated user, then the security will be as good as your authentication system

rustic pebble
#

I want to run a background task where it refreshes the state of membership for my members, I have around 1300 members connected through Stripe

#

I need a way to refresh their data every 12 hours

#

and I am thinking of using crontab

#

Instead of installing something like celery

wind walrus
#

If I already use flask-SQLAlchemy for my databases should I try making a nested comment thread system with SQLAlchemy too?

#

Or would Postgres or MySQL be better

crystal quartz
#

@rustic pebble celery is a pain and overpowered for what you need. Crontab is the right answer here. You can either set it up locally to run on your server, or set up an endpoint through flask/django and have a service like setcronjob senda request to that endpoint when you specify.

rustic pebble
#

Yup