#web-development

2 messages ยท Page 159 of 1

late gale
#

so i need something powerful

jade lark
#

I honestly wouldn't have recommended trying to build an ecomm site if this is one of your first few projects. However... Given the situation I would recommend Heroku or PythonAnywhere.

#

As you don't want to have a security breach on the server.

late gale
#

and not my first proj

jade lark
#

But you haven't deployed before?

late gale
#

pythonanywhere or heroku are the best choice

late gale
#

but when i tried to use 1i8n

#

pythonanywhere doesnt translate

#

though it does in local host

jade lark
#

For this project, absolutely. If you haven't deployed before on your own server then go with a provided solution

late gale
#

but what about the 1i8n feature

#

its not in pythonaywhere , its a multilanguage site

inland oak
late gale
inland oak
jade lark
inland oak
#

or rent cheap VPS and deploy on your own

#

i saw a list of even free VPSes

mystic galleon
#

There is the error could not resolve in vs code

#

Someone have an idea why?

inland oak
#

did you try to read the error?

mystic galleon
inland oak
#

well, wrong import name

#

keycloak is not installed, or you have wrong name used in import

#

or, you don't have activated virtual env for your visual studio code

late gale
mystic galleon
inland oak
#

check at its bottom

#

which one venv is activated

mystic galleon
#

Ahh lol thk dude

#

now is wirking

autumn hedge
#

Anyone here using Flask 2.0?
Im getting an issue after my upgrade from 0.12.5 where multiple api calls are not returning propery state from the endpoints. Rolling back corrects the issue so I'm not clear what changed in terms of controller responses within Flask

late gale
#

Has anyone tried Reactjs with Django

#

I wanna give it a shot

calm plume
late gale
#

Cool

#

oh btw when i change from Sqlite to Prostegrsl , will it improve performance or it doesnt matter

inland oak
#

apperently it is actually quite common usage

#

Django in DRF mode is preferable

late gale
#

yea DRF is so great

late gale
naive rock
#

How is post request different from put request? I know post request would be like creating something new and then put would be updating/editing. We probably cant do put on something that doesnt already exist because there's nothing to update, unless the library falls back on post.

#

If I am using API to update an attribute called quantity for an item, would it matter if I use post or put and rest of the info about an item would stay the same? This is actually the actual question lol.

inland oak
#

For a simple javascript logic it can work fast and well enough

#

There are some alternatives if regular js is not enough

#

Basically... you can use appropriate mixes of regular pages / jinja / dynamic javascript stuff, in any proportions.

React just makes simpler handling a lot of js

late gale
late gale
#

Django isn't so good with templates so it really needs a frontend framework like React or Vue but i will go with react cause i Love it

inland oak
#

I plan one day to learn react too

#

Too big queue of backend+devops stuff at the moment

late gale
#

I learned vue after react , Vue is very easy but react has a lot of features than vue

native tide
#

What to study after learning Js and Dom(js)

late gale
#

there are numerous things to do using Js

native tide
#

full stack developer

#

I know html css js and django

late gale
#

then React

native tide
late gale
#

Also learn Django rest Framework

native tide
late gale
#

for creating RESTFul APi and u need it for React

#

its very easy

native tide
late gale
#

let me recommend u some videos I watched

#

helped me alot

#

both are good , u can choose one

#

or both

#

then there's django + react

#

that's it

#

Tim is the best

native tide
#

thanks ๐Ÿ’ฏ freecodecamp is also good ๐Ÿ˜„

late gale
#

Absolutely , whatever u are comfortable with

mint folio
# naive rock bump

Yes it does matter. You need to use the verb that the api requires for that route.

naive rock
#

If I know where the resource lives, can I still use post?

mint folio
#

@naive rock If the route accepts post then you should send it post. If you did put, you would get an error like 400/405

#

The same applies to other types

modest hazel
#

Hi guys, I came upon this kind of login page:

#

I notice no data is sent in the request body

#

How does the server receive this data?

#

Server: Apache/2.4.25 (FreeBSD) OpenSSL/1.0.1s-freebsd PHP/5.6.30

#

If it helps

thorn igloo
opaque rivet
#

@modest hazel have you checked the headers?

modest hazel
#

It's a porn website lmfao

thorn igloo
#

hmmm

modest hazel
#

i got it now tho, it's just base64 encoded, separated by a :

peak lava
#

i need help with django auth signup form customization:

            {% csrf_token %}
            <div class="textbox">
                <input type="input" class="form-control" name="username" id="inputEmail" placeholder="Username" name="" value="" required>
            </div>
            <div class="password">
                <input type="password" class="form-control" name="password" id="inputPass" placeholder="Password" name="" value="" id="password" required>
            </div>
            <div class="confirm_password">
                <input type="password" class="form-control" name="password" id="" placeholder="Confirm Password" name="" value="" required>
            </div>
            <input class="btn" type="submit" style="opacity: 1 !important;" value="Sign Up">
        </form>```
does anyone know what's the id=" "  of input Confirm Password:?
fallen kindle
peak lava
#

?is it not

#

i mean this type of custom worked for my django auth login form

#

i've just copy-pasted that code here, but added the confim_pass textbox

#

/input

solemn nebula
#

can someone help me with flask? Im getting an attribute error: AttributeError: 'Token' object has no attribute 'test' when i do return render_template("users.html", rows=rows) where rows is directly from a sqlite database

nimble epoch
solemn nebula
#

yeah but i never interact with any kind of Token object @nimble epoch

#

or at least not directly

#

it looks like it's in my virtual env venv\lib\site-packages\jinja2\parser.py

outer apex
outer apex
peak lava
#

i belive it should be a unique id thats already defined within django.contrib.auth library

dusk portal
#

Lmfao!

unkempt salmon
#

Hey guys. Does anyone have advice with learning Django? any youtube videos you can recommend?

nimble epoch
weary bough
#

TIME_ZONE = "Asia/Kolkata"
why even after setting this in django settings I m still getting timezone.now() as 24 as the date?

#

its 25/5 as you will be able to see at the bottom right , but if you see the debugger variables then you will see it's 24

#

from django.utils import timezone

timezone.now()
datetime.datetime(2021, 5, 24, 19, 31, 23, 611639, tzinfo=<UTC>)

#

why?????

autumn hedge
#

@ds12 state meaning the API responses.

#

I think it has something to do with how the flask server teardown the request

quasi relic
#

guys any idea how can I delete a user and the related posts data from the database?

#
    form = DeleteAccount()
    if form.validate_on_submit():
        user = current_user
        posts = Post.query.filter(Post.user_id==current_user.id).all()
        if user.check_password(form.password.data):
            db.session.delete(posts)
            db.session.commit(user)
            flash('Your account has been deleted.')
            return redirect(url_for('logout'))
    return render_template('delete_account.html', title='Delete Account', form=form)```
#

ye forgot to mention the framework==flask , so this is my delete account func and it throws me -> sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.list' is not mapped

nimble epoch
#

you use sqlalchemy right? you can use id to delete all his/her posts but you should use cascade

quasi relic
#

dont look at this point -> db.session.commit(user) mistake

nimble epoch
#

and this view is for deleting user and its posts?

quasi relic
#

so I have to use cascade in my model?

#

ye

#

it should be .. but ye

nimble epoch
#

and i dont know it's your app or not but you dont need any forms to delete user

#

just a button

quasi relic
#

or link?

nimble epoch
quasi relic
#

this is how it looks like

nimble epoch
quasi relic
#

yeah

quasi relic
nimble epoch
#

i dont remeber well sqlalchemy but yeah i think that was something like that cascade="delete delete-orphan" or something

unkempt salmon
#

@nimble epoch What is main docs ๐Ÿ˜ฆ

quasi relic
nimble epoch
#

django official documents

nimble epoch
quasi relic
#

sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.list' is not mapped

#

db.session.delete(posts)

#
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), index=True, unique=True, nullable=False)
    email = db.Column(db.String(64), index=True, unique=True, nullable=False)
    hashed_password = db.Column(db.String(32), index=True, nullable=False)
    joined_time = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    user_post = db.relationship('Post', backref='user', cascade='all, delete, delete-orphan', lazy=True)

    def check_password(self, password):
        return check_password_hash(self.hashed_password, password)
    
    def hash_password(self, password):
        self.hashed_password = generate_password_hash(password)
    
    def __repr__(self):
        return 'User {}\nusername:_{}\nemail:_{}'.format(self.id, self.username, self.email)


