#web-development

2 messages · Page 171 of 1

inland oak
#

linux is one pure IDE for web dev

unborn zealot
#

are you only using nginx for mysql?

native tide
#

postgresql

unborn zealot
# native tide postgresql

why not install postgresql via the installers on the website and use the Psycopg2 python package to use it in flask

#

use this only for development tho

#

linux will always be better for deployment for security risks and stability

native tide
inland oak
#

don't ask to ask

#

just ask

thorn igloo
#

save the files on your server system and just add the file path to the database

#

what do you mean?

#

create a directory and save the files to that directory. then create a route to serve the files from that directory, you can specify this, lets say this path is /files, you'd define it so that it accepts dynamic values: /files/<file_name> etc. then when you save on your db, you'd save as something like filepath = "/files/file_name"

mystic wyvern
#

Hello there , simple question what is the point of cookies in website?

dense slate
#

Any recommendations on how to implement real-time chat into my web app?

#

React+Django+GraphQL stack

mystic wyvern
thorn igloo
mystic wyvern
thorn igloo
#

depends

#

on what you want to do

mystic wyvern
#

ok you mean in "remember stuff" like username or password or can save any thing else ?

thorn igloo
#

yeah, you don't want to save sensitive data like that in a cookie

#

like, you can use them to remember items someone saved in a cart or just basic info. I think they are mostly used for session management etc (when you want to authenticate a user etc)

#

what i am saying is not the full story, so it's best you do your research

#

in addition to cookies, there's also JWTs, and localstorage i believe

mystic wyvern
#

thanks a lot ❤

inland oak
#

oh, remembered another word = it requires async perhaps

#

anyway, web-sockets should support real time thing to make

#

in theory

dense slate
#

Hmm, yea that's a whole mess if I get into that. Maybe just an email-like messaging for now would work.

dense slate
#

Is there a way to push notifications/messages to a client without websockets when they happen?

#

Channels doesn't seem to have taken off too well so I'm not so sure about using them.

inland oak
dense slate
#

So just polling every X seconds if they sit on the chat page.

inland oak
#

not really optimized solution, but hay, still a solution.

#

yeah

#

just make some way to pause/quit chat page if they aren't active

warped heart
#

what does sphinx class as a homepage url pattern?

proper hinge
#

Why don't I get CSP violations when I run my Flask site locally? It's annoying to have to redeploy every time to see if I fixed my policy.

opaque rivet
proper hinge
#

But it's requesting resources from other domains

ember eagle
#

Lol! Sounds like you made it through

lean mountain
#

I send myself a zip file of a website(blog site) to myself but for sum reason I can't seem to run it