class Post(db.Model):
    __tablename__ = 'post'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80), index=True, nullable=False)
    date_posted = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    text = db.Column(db.Text, index=True, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='cascade'), nullable=False)

    def __repr__(self):
        return 'Post {}\n{}\n{}'.format(self.id, self.title, self.date_posted)```
nimble epoch
#

i remember something like that but im not sure whats the solution

#

doesnt it mean that the record you looking for doesnt exist?

quasi relic
nimble epoch
#

ye better

quasi relic
# nimble epoch ye better

When you are adding a non-model-object into the session, you will be getting UnmappedInstanceError. so the solution was to remove the -> db.session.delete(posts) | posts = Post.query.filter(Post.user_id==current_user.id).all() , and it deleted succesfully the user and the related posts to it

#

I only needed to delete the user after I added cascade to my model

#

but still wondering why ๐Ÿ˜„

nimble epoch
#

you use migrations?

#

after updating models?

quasi relic
nimble epoch
#

i think thats because of that BUT this can happen when you have added new field to model and already had a record but that field in the record is empty

white parrot
#

Hey guys just wanted to ask something. Two people including me are working on a django project and both of us have no big experience with github. Whenever we push our codes, mine work fine, but his push generally creates some kind anomaly or what, making the whole branch corrupt. Would putting migrations files into .gitignore a good way or shall I search for something else??

#

Please tag me if you answer this

quick juniper
white parrot
#

Yes sort of

#

I mean i do have my separate branch which works fine with my code

#

But the problem is when we work on the same branch

quick juniper
#

what kind of anomaly do u have, can u be more specific

white parrot
#

I think it's kind of " <<<<<head " appears in code in many different places

quick juniper
#

in the code or specifically in the migrations

#

I hope that this will work for u and your team m8

#

if not i would suggest that u research a bit there are many other people that have the same problems and established a work flow for them self

summer nexus
#

is there a good tutorial for Django?

quick juniper
summer nexus
#

oh cool thanks

quick juniper
#

no problem and good luck

opaque rivet
# white parrot I think it's kind of " <<<<<head " appears in code in many different places
#

just update the current working directory before you both start working on your code.

quasi burrow
#
from simple_websocket_server import WebSocketServer, WebSocket

#Basic server for receiving data from webclient
class basicServer(WebSocket):
    def handle(self):
        global messages, returnMessages, count
        print("GOT NEW MSG",self.data[0:10])
        messages.append(self.data)

        while len(returnMessages) > count:
                self.send_message(returnMessages[count])
                count+=1


    def connected(self):
        global running
        print(self.address, 'connected')

    def handle_close(self):
        print(self.address, 'closed')




server = WebSocketServer('', 80, basicServer)

z = threading.Thread(target=server.serve_forever)
z.start()โ€Šโ€Š

https://github.com/pikhovkin/simple-websocket-server/blob/master/simple_websocket_server/__init__.py
source ^

How can I use send_message outside of basicServer class

GitHub

A simple WebSocket server. Contribute to pikhovkin/simple-websocket-server development by creating an account on GitHub.

devout coral
#

Anyone here know how to import a js library from cdn to use in a js script.

calm plume
#

You can use a <script src="cdn url"> tag I believe

devout coral
#

I mean to put it inside of a js file

#

Not in HTML

calm plume
#

Ah, my bad

devout coral
#

No all good

#

Anything helps, I am lost.

austere eagle
#

I got this error as I was trying to build a simple web app

#

that will display informational graphic

elder laurel
#

Can anyone provide me with a basic understanding of what Flask does?

inland oak
# elder laurel Can anyone provide me with a basic understanding of what Flask does?

Set of libraries
Gathered neatly together
Which solve all your basic problems on the path of making web site

Flask solves for you requests, routes, gives... template language, makes possible easily handling basic operations like login, or any other data insert, web site auto translation(also known as localization), gives basic web server to try running it, handling database connections and migrations and etc

#

Basically, do not reinvent a wheel, when people already all made for you

austere eagle
#

Can anyone help

outer apex
# austere eagle Can anyone help

Just google the full RunTimeError exception message. There seems to be a few threads with potential solutions you can explore.

austere eagle
#

Already have..nothin worked..ty though -sigh-

white parrot
#

@quick juniper @opaque rivet Thank you

native tide
#

I'm working on a blog platform in Flask. I'm trying to simplify the permissions/access for posts that users can create. Every post's access is controlled by two variables: is_published (a bool) and visibility (a enum).

Basically, for every endpoint, I don't want to have to micromanage which user has access to being able to see the post. Is there a design pattern I should use to deal with this, or some kind of library?

outer apex
small cape
#

How do I make div blocks over and over again in jinja2

native tide
#

Right now the way my project is, I have to manage the permissions in every context/endpoint, and this logic the spread out.

Eg, if you want to access a list of all posts in have to customize the query to not show unlisted and unpublished, but if you're the author you should be able to see all of your posts. When you want to edit the post, there's logic there to make sure you're not editing other people's posts. Just seems like I can simplify all of this logic in one place.

I should mention in doing everything server-side. Nonfront end frameworks or anything.

stark tartan
#

How to deploy django with celery

outer apex
#

Can you share some snippets to how you're managing these permissions?

stark tartan
outer apex
#

Talking to @native tide

stark tartan
native tide
dull pier
#

usually you will require 2 things. 1 - check if user has permissions for a single object, 2 - filter the list based on permissions

#

if you design your schema properly then neither becomes a pain. You can write helper methods somewhere in lib, may be a decorator and just use that

#

you should also explore "guard clause" design pattern so that your logic can be simplified

dull pier
stark tartan
#

If yes please guide me

dull pier
stark tartan
dull pier
#

there are more than handful things to take care of while deploying celery with django. that's why I'm suggesting you to go through that guide and try to setup things. If it doesn't work then we'll help

#

otherwise helping you do that will be another exercise to write the same guide here

#

to sum up celery deployment, 1. make sure you have django server running on gunicorn/nginx etc 2. make sure redis/rabbitmq is running and configured correctly 3. run celery worker 4. if you have periodic tasks then use django-celery-beat 5. profit

inland oak
#

hmm, thinking what are the advantages to pack postgres into container

dusk portal
#

Oh

marble spade
#

how can I center something in the middle of the screen, but allow it to be reactive (Things will not overlap).

.wrapper{
    position: fixed;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}
#

I want the items to site around the search-bar

dull pier
inland oak
#

it would be great... but they need to be 'mirror'ed to each other in this case in order to share the same data

#

but it can't be resolved at this level

lusty walrus
#

I know this is a python discord but are CSS questions allowed in here?

#

I can't figure out why multi-lined text in my pseudo table are not being justified

marble spade
#
.search-input{
  margin: auto;
  width: 60%;
  border: 5px solid #FFFF00;
  padding: 10px;
}

how can I make it so that the orange thing goes away, I want the stuff below to flow nexzt to it

thorn igloo
marble spade
#

hm

#

I wanna make it so there is a searchbar and there are elements around the outise

#

closest i

#

have got

thorn igloo
# marble spade

can you make a rough sketch of what you want it to look like?

marble spade
#

the elements on the side

thorn igloo
#

oh

#

you can use positioning to achieve that

marble spade
#

but like when I position it, the elements don't go around it

#

it creates a margin

#

even if I set margin to none

thorn igloo
#

no, i mean the position property

marble spade
#

you mean position; relative:?

thorn igloo
#

you can change it's z index to bring it ontop of the other elements

thorn igloo
marble spade
#

I tried that

#

it sets a margin around the outside

#

therefore the items will not sit around the outside

#

I need the div to stay as the yellow dimensions

#

instead thats what it looks like

vestal hound
#

the search bar to be in the middle?

marble spade
#

I mean yes

thorn igloo
#

man, i dont understand what you want

vestal hound
#

yeah I don't either

marble spade
#

hmm

vestal hound
#

can you

marble spade
#

I want the searchbar in the middle, and the other items to float around it

hoary brook
#

I see what you're trying to achieve, but I think to make it nicer for users I'd just make the search bar span 100% at the top instead of embedding it between search results.

vestal hound
#

draw EXACTLY what you want

marble spade
#

oh wait I have a screen design

#

1 sec

vestal hound
#

then it needs to be in the same container

#

as the results

#

that sounds...weird...though

#

IMO

marble spade
#

ignore the search results

vestal hound
#

wtf

marble spade
#

but it should look something like that

#

im' pretty fast

vestal hound
#

that looks nothing like the above result

#

I'm even more confused

marble spade
#

hm

vestal hound
#

okay

#

do you want

#

something like this

marble spade
#

thats not an exact design

vestal hound
#
result result result result result
result SEARCHBAR GOES HERE  result
result result result result result
#

or

marble spade
#

more like ```
result SEARCHBAR GOES HERE result
result SEARCHBAR GOES HERE result
result result result result result
result result result result result