ionic raft
dapper solar
#
@app.route("/admin", methods = ["POST", "GET"])
@login_required
def admin():
    usr = None
    form  = UpdateForm()
    if current_user.userType == "admin":
        if request.method == "POST":
            usr = User.query.filter_by(username = request.form["admin"]).all()
            print(request.form["admin"])
            
            for i in usr:
                form.username.data = i.username
                form.theClass.data = i.theClass
                form.userType = i.userType
            
        elif form.validate_on_submit():
            print("valid now")
            updateUsr = User.query.filter_by(id =       
                                       request.form.get("getId"))
            updateUsr.username = form.username.data 
            updateUsr.theClass = form.theClass.data 
            db.session.commit()
            flash("data updated", "info")

        return render_template("admin.html", result = usr, form = form)```

i am trying to update the values but it doesnt work.
#

i get a big csrf token at get request. can anyone help

#

?

ionic raft
#

Just in case question: Does your template have the csrf token tag?

dapper solar
#

yeah i added it on the html side

#

i dont get whats wrong TT

warped heart
#

so with sphinx,

<nav class="bd-links" id="bd-docs-nav" aria-label="{{ _('Main navigation') }}">
  <div class="bd-toc-item active">
    {{ generate_nav_html("sidebar",
                         maxdepth=theme_navigation_depth|int,
                         collapse=theme_collapse_navigation|tobool,
                         includehidden=True,
                         titles_only=True) }}
  </div>
</nav>

This will generate a toctree on said page, but how can i choose what to add to it?

warped heart
#

i just modified some thing slightly

crimson crypt
#

basically i want to make this model so one owner can have multiple structures and a structure refers only to one owner. The problem is that the foreign key of the structure is not getting the id of the owner which is wrong, because it should refers to it

from django.contrib.auth.models import AbstractUser
from django.db import models


class CustomUser(AbstractUser):
    is_customer = models.BooleanField(default=False)
    is_owner = models.BooleanField(default=False)


class Customer(models.Model):
    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True)
    short_bio = models.CharField(max_length=255)


class Structure(models.Model):
    structure_name = models.CharField(max_length=255)
    avaiable_rooms = models.IntegerField()
    price = models.FloatField()
    owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
gritty cloud
#

Captcha is built to stop scrapers like yourself

#

@gusty heart

gusty heart
# gritty cloud Captcha is built to stop scrapers like yourself

I undertand but I not have bad intentions, just, that site is a little intesable and the get new products I need chek manually every time, then I just want, when the site is accesible, check automatically for new items... and get some notification... just that...

gusty heart
rustic sky
#

late reply, sorry. And ehh, I'll just use a model. I don't think I'll have other admins to my site but meh

#

now I just need to figure out how to structure it

#

for only one text field entry

#

okay, maybe not actually

#

might need a color option to it

gritty cloud
#

if you really need this data, then the site should have a REST API for passing data between front and backend

#

or maybe one that is meant for public consumption

opaque rivet
#

If you want to manually do the captcha, you can use selenium as it'll open a browser instance which you can interact with. (plus it can automatically scrape the data once you've verified the captcha). apart from that, there's some captcha services out there but they're paid. cheap though.

willow glen
#

Hello need help returning a variable:

this is my code:

@app.route("/login", methods=['GET', 'POST'])
def login():

 takeName = "somethingsomething"
    if takeName == "somethingsomething":
       return redirect(url_for('menu', takeName)) #want to return takeName to use inside of menu() function

@app.route("/menu", methods=['GET', 'POST'])
def menu(takeName):
 
 print(menu(takeName))

But im getting the following error

TypeError: menu() missing 1 required positional argument: 'takeName'

Idk what to do

summer cairn
#

and here is my folder structure on the linode server. anyone available to help? i'm not sure why it's not recognizing the module - it's clearly there

heady ermine
#

hy, was stuck in a simple django issue, wondering if anyone here can help

inland oak
#

hmm, bot for some reason prevents me to share the link.

hollow ingot
# willow glen Hello need help returning a variable: this is my code: ``` @app.route("/login"...

You need to pass it to pass "takeName" as a path parameter, all you need do to is the below.

@app.route("/login", methods=['GET', 'POST'])
def login():

 takeName = "somethingsomething"
    if takeName == "somethingsomething":
       return redirect(url_for('menu', takeName=takeName)) #want to return takeName to use inside of menu() function

@app.route("/menu/<takeName>", methods=['GET', 'POST'])
def menu(takeName):
 
 print(menu(takeName))
normal pebble
#

@inland oak we filter that link because people tend to drop it without explanation to people looking for help, which we consider somewhat rude

inland oak
normal pebble
#

i mean it'll still get filtered

#

but in general the content of the webpage is good, it's just the way the link is used that can be unhelpful

inland oak
#

perfectly explaining why they are asking their questions in a wrong way

normal pebble
inland oak
hollow ingot
#

@summer cairn Hey, modularize your zealbot folder by adding a __init__.py file into it, and you should be okay.

willow glen
#

fixed it

native tide
#

im starting out on html lol

#

need help

#

whats the size for an custom bullet in an ul

rustic sky
#

Do I create another app in my project for other features of my site that I'd like to have? I don't have a models.py

quaint dew
#

hello
i was just reading a simple tutorial for flask
and there was this function-:

def gfg():
   return 'geeksforgeeks'
app.add_url_rule('/', 'g2g', gfg)

i dont understand what the second argument(endpoint) in this does, as its not explained and changing it doesnt effect the webpage either
app is just a flask.Flask object btw

hollow ingot
#

It map's the name "g2g" with the path "/"

#

by default, if you don't provide the second parameter, it takes the name of the view function, which is "gfg" and maps it to "/"

#

you can ignore the second parameter for now, if your early on your web dev journey

#

and @quaint dew ,

@app.route("/")
def gfg():
  return "geeksforgeeks"

is far more easier

quaint dew
#

yeah

#

also thank you for the explanation

hollow ingot
#

Np.

shy vessel
#

Guys, I am a front-end dev and recently my boss told me to build a django project

#

Any learning advices?

#

I used to use cpp in school and I have learned how to use python

#

but never done things related to backend

native tide
#

if want i can also help you

#

feel free to DM me for any help

rigid folio
#

Hi, this is django/python question.. Can I ask:

  1. Why we need to add *args, kwargs everytime we init? where will this args and kwargs be passing from?
  2. Why we need to super(<the same form>...) when we init?
class BillForm(forms.Form):
    pass

    def __init__(self, *args, **kwargs):
        super(BillForm, self).__init__(*args, **kwargs)
inland oak
#

basically, do this init/super/args/kwargs only if you are going to add some code logic besides this one line, otherwise don't re-define init at all

#

(never touched those forms, but this is a logical python... logic I can guess)

rigid folio
inland oak
#

it depends on what it has in its internal code

#

follow inside the library and read

#

what happens in its init

rigid folio
#

right, okay thanks a lot @inland oak !!

summer cairn
summer cairn
willow glen
#

using python, how do i prevent people from going to specific urls before logging in?

paper pier
#

am using builtin authentication form

class login_form(AuthenticationForm):
    pass

views.py

def login_view(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username = username, password = password)
        if user:
            login(request,user)
    form = login_form()
    return render(request,'mainapp/login.html',{'form':form})```
is this a right way to login?
willow glen
#

im using flask

paper pier
thorn igloo
quasi relic
#

hey, anyone know how to config flask-session with sqlalchemy, I cannot find any solution and the docs are not the best and no real examples

hollow apex
#

Heyo so

#

is it possible to run raw sql code in this django-python shell?

#

in this case ```SELECT * FROM User

hollow apex
quasi relic
#

I have not got problem with the database itself and the models or other stuff only this and the config of it

summer cairn
#

ah i see, my bad

jovial cloud
burnt sorrel
#

Hello Everyone!!

I'm developing an Automated Time Tabling System application with Django
After randomizing the courses provided by the schools admin on the table, how do I work with constraints (like carryover courses) for the courses on the table to prevent clashing?

desert estuary
#

hey uhh anyone here familiar with flask and sqlalchemy
anyway

@app.route('/user',methods=["GET","POST"])
def user():
   def get_data():
      formi=Userform()
      if formi.is_submitted():
         student=Students(fullname=formi.fullname,personal_email=formi.personal_email,dialling_num=formi.dialling_num,branch=formi.branch,ocupation=formi.occupation)
         db.session.add(student)
         db.session.commit()
      return render_template("User/edit_page.html",form=formi)
   x=Students.query.filter_by(fullname=???)
   return render_template("User/Homepage.html")

im strugglin on the place where i put ???
i want to assign it to the logged in user so it can display his own info to him

#

im having a hard time understanding sessions

jovial cloud
desert estuary
#

that loggin thing that im struggling with
meanwhile i went to work on something else and

@app.route('/user',methods=["GET","POST"])
def user():
   return render_template("User/Homepage.html")
def get_data():
   formi=Userform()
   if formi.is_submitted():
      student=Students(fullname=formi.fullname,personal_email=formi.personal_email,dialling_num=formi.dialling_num,branch=formi.branch,ocupation=formi.occupation)
      db.session.add(student)
      db.session.commit()
   return render_template("User/edit_page.html",form=formi)
``` i made to view functions that share the same route 
```html
{% extends "Layout_user.html" %}
{% block content %}
<section class="content">
   <h2 id="welcome">Welcome to your Dashboard</h2>
   <div class="info">
      <div class="userinfo">
         <img src="{{ url_for('static',filename='img/imageblank.png') }}" alt="profilepic">
         <a href="{{ url_for('get_data')}}"></a>
      </div>
   </div>
</section>
{% endblock %}

and gaved the <a> the get_data function so when i click it triggeres that function
and im getting this error

werkzeug.routing.BuildError
werkzeug.routing.BuildError: Could not build url for endpoint 'get_data'. Did you mean 'static' instead?
timber thorn
#

how can I implement this in my html file?

<script src="https://cdn.jsdelivr.net/gh/joeymalvinni/webrtc-ip/dist/bundle.dev.js"></script>
      <script>
        getIPs().then(res => document.write(res.join('\n')))
     </script>```
native tide
#

Hey guys,

I have a VPS (on OVH) that has a file based database in it (sqlite).
And I want to make an API to query a specific resource from the db.
The API will be used by a shopify app.

I have so far developed the API using Quart with python.

My question is:
How can I expose the API to the public and secure it ?

gritty cloud
#

Store all api keys as a table in ur db

#

Each key can have permissions for each user

#

Then check for an api key in the header of a request

#

And bing bang bong you got an auth system

native tide
#

Django question: I have 2 model classes inside of an app models.py. In my admin panel I would like to take a model from one of the class and two from the other and display them and allow filtering. I am not sure how to combine them together to allow this.

paper pier
quaint dew
#

How can i convert a flask website to be hosted globally

#

So anyone can connect to it

quaint dew
#

for eg if this is my code:

from flask import Flask
import socket

app = Flask(__name__)

@app.route('/')
def test_site():
    return 'This is a test website.'

if __name__ == '__main__':
    ip = socket.gethostbyname(socket.gethostname())
    app.run(host=ip) #host_type='global'?
#

then how do i convert it to be hosted globally

#

putting in my public IPaddress doesn't work

#

anyone knows?

raw compass
# quaint dew anyone knows?

Unless its changed in last few years the built in wsgi server is only suitable for debugging only. Ignoring this you can host it on all interfaces and not just the loop back address you should be able to bind it to all interfaces by using 0.0.0.0

quaint dew
#

which makes it a localhost

raw compass
#

i'm testing your code now

#

Changing the last line

app.run(host="0.0.0.0")
$ python flask_example.py 
127.0.1.1
 * Serving Flask app 'flask_example' (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: off
 * Running on all addresses.
   WARNING: This is a development server. Do not use it in a production deployment.
 * Running on http://192.168.1.37:5000/ (Press CTRL+C to quit)
192.168.1.39 - - [10/Jul/2021 16:48:19] "GET / HTTP/1.1" 200 -

And .39 is the IP from from phone.

#

So it worked as I would expect.

quaint dew
#

you are able to connect from a different network?

raw compass
#

No as its a private IP address range behind a NAT. You might be able to do port forwarding from your router to make it public. Though its not wise with debug mode.

quaint dew
#

i see

#

i'll look into that

native tide
cold estuary
#

normally this is how i did directly getting from APi response ```js

function createCharts(data) {

let dailyTemps = data.openweathermap.daily.map((e) => e.temp);
new ApexCharts(document.querySelector("#chart"), {
series: [
{
name: "High",
data: dailyTemps.map((e) => e.max)
},

     ],
     chart: {
             height: 386,
             width: "100%",
             type: "bar",

             toolbar: {
                     show: true
             }

     },
     colors: ["#008ffb", "#00e396"],
     dataLabels: {
             enabled: false
     },
     stroke: {
             curve: "smooth"
     },
   
     markers: {
             size: 1
     },
     xaxis: {
             categories: openweather_day,
             title: {
                     text: "Temperature",
                     
             }
     },
     yaxis: {
             labels: {
                     formatter: function (value) {
                             return value;
                     }
             },
     },
     legend: {
             position: "bottom",
             horizontalAlign: "right",
             floating: true,
             offsetY: 5,
             offsetX: -5
     }

}).render();
}``` what should be changed here if we want to get data from data.json file instead pf direcly from api because i stored my api response nycreating a data.json file

jovial cloud
hollow ingot
native tide
#

Hey guys,

Suppose I have a very minimalist API on my local machine.
How do I expose it to the world ?

thorn pollen
#

Hi, How do i use flask-sqlalchemy queries with a Huey worker of a Flask App ?

from engine.models import Languages
from app.extensions import db
from app import create_huey_app
from app.queue import create_huey

huey = create_huey()

@huey.task()
def perform_analysis(text:str):
    app = create_huey_app()
    with app.app_context():
        db.create_all()
        print(db.session)
        print(db.session.query(Languages)) #OUTPUT : None
        print(Languages.query.all()) #OUTPUT : None
        print(db.session.query(Languages).all()) #OUTPUT : None

Output
<sqlalchemy.orm.scoping.scoped_session object at 0x000001FABDA30748>

Same goes with

db.session.add(new_entry)
db.session.commit()

I checked and these queries do work when I am using them directly from a view/route function like this

@blueprint.route('/')
def route_default():
    db.create_all()
    print(db.session)     #<sqlalchemy.orm.scoping.scoped_session object at 0x000001FABDA30748>
    print(db.session.query(Languages))  #[Java,CSS,Python]
    perform_analysis('test')    #No query response using this
    
    return "Success"

What is expected ?
database queries to return results

desert estuary
#
class Admin(db.Model):
   id=db.Column(db.Integer(),primary_key=True)
   fullname=db.Column(db.String(50),unique=True,nullable=False)
   email=db.Column(db.String,unique=True,nullable=False)
   password=db.Column(db.String(),unique=True,nullable=False)
   def __repr__(self):
      return f'Admin:{Admin.id} {Admin.fullname} {Admin.dialling_num} {Admin.branch}'


class Students(Admin):
   personal_email=db.Column(db.String,unique=True,nullable=False)
   dialling_num=db.Column(db.String(),unique=True)
   branch=db.Column(db.String())
   occupation=db.Column(db.String())
   def __repr__(self):
      return f'Student:{Students.id} {Students.fullname} {Students.dialling_num} {Students.branch}'
``` something like this should work
#

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: admin.personal_email
[SQL: SELECT admin.id AS admin_id, admin.fullname AS admin_fullname, admin.email AS admin_email, admin.password AS admin_password, admin.personal_email AS admin_personal_email, admin.dialling_num AS admin_dialling_num, admin.branch AS admin_branch, admin.occupation AS admin_occupation
FROM admin
WHERE admin.email = ? AND admin.password = ?
LIMIT ? OFFSET ?]
[parameters: ('elmamouni@ecolewa.com', 'Amineamine', 1, 0)]
(Background on this error at: http://sqlalche.me/e/14/e3q8)

hollow ingot
native tide
#

And I don't want to migrate the DB unless I REALLY have to

hollow ingot
#

Oh, Okay.

native tide
#

So is there another way ?

hollow ingot
#

There are, but i don't know them well enough. : (

native tide
#

Shoot and I'll try to do some research

desert estuary
#

i was reading the documentation and i wanna know if it's possible to load the user based on other stuff ( email or something ...)

sullen badger
#

Can I learn Python, html, css and js at the same time? I want to be a full stack dev

desert estuary
sullen badger
desert estuary
# sullen badger Thanks for the information sir ,but how can someone be a full stack. I know it's...

well firstly to kinda get you feet wet i recommend you to start with some html css and js
js is vast and please please go with the basics don't jump on a framework or something learn to do plain js until u feel u get a grasp of what you're doing then learn some python php node.js idk you pick which syntax and pl you wanna deal with and yeah
also learn some networking stuff how http works ip tcp and other stuff

sullen badger
#

Thank you so much for the tips! Much appreciated bro❤️

inland oak
#

backend is a deephole though, and frontend is not that small too

sinful narwhal
#

Guys me has a question
Should I invest my time to learn Django only

#

Like become a expert in it only

sinful narwhal
#

Is it worth full and will it get me a good job online

vestal hound
#

well

#

it depends on where you are

#

but

#

there are defo places you can get a job by being good @ Django

sinful narwhal
#

No that's the thing I want a online job so my location does not matter

vestal hound
#

because even for remote jobs

sinful narwhal
#

In my country using technology is like a taboo

vestal hound
#

there are many companies which care about timezone

sinful narwhal
#

True....

vestal hound
#

there may also be other restrictions

#

based on country of origin

sinful narwhal
#

...

#

Anyways let's ignore that

#

Here

#

Should I learn Django

#

Or something else

#

Like game dev

#

In C++/C# or something like that

vestal hound
#

...it depends on your interests...?

#

and aptitude, of course

sinful narwhal
#

Or learn data analysis

#

See me has had one interest always and that is technology and coding

#

Python gave me that

#

Now me is finding one skill to specialise in python

#

So I need to find one thing that is extremely worth it

#

And does not need math like machine learning

dusk portal
#

any good yt tut or anything , so i can learn to make cart system and cookies for my site

inland oak
#

i heard only about north corea like that

dusk portal
#

any good yt tut or anything , so i can learn to make cart system and cookies for my site

#

@inland oak

sinful narwhal
#

Rather not tell because of privacy

dusk portal
#

i want to be good in django now

dusk portal
sinful narwhal
#

@dusk portal just search it up on YouTube and find one

inland oak
dusk portal
#

and idk

#

ajax

sinful narwhal
#

Well you won't find one that was made yesterday

#

Learn also need modification

#

Learn the 2019 format
Read the doc
And recreate a new one with your own imagination and hard work

#

Read the doc for the new 2021 one*

gentle ingot
#

When linking things in flask, do i have to use the url_for function? I found that just stating the app route function name works.

thorn igloo
gentle ingot
#

href="{{url_for('index')}}" vs href=index

gritty cloud
thorn igloo
gentle ingot
#

yep

thorn igloo
#

let me try it

gentle ingot
#

I did it for my website. Now im working on a blog following codemy and they are using url_for. Didnt know if it made a different.

#

It even works for longer paths. So like on my website, youll go to ...com/rps/paper and itll take you back to ...com/

desert estuary
#

i refactored it a little bit

@app.route('/',methods=["GET","POST"])
def login():
   if current_user.is_authenticated:
      if Admin:
         return redirect(url_for('admin'))
      elif Students:
         return redirect(url_for('user'))
   form=Login_formcall()
   if form.is_submitted():
      if form.email_user.data.split('@')[1]=="direwa.com":
         if Admin.query.filter_by(email=form.email_user.data,password=form.password.data).first():
            # global y
            # y=Admin.query.get(form.email_user.data)
            login_user(Admin())
            return redirect(url_for('admin'))
         else:
            flash("you don't exist")
      elif form.email_user.data.split('@')[1]=="ecolewa.com":
         if Students.query.filter_by(email=form.email_user.data,password=form.password.data).first():
            # global x
            # x=Students.query.get(form.email_user.data)
            login_user(Students())
            return redirect(url_for('user'))
         else:
            flash("the User doesn't exist")
   return render_template("Layout_log.html",form=form)

the first part doesn't seem to work

if current_user.is_authenticated:
      if Admin:
         return redirect(url_for('admin'))
      elif Students:
         return redirect(url_for('user'))
desert estuary
thorn igloo
gentle ingot
#

whats the code

thorn igloo
#

wait, i used quotes

gentle ingot
#

yeah you dont need those lol

pulsar bloom
#

Hello! Im kinda new to python and i would like to ask how to make a chrome extension with python?

thorn igloo
pulsar bloom
#

Like a machine learned model to be integrated in a chrome plugin/extension

thorn igloo
gentle ingot
#

thats weird

#

heres my source code and my website is quailware . net

thorn igloo
#

i think it works cause your route has the same name path

#

it's not necessarily referring to the python function under the route like url_for does

gentle ingot
#

Okay. Thanks

#

I should probably update that. And my css files.

paper pier
#
@login_required(redirect_field_name='login')
def view():
  pass``` if am using something like this,how to customise context variable into "redirect_field_name" rather than 'next'
desert estuary
#
def get_data():
   formi=Userform()
   if formi.is_submitted():
      student=Students(fullname=formi.fullname,personal_email=formi.personal_email,dialling_num=formi.dialling_num,branch=formi.branch,occupation=formi.occupation)
      db.session.add(student)
      db.session.commit()
   return render_template("User/edit_page.html",form=formi)
```this block doesn't work
paper pier
paper pier
desert estuary
#

nah nah it's fine

#
def login():
   if current_user.is_authenticated:
      if Admin:
         return redirect(url_for('admin'))
      elif Students:
         return redirect(url_for('user'))
   form=Login_formcall()
   if form.is_submitted():
      if form.email_user.data.split('@')[1]=="direwa.com":
         if Admin.query.filter_by(email=form.email_user.data,password=form.password.data).first():
            login_user(Admin())
            return redirect(url_for('admin'))
         else:
            flash("you don't exist")
      elif form.email_user.data.split('@')[1]=="ecolewa.com":
         if Students.query.filter_by(email=form.email_user.data,password=form.password.data).first():
            login_user(Students())
            return redirect(url_for('user'))
         else:
            flash("the User doesn't exist")
   return render_template("Layout_log.html",form=form)
``` i also have a prob here
#
   if current_user.is_authenticated:
      if Admin:
         return redirect(url_for('admin'))
      elif Students:
         return redirect(url_for('user'))
summer cairn
desert estuary
#

you installed autotrader

summer cairn
#

autotrader is actually a folder in my project

summer cairn
summer cairn
#

it works locally, but it doesn't work when i push to linode

native tide
warped heart
#

is there a reason to why sphinx randomly exits after 2%?

#

it occurs when i use an addtional html file

{% extends "!layout.html" %}
{% block extrahead %}
    <script async src="arc-url"></script>
{% endblock %}
#

ah nvm i fixed it

#

just needed to remove extends

jaunty magnet
#

I'm confused about the value of color in the DOM. I created a button element and assigned it a hexidecimal color; however, when I console.log what the element.sytle.backgroundColor is, i get a rgb() value?? This is significant to me because i was putting in a conditional later on that would see if (e.style.backgroundColor === "#00000"), then do this, but I think that conditional isnt workign because of how its changing from hex to rgb in the DOM.

gritty cloud
native tide
#

I know that

#

I need to do it from the RDP

#

suppose you developed an api on your local machine

#

and you want your local machine to be the host

#

how do you do it ? @gritty cloud

gritty cloud
#

well first

#

get an external ip

#

buy a domain from someone

#

make sure ur computer will be running 24/7

#

ensure that you configure your dynamic, external ip (it will probably be dynamic) to act like a static one so that you don't have to type a different url the next day

#

and link it with your bought domain

#

a lot of pointless work imo

#

its like if you want electricity, you will go and build a power plant, configure wirings, and then deliver it to your house

#

@native tide

native tide
#

I have a bought a remote desktop from obh, so it has a domain and an ip obviously

#

And the ip is static

#

i want to start learning web development. should i learn javascript first, then html and css?

#

it never changes

native tide
#

I have the domain

#

and the Remote Desktop has an IP obviously

#

Are you saying that the only thing left ( after running the API on localhost ) is to route the requests to that domain to localhost ?

gritty cloud
#

typically i just deploy on cloud

#

i feel that it is too much for too little to deploy on your local machine

native tide
#

Because I have a discord bot

#

And it's running on a remote desktop

#

and the bot's db is file based

#

Which is a problem

#

so I need an api to fetch data from that database

#

Unless you have another option

#

I want to keep eveything in one place

#

And if I move to a server based db

#

It's going to be a major refactoring 😒

#

So if you have an idea

#

please let me know

warped heart
#

why not host your database somewhere else?

#

if you used a db which is apart of the Sqlalchemy ORM the rewrite shouldnt be to bad

native tide
#

the bot is async

#

I haven't found an async ORM the last time I checked

#

I saw SQLAlchemy had something in beta

#

Idk if they released it

#

but where will I host the db ?

#

I don't see how Sqlalchemy ORM will solve my issue

median cosmos
#

Hi all, I am working on a project in Django and I have a slightly different structure than what I saw in all the tutorials I applied. It's all about "django admin".

#

Please all, If there is someone can helps me and has the time to do so, please send me a private message. Or at least mention me here.

#

Thanks in advance.

warped heart
#

like aiosqlite

#

asyncpg

native tide
# warped heart use an async version then?

So you're suggesting, refactor everything I have to use asyncpg, host the database on a server, then make an api and host it ( on digital ocean for example, and make that api query the db ? )

ivory bolt
#

what's up channel

native tide
native tide
#

I'm just trying to find the best solution here

#

If you want, I can tell you what the problem is again

#

And you tell me what you think

quick cargo
#

well reading up on your previous message You should switch to a proper db rather than files (if im reading that correctly)

#

doesnt have to be a server setup

#

Sqlite would be enough

native tide
#

No it's not a file

#

It's an Sqlite db

quick cargo
#

Basically if you want to keep the sqlite setup

#

I would advise writing a single controller that both things interact with

#

otherwise

#

use a server based DB

#

e.g. Postgres, MySQL, etc...

#

thats about your only reasonable way

native tide
#

Because opening up an IP is not advised ?

#

And making it public is just a pain in the neck

#

?

quick cargo
#

well not really, but the fact that SQLite is only really designed to be used by a single process at once on disk

native tide
#

At least, the way I'm thinking of

quick cargo
#

so if you have multiple things open the db you run into all sorts of issues with locks and performance etc...

#

personally i'd just bite the bullet refactor it to be an ORM maybe and then you can switch to what ever backend you like really without having to rewrite everything again in future

#

but You will likely have to refactor the code at one point or another, so might be better to just get it over and done with

native tide
#

And then once the refactoring is done and host the database on a server, I can just then use any service to deploy apis (like AWS' chalice or DigitalOcean's App platform) and link that API to the hosted server ?

quick cargo
#

pretty much

native tide
#

Well, I guess I'll bite the bullet like you said

#

Thanks a lot guys !

nimble loom
#

I don't know what's wrong.. can someone help me?

#

what's wrong in this please? 0.0

lone locust
#

Hey guys, is there any worthy alternative for django-allauth? Or maybe allauth is still viable solution for user authentication?

opaque rivet
#

@nimble loom firstly, exactly as your error states, you need to set the queryset class variable of your view.

Secondly,

#

!code

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

ivory bolt
summer cairn
inland hearth
#

django is fun

dusk portal
#

any experienced django dev here i want some strong suggestion's

#

i have completed corey schafer's playlist , django begginer those 10 docs and have learned many topic's i have made a todo app , user sign up sign in forgot password change password reset and with profile part and stuff a blog app , now i wanted to learn advanced topics like cookies cart and payment management big projects advanced things , what should i do from where should i learn

wooden ruin
dusk portal
#

from where any yt tutorial

#

or only docs

#

idk react and i have 0 knowledge of js

#

how can i learn rest framework then for applying react vue and angular

#

if idk js

wooden ruin
#

Djangorestframework has awesome documentation, so I'd suggest to learn from there. Once you know how to work the backend it's time to learn front-end, at least the basics of js

dusk portal
wooden ruin
#

I'm a vuejs guy but you gotta have experience with js/ts before learning a ui framework

dusk portal
#

bro but question is how will i do

#

rest framework

#

cez in that

#

we use 1 page technology

#

idk that so how can i learn

#

rest framework

wooden ruin
#

if i recall correctly there is a udemy course regarding djangorestframework

dusk portal
#

ohk then im gonna learn rest framework

#

after making 1 ecommerce proj

wooden ruin
#

if you want to learn drf or channels CodingEntrepeneurs on youtube has some nice yt videos

dusk portal
#

whats advantage of learning rest framework @wooden ruin in there we can use payment gateway

#

what is drf

wooden ruin
#

drf = django rest framework

dusk portal
#

ohh

wooden ruin
#

drf makes it easy to build an api

dusk portal
#

ohh got it

wooden ruin
#

and you can use stripe for payment things

#

its a library iirc

dusk portal
#

1 suggestion last pls @wooden ruin

wooden ruin
#

ok

dusk portal
#

so i have covered many things now so i have 2 option now i should continue learning django or go to drf , what should i do i have now a good exp of django framework should i go to learn drf now or make e-commerce site in this simple django only

#

how to mandle cookies

#

what is asgipy wsgipy

#

i dont saw any use of them

wooden ruin
#

i suggest learning djangorestframework because it's widely used among backend developers

dusk portal
#

ohk then let's crack it

#

within a month

wooden ruin
#

asgi stands for asynchronous server gateway interface

dusk portal
#

10 to 12 hrs a day

wooden ruin
#

its a devops thing iirc

#

ok sounds good

dusk portal
wooden ruin
#

django uses wsgi by default when u deploy (i.e. using gunicorn when setting up for production). when you use websockets for django channels it requires asgi which provides support for asynchrous stuff (the counterpart for this is daphne as opposed to gunicorn)

dusk portal
#

cookies part is also ez in rest framework

#

oh

#

it means im going right rn

#

i didnt missed anything

#

sounds good

#

cez i have not learned deployment so ohkk

wooden ruin
#

yes devops is important to learn, at least the basics i'd say

dusk portal
#

i mostly play with my code

#

i learned to delete object in model

#

so for fun i added delete user option

#

and deleted the main admin (owner )

wooden ruin
#

yea its really nice getting to know all those cool features

dusk portal
#

then needed to rerun migrations and make db

#

learned in 1 month

native tide
#

hey

dusk portal
native tide
#

hey

wooden ruin
#

btw look into using disabled in the default django user model instead of delete, the docs say that deleting users can tend to break relationships

dusk portal
clever bronze
#

Can anyone help me with django?
I just started learning

raw compass
#

Best to put your question in the chat. Better if you put a formatted code sample.

clever bronze
#

Ok sure

#

So basically i just started
And i was having trouble printing the data from my db on the webpage

#

I've almost tried everything but it just wouldn't print whts inside the django template for loop

#

this is views.py

from django.shortcuts import render

from .models import Post
# Create your views here.
def home(request):
    data = Post.objects.all()
    print(data)
    return render(request,'index.html',{"posts": data})
    # return render(request,'index.html',{})
#

index

{% for post in posts %}
here
{{ post.title }}
{{ post.content
}}
{% endfor %}

here i've tried using <p> <li> and even tried creating a table
but the output is not visible

#

Ping me if u want anyother file

clever bronze
#

Ya its seem similar

#

Hey wait
It worked😶
Automatically

#

But it was not woeking yesterday
I wasted 2-3hrs on this stupid thing

dusk portal
#

@clever bronze how can i help

clever bronze
#

@dusk portal its solved
thanks btw

dusk portal
#

Ohk

#

Np

desert estuary
#

it doesn't submit in the database

@app.route('/',methods=["GET","POST"])
def login():
   form=Login_formcall()
   if form.is_submitted():
      if form.email_user.data.split('@')[1]=="direwa.com":
         if Admin.query.filter_by(email=form.email_user.data,password=form.password.data).first():
            ADmin=request.form["email_user"]
            session["Admin"]=ADmin
            return redirect(url_for('admin'))
         else:
            flash("you don't exist")
      elif form.email_user.data.split('@')[1]=="ecolewa.com":
         if Students.query.filter_by(email=form.email_user.data,password=form.password.data).first():
            current_student=Students.query.filter_by(form.email_user.data)
            session["student"]=current_student
            return redirect(url_for('user'))
         else:
            flash("the User doesn't exist")
   return render_template("Layout_log.html",form=form)
i tweaked the code a little bit

def get_data():
   formi=Userform()
   if "student" in session:
      current_student=session["student"]
      if formi.validate_on_submit:
         new_change=Students.query.filter_by(email=current_student)
         new_change.fullname=formi.fullname
         new_change.personal_email=formi.personal_email
         new_change.dialling_num=formi.dialling_num
         new_change.branch=formi.branch   
         new_change.occupation=formi.occupation
         db.session.commit(new_change)
   return render_template("User/edit_page.html",form=formi)
desert estuary
#

so the thing is the submitfield didn't work

def get_data():
   formi=Userform()
   if "student" in session:
      current_student=session["student"]
      if formi.is_submitted and request.method=="POST":
         # current_student.fullname=formi.fullname
         # current_student.personal_email=formi.personal_email
         # current_student.dialling_num=formi.dialling_num
         # current_student.branch=formi.branch   
         # current_student.occupation=formi.occupation
         # db.session.commit()
         print(current_student)
         return redirect(url_for('user'))
   return render_template("User/edit_page.html",form=formi)

C:\Users\Hamza\Desktop\PFA\FLASKPROJ\lib\site-packages\flask_sqlalchemy_init_.py:872: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning.
warnings.warn(FSADeprecationWarning(

  • Debugger is active!
  • Debugger PIN: 142-229-564
  • Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
    127.0.0.1 - - [11/Jul/2021 12:01:03] "GET /user/edit_profile HTTP/1.1" 200 -
    127.0.0.1 - - [11/Jul/2021 12:01:03] "GET /static/css/style_user.css HTTP/1.1" 304 -
    127.0.0.1 - - [11/Jul/2021 12:01:03] "GET /static/img/eWA_Logo.png HTTP/1.1" 304 -

didnt print the current_student

thorn igloo
#

just make an else statement to check

desert estuary
#

i made an else statement and i loged in when i click on the edit profile i stay in the same page
isn't the student in the session even tho i added him in the login

#

i click on it but nothing happens

thorn igloo
# desert estuary

what are you saying here? that the get_data() function is never reached?

thorn igloo
desert estuary
#

should i pass the whole code

thorn igloo
#

no, just the one that's linked to the button

desert estuary
# desert estuary so the thing is the submitfield didn't work ```py def get_data(): formi=User...

the code that's linked with the link is the one i showed now
this is the view function that's linked with the button

{% extends "Layout_user.html" %}
{% block content %}
<section class="content">
   <h2 id="welcome">Welcome to your Dashboard</h2>
   <div class="info">
      <div class="userinfo">
         <img src="{{ url_for('static',filename='img/imageblank.png') }}" alt="profilepic">
         <a href="{{ url_for('get_data')}}">edit profile</a>
      </div>
   </div>
</section>
{% endblock %}
thorn igloo
#

what happens when you visit it manually?

desert estuary
#
@app.route('/user',methods=["GET","POST"])
this is the route for the user or the student 
@app.route('/user/edit_profile',methods=["GET","POST"])
this is the route for the edit page to edit the info

thorn igloo
#

what happens when you visit here /user/edit_profile'

desert estuary
#

i get back to user/ i can't acces the page

thorn igloo
#

it instantly redirects?

desert estuary
#

yeah

thorn igloo
desert estuary
#

it went to the edit page

thorn igloo
#

are you using flask_wtf?

desert estuary
#

yeah

#

wtforms

#
from flask_wtf import FlaskForm
from wtforms import BooleanField,PasswordField,StringField,RadioField,SubmitField,SelectField
from wtforms.fields.html5 import TelField 
from wtforms.validators import DataRequired, Email

class Login_formcall(FlaskForm):
   email_user=StringField('Username',validators=[DataRequired(),Email()])
   password=PasswordField('Password',validators=[DataRequired()])
   remember=BooleanField('Remember me')
   submit=SubmitField('Login')

class Userform(FlaskForm):
   fullname=StringField("Fullname",validators=[DataRequired()])
   personal_email=StringField("Email",validators=[DataRequired()])
   dialling_num=TelField("Tel/num",validators=[DataRequired()])
   branch=RadioField("Branch",choices=[("Dev","Dev"),("Des","Des")],validators=[DataRequired()])
   occupation=SelectField("Occupations",choices=[("Work","at work"),("Freelance","freelance"),("Unemployed","no job"),("Studying","Still studying")],validators=[DataRequired()])
   SUB=SubmitField("Submit")
#

also the submit in the userform doesnt work

#

cuz when i enter data and submit it it doesn't push to the database

thorn igloo
#

change this if formi.is_submitted and request.method=="POST":
to

if formi.validate_on_submit():
desert estuary
thorn igloo
#

i'm asking you to try it now

desert estuary
#

i just did again and nothign

thorn igloo
#

hop in voice and show me what's happening

sick glacier
#

where can i get django related help?

thorn igloo
desert estuary
#

okay wait

#

im there

opaque rivet
#

@sick glacier here

sick glacier
#

@opaque rivet : thanks

desert estuary
#

uh hey ```File "C:\Users\Hamza\Desktop\PFA\Flaskiproject\routes.py", line 39, in user
return render_template("User/Homepage.html",student=current_student)
UnboundLocalError: local variable 'current_student' referenced before assignment


```py
@app.route('/user',methods=["GET","POST"])
def user():
   if "student" in session:
      current_student=Students.query.get(session["student"])
   return render_template("User/Homepage.html",student=current_student)
```how can i correct this
summer cairn
native tide
#

I have made a location tracker but I am getting this error

#

I am getting those yellow lines

warm igloo
#

and what does your editor say those yellow lines mean?

#

when you put your cursor on them, or in your Problems tab (if this is vscode)

#

_name_ should be __name__ btw

native tide
warm igloo
#

and services_operator is typoed in the one highlighted

#

and your import can't be resolved, so look at how to do imports and check to make sure you've set up phonenumbers correctly to be imported

#

So you have 2 typos and phonenumbers isn't imported because you've not created it, installed it, or something.

#

_main_ should also be __main__

native tide
#

I had done pip install phonenumbers

native tide
warm igloo
#

so is the only error you have now about phonenumbers?

native tide
warm igloo
#

From where you think you installed phonenumbers module, run pip list

#

You should really be doing all of this in a venv btw because otherwise you're installing modules at the global level.

native tide
#

venv?

#

@warm igloo

warm igloo
#

Can also checkout poetry or pipenv

desert estuary
#

can you use f'string' in jinja

<h1>{{ print(f"fullname:"{student.fullname}) }}</h1>
<h1>{{ print(f"personal-email:"{student.personal_email}) }}</h1>
<h1>{{ print(f"dialling-number:"{student.dialling_num}) }}</h1>
<h1>{{ print(f"branch:"{student.branch}) }}</h1>
<h1>{{ print(f"occupation:"{student.occupation}) }}</h1>
warm igloo
#

you .. don't need to

#

just put the variable

#

jinja templtes are interpolated

desert estuary
#

i wanna write something beforehand

#

fullname: x

warm igloo
#

then write it plaintext

native tide
#

Do I need double underscore in
if __name__=="__main__":

warm igloo
#

everyting inside {{}} gets printed

#

yes, dunder on name and main

native tide
warm igloo
native tide
desert estuary
#

oh shit yeah eya im dumb @native tide thanks

native tide
#

??

warm igloo
#

they mean me lol

#

but you're welcome

native tide
#

What should I do of those yellow lines

wicked pier
#

this might be a better place than general to ask for flask/celery help haha. please let me know if not

#

trying to set up some way to see print statements.
I have a logger set up for the tasks, where it's just a matter of get_task_logger, but I'm not sure what I need to do to see print statements in Flask routes

#

actually...may have found the answer already

#

I think it lies in Flaskland somewhere as opposed to celery

native tide
#

yellow lines

thorn igloo
wicked pier
native tide
#

@thorn igloo

thorn igloo
native tide
#

ok wait I will send you

#

ohh its working now

#

srry

#

But the yellow lines are still there

thorn igloo
#

ok, if it's working ignore the lines

#

you don't really have a problem

eternal blade
#

It's probably the linter doing a bad job

haughty edge
#

Needed some beginner help with Python / Django:

Is it possible for user to create two objects from the same form? For example, am trying to create a to-do list webapp. When a user creates a task, they should have the option to:

  1. Choose from existing tags (another object that has many:many relationship with 'task', or

  2. Create a new 'tag' if the existing ones don't suffice.

Is it possible to do this from single form? Currently, when I create the form for 'task' using Model form, all it allows the user to do is (1).

desert estuary
#

how can i eliminate this and make instead of choose file make it like a field to drop items in

hollow apex
#

Hello so, idk whats the problem here

#
def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid:
            username = form.cleaned_data.get('username')
            messages.success(request,f'Account created for {username}!')
            return redirect('blog-home')

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

even tho I have used cleaned_data after is_valid, it still gives me this error

#

I hate programming, I found it, its the "()" on is_valid

wooden ruin
#

Does Django have support for mongodb?

eternal blade
#

I think there is a external library you need to use if you want to use Django with mongodb

desert estuary
#

btw

#

db.add_column(upload)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'SQLAlchemy' object has no attribute 'add_column'

languid raptor
wicked pier
#

what is the standard way for terminating a task using celery?

#

is it really revoke(task_id, terminate=True, signal='SIGUSR1')? that seems really obtuse

#

like, I'm looking for something which doesn't abuse signals, like how they expect people to be able to end a running task

warm igloo
#

what do you mean doesn't abuse signals?

#

The default is sigterm and sigterm can be handled or ignored. The TERM goes to your task, and it is up to your task to handle it gracefully (or not-gracefully depending on what you want to do)./

ivory lotus
#

Django?/

desert estuary
#

hey i got a small prob here

@app.route('/user',methods=["GET","POST"])
def user():
   if "student" in session:
      x=Students.query.get(session["student"])
      form=Userform()
      if form.validate_on_submit():
         x.upload=form.uploadwork.data
         db.session.commit()
         return redirect(url_for('user'))
   else:
      return redirect(url_for("login"))
   return render_template("User/Homepage.html",student=x,form=form)

it doesn't upload in the database

final rock
#

hi guys, i have a problem in django: TemplateDoesNotExist at /
homepage.html ,, when i try to runserver command
i tried the common solvings but they are not working

#

can anyone help this

wet robin
#

it means there’s an error with your code

desert estuary
#

i kinda get it but the student model have upload

class Students(db.Model,UserMixin):
   id=db.Column(db.Integer(),primary_key=True)
   fullname=db.Column(db.String(50),unique=True,nullable=False)
   email=db.Column(db.String,unique=True,nullable=False)
   personal_email=db.Column(db.String,unique=True,nullable=False)
   password=db.Column(db.String(),unique=True,nullable=False)
   dialling_num=db.Column(db.String(),unique=True)
   branch=db.Column(db.String())
   occupation=db.Column(db.String())
   upload=db.Column(db.String())

127.0.0.1 - - [11/Jul/2021 22:42:16] "POST / HTTP/1.1" 302 -
Student:Students.id Students.fullname Students.dialling_num Students.branch
when i use print idk why it's not displayed even tho i made it from the cli and got it in the db

eternal frigate
# final rock hi guys, i have a problem in django: TemplateDoesNotExist at / homepage.html ,, ...

where is homepage.html file located? is it at ../myapp/templates/myapp/homepage.html? try referencing it with myapp/homepage.html. "myapp" is a placeholder for your app name. In code templates path are relative to some directory defined in TEMPLATES setting, the default setting makes django search templates in ../myapp/templates directory for all installed apps, to avoid template name collision between different apps you create a subfolder with app name and put your templates there, so you reference it with appname/mytemplate.html.

nova pewter
#
from first_app import forms
from first_app.models import AccessRecord


# Create your views here.
def index(request):
    webpages_list = AccessRecord.objects.order_by('date')
    date_dict = {'access_records': webpages_list}
    return render(request, 'index.html', context=date_dict)


def help(request):
    my_help = {'insert_help': "hey, i need help!"}
    return render(request, 'help.html', context=my_help)


def form_name_view(request):
    form = forms.FormName()

    if request.method == 'POST':
        form = forms.FormName(request.POST)

        if form.is_valid():
            print("Verification Done")
            print("Name:" + form.cleaned_data['name'])
            print("Email:" + form.cleaned_data['Email'])
            print("Comment:" + form.cleaned_data['comment'])

    return render(request, 'forms.html', {'form': form}) ```
#
from django.forms import Textarea


class FormName(forms.Form):
    name = forms.CharField()
    Email = forms.EmailField()
    comment = forms.CharField(widget=forms.Textarea) ```
#

i am not getting any error but the form_name_view method doesn't seem to work

#

sorry for the mess!

eternal frigate
nova pewter
#

yeah the web page opens but when i submit it doesn't print out ("verification done')

#

i am just trying to check if the "POST" method works

eternal frigate
#

and the form does not displays any error?

nova pewter
#

yep no error

#

when i submit it doesn't do anything

eternal frigate
#

how is your form template? you followed django's tutorial?

nova pewter
#

i am learning from a course on udemy.

#

form template is working fine

desert estuary
#
class Uploading(FlaskForm):
   uploadfile=FileField("upload",validators=[FileRequired(),FileAllowed(["jpg","png","pdf","txt"])])
   Submitting=SubmitField("Submit")


@app.route('/user',methods=["GET","POST"])
def user():
   if "student" in session:
      current_student=Students.query.get(session['student'])
      print(current_student)
      form=Uploading()
      if form.validate_on_submit():
         current_student.upload=form.uploadfile.raw_data
         db.session.commit()
         return redirect(url_for('user'))
   else:
      return redirect(url_for("login"))
   return render_template("User/Homepage.html",student=current_student,form=form)

class Students(db.Model,UserMixin):
   id=db.Column(db.Integer(),primary_key=True)
   fullname=db.Column(db.String(50),unique=True,nullable=False)
   email=db.Column(db.String,unique=True,nullable=False)
   personal_email=db.Column(db.String,unique=True,nullable=False)
   password=db.Column(db.String(),unique=True,nullable=False)
   dialling_num=db.Column(db.String(),unique=True)
   branch=db.Column(db.String())
   occupation=db.Column(db.String())
   upload=db.Column(db.String())

   def __init__(self,fullname,email,personal_email,password,dialling_num,branch,occupation,upload):
      self.fullname=fullname
      self.email=email
      self.personal_email=personal_email
      self.password=password
      self.dialling_num=dialling_num
      self.branch=branch
      self.occupation=occupation
      self.upload=upload

   def __repr__(self):
      return f'Student:{Students.id} {Students.fullname} {Students.dialling_num} {Students.branch} {Students.upload}'

so this is my code and when i try to submit some file to the database it doesn't wanna be pushed to the data base

desert estuary
#

what do you mean by read

#

you wanna present the data right

#

i guess you should do this

#
fileread = filesubmit.file.data()
```since it doesn't have such thing as read and you want to display the data that you got from the field right
#

if not and you want to get it from the database i guess you should do something like this

x= Filesubmitproject.query.filter_by(file=fileread)

at least from what i understood

warm igloo
#

what is your .read() line I didn't see it in the code above

mossy osprey
#

Not sure if this is the place to post this, but any thoughts?

warm igloo
mossy osprey
warm igloo
#

Off top of head I think you need filesubmit.file.data.read()

#

let me go look at a flask app I have with a file upload, see how I did it cause I can't remember atm

#

dude, I'm an "architect" and I've spent hours recently looking for a single ' that was effing up my world. It happens to all of us. 😄

#

I'll go find my code too just to be sure

#

wait did it work?

#

lmfao

#

welcome

#

pulled that shit out of the air

#

haha been there

#

uhoh

#

well, they're bytes yes

#

you gonna store them as a blob in the db?

#

make sure you save a filename or at least mimetype with them too

#

cause that will matter

#

I have in the past as another column. Main thing when you want to print out the blog back to an image, you'll need to say "oh save this to disk as a .jpg" or "stream this to the client as a .jpg". But if your clients can upload all those different file types, how will you know what to send them back?

For instance, you could store the original filename or extension and just use that when you spit it back out. And if you're streaming it back to them, you may need to set the Content-type to image/jpg so the browser knows what to do.

#

But before you even go there, give it a try and see what the hell happens

#

🙂

mossy osprey
#

yayyyy!!!

warm igloo
#

@mossy osprey Did you figure out your xpath syntax?

mossy osprey
#

Lmaooo all good @fair shale

mossy osprey
warm igloo
#

same issue

mossy osprey
#

So just a bit of a context. I'm trying to write a simple script that returns a list of followers from one of my Instagram accounts. So I don't think there's an Instagram Python API that I can use, I'm just using selenium.

#

Bruh I'm blind.

#

I saw the xpath after you just pointed it out @warm igloo. Anyway what exactly is an xpath?

warm igloo
#

so, you're trying to select some element on the page and it is saying "sorry, that isn't there"

#

you need to catch that exception and do something accordingly

mossy osprey
#

Oh so the element "/html/body/div[4]/div/div..." doesn't exist for some reason right?

warm igloo
#

xpath is just a syntax for selecting elements from a tree of nodes like in html or xml

#

right, I'm guessing you're using selenium commands and trying to find some div/button/element/whatever and this is saying "you're wrong, that's not there"

native tide
#

Hey, I'm working on one thing regarding Ubisoft and I need to connect into account using email and password and get authorization, but unfortunately I'm struggling with it. I found the same thing that I need in C# but unfortunately I dunno it and I can't really make it in python for some reason, any ideas?

var basicCredentials = Convert.ToBase64String(
              Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["mail"] + ":" + ConfigurationManager.AppSettings["password"]));

            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                Headers = {Authorization = new AuthenticationHeaderValue("Basic", basicCredentials)},
                RequestUri = new Uri("https://public-ubiservices.ubi.com/v3/profiles/sessions"),
                Content = new StringContent("{\"Content-Type\": \"application/json\"}", Encoding.UTF8,
                    "application/json")
            };