vestal hound
#
result |                    | result
result |                    | result
result |  SEARCH GOES HERE  | result
result |                    | result
result |                    | result
marble spade
#

yeah 2nd one

#

looks closer

vestal hound
#

then

#

that is simpler

#

use flexbox

#

with 3 columns

#

middle column contains search

#

done

marble spade
#

ok lemme try

vestal hound
#

honestly

#

weird ass design though

hoary brook
#

If I can just give my opinion on this, I recommend sticking to the layout below, it's more accessible and has better visual hierarchy:

<search result> <search result> <search result>```
marble spade
#

its gon look clean asf in the end dw

vestal hound
marble spade
#

its gon be a unique design

vestal hound
#

it also seems to have accessibility issues

marble spade
#

ill ping u when I do it

vestal hound
#

no need to ping me

hoary brook
#

E.g. FontAwesome is a good example of a nicely structured search.

marble spade
#

kk

vestal hound
#

I have done enough UI/UX design to see

#

lots of people

#

who think their design is new and unique

#

indeed it is

marble spade
#

xd

vestal hound
#

but most of the time

#

it also fails miserably in the usability department

#

new and unique is easy

#

new and unique and PRETTY is not difficult

#

new and unique and pretty AND usable is hard.

#

but I'm sure you've done your user interviews and gathered your focus groups

#

and thereby validated your design

hoary brook
#

@marble spade One more thing, your design doesn't look it it will be responsive, especially on mobile.

#

You'd have to start moving things around and most likely get rid of the 3 columns on mobile anyway...

surreal portal
#

If there's something I retained on frontend/UI/UX is that you have to keep it as simple as you can

#

I say this while I barely know how frontend works and my speciality is changing font sizes, weights and colors

hoary brook
#

The first thing I learned it to keep the basic rules in mind like visual hierarchy, scale, use of whitespace, etc. As long as you have that you can expand on it and create your own unique design.

proud lintel
#

hi, I want to display my image as url as follows
127.0.0.1:8000/media/images/product123.jpeg

How, can I do this?

I am storing my image as follows
image = models.ImageField(upload_to="images")

mental veldt
#

i have those models, I am trying to make an api call that returns something like:

#

{
class_a:
{
firstname: john,
lastname: do,
total_score: 200,
},
{
firstname: jane,
lastname: do,
total_score: 300,
}
class_b:
{
lastname: steve,

},

#

something like that. somebody help

surreal portal
#

Btw is there a way to deploy a dockerized service without using swarm or Kubernetes?

#

I have something working with docker-compose

nimble epoch
#

make sure you adding static to urls

proud lintel
#

Can you please tell me what I have to add?

nimble epoch
#
from django.conf import settings
from django.conf.urls.static import static

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
#

use this code in DEBUG mode

#

you can do something like ```py
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

proud lintel
#

I have added this then it creates another error.

nimble epoch
#

what error?

proud lintel
#

When I am writing debug =false it is not working.

nimble epoch
#

of course it wont work

#

if you on deployment mode use whitenoise

proud lintel
#

So, how can this work with debug =false

proud lintel
nimble epoch
#

not working?

proud lintel
#

Not working

nimble epoch
proud lintel
#

Yes

nimble epoch
#

do static files work? i mean static files not media files

#

and did you do a migration?

proud lintel
#

Yeah,..

#

Have I done the things in a correct way?

nimble epoch
#

whitenoise middleware should be under securitymiddleware

proud lintel
#

You mean this...

nimble epoch
#

yep

proud lintel
#

But still I am getting this๐Ÿ˜ญ

nimble epoch
#

do another migration of course if its necessary then try it

proud lintel
#

With debug =false it is working fine...

proud lintel
proud lintel
#

No , django

native tide
#

How to add a simple messaging feature to my django website using websockets ?

thorn igloo
#

i think your issue can be solved with dynamic routing

native tide
proud lintel
native tide
proud lintel
native tide
#

okay let me look into it and thankyou

thorn igloo
# proud lintel What is this, and how can I do this...

i'm not sure how to do this in django but in flask you would have something like this

@app.route("/media/images/<filename>")
def getImage(filename):
  #here would be some function to return an image based on the filename
proud lintel
#

I am not familiar with flask ...

proud lintel
#

I know this name only.. nothing more than this

thorn igloo
#

maybe this will be helpful

#

again i'm not familiar with django

#

so i'm just taking a leap and guessing here

proud lintel
thorn igloo
#

ok then

proud lintel
#

Hmm

#

@nimble epoch , I have to access my image as follows.

nimble epoch
#

i know im trying to fin out

thorn igloo
# proud lintel

ok, can you explain how dynamic urls dont solve this problem for you?

nimble epoch
#

ill let you know

proud lintel
proud lintel
thorn igloo
#

you get the filename from the dynamic url, you use the filename to find and serve the image

#

ultimately you want something like this right?

proud lintel
#

Yes...

#

Exactly, like this, but in django

thorn igloo
#

yes, i'm achieving this with dynamic urls

thorn igloo
proud lintel
#

I have filename but I am not able to serve it.

#

In production mode.

#

I am able to serve it in debug mode.

thorn igloo
#

hmm

#

weird

proud lintel
#

Hmm

inland oak
#

if you don't want your website being discovered

#

is it safe to attach it to 80, 443

#

or better hide to some other port

proud lintel
#

Hide to some other port

opal vale
#

Which one is the better option?

  1. PUT /message/{message_nr}
  • payload
{
  "text": "string",
}
  1. PUT /message
  • payload
{
  "text": "string",
  "nr": 0
}
mint folio
mint folio
#

I know

#

But to pass it through the url, since itโ€™s identifying a resource

#

And benefits of that is also some frameworks can auto resolve it for you through dependency injection.

prisma canopy
#

hi, I am having a problem

#
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

@app.route("/hi")
def rudransh():
    return "Hello rudransh!"


if __name__ =="__main__":
  app.run(debug=True)


#

when i run the code and change the end point to /hi

#

it shows error 404

surreal portal
#

Anybody knows how to set a docker-compose so the proxy/front is exposed on one particular host and port?

prisma canopy
#

@surreal portal can you help with my problem

#

idk why it's happening

surreal portal
prisma canopy
#

no

#

i did that in terminal

peak sandal
#

hey guys, Does anyone know how to use adafruit feeds on django?

prisma canopy
#

i mean i just ran my code

surreal portal
prisma canopy
#

no

surreal portal
#

Because a correct launch means your terminal is runnung your Flask app and you can access it at http://localhost:5000

surreal portal
prisma canopy
#
 * Serving Flask app "FLASK WEB APP" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 311-665-859
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
prisma canopy
surreal portal
prisma canopy
#

that's not showing

surreal portal
#

But if you added more routes in the meantime, you have to stop with Ctrl+C and restart your app

prisma canopy
#

it's showing a error instead

dusk portal
#

Oh

surreal portal
#

Yeah 404 means the route doesnโ€™t exist. Meaning you added it after you launched your app for the first time

prisma canopy
#

yeah

surreal portal
#

If you want /hi to be shown, you have to stop your Flask app and restart it (also donโ€™t forget to save)

prisma canopy
#

but i reloaded also

#

i saved it, I restarted it