warm igloo
#

keep in mind for instagram their HTML might not be rendered and may all be client side generated with JS so you'll need to make sure whatever you're using as your selenium browser engine is rendering the JS of the page too (I think by default it should be doing that but I can't recall atm)

mossy osprey
warm igloo
#

@mossy osprey do you have some code you can share?

mossy osprey
#

sure

warm igloo
#

!code

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

warm igloo
#

just in case

mossy osprey
#

Do you want me to send the entire thing or just a fraction? (the entire thing is 73 lines)

warm igloo
#

@native tide What are you building with that?

#

!paste

lavish prismBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

warm igloo
#

Put the 73 lines there

#

I write a lot of spiders using selenium, beautifulsoup, etc so hoping I can help you

native tide
warm igloo
#

Actually something I need to remind both of you: make sure you are not violating the TOS of the site you are trying to scrape.

native tide
#

And I need to get auth of that account as well

mossy osprey
mossy osprey
mossy osprey
# native tide What's ur problem?

just trying to return a list of users from one of my accounts. It's more of a learning experience/really simple project. Nothing deeper than that right now.

warm igloo
#

@native tide You can make those same calls with python. Take note of the steps and the headers and make the same request to the same url. Try to write the code and I'll try to help you, but I can't do a direct translation for you.

native tide
warm igloo
#

@mossy osprey Since you borrowed this code and its not yours, what could be happening is that particular layout has changed and the xpath is now incorrect cause the elements on the page you're looking at are different now.

So for instance the page could have been "<div>Hello Swift!</div>" last week but this week is "<div><span>H</span>ello, <em>Swift!</em></div>" this week so the code says "gimme the div at this xpath" and of course .. the path is now different.

mossy osprey
warm igloo
#

Usually how I do it is 'Inspect Element' in my browser. Depending on which browser you can see the xpath at the bottom of the console (though not in xpath syntax necessarily).

#

Ooh, in Firefox I can right click on an element in the inspector and then copy the xpath from there: /html/body/header/div/div[1]/a[2]/span for instance that came from an element on a page I was just on

#

So I went to instagram and popped open the followers modal and selected the xpath of the div containing my list of followers: /html/body/div[5]/div/div/div[2]

#

Or rather this: /html/body/div[5]/div/div/div[2]/ul/div is "further down" and closer to the data

#

Reminder: make sure the script you're making is opening the modal window too or the element you're searching for won't exist

#

tricky stuff scraping from javascript heavy front ends

mossy osprey
#

@warm igloo Did you do this in firefox or chrome? rn, i'm doing this in chrome

#

I could try in firefox

warm igloo
#

I'm in FF right now. Don't have Chrome on this box as its just my gaming box. 🙂

#

I'm sure Chrome is similar though

native tide
#
        private static async Task<UbisoftToken> GetToken()
        {
            _httpClient.DefaultRequestHeaders.Add("Ubi-AppId", "2c2d31af-4ee4-4049-85dc-00dc74aef88f");
            _httpClient.DefaultRequestHeaders.Add("Ubi-RequestedPlatformType", "uplay");
            _httpClient.DefaultRequestHeaders.Add("user-agent",
                "Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3");

            Console.WriteLine("Connecting to the Ubisoft Servers.");

            var basicCredentials = Convert.ToBase64String(
                Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["mail"] + ":" + ConfigurationManager.AppSettings["password"]));

            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                Headers = {Authorization = new AuthenticationHeaderValue("Basic", basicCredentials)},
                RequestUri = new Uri("https://public-ubiservices.ubi.com/v3/profiles/sessions"),
                Content = new StringContent("{\"Content-Type\": \"application/json\"}", Encoding.UTF8,
                    "application/json")
            };
            var response = await _httpClient.SendAsync(request);
            if (!response.IsSuccessStatusCode)
                throw new UnauthorizedAccessException("Unable to retrieve authentication ticket. Thanks ubisoft mf!");
            return JsonConvert.DeserializeObject<UbisoftToken>(await response.Content.ReadAsStringAsync())!;
        }
#

This is whole function

warm igloo
#

oh yeah you'll need to add all those other headers to your python too, not just the auth

#

the appid, uplay one, etc

velvet yew
#

I'm looking for a learning partner who would like to contribute to my Django web app project by creating a modern design for a simple dashboard.
I'm a back-end developer and not experienced with JS nor have the design skills for sexy CSS.

If you would like to help please send a DM with your portfolio (if you have one, if not that's fine too)!

mossy osprey
#

@warm igloo so I did what you said: right-click, inspect element. But this doesn't like an xpath to me?

#

I took your advice and logged into Instagram on Firefox ^^

native tide
# warm igloo oh yeah you'll need to add all those other headers to your python too, not just ...
headers = {
    'Ubi-AppId':'880650b9-35a5-4480-8f32-6a328eaa3aad',
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36',
    'Ubi-RequestedPlatformType':'uplay'
}

r = requests.post("https://public-ubiservices.ubi.com/v3/profiles/sessions", auth=(email, password), headers=headers)
rData = r.json()
print(rData)

I tried this but it still doesn't work

#

Normally there's Authorization in headers too and there's the auth token but I need to login using email and password in this case

#

And I'm getting The Authorization header is missing error since I don't have any there

grim plaza
#

Can anyone help me?

#

I am unable to install any python module thru pip from Anaconda prompt

inland oak
#

pip is replaced to conda in conda

#

something like that perhaps

#

according to this guide, you still need to use pip though

#

just in different console

grim plaza
#

Thanks everyone

#

I am unable to pip install pyautogui

stark tartan
tulip haven
#

can we make websites for discord bots in python?

reef elm
#

can anybody recommend me some resources to learn CSS

hybrid dome
#

why does it says template not found

#

im new to flask ;-;

ionic raft
#

You need a templates folder

hybrid dome
#

ohh new folder?

ionic raft
#

yah...

hybrid dome
#

um alright but where

ionic raft
#

In root should do it

#

Flask looks for /templates/ for all templates

hybrid dome
#

oh

ionic raft
#

It will make sense later. And it makes it easier to organize files as the project grows.

hybrid dome
#

um-

#

not working

tawny gazelle
hybrid dome
#

nvm fixed

#

how do i make a button in html when clicked does something using python code

inland oak
hybrid dome
#

im not making a submit form

inland oak
#

that makes fetch request to your python api

hybrid dome
#

wdym javascript

#

idk js

inland oak
#

as far as I know there are only two ways. I can't offer you third one.

hybrid dome
#

why

thorn igloo
#

he just explained that there are two ways??

#

it's either you submit a form or you make ajax calls from JavaScript

inland oak
lavish prismBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

tawny gazelle
#

!rule4

#

!rule 4

lavish prismBOT
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

tawny gazelle
#

!rule 6

lavish prismBOT
#

6. Do not post unapproved advertising.

tawny gazelle
#

I will ask other channel about bypass cloundflare

inland oak
tawny gazelle
#

!rules

lavish prismBOT
#

The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.

vestal hound
#

submit a form

hybrid dome
#

wdym by form

tawny gazelle
#

Hello guys, Which module I should use for connecting database(i.e MySql)?

#

which one is the best python module for connecting database?

inland oak
#

anyway, SQLAlchemy is a nice average choice

tawny gazelle
tawny gazelle
cold estuary
#

have any one tried getting previous day data from openweather API

glacial stirrup
#

Hi,

I'm trying to populate the admin field directly from the created_by field on save of a group instance though I'm getting error "direct assignment to the forward side of a many-to-many set is prohibited" How can I work around this ?
Here's my code

class Group(models.Model):
group_name = models.CharField(max_length=200, blank=True)
description = models.TextField(
help_text='Describe this group...', max_length=350, blank=True)
admin = models.ManyToManyField(
"profiles.Profile", blank=True, related_name='group_admin')
members = models.ManyToManyField(
"profiles.Profile", blank=True, related_name='members')
posts = models.ForeignKey(
"posts.Post", blank=True, on_delete=models.SET_NULL, null=True, related_name='group_posts')
created_by = models.ForeignKey(
"profiles.Profile", on_delete=models.SET_NULL, null=True, related_name='group_creator')
created = models.DateTimeField(auto_now=True)

digital flame
#

Hello,
I just have a simple question regarding Django administration. I know how it functions and have explored it a bit. Django Admin offered all sort of CRUD features directly into my database. Now I am supposed to build a simple web API for my client where I am supposed to do simple CRUD tasks. If Django Admin directly offers it, should I use the libraries that the django admin uses or do i need to write codes for the client myself? Also, for whom is Django admin targeted for? Is it for server people or developers only? Or can it be passed to the client? I have done alot of API's in NOdejs but I have recently started Django so I am a bit confused on the Django Administration. Any help would be appreciated.

inland oak
coarse dawn
#

Hello everyone, I have simple, maybe not, question for Django CMS. I have a major error and don't know where to look. So the issue is following:

  1. I am using Django CMS show_menu, using my own template etc.
  2. I have a specific menu tree that I have on Django Admin panel with all pages and menu items, half of which are marked as they should not be visible in menu
  3. When I open webpage that I am working on, it shows me menu and all items that are in that menu tree, like all of them, including the items, that have been switched off.

The tag i am using to show menu is following: {% show_menu 0 100 100 100 "*link to template*"%}
Could you please assist and tell me where could possibly error be? Thank you!

final rock
#

Hi ,
I am struggling with django errors, i tried many things to solve, but every time, i got a new one. Although i am doing same things in the video , i got an error message, i don't know why it is like that:

marble topaz
#

ur tryna make a account bruteforce

native tide
#

Um, what?

#

I'm trying to login into account lol

#

Using email and password instead of auth token

marble topaz
subtle hamlet
#

assets = db.execute("SELECT symbol, action FROM account, SUM(shares) WHERE action = buy - SUM(shares) WHERE action = sell AS shares WHERE userid = ? GROUP BY symbol", session["user_id"])
i think it's not allowed to have multiple WHERE in SQL? there's a syntax error, how do i achieve this effect

#

i want to select the data from account table to get data for bottom

raw compass
# subtle hamlet i want to select the data from account table to get data for bottom

Most SQL languages will allow a case statement that would do a if statement that will be more suitable.

For example in PostgreSQL

with processing (
SELECT 
  symbol, 
  CASE action 
    WHEN 'buy'  THEN shares 
    WHEN 'sell' THEN shares * -1 
    ELSE null 
  END as shares 
FROM account WHERE userid = ?
)
Select symbol, SUM(shares) from processing group by 1;

This is a combination of a CTE so I could logically seperate the query and do the group by afterwards as you can't always do it at once...

native tide
#

Hey, so I'm basically making script that logins into Ubisoft account using email and password, but I don't know how to do it.

headers = {
    'Ubi-AppId':'880650b9-35a5-4480-8f32-6a328eaa3aad',
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36',
    'Ubi-RequestedPlatformType':'uplay'
}

r = requests.post("https://public-ubiservices.ubi.com/v3/profiles/sessions", auth=(email, password), headers=headers)
rData = r.json()
print(rData)

Normally there's Authorization: 'token' in headers and there's the auth token but I need to login using email and password in this case and I dunno how to write the syntax in that case. (I'm building a stat checker, not anything malicious or whatever)

#

hm

gritty cloud
native tide
#

this is an interesting channel

#

so what can i use to tell what should happen when someone clicks on a button with Python

gritty cloud
#

Then reuse the auth token they give you

native tide
#

considering the button was written in HTML and styled with CSS

gritty cloud
#

Assuming they use tokens amd not sessions

native tide
#

is Flask the way to go?

native tide
# gritty cloud You would first have to make a post to the login / signup url

This is the "thing" that I need but in csharp, and I barely understand it so I'm really not able to convert it into python

        private static async Task<UbisoftToken> GetToken()
        {
            _httpClient.DefaultRequestHeaders.Add("Ubi-AppId", "2c2d31af-4ee4-4049-85dc-00dc74aef88f");
            _httpClient.DefaultRequestHeaders.Add("Ubi-RequestedPlatformType", "uplay");
            _httpClient.DefaultRequestHeaders.Add("user-agent",
                "Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3");

            Console.WriteLine("Connecting to the Ubisoft Servers.");

            var basicCredentials = Convert.ToBase64String(
                Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["mail"] + ":" + ConfigurationManager.AppSettings["password"]));

            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                Headers = {Authorization = new AuthenticationHeaderValue("Basic", basicCredentials)},
                RequestUri = new Uri("https://public-ubiservices.ubi.com/v3/profiles/sessions"),
                Content = new StringContent("{\"Content-Type\": \"application/json\"}", Encoding.UTF8,
                    "application/json")
            };
            var response = await _httpClient.SendAsync(request);
            if (!response.IsSuccessStatusCode)
                throw new UnauthorizedAccessException("Unable to retrieve authentication ticket. Thanks ubisoft mf!");
            return JsonConvert.DeserializeObject<UbisoftToken>(await response.Content.ReadAsStringAsync())!;
        }