surreal portal
#

Refresh your browser

prisma canopy
#

it doesn't work

#

not working

surreal portal
#

If nothing works, clear the cache and restart your FLask app

#

Or open your route in a private tab

prisma canopy
#

i am screwed man

#

anything doesn't work

surreal portal
#

Iโ€™m sure you probably forgot one of the steps Iโ€™ve indicated

dense slate
#

Anyone know why vs code might not let me connect to the server via any browser sometimes but then if I just restart my pc it works? It seems to be happening like 50% of the time that I can't connect.

surreal portal
#

Also never name your Python files like you did. Python files must be named with snake_case.py

prisma canopy
#

nothing works

#

did everything

#

i am SCREWED!!!!!!!!!!!!!!!!!!!!!!!!!

surreal portal
#

The other recommendation I can offer is to start over with a virtual environment with Flask 2.x installed and follow the quickstart tutorial just one more time

dusk portal
#

Lpl

dense slate
# prisma canopy i am SCREWED!!!!!!!!!!!!!!!!!!!!!!!!!

Just take it one step at a time bro. Debugging is always going to be an issue. No point in getting frustrated. Just take a breather, get some air or some coffee and take another look or start from the beginning. ๐Ÿ™‚

surreal portal
#

Btw I wanted to know if there were any webdevs who successfully deployed a dockerized app on a VM with a fixed IP and a fixed port. How do you bind your app (the front-end network) on that fixed host + port, through docker-compose ?

inland oak
#

shrugs, I do separate docker-composes for separate code projects

#

I only make multi conterized dependencies for the same project only for

#

backend app + redis + postgres + nginx + celery

surreal portal
#

Yeah, my goal was to expose the frontend's ports while the backend communicates with the frontend on a private network

#

My docker-compose.yml files englobe the whole project. Never tried to override them in case it gets too complex

inland oak
#

well, there is expose flag which exposes port of container for internal private network inside of docker-compose

surreal portal
#

Ok I tried something on the port param:

ERROR: for web  Cannot start service web: driver failed programming external connectivity on endpoint react-frontend (CONTAINER_ID): Error starting userland proxy: listen tcp4 XX.XXX.XXX.XX:YYYY: bind: cannot assign requested address

Where XX.XXX.XXX.XX:YYYY is the address I want to bind my container on

inland oak
#

what is XX.XXX.XXX.XX: YYYY

#

VPS external IP like 216.65.234.65?

surreal portal
#

Yeah the XX is an IPv4 while YYYY is the port number

inland oak
#

it makes application exposed to the network outside, while taking exernal IP as its

surreal portal
#

Ok. I'll try the universal IP and see what gives

#

Man, next time I'll try Swarm or Kubernetes

dull pier
#

just install nginx on the server and reverse proxy it to docker container port

surreal portal
dull pier
#

why is it image?

#

I meant have it installed natively on the vps server

surreal portal
#

Because I set up a Dockerfile for production ready to use

dull pier
#

it will take additional efforts to bridge the networks, no?

#

your docker-compose net will have it's own subnet and stuff. then your nginx image will require to co-ordinate between external world and docker's internal network

#

and the nginx within container will never see your host machine's network adapter, hence it won't be able to bind to that ip address

#

what is the host os on your vps server?

surreal portal
surreal portal
dull pier
foggy canopy
#

Print ("hello")

inland oak
dull pier
#

could you please share your docker-compose?

surreal portal
surreal portal
# dull pier could you please share your docker-compose?

Here:

version: '3'

services:
  api:
    restart: always
    build: ./api
    env_file: ./api/.env
    expose:
      - 8000
    ports:
      - 8000:8000
    volumes:
      - ./api:/api
    container_name: fastapi-backend
    restart: always
    networks:
      - api-front

  web:
    build:
      context: ./web
      dockerfile: ./Dockerfile.prod
      args:
        environment: prod
        status: stable
    expose:
      - 80
      - 443
    ports:
      - 0.0.0.0:4000:80
      - 0.0.0.0:4001:443
    container_name: react-frontend
    volumes:
      - ./web:/web
    networks:
      - api-front

networks:
  api-front:
surreal portal
dull pier
#

ports are mapped as host:container, this means your web container internally has something running on 80 and 443 that you are binding to 4000 and 4001, is that correct?

#

also, you should not set container names in the docker files. containers should be stateless and if you somehow want to recreate the containers then names will clash and compose start will fail

inland oak
surreal portal
# inland oak can we see docker file of your front at least its ending / entry point / cmd

Here:

# Build env
FROM node:16.0.0-buster-slim AS build
WORKDIR /web
ENV PATH /web/node_modules/.bin$PATH
COPY package.json ./
COPY package-lock.json ./
RUN npm ci --silent
RUN npm install react-scripts@4.0.3 -g --silent
COPY . ./
RUN npm run build

# production environment
FROM nginx:stable-alpine
COPY --from=build /web/build /usr/share/nginx/html

# If you have a nginx.conf file, copy it
COPY nginx.conf /etc/nginx/conf.d/default.conf

EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
inland oak
#

nginx conf?

dull pier
surreal portal
#
server {

  listen 80;

  location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
    try_files $uri $uri/ /index.html;
  }

  error_page   500 502 503 504  /50x.html;

  location = /50x.html {
    root   /usr/share/nginx/html;
  }

}
#

@inland oak

inland oak
#

hmm

dull pier
#

also, is your react-frontend expecting to connect to fast-api server on localhost:8000 ?

inland oak
#
version: '3'

services:
  api:
    restart: always
    build: ./api
    env_file: ./api/.env
    expose:
      - 8000
    volumes:
      - ./api:/api
    container_name: fastapi-backend
    restart: always
    networks:
      - api-front

  web:
    build:
      context: ./web
      dockerfile: ./Dockerfile.prod
      args:
        environment: prod
        status: stable
    ports:
      - 0.0.0.0:80:80
    container_name: react-frontend
    volumes:
      - ./web:/web
    networks:
      - api-front

networks:
  api-front:
#

technically it is supposed to be something like that

#

if we will remove all not working ports

#

0.0.0.0:4000:80 as alternative, if you don't want being published at 80 port

dull pier
#

react-frontend won't find the fastapi server because react-frontend will try to connect "within itself" when pointed to localhost. For this connectivity you need to specify fastapi host as "api" <- this is the key you have define in docker compose as service name. Docker's dns server will help resolve the correct ip on it's internal network

#

there are 2 networks here. one is "api-front" that docker manages. and your "web" should be able to locate "api" on this network. Second is the actual network of host that connects it to the internet. That one you'll be binding on using ports directive under "web"

surreal portal
dull pier
#

and change the way you have mapped ports on web, as I have suggested above and give it a try

#

I just referred to some of my old deployment files

#

ports are mapped host:container

surreal portal
#

Hold on, that means I have to edit the middleware too

peak thicket
#

I've got a request that if a condition is true, it'll re-try in the backend in ~30 minutes after, for the response to the client explaining that this is going to happen, should I use status code 202 for accepted or status code 425 for too early?

dull pier
#

make it configurable from env vars

#

take a step back and understand how docker's private network works and what localhost means for a container. It means itself! Once you understand this part, docker-compose and networking will be very handy!

surreal portal
#

Time to take networking classes ๐Ÿ˜›

dull pier
# peak thicket I've got a request that if a condition is true, it'll re-try in the backend in ~...

if you are actually acknowledging the incoming request and pushing it to some sort of queue then 202 makes sense. If not then 425. Depending on this status code client will define their behavior, right? if you have ack'ed but reply with 425 then client will keep retrying may be every 5 minutes to get it in. If you were not ack'ing the request but responded with 202 then client would be under the impression that it doesn't have to do anything and just wait for it to complete.

dull pier
peak thicket
#

but thank you

#

ill use 202

dense lynx
humble raft
#

I want the output(string) of my python code to become a headline in a HTML file

#

any help?