#

bro

native tide
#

yo

gritty cloud
#

Then throws an error if the request fails

native tide
#

Would u be able to show me the syntax of how it should be in python? I was trying to do this yesterday for over 3 hours but I have no clue

gritty cloud
#

I also don't lol

#

But you just would need to requests.get with the headers

native tide
#

Many times using many ways

gritty cloud
#

¯\_(ツ)_/¯

#

Maybe ubisoft has a public api

native tide
#

Unfortunately they do not

gritty cloud
#

Hm

rocky ferry
#

can someone please help me i wonder why i getting error

thorn igloo
rocky ferry
#

@thorn igloo thanks

#

do u have any list for python functions in jinja

#

?

thorn igloo
#

mate, you can google for that

rocky ferry
#

i did

#

but i couldn't find

thorn igloo
#

if you can't find it what makes you think i will?

rocky ferry
#

ohk, sorry

#

thank u so much for help 🙂

thorn igloo
#

just look in the jinja2 documentation

rocky ferry
#

ohk

subtle hamlet
#

cuz my ide supports that

digital flame
inland oak
#

second question is not providing enough information to answer

digital flame
#

@inland oak I researched it a bit and your verification made everything clear. Thanks again.

dense slate
#

Anyone worked with Django channels? Does it generally require an ASGI server in production for the entire project?