paper pier
#
<a href="/create">Create</a>
``` urls.py ```py
path('create/',views.create,name='create')
```  its not working anyone know how to fix this?
paper pier
proud lintel
#

Can anyone tell me why I am getting this, when I am doing debug =false it is giving 404 error and when debug=true it is giving 200 code .

humble raft
opaque rivet
paper pier
humble raft
#

nvm i'll use js

austere eagle
#

So I have a site that saves whatever is uploaded to the site. How to get the web app (using python and django) to just print the JSON file uploaded? End goal is to eventually allow user to pick any graph they wish their JSON file to be represented in , and show the statistics that way

glossy panther
nimble epoch
proud lintel
#

I am not using django-storages, yeah, I also understand this that media file is not showing in production because of whitenoise, after creating a different project and doing all the things except whitenoise, but the problem is that I have to use whitenoise because I am deploying it into heroku.

nimble epoch
proud lintel
#

Whitenoise is creating a different folder for static files as staticfiles, means it has not to take anything from static folder , may be it is also ignoring media folder, I am not sure.

languid beacon
#

is django and react a good combination?

nimble epoch
wraith rampart
#

hi all.. i have an issue about django, can anyone help?

#

can i leave a stackoverflow link here?

#

anyone?

nimble epoch
nimble epoch
languid beacon
#

hey, can anybody recommend some js courses which are good

wraith rampart
#

im new so cant figure out why pinax implementation isnt working, in summary i used {% url 'django urls -for a signup button, but when i click it it redirects me to the index page. migrations are all working. it seemslike im missing something really basic but i cant see it since morning.

tough valve
#

What's the key difference in using management command and runscript in django?

worthy lake
#

IS it login_redirect_url setting?

austere eagle
#

How do I take a JSON file that has user data and convert it into graph data in my python django web app?

So far I managed to get two graphs showing on web page with generic info. However, I wish to have it where one can upload a JSON file of random user data to be displayed in a graphical form of one's choosing(pie char, bar, etc)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Please Upload File Here</title>
</head>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>


<!---- Code used to have multiple graphs on one page -->
<canvas id="myChart1" style="width:100%;max-width:600px"></canvas>
<br/>
<canvas id="myChart2" style="width:100%;max-width:600px"></canvas>


<!---Chart 1--->
<body>
<script>
var xValues = ["Male", "Female"];
var yValues = [55, 49];
var barColors = [
  "#b91d47",
  "#00aba9",
  "#2b5797",
  "#e8c3b9",
  "#1e7145"
];

new Chart("myChart1", {
  type: "pie",
  data: {
    labels: xValues,
    datasets: [{
      backgroundColor: barColors,
      data: yValues
    }]
  },
  options: {
    title: {
      display: true,
      text: "Test1"
    }
  }
});
</script>
</body>

<!----- Chart 2 --->
<body>
<script>
var xValues = ["Male", "Female"];
var yValues = [55, 49];
var barColors = [
  "#b91d47",
  "#00aba9",
  "#2b5797",
  "#e8c3b9",
  "#1e7145"
];

new Chart("myChart2", {
  type: "pie",
  data: {
    labels: xValues,
    datasets: [{
      backgroundColor: barColors,
      data: yValues
    }]
  },
  options: {
    title: {
      display: true,
      text: "Test2"
    }
  }
});
</script>
</body>
<!---- end of chart 2-->


<body>

<form method= "POST" enctype = "multipart/form-data">
    {% csrf_token %}
  <input type = "file" name = "file">
  <br>
  <input type = "submit">
  </form>


</body>
</html>```
#

I have managed to have button where you can upload any file and it is saved(I check admin side and see said uploaded files save so I got that going)

#

But no proper functionality to my web page

#

My goal is to essentially do this:

Making a single-page web app that displays informational graphics about the randomly generated users.
On the initial page load, the user should see a form that allows them to either paste the JSON into a text input field or upload it as a file.
Once the data has been entered, you should display the statistics in graphical form, using any charts, text, or interactive elements that you like.


Back End 
Please expose a REST API endpoint that takes random user JSON data and a file format as input, and returns a file containing the statistics.
Supported file formats for the results should include JSON, plain text, and XML. For example, the plain text file returned by your API endpoint should 
contain a line like, "Percentage female versus male: 66.6%".
For bonus points, instead of requiring the user to specify the file format, determine it automatically from the "Accept:" header in the HTTP request. 
The specific format of the data or text your API returns is up to you, as are the details of the URLs you expose```
thorn igloo
#

nvm. bar graphs, plots and pie charts etc are normally produced with numerical data. sounds like what you need to do is basically use the random json data to produce numerical data that can be used to plot whatever it is you want

austere eagle
#

It does have calculations

#

I did percentages

#

On a python file I have

#

Of course the code currently is doing statistics /calculations based on the file I specified to open

#

But I do wanna have it tweaked where it can do it for any JSON file uploaded to page

#

Kinda likeโ€ฆ putting puzzle pieces together

thorn igloo
austere eagle
#

Percentages

#

Sorry if I respond late moght nap

#

I feel tired

thorn igloo
inland oak
surreal portal
#

That's a good thing since I can't rely on matplotlib forever

#

Else I might be stuck with apps like streamlit

desert estuary
#

hello everyone i hope you're doing pretty fine so anyway i got some questions, im a newbie in webdev and im willing to become a full-stack web developer so im starting with the front-end (html,css) and i kinda grasp it a bit and in parallel i'm learning python and still in the basics(loops, functions and i will start in classes soon enough) and after that im thinking to study a bit of backend
note: i made two projects in python gui ( using tkinter i made a calculator and a tic-tac-toe) and now i wanna get my hands on the backend i still have some difficulties in the language itself "python" and im here to ask for your help, please :

  1. how can i improve myself in python to go from just the basic to a moderate or even advanced level in it, how to get out of tutorial hell basically and start making ideas happen and to kinda go from that obscure big idea to the small technical details you'll develop in python and also if there is a detailled tutorial that goes from babysteps to big outstanding advanced concepts
    2)i find a difficulty of grasping the backend and a bit overwhelmed since i feel a bit inferior to where i should be if anyone knows a ressource a where i can learn the fundamentals and the basics of the backend using python
  2. can i develop the backend using only vanilla python and without being tied up to framework ( i'm not planning to build apps in using only python ofc ill use a framework just out of curiosity and i might do that if im good at python)
vestal hound
#

building a backend from scratch is possible

#

but way too complicated for you right now

#

thereโ€™s a lot of routing code which requires you to have a good low-level understanding of networking

#

itโ€™s not trivial

desert estuary
vestal hound
#

but I would not reco building your own backend

#

it doesnโ€™t really train the right thing

#

because the whole point of a framework

#

is to abstract away the details of routing etc.

#

so you can focus on the business logic

#

it would be like trying to become a better racer by working as a mechanic

#

like sure you might learn some tangential optimisation techniques but that would likely also be a sign of a leaky abstraction

desert estuary
#

ohh i get it and what about sharpening my coding skills in python what do you recommend i just thought to start python all over again from the very beginining starting with this

limpid pivot
#

I have an app with a home page, where there is a button named "Run", which when clicked will create an excel file that is stored in some location in the project folder. Now I want to give a download option to download that excel file. I tried with HTML attribute
<a href="path\_to\_file" download="file\_name.xlsx"></a>
Now this will download the file properly. But when I try to open the file in Ms-Excel it gives an error.

Cannot open the file, the file is corrupt or file format is not supported.

native tide
#

So I'm working on this blog engine in Flask, I have it all quite nicely as I want it including a fully functioning REST API.

Should I use a frontend framework? or just keep using server-side pages with Blueprints, Jinja templating, and all that? What's the decision process that goes into this?

I should note that I want this blog's viewing to be as absolutely lean and stripped-down basic as possible. I hate how frontend JavaScript's frameworks are so computationally intensive, but if there's one that is very simple I'd happily use that.

minor bobcat
#

In my opinion, a framework would be easier because you can use pre-existing libs, e.g. material-ui

native tide
#

I'm already encountering complexity, having to code up a lot of crazy metaprogramming solutions to manage Jinja macros, blocks, extends...

Are JS Frameworks inherently laggy, or is it in how you code it?

jolly star
#

how do you define variables in an html page ( jinja template)

minor bobcat
native tide
#

Oh there's also Elm! Forgot about this thing

native tide
#

It looks like Elm's development has been stagnation. That is unfortunate. It's been ranked as one of the fastest frontend frameworks.

woeful swan
#

how to use django.db.models.Q standalone

#

for ex. Q(name__icontains='test')
how i can get a string from above like "name like %test%"
i want to write raw query which will take condition using the Q object, so that i can use OR and AND

native tide
#

Is there any way to render two html files in flask?

#

like this

#
time.sleep(2)
return render_template('wassup.html')```
ashen summit
#