#

I'm looking to create subscriptions with GrapQL to Django, but it looks like there's a lot of work on the backend to get that working.

inland oak
#

even its depended libraries are mentioned

dense slate
#

Yea I've read it, I'm more curious about people's experience with it. How difficult it was to setup and get running in production, et.

inland oak
#

shrugs. The page mentions it uses Daphne ASGI

#

I heard Daphne is made specifically for Django

#

it was actually made specifically for Django Channels ;b

gloomy glade
#

Hello people I am working on making a RPC like framework using Zeromq. Any suggestions are welcomed!
https://github.com/Ananto30/zero

GitHub

Zero: A high performance and fast Python microservice framework (RPC + PubSub) - Ananto30/zero

rocky ferry
#

how to debug django on visual studio code

#

i don't see any option to choose django 😦

#

can someone please help me out

thorn igloo
rocky ferry
#

i mean on visual studio code

thorn igloo
#

what do you mean by debug is this context?

rocky ferry
#

watching from 36:40

#

for him it is showing django

#

for me it is not

thorn igloo
#

let me check

rocky ferry
thorn igloo
#

i tried it and the django option is there for me

rocky ferry
#

i didn't get bro

#

i did

#

still same

thorn igloo
thorn igloo
#

i it's returning it because that's what you are telling it to return

inland oak
#

but it is not needed in my opinion

#

because there is option to run pytest ;b

#

debugging pytest is the only needed thing in my opinon

#

no point in debugging launched application

thorn igloo
#

look here

#

see how x wasnt affected

#

but the function needs to be called first before the change can happen, keep that in mind

lapis basalt
#

I have a question please
I have a list of dataframes
I want to render each one in one tab
of a html flask project template
The dataframe is very complex in syntax it is muti indexed
in the usual way to return only one dataframe not a list of dataframes in one template I used dataframe.to_html()
return render_template(
"table_tfidf_trame.html",
mot=word,
liens=nb_links,
tables=[
output_f.to_html(
classes="table table-striped table-hover table-sm",
header="true",
justify="center",
)
],
)
and in the html I used
{% for table in tables %}
{{ table|safe }}
{% endfor %}

tardy hill
#

good night, i wanted to create a plugin module in jpython for the autopsy tool. fetch data from SQLLITE databases.

warped heart
#

hi, so i have multiple files that i want to return back to the web browser, except these files are open with BytesIO, is there a way to do this and for context i am using flask

warped heart
errant spire
#

I'm looking for some help creating a parent/child relationship with a single model. Essentially I have a model called Systems which can have children as subsystems (which can themselves have subsystems). I want to create a many-to-many relationship between them, but I'm getting errors when I try to use this