hey, is there any way to use requests_html to continuously execute a javascript command on a webpage then save the html to a file?

#

ive got it down to where it can save the original webpage, how it changes after the first command, but then after that it just saves it like its the 2nd page alone

#
from requests_html import HTMLSession
import os
session = HTMLSession()
resp = session.get('https://rgl.gg/Public/PlayerBanList.aspx?r=24')
a = 1
for x in range(170):
    if not os.path.exists(f'./bans/{a}.html'):
        print(f'Writing {a}.html to files')
        f = open(f"./bans/{a}.html","w")
        f.write(resp.html.html)
        f.close()
        resp.html.render(sleep=5,script="javascript:__doPostBack('ctl00$ContentPlaceHolder1$btnNext','')",reload=False)
    else:
        print(f'{a}.html already exists')
    a += 1```
here is the relevant code
inland oak
#

what is better for react? served with npm serve, or perhaps better would be nginx

#

I feel like, Nginx is trusty and more secure way to serve react

#

actually perhaps it is so

dull pier
#

nginx ftw

surreal portal
#

I heard nginx was the nยฐ1

#

Isn't traefikv2 its main rival?

dull pier
#

there are more haproxy is also good

surreal portal
#

Btw @inland oak I tried your solution and I have this error ERROR: for web Cannot start service web: driver failed programming external connectivity on endpoint react-frontend (5f3e24bb667b521ad65ba2704315a42eac3ad1a2e83d888ac5e55affe5dd039b): Error starting userland proxy: listen tcp4 0.0.0.0:80: bind: address already in use

inland oak
#

well, I am experiencing similar troubles

#

fighting with nginx at the moment for react

jolly star
inland oak
#

having happy debugging time

#

oh, I actually was able to solve it

#

not in the best way yet though

#

yup, I solved for sure now

inland oak
#

there is application running (basic nginx page)

#
COPY nginx/nginx.conf /etc/nginx/sites-available/default
RUN service nginx stop
CMD nginx -g 'daemon off;'
#

I replaced its default file with mine

surreal portal
#

service nginx stop shuts down the current NGINX service outside the container and keeps port 80 busy, right?

solar valve
#

does 'rest_framework.authtoken' causes problem with simple jwt ?

mellow kettle
#

class Student(models.Model):
name = models.CharField(max_length=20, blank=True, primary_key=True)
omang_id = models.CharField(max_length=20, blank=True)
email = models.EmailField(max_length=254, blank=True)
male = 'male'
female = 'female'

gender_CHOICES = [
    (male, 'male'),
    (female, 'female'),
]
gender = models.CharField(
    max_length=7,
    choices=gender_CHOICES,
    default=None,
)
phonenumber = models.CharField(max_length=20, blank=True)
course1 = models.CharField(max_length=20, blank=True)
course2 = models.CharField(max_length=20, blank=True)
result1 = models.CharField(max_length=20, blank=True)
result2 = models.CharField(max_length=20, blank=True)
DateOfBirth = models.DateField(max_length=20, null=True)
New = 'NW'
Renewal = 'RL'

Purpose_CHOICES = [
    (New, 'New'),
    (Renewal, 'Renewal'),
]
Purpose = models.CharField(
    max_length=2,
    choices=Purpose_CHOICES,
    default=New,
)
address = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()

def __str__(self):
    return self.name
#

@login_required()
def Profile(request):
UserProfile = Student.objects.all()
return render(request, 'W/Profile.html', {'UserProfile': UserProfile})

#

i would like to know how i can only show the currently logged in users information and not just everyones information

#

also im a newbie thus i do not understand how to override the queryset

nimble epoch
#

ether in views or templates

burnt night
#

So...
I deleted my app from heroku, and I created a new one in the cli.
It says the app is created, but when I try to push, it is still trying to push the old one that got deleted and is therefore raising the error about how the old one does not exist.
How do I get it to look at the new one?

devout venture
#

Hey hey just a quick question I'm using flask to create an API, i'm trying to get the client to send a .wav file to the server but I can't find much online to help me out

#
import requests
BASE="http://127.0.0.1:5000/"
with open('audio.wav','rb') as file:
    files={"audio":file}
    resp=requests.get(BASE+"SAVAVOICE",{"audio":files})
    print(resp.json())```
#

This is my client side

#
class SAVAVOICE(Resource):
    def post(self):
        request.files['audio']
        audio = speech.RecognitionAudio(request.form['audio'])
        config = speech.RecognitionConfig(
            encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
            sample_rate_hertz=16000,
            language_code="en-US",
        )
        for result in response.results:
            print("Transcript: {}".format(result.alternatives[0].transcript))
        return ''```
#

And this is my server side

#

I'm trying to use the google speech to text API but I need to get the audio sent over first of all

#

Could anyone lend me a hand?

tacit snow
#

Then, on the server side, you'll probably want to do speech.RecognitionAudio(request.files['audio'].read())

#

Though, looking at the docs of the recognition API, it might need some changes.

#

speech.RecognitionAudio(content=request.files['audio'].read())

#

But I'm not sure about that part.

native tide
#

Hi, according to the django doc, I try to conf templates. I have APP_DIRS : True and I have templates folder in app directory, but it doesn't work. I also try to add path to templates folder to DIRS but still nothink. Were is my mistace?

prisma canopy
#
from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def hello_world():
    return render_template('index.html')

@app.route("/about")
def my_name():
    name = "rudransh"
    return render_template('about.html', name=name)

@app.route("/bootstrap")
def bootstrap():
    return render_template('bootstrap.html')

app.run(debug=True)```
#

this is my code, when i go to /bootstrap it shows error

#

I had suffered with this error before and had to start all over

thorn igloo
native tide
#

I need HELP...I want a tree text file...I have some mp3's and folders in my e drive...each folder has mp3's and subfolders with more mp3's...there r other pdf and other format files as well...I want to create a text file which contains all the mp3's names in lists under album names with album numbers all sorted by hierarchy and order....for example...album1 would contain the names of all the mp3's in the home page of e drive...album2: names of all the mp3's in the 1st folder of e drive...album3 would be names of all mp3's in 1st subfolder of 1st folder...if 1st subfolder has no more sub folders, album 4 would be the names of all mp3 files in 2nd subfolder of 1st folder...if 1st folder has just 2 subfolders then move on to the next folder in e drive and so on...All other files lyk pdf,etc r to be ommited

prisma canopy
native tide
prisma canopy
#

it has solved but when i run my 1st file it works and then when i run my 2nd file it doesn't work

thorn igloo
#

if the file present?

#

also did you add the route while the server was running etc

prisma canopy
#

see

prisma canopy
thorn igloo
prisma canopy
#

in sublime text it is

#

i mean at the templates folder

thorn igloo
#

expand the folder

prisma canopy
#

so when i run firstapp it works, but when i run wow it doesn't work

thorn igloo
prisma canopy
#

i did

#

most of the time

prisma canopy
thorn igloo
#

do your files have the same code?

prisma canopy
#
from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def hello_world():
    return render_template('index.html')

@app.route("/about")
def my_name():
    name = "rudransh"
    return render_template('about.html', name=name)

app.run(debug=True)```
#

code of first app

#
from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def hello_world():
    return render_template('index.html')

@app.route("/about")
def my_name():
    name = "rudransh"
    return render_template('about.html', name=name)

@app.route("/bootstrap")
def bootstrap():
    return render_template('bootstrap.html')

app.run(debug=True)```
#

code of wow

thorn igloo
#

ok what is the issue again?

prisma canopy
#

firstapp code runs and I can see bootstrap.html page, but when i run wow.py it shows 404 error

#

what;s the problem I dk

thorn igloo
#

how is the first app working when it has no bootstrap path?

prisma canopy
#

ah, okay. Sorry for disturbing. It worked, I restarted

#

thanks btw bruh

mellow kettle
tacit snow
native tide
tacit snow
chilly falcon
#

can some one teach me django rest framework authentication like basic session token??

native tide
#

Hey guys, how do I sell a single line from a text using django.
An example would be keys of a software. I paste many keys and it mails one of it on purchase.

thorn igloo
#

sounds like ecommerce

native tide
native tide
haughty shadow
#

Hi

#

Please Can someone help me with my django errpr

#

error

silk charm
#

Hello, I want to get simplest tracert in Scapy, maybe someone has one? mention me or dm me please if you got one

inland oak
native tide
north aspen
#

Anyone have any experience with getting Cloud Run to access a PostgreSQL DB in Cloud SQL?

#

On GCP?

nova nacelle
#

should i simply type the html divs in a single line to append using js?

peak lava
#

why tf does my web page not update when i make css/html changes

#

i've sent the same exact folder to my friend and for him it applies the new changes for me it doesnt...

indigo kettle
#

css might be cached by the browser

#

go to dev tools network tab and disable cache

peak lava
#

in my vscode or my browser

indigo kettle
#

browser

peak lava
#

thanks

#

do i have to reset the broweser or?

indigo kettle
#

no

calm plume
#

How does Django's template language introduce new syntax into html, do stuff with it, and not make editors scream in pain? How is it able to do that?

indigo kettle
#

probably because the syntax parser has been updated to expect these kinds of templating additions

calm plume
#

Ok, but how does it change normal HTML syntax? Some editors would probably scream, but they don't. Why is that?

indigo kettle
#

if the editor is not complaining then the syntax parser being used is updated and allows for this new syntax

#

or it is simply legal html and the parser thinks that the templating syntax is just text within the element tags

calm plume
#

Ty

indigo kettle
#

if you want to know the real answer you should see if you can find information on the parser being used in your editor

peak lava
#

nvm it worked, but it only worked when i kept my dev tools open

coarse haven
#

the devs of the editor scream in pain instead

#

:^)

indigo kettle
#

normally css is not changing on each pageload so the browser will just cache it and use what it saw last time

#

I think there is some hot key like ctrl-shift-r or something which will hard refresh the page

#

and not use cached resources

nimble epoch
green star
#

Anybody know where I could code a website using python?

calm plume
#

You would use your editor/IDE

green star
calm plume
#

You could technically use something like replit

granite glade
#

any advice on handling routes with flask. Whenever i see projects they're usually all handled in one file but i can't help but feel this formatting is for the sake of ease for tutorial purposes

nimble epoch
granite glade
nimble epoch
#

you can use add_url_rule

#

if im right

#

in flask

#

search it

quick cargo
#

yes but the decorators are there for a reason :P

#

they make it a bit cleaner having the routes next to the function

nimble epoch
#

no difference right?

quick cargo
#

you should look at blueprints if you want to separate things into separate files

#

No difference in terms of how they work

#

the decorator is a helper function

#

it makes stuff cleaner

granite glade
quick cargo
#

no, I would use blueprints

granite glade
#

ah okay

quick cargo
granite glade
#

thank you

drifting radish
#
{% extends "base.html" %} {% block title %}Profile{% endblock %}{% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'login.css' %}">


    <section>
      <div class = "box">
        <form method="POST">
          <h3 align="center">Login</h3>
          <div class="form-group">
            <label for="email">Email Address</label>
            <input
              type="email"
              class="form-control"
              id="email"
              name="email"
              placeholder="Enter email"
            />
          </div>
          <div class="form-group">
            <label for="password">Password</label>
            <input
              type="password"
              class="form-control"
              id="password"
              name="password"
              placeholder="Enter password"
            />

            <a href=https://d title="Please visit our discord server to reset your password">I forgot my password</a>
          </div>
          <br />
            <form class="form-inline">
              <button type="sumbit" class="btn btn-outline-success" type="button">Login</button>
            </form>
        </form>
      </div>
    </section>
{% endblock %}


```    {% extends "base.html" %} {% block title %}Profile{% endblock %}{% load static %}
jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'load'.
#

;0

#

python + html + css :c

#

pls help

nimble epoch
dense slate
#

Had anyone used next-auth with Django, or really any other existing app? I'm having trouble fitting it into an existing schema with the custom database/model options.

#

I can get next.js working with a JWT but i would really like to use next-auth to take advantage of email and social tokenization.

#

It just feels like trying to fit a square peg into a round hole.

buoyant shuttle
#

How do i know if the content of 2 array is the same as the other aray in js without looping

buoyant shuttle
#

Since Javascript doesn't have it, I'll develop a third party app

calm plume
#

@buoyant shuttle Why not just stringify them or use a loop?

#

Imo, you don't need a whole thing to just compare two arrays

buoyant shuttle
#

It's weird js doesn't have a built in function like that

vestal hound
vestal hound
#

you would need a recursive function with cycle detection to cover all cases cases

drifting radish
vestal hound
devout venture
#

Heyo so small question but I'm trying to send audio with flask over http post and then run it through the google speech to text api, I think I got the audio to send over fine but the google speech to text api isn't responding with anything and I was wondering if someone here could give me a hand

#

The client side code is thisss

#
import requests
BASE="http://127.0.0.1:5000/"
with open('audio.wav','rb') as file:
    files={"audio":file}
    resp=requests.post(BASE+"SAVAVOICE",files=files)
    print(resp.json())```
#

and the server side is

#
class SAVAVOICE(Resource):
    def post(self):
        #request.files['audio']
        audio = speech.RecognitionAudio(content=request.files['audio'].read())
        config = speech.RecognitionConfig(
            encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
            sample_rate_hertz=16000,
            language_code="en-US",
        )
        response = client.recognize(config=config, audio=audio)
        print(response)
        for result in response.results:
            print(f"Transcript: {result.alternatives[0].transcript}")
        return {"data":"Gotcha"}
#

At the moment i'm just trying to get it to print it out to the server terminal but response doesn't seem to return anything

#

That blank line is where it tries to print out response

regal raven
#

wow you really do have big eyebrows

dusk portal
#

hey

#

anyone's up?

autumn hedge
#

maybe..cuz my app sure isn't ๐Ÿ˜†

dusk portal
#

@autumn hedge hey

limpid pivot
#

I have an app with a home page, where there is a button named "Run", which when clicked will create an excel file that is stored in some location in the project folder. Now I gave a download option to download that excel file. I tried with HTML attribute

<a href="path\_to\_file" download="file\_name.xlsx"></a>

This will download the file properly. But when I try to open the file in Ms-Excel it gives an error.

Cannot open the file, the file is corrupt or file format is not supported.

austere relic
#

Because like, it'd just be the same as the href value anyway

#

Second of all, did you try just opening your file directly to see if it has even got anything to do with the server?

autumn hedge
#

Anyone know how to install or update a local version of Flask to 2.0.2? using pip

limpid pivot
#

when i tried to include the file name in href it download with "No file" tag
and yes there is file created after clicking run in the server.

#

@austere relic

autumn hedge
#

I tried that already

#

thanks @austere relic

#

--upgrade yields the same error as well

austere relic
#

well, newest version on pypi seems to be 2 0 1

#

soooooooooooooooooooo.......

autumn hedge
#

my app worked using an old version, but partially works after upgrading to latest Flask

austere relic
autumn hedge
#

the 2.0.x and above release are problematic

austere relic
#

it seems like a very simple fix as well, so maybe you can just copy paste it into your version?

autumn hedge
#

my working version was 0.12.5

#

good idea @austere relic

limpid pivot
# austere relic not sure I understand?

When I tried to include filename in href without giving any attribute to download it doesn't even download the file properly, it says file downloaded but with 0KB with tag "No file".
and replying to your second query : When i click on the run button it create the excel file in server though ans it is properly opening (hope you understood)

austere relic
austere relic
#

one moment

limpid pivot
#

i will send you the repo link wait

austere relic
#

alright

jolly star
#

how do i set a complex url

limpid pivot
jolly star
#
@app.route("/admin")
def admin():
    return  render_template("Admin.html")

@admin.route("/roomdetails")
def roomdetails():
    return "Room Details"```
or
```py
@app.route("/admin")
def admin():
    return  render_template("Admin.html")