#
class System(models.Model):
    system_name = models.CharField(max_length = 100)
    description = models.CharField(max_length = 500)
    pub_date = models.DateTimeField('date published')
    stages = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(20)])

class Subsystem_relation(models.Model):
    parent = models.ManyToManyField(System)
    child = models.ManyToManyField(System)
night radish
#

Anyone with a helping hand?

#

Consider me a complete noob because I totally don't how to do what I am about to say or even if I'm in the right place for it, can we upload images to some sort of a temporary server or website atleast 1 image per second with enough speed that discord can render it like a really low fps game in an embed yes this is a discord bot project idea

#

This is completely indirect to the discord.py library

#

Mate, this has got nothing to do with the library, just that this is for a bot. What I want to do is to upload an image to a web of sorts and be able to render it from discord with an embed. So is it possible/is there a website or library Which can help me upload an image to a database and handle it fast enough?

#

Oh

#

Thanks .. I'll try to do something,

#

Thanks for ur effort

lyric mason
#

does anyone know how to get started with python web dev?

pallid spade
#

I am going through the official flash tutorial for the first time.

It seems that string interpolation doesn't work?

def show_user_profile(username):
    # show the user profile for that user
    return f'User {escape(username)}'```
#

I get invalid syntax

tiny snow
pallid spade
#

Python 3.9.6

#
from markupsafe import escape

app = Flask(__name__)


@app.route("/")
def hello_world():
    return "<p>Index Page</p>"


@app.route('/hello')
def hello():
    return "<p>Hello World</p>"


@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return f'User {escape(username)}'```
tiny snow
#

are you sure that's the version of Python that's executing this script?

pallid spade
#
Python 3.9.6
#

?

tiny snow
#

try py -3.9 that_scripts_name.py

#

or python3 that_scripts_name.py

pallid spade
#
Unknown option: -3
#

I am simply doing the official tut

tiny snow
#

no, do it without -3.9

#

either you do

py -3.9 hello.py
#

or

python3 hello.py
pallid spade
#

ModuleNotFoundError: No module named 'flask'

tiny snow
#

yeah you didn't install flask on your python 3.9 version

pallid spade
#

hmmm

#

ok....

tiny snow
#

do

pip3 install flask

or whatever you need to install it on linux

#

you're on linux, right?

pallid spade
#

no mac

tiny snow
#

well whatever

#

pip3 install flask

pallid spade
tiny snow
#

can you please do

from sys import version
print(version)

in your code and tell me what it says when you do

python3 hello.py
#

like what version of Python does it say

pallid spade
#
3.9.6 (v3.9.6:db3ff76da1, Jun 28 2021, 11:49:53) 
[Clang 6.0 (clang-600.0.57)]
Traceback (most recent call last):
tiny snow
#

and then there is this error of flask being unknown right

pallid spade
#

ModuleNotFoundError: No module named 'flask'

#

but flask works

#

I can do index and hello routes

#

but when is gets to the formating it says it can't do it

#

but I know it is available in this verison of python

tiny snow
#

yeah so, PyCharm starts python2 for some reason

#

and flask isn't installed for python3 for some reason for you

#

i don't know

#

are you in a virtual environment

pallid spade
#

yeah I am just bc I am following allow the tut

patent glade
#

Javascript question

tiny snow
#

did it tell you to run these or something similar

patent glade
#

How can I detect when an event has completed propagation

tiny snow
#

note python3

#

then that

#

all that before you pip3 installed flask

#

or just pip i guess

pallid spade
#

yeah I did all three steps and copied the lines

tiny snow
pallid spade
#
Requirement already satisfied: flask in ./venv/lib/python3.9/site-packages (2.0.1)
Requirement already satisfied: click>=7.1.2 in ./venv/lib/python3.9/site-packages (from flask) (8.0.1)
Requirement already satisfied: Werkzeug>=2.0 in ./venv/lib/python3.9/site-packages (from flask) (2.0.1)
Requirement already satisfied: itsdangerous>=2.0 in ./venv/lib/python3.9/site-packages (from flask) (2.0.1)
Requirement already satisfied: Jinja2>=3.0 in ./venv/lib/python3.9/site-packages (from flask) (3.0.1)
Requirement already satisfied: MarkupSafe>=2.0 in ./venv/lib/python3.9/site-packages (from Jinja2>=3.0->flask) (2.0.1)
#

going to take a break

tiny snow
pallid spade
#

I have no idea

tiny snow
#

maybe now it will work

#

since it says it's there

pallid spade
#
(venv) ~/PycharmProjects/flask-tut $ python3 hello.py
tiny snow
#

does it mean it worked?

pallid spade
#

there is no output

tiny snow
#

oh wait did you remove the line where it runs it like that

pallid spade
#

hold on I got a friend calling that is programmer

tiny snow
#

@pallid spade try just running flask run now

pallid spade
#

I uninstalled flask and reinstalled and it worked? I think

#

works now? but I don't know what excatly fixed it

patent glade
#

How can I detect when a javascript event object has finished propagating?

#

I'm writing a program that creates a virtual/proxy DOM in python to represent a living webpage. Whenever an event occurs in Javascript, its transmitted to Python which creates a proxy object representing the event, dispatches it, and then sends any DOM changes/etc triggered by the event back to javascript

#

So in Javascript, every time an event handler is triggered, it sends the event's data over to Python which fabricates a proxy of the event object. The problem is that a single event object in Javascript may trigger numerous listeners as it traverses its bubble chain

#

Each time an event occurs JS, potentially more than one event object representing it is generated on the python side as a result. I want to eliminate this behaviour

#

If I create a cache of event objects within Python, I can prevent the default behaviour that is auto-fabricating an event when one is received from Javascript by checking if one has already been cached for the JS counterpart

#

The problem with this approach is, when do I kill the pythonic copy?

#

If I don't, that dictionary just continues to grow. What I really need is an OnDeallocate method to fire on the object when it's garbage collected in Javascript, to signal to python to do the same

plain zealot
#

Anyone knows how to deal with multi click issue? Like every time I click the button it increases by x2

smoky whale
#

anyone knows how to get cam input from my website into pyopencv ?

#

i am trying to make a website that makes face filters

ionic raft
#

Django Question. I'm trying to query the db to get the pk of the current object. I have this:

query_article_object = get_object_or_404(Article, pk=self.kwargs['pk'])

However, this returns

KeyError at /articles/
'pk'

Side note. The following variation produces the same error:

query_article_object = get_object_or_404(Article, id=self.kwargs['pk'])```
Thoughts?
mossy osprey
#

How do I figure out the xpath of an element on Chromium? I'm using selenium.

ionic raft
mossy osprey
ionic raft
cloud harbor
#

i am trying to make an api with fastapi can i ask questions here?

ionic raft
cloud harbor
#

oh ok

#

i just wanted to know if there is a way to return image url rather than the image itself with the fileresponse

#

is there a way to upload image as an endpoint

patent glade
#

For some reason I'm having a terrible time explaining why I need this this, but, I need a way to detect when an event has finished propagating

#

Some sort of an 'OnComplete' method on event class

#

Sorry, this is in Javascript

#

Any thoughts?

inland oak
#

when you connect to chrome API

#

it is actually even named in exactly same way I think 😉

#
#

perhaps it could of some help

#

oh!

#

as example of chrome extension

#

they provide the next javascript code

#
document.addEventListener('DOMContentLoaded', function() {

 // here I attach my listeners

}
#

this could be used perhaps without chrome API, it should be available just in JS I think

#

besides DOMContentLoaded perhaps there other events you can attach yourself to

sick glacier
#

Hello all have following issue jango rest framework

#

{
"detail": "Authentication credentials were not provided."
}

#

This error occurs even though i am passing the correct token in the post request postman

inland oak
rocky ferry
#

i tried to use debug tool of django, i did everything as it is written on django debug tool document

#

but i don't why i getting this error, please help me 🙂

sick glacier
inland oak
rocky ferry
#

#django

inland oak