@app.route("/admin/roomdetails")
def roomdetails():
    return "Room Details"```
austere relic
limpid pivot
#

yes

austere relic
#

It needs to go like this

#

<a href="../../../floorsheet.xlsx" download </a>

#

that's why it was downloading an empty file

#

download value is used to give new name to the file

#

not locate it on your pc

autumn hedge
#

looks like Flask 2.0.x is multi-threaded by default

#

which at times will cause my application to return the incorrect response values when both ajax requests are sent out simulataneously

limpid pivot
#

I have tried this earlier too. I told you that too in earlier text. It says No file

austere relic
#

did you try just accessing the url?

#

maybe it's not serving the file properly

autumn hedge
#

@austere relic so much to unpack and I'm not 100% certain if its the way my app is constructed or Flask 2.0.1 itself

#

my work around on the frontend is the delay each ajax request by 2 secs to avoid Flask from clashing somehow when each request is sent

limpid pivot
austere relic
#

Was it that?

limpid pivot
#

solved issue

austere relic
autumn hedge
#

I really think its a Flask threading issue TBH.. just not sure But as I was pausing the python debugger to create this image, unpausing the process resolved each request as well. BUT as you can see the Menu data is also the same as the table data.

silver cargo
#

Hi,
Is there any advantage of using httpx module over using request module?

austere relic
#

it's newer

#

and uhhh

#

async

#

I use httpx myself

silver cargo
#

Yeah like if I am already using request module for one of my project
Will it make sense to switch to httpx in the long run

#

I am also considering community support for the module here

austere relic
#

I think they are awfully similar

#

You can probably just import httpx as requests and get away with it

#

I might be wrong though

silver cargo
pearl patio
#

Can anyone please help me with heroku deployment? I want to deploy my python app, also have created heroku app, added Procfile, requirements.txt, setup.sh files to my working application repository and have also installed heroku client. Need further assistance!

silver cargo
#

Also does httpx support synchronous request execution ?

austere relic
silver cargo
austere relic
#

np

outer apex
jolly star
#

i meant a sub sub url

#

and it started working

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @shut stratus until 2021-05-27 07:29 (9 minutes and 58 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

bright lodge
#

can anyone help me with some html ...i have right src set for img tag but image wont load

vale aurora
#

Send a image of the code

#

Where u have the img input line

bright lodge
#

can i screenshare ?

vale aurora
#

I dont have time rn

#

Im doing smt else

#

I can take a peak at ur code tho

bright lodge
vale aurora
#

Where is that file located

#

Maybe send it here in discord

bright lodge
#

in the static folder

vale aurora
#

And then copy the link

#

And replace ./static/img_5terre.jpg

#

Like send image here or anywhere really

#

Right click

#

And copy media link

#

That usually works unless ur tryna upload code to web

#

Then it isnt the best solution

bright lodge
#

yeah but why would this not work ...this was working when i worked on this project earlier

nimble epoch
bright lodge
nimble epoch
#

yw

vale aurora
#

Yea iv never used images from static folders

#

Sorry

#

I ususally upload to discord and copy the link

#

So when i send the code for review i dont have to send the images too

bright lodge
nimble epoch
#

folder path

bright lodge
vale aurora
#

Ye i just got used to copy link from discord... the issue is that i rely on discord to hold the images

#

Which has so far been decently reliable

nimble epoch
#

you not accessing outside of the templates folder you actually inside templates folder(same folder) with only single .

bright lodge
nimble epoch
#

yes

drifting radish
#

{% extends "base.html" %} {% block title %}Login{% endblock %}{block content}{% load static %} what block is no open

nimble epoch
#
{% extends "base.html" %}
{% load static %}
{% block title %}Login{% endblock %}
{% block content %}
...
{% endblock %}
drifting radish
#

a oke

#
jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'load'.``` I was looking for a solution to this, I followed similar steps and no effects
#

!PASTE

#

I do not know blocku does not see me or what

outer apex
drifting radish
nimble epoch
#

@drifting radish visit the jinja2 main docs probably youll find the solution. and yeah i think jinja doesnt have load tag.

drifting radish
#

ok

nimble epoch
#

yw

native tide
#

need help, I have set in settings

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

and in project directory I have folder templates with all html file and base.html

#

but on web there is...this

#

where is my mistake?

#

ok I now where is issue. Dont put space between { and %

chrome reef
#

Django question - Weird thing. When I try to attach a function to a div it works fine: <div type="button" id="edit" onclick="edit('{{ post.id }}')">Edit</div>
but when I make it into a button it say Uncaught TypeError: edit is not a function
at HTMLButtonElement.onclick <button type="button" id="edit" onclick="edit('{{ post.id }}')">Edit</button>

dense lava
vestal hound
#

that's not trivial

#

and

#

it's also not related to web development

#

like

#

have you even started on it?

#

or are you just like "I want help help me"

nimble epoch
chrome reef
#

yes

#

it works when it get's called from a div, but not from a button

nimble epoch
#

oh no idea

carmine terrace
#

how can i post something in a livechat via webbrowser?

void wagon
#

hello , can somebody tell me how to reduce the font size in css by a specific percent , like 100px : 80%=80px

#

instead of hardcoding the font size

calm plume
calm plume
carmine terrace
calm plume
#

You would send a post request with the message content over the websocket, and then forward it elsewhere over a TCP connection

void wagon
#

i want to reduce the font size when the screen is less than 800px , instead of putting a smaller font size for the "mobile version " , can i reduce it dynamically

carmine terrace
calm plume
#

In Youtube? You just click send

#

Oh wait, you want to automate it

carmine terrace
#

yes

calm plume
#

I'm not sure, sorry

carmine terrace
#

ok thanks nevertheless

void wagon
#

@calm plume Youtube API ?

calm plume
calm plume
carmine terrace
void wagon
#

maybe try using it . might solve your issue

silver cargo
#

Are there any cons if I use httpx over requests module?

#

Like I get all the advantages like async and stuff, I am just getting my head around that why one would not switch to httpx

native tide
#

I have a question about the directory structure for a web app. How should I organize the front end and back end code? My friend and I are working on our first web application and we want to know this.

rapid spindle
#

hi, been tryna import HyperLinkIdentifyField in my django app, is anyone know to import the lib, i've checked some stuff in google but it still doesn't working..

quasi relic
#

hey I need some help , I have an issue with saving uploaded profile pics from my form to db and also static folder

#
    hex_name = os.urandom(8).hex()
    _, ext = os.path.splitext(form_image.filename)
    new_name = hex_name + ext
    new_path = os.path.join(myApp.root_path, 'static/profile_pics', new_name)

    size = (125, 125)
    img = Image.open(form_image)
    img.thumbnail(size)
    img.save(new_path)

    return new_name```
#

this is the func

#
@login_required
def account():
    form = UpdateAccount()
    user_image = url_for('static', filename='profile_pics/' + current_user.profile_picture)
    if form.validate_on_submit() and current_user.check_password(form.password.data):
        if form.profile_picture.data:
            picture_file = upload_image(form.profile_picture.data)
            current_user.profile_picture = picture_file
        current_user.email = form.email.data
        current_user.username = form.username.data
        db.session.commit()
        flash('Account succesfully updated.')
        return redirect(url_for('account'))
    elif request.method == 'GET':
        form.email.data = current_user.email
        form.username.data = current_user.username
    return render_template('account.html', title='Account', form=form, user_image=user_image)```
#

I use pilow package for image resizin and save

#

basically the func accepts the file name from the flaskform and somehow it does not save it

native tide
#

How to add a chat option to a django website?

#

The easiest way

calm plume
#

Set up a websocket server and send message content over TCP connections

thorn igloo
quasi relic
#

nope, cuz this function works well the problem is with my form it returns nothing when I select a image then submit the update on an account

thorn igloo
# quasi relic

so the problem is that you are receiving nothing when you submit the form?

quasi relic
#

yes

thorn igloo
#

oh

mint folio
#

Show the html

thorn igloo
#

is this flask?

quasi relic
thorn igloo
lavish prismBOT
#

Hey @quasi relic!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

โ€ข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

โ€ข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com