#web-development

2 messages · Page 233 of 1

bleak adder
#

@orchid hamlet i dont have the exact code right now but its something like that (as i remember it lol)

#

----- flask code -------
@app.route("/start")

this executes func1()

def start():
func1(param1, param2)
return render_template("index.html")

@app.route("/download")

this is for downloading a file when the button is clicked

def download():
file = func2()
return send_file(file)

-------python code (backend) -----
global_var = ""
def func1(k8s, name):
global global_var
global_var = f'{name}{date.now()}.pcap'

def func2():
global global_var
file = global_var
return file

orchid hamlet
#

ok so you want to get the value of the global variable?

#

i.e download the file

bleak adder
#

Yes ... if i call func2() in the /start route it works fine but this doesnt work in separate routes

orchid hamlet
#

did you declare the global_var

#

variable

#

ok yes you did

bleak adder
#

Yes # global_var = ""

#

indeed, func2() returns a blank global_var

#

is there a way to store the value returned by func1() for later use when i call func2()?

orchid hamlet
#

yes it is

#

though i think you need to use sql

#

for string the val of func2() you might require sql

#

if you cannot manage with the global var

#

sqlite3 comes preinstalled with python so yes you can

bleak adder
#

i'll try it if it doesnt complicate things 😅

orchid hamlet
#

yes i will just give you the formatted code

hexed current
#

Hello

#

guys

#

I need help with something

#

I'm using selenium and python and i want to submit a captcha token

#

but I can do so because there is no submit button

#

I tried making a button

#

but it didn't really do anythig

orchid hamlet
#

this will only use 2 lines

bleak adder
#

Without sql ?

orchid hamlet
#
@app.route("/start")
func_1_val = str()
# this executes func1()
def start():
    global func_1_val
    func_1_val = func1(param1, param2)
    return render_template("index.html")

@app.route("/download")
# this is for downloading a file when the button is clicked
def download():
    file = func2()
    return send_file(file)

-------python code (backend) -----
global_var = ""
def func1(k8s, name):
    global global_var
    global_var = f'{name}{date.now()}.pcap'
    return global_var

def func2():
    global global_var
    file = global_var
    return file```
#

yes that is done

#

@bleak adder

#

@bleak adder

bleak adder
#

Thank you @orchid hamlet i will try it

orchid hamlet
#

I just stored the value by returning func1 to func_1_val

bleak adder
#

i hope it will work when i call func2() 🤞

orchid hamlet
#

oh yes the value is stored in func_1_val, so edit your code accordingly

bleak adder
#

Alright ... thank you 😋

main kayak
#

I'm building a form in Flask using Flask-WTF and wtforms. Everything works except for my BooleanFields, which always return false -even when checked on the front end.

In my form class, I just have them listed as:

field_name = BooleanField('field_label')

Am I missing something?

orchid hamlet
main kayak
#

Typo

orchid hamlet
#

can you send the code?

main kayak
#

Standby

#

Sorry, its too long - one sec.

#

Ugh lol, nevermind. I figured it out. Copying the relevant jinja code made me spot the issue.

orchid hamlet
#

no problem.

main kayak
#

Thats the problem with coding at 2 in the morning.

orchid hamlet
#

whats the issue btw

#

was*

main kayak
#

I had value = "" as an attribute of each boolean field in my jinja template.

#

So I guess it was forcing them all to be false.

#

removed that, and now it works as expected.

#

Not sure why I put that in there to begin with.

orchid hamlet
#

oh so the value kind of reseted

main kayak
#

¯_(ツ)_/¯

mystic wyvern
#

It's Impossible in the model bcz you have to migrate everytime anyone logged in or logout, then the solution should be in the view, your author field should be updated everytime you go to this form page by enter the logged in user

stable bear
#
{% extends "layout.html" %} 
{% block title %}About{% endblock %}
{% block body %} 
<img src="about.jpg" alt="About" width="500" height="600">
{% endblock %}

This is my HTML code to display an image. However, the image does not show, and instead the alt text does.

obtuse robin
#

the image src is incorrect then

tribal onyx
#

Hi, I am integrating mysql and flask and I'm trying to search for a matching substring in a mysql row in my flask web api.

I got this code in another file listing.py

 def getTravelPackageBySubstring(cls,substring):
     try:
         dbConn = DatabasePool.getConnection()
         db_Info = dbConn.connection_id
         print(f"Connected to {db_Info}");
         cursor = dbConn.cursor(dictionary=True)
         sql = "SELECT * from `travel listing` where description or country LIKE '%",(substring),'%"'
         substring=cursor.execute(sql,(substring,))
         substring = cursor.fetchall()
         return substring
     finally: 
         dbConn.close()
         print ("release connection")

How can I get it to run in app.py?

I tried

@app.route('/listing/<string:substring>')
def getTravelPackageBySubstring(substring):
    try:
        jsonListing=TravelPackage.getTravelPackageBySubstring(substring)
        jsonListing={"Travel Listing":jsonListing}
        return jsonify(jsonListing)
    except Exception as err:
        print (err)
        return {},500

and it gives an error ''tuple' object has no attribute 'encode'

prisma oracle
native tide
#

@tribal onyx

Looks like the variable sql is of type tuple - I don't know if it should be.

>>> substring='foobar'
>>> sql = "SELECT * from `travel listing` where description or country LIKE '%",(substring),'%"'
>>> print(sql)
("SELECT * from `travel listing` where description or country LIKE '%", 'foobar', '%"')
#

The reason it probably errors with the message tuple object has no attribute 'encode' is the method cursor.execute calls encode(...) on the first argument you pass it, which is of type tuple and not type string

#

That line should use the + operator to concatenate those strings (Actually this is vulnerable to SQL Injection, so...you may want to use prepared statements) instead of using , to make sure the type is string and not tuple

hollow dragon
#

How much OOP should I know? I've been doing only leetcode lately but was wondering about OOP

pallid hill
#

I am trying to make a chat room, but for some reason the box that loads in messages (the div) extends the whole web page when it is filled with messages, but I want the box (it's the div) to scroll when it runs out of space, so it can fit more messages. But, I don't know how to do that. ```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Chat App</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.1/socket.io.js"></script>

<style>
#sendBtn {
    display: inline-block;
    vertical-align: middle;
    transform: translateZ(0);
    box-shadow: 0 0 1px rgba(0, 0, 0, 0);
    backface-visibility: hidden;
    -moz-osx-font-smoothing: grayscale;
    transition-duration: 0.3s;
    transition-property: transform;
}

#sendBtn:hover,
#sendBtn:focus,
#sendBtn:active {
    transform: scale(1.1);
}
</style>

<h1 style="text-align:center; font-family: Monospace, Arial">Chat App</h1>

</head>

<body style="text-align:center; font-family: Monospace, Arial; font-size: 14pt">
<script type="text/javascript">
$(document).ready(function() {
var socket = io.connect("server")
socket.on('connect', function() {
socket.send("User Connected!");
});

    socket.on('message', function(data) {
        $('#messages').append($('<p>').text(data));
    });

    $('#sendBtn').on('click', function () {
        socket.send($('#username').val() + ':  ' + $('#message').val());
        $('#message').val('');
    });
})

</script>
<div id="messages" style="margin: 0 auto; width: 60%; text-align: left; min-height: 300px; border: 1px solid black;">

</div>
<input type="text" id="username" placeholder="Username">
<input type="text" id="message" placeholder="Message">
<button id="sendBtn">Send</button>
</body>
</html>```

slate marlin
#

is here someone that could help me with making a cta that redirects to another html within a flask app

frank shoal
#

!d flask.redirect

lavish prismBOT
#

flask.redirect(location, code=302, Response=None)```
Create a redirect response object.

If [`current_app`](https://flask.palletsprojects.com/en/latest/api/#flask.current_app "flask.current_app") is available, it will use its [`redirect()`](https://flask.palletsprojects.com/en/latest/api/#flask.Flask.redirect "flask.Flask.redirect") method, otherwise it will use [`werkzeug.utils.redirect()`](https://werkzeug.palletsprojects.com/en/2.1.x/utils/#werkzeug.utils.redirect "(in Werkzeug v2.1.x)").
clever needle
#

Then I am referencing

@login_manager.user_loader
def load_user(user_id):
    return User.get(user_id)

@home_bp.before_request
def before_request():
    if login_manager.is_authenticated and request.endpoint != 'login':
        return redirect(url_for('login'))``` in a routes file that gets imported into the create_app function
worthy lake
#

I've set up a self signed localhost cert for my staging server. It works, but I'm getting this error from this nginx config

upstream django_app {
    server web:8081;
}

server {
    listen 80;
    server_name localhost;
    rewrite ^(.*) https://localhost$1 permanent;

    location / {
        proxy_pass http://django_app;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }

    location /.well-known/acme-challenge/ {
        allow all;
        root /var/www/certbot;
    }

}

server {
    listen               443 ssl;
    ssl_certificate      /etc/ssl/certs/localhost.crt;
    ssl_certificate_key  /etc/ssl/certs/localhost.key;
    ssl_ciphers          HIGH:!aNULL:!MD5;
    server_name          localhost;
    location / {
        proxy_pass  http://django_app;
    }

    location /static/ {
        alias /home/app/web/staticfiles/;
    }

    location /media/ {
        alias /home/app/web/mediafiles/;
    }
}
DisallowedHost at /

Invalid HTTP_HOST header: 'django_app'. The domain name provided is not valid according to RFC 1034/1035.

Request Method:     GET
Request URL:     http://django_app/
Django Version:     4.0.4
Exception Type:     DisallowedHost
Exception Value:     

Invalid HTTP_HOST header: 'django_app'. The domain name provided is not valid according to RFC 1034/1035.

Exception Location:     /usr/local/lib/python3.9/site-packages/django/http/request.py, line 149, in get_host
Python Executable:     /usr/local/bin/python
Python Version:     3.9.6

What can I change to make this work for https://127.0.0.1/ on a safe stage server?

#

is this as simple as adding django_app to ALLOWED_HOSTS lol

#

that did not seem to work

#

nah, not really i already had all that stuff set

#

the nginx config is working, it django that seems to not like this.

#

I wish that django had built in configs to understand, "This is a staging server. Just go with it."

boreal minnow
#

hey, could someone please explain unit testing mocking to me?
im learning nestjs rn, and one thing i noted is that most tests in the most popular test repo (https://github.com/jmcdo29/testing-nestjs) use mock functions for testing
isn't that approach objectively wrong? since we always know what mock function returns, the test is always gonna pass, while the actual controller logic is not tested at all

GitHub

A repository to show off to the community methods of testing NestJS including Unit Tests, Integration Tests, E2E Tests, pipes, filters, interceptors, GraphQL, Mongo, TypeORM, and more! - GitHub - j...

#

let's say we have mock func of findall returning array 1, 2, 3
then we test this function for element at index 2 being 3, and ofc, test passes
but actual logic used in controller is not tested at all this way
what's the point of mocking then?

worthy lake
lapis spear
#

i created a news model that admin can create news and show it on pages now each user can comment on posts so i created comment form inherited the modelForm
now if i display my form it shows the user_id and news_id which is supposedly filled up automatically depending on the post selected and currently logged in user

#

or should i use forms.Form?

orchid hamlet
#

@stable bear

native tide
#

how to solve this errror

native tide
#

Use the .get(key, default) method instead to provide a default value when the key is not found. And if you're sure the key must exist, then it's probably missing. Debug the part where you're adding parameters to your GET request

sudden sierra
bleak adder
#

Hello, i need to use js in my project but i'm not really good at it so i need to complete this task:

#

i have an html table with buttons on each row some i'd like to have the row data whenever i click the button present in that row
How can i do that with js??

#

Any code examples ?

unkempt dagger
#

My scrollbar is moving but the page itself doesnt move, any ideas?

dreamy shadow
unkempt dagger
#

ah i see

#

thansk ill check now

#

ok yes you are right, sorry that was a very dumb issue. i am still quite new to this

royal crown
#

Hi, I built my project using Angular, Django and PostgreSQL
I have never deployed my projects before
I want to deploy on Heroku or AWS
Any tutorials or documentations please?

lapis spear
#

and in my template i just remove the 2 fields as it will be filled on the views.py ?

lapis spear
#

or should i just not use modelForms for this? its just the comment model

sudden sierra
# lapis spear something like this?

Maybe you should use the initial argument when creating the form instance, and the pass the user and news like this

user_id = request.user
news_id = id # or maybe you need the object, not the id

form = CommentForm(initial={"user_id": user_id, "news_id": news_id})
sudden sierra
timber jungle
#

Hello
I am using an html form in Flask.

And i have an input box. Someone managed to send an URL through that text input box. 🙂

How can i transform this into a harmless string? ```html
<a onmouseover="alert('reason')" href="https://www.google.com">google</a>

lapis spear
agile pier
#

i have made a webpage which shows the youtube videos based on the query result using the youtube data api

#

i want to call the YouTube API continuously in background (async) with some interval (say 1 min) for fetching the latest videos for the search query and it updates the webpage every 1 min automatically

#

how can i implement that in django?

inland oak
# agile pier how can i implement that in django?

Dumb way: Client side javascript REST API calls in a loop to your Django Rest Framework endpoint
Smart way: Web sockets (Feel free to check Django Channels in addition for Django with web sockets flavour)

frank shoal
#

I'm adopting lodash into my project. Would this be the correct way to convert this function? ```ts
const rows = {} as Record<string, string[]>;
for (const item of selectedItems) {
const [name, rack] = splitLabRow(item);
if (!(name in rows)) {
rows[name] = [];
}
rows[name].push(rack);
}
return Object.entries(rows);

to
```ts
  return _.chain(selectedItems)
    .map(splitLabRow)
    .groupBy(0)
    .mapValues((v) => _.map(v, 1))
    .toPairs()
    .value();
agile pier
#

also pls share any yt video or resource if any..

inland oak
#

though it will require from you some level of Javascript understanding how to do it 🤔

nova vessel
#

Hey I’m on windows 10. And vscode isn’t recognizing pipenv

#

Working on a project using Django and I can’t get venv setup

frank shoal
#

Is pipenv installed via pip install --user pipenv?

#

maybe you're using pipx?

nova vessel
#

Still not working

nova vessel
frank shoal
#

set your path and restarted your shell?

nova vessel
frank shoal
#

just log off and back in

nova vessel
#

Did that too 😂

frank shoal
#

are you using cmd bash or powershell?

nova vessel
#

Power shell

frank shoal
#

run get-command pipenv

nova vessel
#

Okay

#

Will do after lunch

frank shoal
#

if it can't find it, double check the path via $Env:Path

#

It installs your applications to ~/.local/bin

nova vessel
#

Then source /bin/local/activate to set venv right?

frank shoal
#

no, that's handled by pipenv

nova vessel
#

Oh

frank shoal
#

It's been a while since I used pipenv (I use poetry now), but I think it's just pipenv install <package> then pipenv run yourcommand

#

there may also be a pipenv shell command.

nova vessel
#

Okay bet I’ll try that

agile pier
nova vessel
#

@frank shoal hey got pipenv to work, do you have the documentation site for it>

frank shoal
#

.. why is the site in cursive?

nova vessel
#

its normal for me...

frank shoal
#

This isn't cursive for you?

nova vessel
#

You broke the website

frank shoal
#

I wonder why it's different in firefox

#

The old one was from when it wasn't part of pypa

native tide
#

Let's supposed I'm making a Django user model that should have a dozen attributes I've assigned, with many of them belonging to other models. Should I explicitly state every single one of those attributes on the user model or would just stating them on the attribute models be enough?

edgy isle
frank shoal
#

firefox?

edgy isle
#

Yep

frank shoal
#

it's actually cursive for some reason

edgy isle
#

Chrome is completely broken for me, so I cant test it on there

native tide
#

Any ideas why the "User" is repeated twice in my django admin interface? I want to use a custom User field, but not if I won't be able to use the built-in authentication.
https://prnt.sc/8C4e0Zx89e5n

Lightshot

Captured with Lightshot

chilly summit
#

flask is pretty useful

nova vessel
#

Sorry for the late reply

native tide
#

Question: let's say I have 3 models: user, country, and region.

Each user has a region and a country, and each region has a country.

How can I make it so that when either I'm in my admin panel and adding new users, or users are registering on the website, I/they only get to see the regions depending on the country they've selected(Since I wouldn't want to show them regions belong to other countries)?

glacial wigeon
#

Exactly when does heroku delete user uploaded files from its ephemeral storage? I'm new to webdev,
making a django webapp that takes user uploaded files(text files; pdf,docx,epub etc) and does some processing on it and shows an output in the form of a plotly graph. I am fine with heroku deleting the file after I'm done displaying the graph to the end user. Will heroku fit these specifications?

native tide
#
    href="{{ url_for('static', path='styles/index.css') }}"
  File "Z:\Code\Friends Computer\lib\site-packages\starlette\templating.py", line 72, in url_for
    request = context["request"]
  File "Z:\Code\Friends Computer\lib\site-packages\jinja2\runtime.py", line 331, in __getitem__
    raise KeyError(key)
KeyError: 'request'```
#

jinja2 giving this err

#

fastapi

agile pier
glacial wigeon
glacial wigeon
#

I don't care if it gets deleted in 5mins or whenever the dyno restarts

manic crane
#

can someone help with this error please => from rest_framework_simplejwt.tokens import RefreshToken ModuleNotFoundError: No module named 'rest_framework_simplejwt' my settings.py file => 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', # <-- And here ], im confused because i have the module installed

minor jetty
#

So I'm creating one django model for versioning.. so what is the correct django model naming convention? Should I name the django model as Versioning or just Version?

main sorrel
#
<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Website</title>
</head>
<body bgcolor="black">
    <h1>heading</h1>

</body>
</html>
h1{
    color: white;
    font-family: 'Courier New', Courier, monospace;
}

Anyone know why this does not display anything?

#

pls ping on response

errant mist
#

are you asking why you css isnt displaying? @main sorrel

main sorrel
#

yes

#

omg

#

bruh

errant mist
#

You havent linked your stylesheet

main sorrel
#

this is deadass my que to kms

#

alr thanks

errant mist
#

nah it happens haha

iron magnet
#

Does anyone here use FastAPI and the companion SQLModel? I've done an app with them and it's all fine and great until I need to delete lots of rows. I can't figure out how to do a "delete from x where something something".

#

I can select all the objects that should be deleted and could probably do a session.delete(obj) in a loop, but that sounds beyond daft.

agile pier
#

how do I change the format of 2022-06-28T05:44:45Z in the django template?

inland oak
#

i am not sure about the details too

#

but it should be possible to request deleting all necessary objects in one sent bulk request to db

main prairie
#

hey

#

i was wondering if there were any quick web libraries to display some statistics?

#

i have a project which tracks individual stocks and being able to show their current prices, charts, etc on a simple list web UI would be helpful

iron magnet
#

I asked here because my searches turned up nothing. The session object doesn’t work like the one in SQLAlchemy.

novel stream
novel stream
manic crane
inland oak
novel stream
manic crane
novel stream
#

well I would strongly advise you to use a virtualenv then. Create one with python -m venv .venv it will create a directory called .venv where you can activate by source .venv/bin/activate then inside that env you can install all your packages. The problem your facing is really common when you're installing packages globally

manic crane
#

hmmm ill try thanks

iron magnet
manic crane
#

i tried installing venv with sudo and got this => sudo: apt-get: command not found

novel stream
manic crane
#

oh really

novel stream
manic crane
#

oh wondeful

novel stream
#

run the following: which python

manic crane
#

/usr/bin/python

#

im using python3 because for every command i have to run python3 like python3 manage.py runserver

novel stream
#

That's weird. What is your python version? and which OS you're using (windows I suppose)

manic crane
#

macbook

#

Python 2.7.16

novel stream
# manic crane Python 2.7.16

You might also have python3 installed. Try the following: python3 -m venv .venv - if my assumption is correct this would create the .venv folder inside the directory you're in

manic crane
#

this is what i get when i install simplejwt

#

Requirement already satisfied: pytz in /usr/local/lib/python3.9/site-packages (from django->djangorestframework-simplejwt) (2021.1)

novel stream
#

after creating the .venv you need to activate it and then install your dependencies

manic crane
#

hmmm i do have venv folder but still got the same error

lapis spear
#

yo ive been stuck here help me 😅
i am getting the "form is invalid" output on my terminal meaning i failed the form.is_valid check how to debug that?

novel stream
lapis spear
#

how do it know why is my form.is_valid() failed?

manic crane
novel stream
novel stream
lapis spear
novel stream
#

the if request.method == 'POST'

manic crane
novel stream
#

I'm in Live-Coding

lapis spear
manic crane
#

i think u can only do that for html and css

novel stream
novel stream
manic crane
#

ill send in private chat

lapis spear
novel stream
lapis spear
#

but i still got my main problem my form is invalid

#

this is my model

#

and this is my modelform

#

since user and news_id should be automaticall filled based on the id and currently logged in user i filled it on view by the initial={} argument and the only thing i am getting on the form is the comment field

#

i feel like this is a simple problem with simple solution but i still cant figure it out im at dark with this django hahaha😅

novel stream
lapis spear
novel stream
lapis spear
novel stream
#

When the server stops there you can do the following:

lapis spear
#

its seems my form is empty

lapis spear
novel stream
#
print(form.is_valid())
print(form.errors)
#

it will show you what are the errors in your forms

lapis spear
#

there it is my form are empty

#

but when i print the news and user variables i got values of them

#

or do i need the ids? because they are foriegn keys?

novel stream
lapis spear
#

its the same even i pass the ids on the forms same form.errors

#

this is how the code looks like now

#

btw how do i stop that breakpoint()?

novel stream
#

to stop it or just go you press c and enter

lapis spear
#

oh i got it nice this is a handy tool e h

#

anyways back to my horror story

#

why is my forms becoming empty? the code shows that they have values but they are infact empty

novel stream
#

yeah I'm a little bit confused 🤔

#

can you run again and then print the value of request.POST?

main sorrel
#
const getData = new XMLHttpRequest
getData.open("GET","https://api.ipify.org?format=json");
getData.send();
ipData = getData.responseType = 'json';
document.getElementById("tag1").innerHTML = ipData

umm anyone know why this wont work

#

im a bit new to requests in javascript so

lapis spear
frank shoal
#

and call the constructor. new XMLHttpRequest()

#

though you should prefer using the fetch api

#
function onSuccess() {
  document.getElementById("tag1").innerHTML = this.responseText
}
const xhr = new XMLHttpRequest()
xhr.addEventListener("load", onSuccess);
xhr.open("GET", ...)
xhr.send()

// vs

fetch(...)
  .then((data) => data.text())
  .then((data) => {
    document.getElementById("tag1").innerHTML = data
  })
novel stream
novel stream
lapis spear
novel stream
lapis spear
novel stream
lapis spear
novel stream
# lapis spear you mean the widgets? btw is this a correct approach? or there is a better way t...

if you have fields that you don't want to show to the user in the form, you have either two options:

  1. override these fields in your ModelForm and make them not required. Then pass the values from the initial option (you might need to also override the ModelForm __init__ to set these values. With this when you submit the form again your form won't complain saying that some fields are missing
  2. In your form you use the widget approach to make them hidden so that only the comment field will appear in the frontend and then set the initial values in your form
frank shoal
#

In lodash, is there a shorthand for this? ```js
_.map(x, (id) => object[id])

#

I managed to do _.partial(_.get, object)

lapis spear
lapis spear
lapis spear
#

widget thing can be altered on html by browser

#

but i dont understand this option one haha imma rest for now see you again next time sir thank you @novel stream

copper juniper
#

How to make migrations in Django after deleting the migrations and pycache dirs and after flushing the db? Tried migrate and makemigrations and it keeps saying nothing to do

#

Goddamnit, why it has to be always so rtarded in django with all the migrations stuff

golden bone
copper juniper
#

Yeah, and I'm back to where I was before deleting those dirs, now i got this annoying err ```
File "C:\Users\ansga\Desktop\SHOP2\django\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 477, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such column: store_product.safe_name

#

So its like I got this in my models, but migrations are not following it, and there is no such record in db yet, weird thing

#

Oh, my model was bad, I've noticed it after fixing manually the migrations that I'm putting the raw bytes into a CharField, I'm dumb, move along nothing happened here

opaque rivet
#

hi guys, I'm using SQLAlchemy and I'm trying to delete a row after it's been updated like so:

@event.listens_for(Emails, 'after_update')
def delete_retrieved_email(mapper, connection, target):
    # If email row has been retrieved, it has been saved in the client's local storage. We now delete it off the server.
    if target.retrieved:
        with Session(engine) as session_:
            session_.delete(target)
            session_.commit()

The issue is that the row is not being deleted. Any help please?

native tide
#

What's the difference between:

class customUser(AbstractUser):
pass

and

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

?

proper hinge
#

The former is meant to be a replacement of the user model, so that setting needs to be updated, and it will require a potentially difficult migration if you're not doing this at the start of your project.

#

The latter creates a separate table with a FK to the user table

#

At a higher level, I think the choice comes down to a semantic difference.

#

Like, if you have data associated with a user that's only relevant/useful in certain contexts, then the OneToOne approach may be more suited to that.

#

Though when you start your project, it's good practice anyway to subclass AbstractUser and create a custom user model (in case you need it in the future)

native tide
#

how to add two numbers in js and show output in different page?

harsh helm
manic crane
#

can someone explain why im getting this error when i have the package installed => from .utils import generate_access_token ModuleNotFoundError: No module named 'Occupier.utils'

delicate ore
#

if user has downloaded css from a cdn and cached it, will the browser also detect if the same css is given locally?

dusk sonnet
#

hi, Is this the correct way to include the csrf_token in JS using fetch?

const csrftoken = document.querySelector('input[name=csrfmiddlewaretoken]').value
            
  fetch(likeUrl, {
     method: "PUT",
     headers: {
         'X-CSRFToken': csrftoken
     },
     ...
hushed crow
#

is django just a debugger or full website builder? i mean i need to know html/css or just python?

novel stream
# delicate ore and load the cached one?

probably yes. the project that serves the css from the CDN usually also serves it with a key by the end so that when a new one is created the browser will invalidate the cache and retrieve the new CSS file instead of the old one

novel stream
hushed crow
#

hoping i can achieve a live update of these lol

elder raven
#

Hey guys! I am trying to use Mongo db in my django project using djongo. But I am getting "int() argument must be a string, a bytes-like object or a number, not 'ObjectId'" on rest model serializes when POST resource. i have refereed many resources online but it doesn't mention an issue like this. guys give me some insights on this. i have tried to add an _id field with ObjectId field type from djongo. but with that solution i can create resources in POST but can't get resource using _id or id field. did anyone face this issue before? how do i fix it? have any useful resources ? if have please share. thanks

manic crane
silver marsh
formal torrent
#

im working on my frist django project ```py

q = Question(question_text="What's new?", pub_date=timezone.now())
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\HP\Desktop\DAMINDU\my-site\venv\lib\site-packages\django\db\models\base.py", line 559, in init
raise TypeError(
TypeError: Question() got an unexpected keyword argument 'question_text'

anyone know why this coming? help please 🥺
silver marsh
manic crane
#

its a package

#

ohhhh let me fix that

formal torrent
# novel stream how's your `Question` model?
import datetime

from django.db import models
from django.utils import timezone

class Question(models.Model):

    def __str__(self):
        return self.question_text
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):

    def __str__(self):
        return self.choice_text
novel stream
hazy jungle
#

Django Question:

I want to pass a search via a search bar of: dog, blue, tall

That will look up all tall, blue dogs in my database.

qs = qs.filter(dog__icontains=dog_contains_query)

only allows me to look up one parameter at a time, and will return all results with dog, bu tif I have dog, blue, will look for a match of dog,blue, and will return nothing.

So far ive given heavy consideration to AND as well as OR, and have even considered UNION, but I dont know if union would work, or even how to get it to work, and Im not sure what security flaws it may introduce, but Im pretty sure its not as bad as: raw() Execute a raw SQL statement

#

i also tried this, which it shows very promising results, but I had to add this to the URL directly, vs using the search bar

native tide
#

Finally complete my project

#

I'm a django beginner give me some feedback

high hemlock
velvet vale
#

data = User.objects.all().annotate(user=Count('bid')).aggregate(max=Max('user')) i want get user which has the most bids currently. i get number of bids {'max'2} but i don't understand how to get id of this user

rough root
#

im trying to set up django with react to create a little project. im tying to load in an html file and django doesnt find it because the source its looking for is wrong, can someone tell me how to rewrite the base url so it can find the files correctly? my project is in a dir containing the django file, a venv and the react files in it

onyx lava
#

Is it smart to use any python backend framework with an javascript frontend framework for example react with flask?

agile arch
#

anyone know what the default timeout length for a flask request is?

outer apex
agile arch
#

yeah thats kinda what I figured, thanks

pallid hill
#

Hey can someone please help me in #help-bagel, it has to do with Flask and a Chat Apps formatting issues.

native tide
#

@pallid hill For some reason I can't type in the help channel. I didnt read your code because I'm on mobile at the moment but based on what your asking for i think overflow-x or overflow-y would solve your problem. Heres a good reference: https://www.w3schools.com/CSSref/css3_pr_overflow-x.asp

ionic raft
# onyx lava Is it smart to use any python backend framework with an javascript frontend fram...

I've seen a number of web devs speak highly of Django and React. I haven't gone there yet, but the reasons-for presented have made sense.

And so, as for how smart this practice is likely a case-by-case situation. I haven't used React because the problems I've focused on have been functional-centric. However, I hear very good things in terms of managing front-end behaviour. React also appears to have a decent collection of libraries and an active community.

What I wonder about is that Flask is a fairly straightforward web dev framework. You can build out a lot of functionality, but one doesn't have to wander too far along the spectrum before Django presents good reasons to be used over Flask. I would be curious to learn about use-cases for Flask+React.

ionic raft
# native tide I'm a django beginner give me some feedback

That's a HUGE question 😄 But I understand. I'll offer reflections from 10 minutes quickly scanning the github:

  • **bike **is an interesting project name for a web app selling cars 🙂
  • settings.py > brush up on environment variables, and secure all KEYS. SECRET_KEY should be changed, and hidden within an env var.
    -** use of sqlite3 **> If you're serious about Django, read up on other DBs, such as PostgreSQL.
  • **MEDIA **on a django server is fine for small projects. If you plan to go production with a web app storing uploaded media files I'd brush up on other ways to do that. When you include Media on your Django app it is no longer stateless (Load balancing issues if project takes off) and there are security risks that come with file uploads
  • naming of home app > I've not taken that approach. I name my apps based on their functional focus. The functional focus of home is...the home page? Looking at home.views.py very quickly reveals that this is the main car app. Perhaps car_sales_engine or something like that might be more descriptive. This is a minor detail, but when you're expanding your coding chops with projects containing more than 3 to 4 apps how you name apps is going to make a difference long term...

I'll stop there. That was the first 10 minutes. I hope that helps. Good luck. Love the energy and the movement towards full-stack dev.

Book I recommend: https://www.feldroy.com/books/two-scoops-of-django-3-x

pallid hill
proper hinge
native tide
#

I will read this book

pallid hill
#

Instead it just resizes the box and scrolls the whole page in that process. Please help.

dusk sonnet
#

hi, for my current project im using the html data attribute quite alot but im very concerned about the security of the website because anyone can change the values of the data attributes in the developer tools. how can i protect against this?

#

is there a way to hide them or something

onyx lava
#

Thanks guys for the answer @ionic raft @proper hinge

orchid hamlet
#

Hello9 i am having issue

#
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href={{url_for('static', filename='style.css')}} />
    <title>Document</title>
  </head>
  <body>
    <h1>Crypto Currency, create your own!</h1>
    <form onclick="on_action" method="post">
      <form>
        
      <center><p>Name: </p><input class="inputtype" name="name" type="text" /></center>
      <br/>
      <input type="submit"/>
    </form>
    <p>{{name}}</p>
  </body>
</html>
#

index.html

#
from flask import Flask, render_template, request

app = Flask("__app__", static_folder="static")

@app.route('/', methods=["POST", "GET"])
def on_start():
  return render_template("index.html")

@app.route("/on_action", methods=["POST", "GET"])
def take_action():
  if request.method == ["POST", "GET"]:
    yourname = request.form["name"]

  return render_template("index.html", name=yourname)

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

can anyone tell why I can't see {{name}} after clicking submit?

dreamy seal
orchid hamlet
#

what?

dreamy seal
#

<form onclick="on_action" method="post"> to <form onclick="take_action" method="post">

#

its been ages i have used flask. can you check that?

orchid hamlet
#

oh yeah i am stupid lol

clever needle
#

Has anyone used pythonanywhere before?

dreamy seal
#

🙂

manic crane
#

hey could use a bit of help im getting this error => Import "rest_framework_jwt.views" could not be resolved , "generics" is not defined, response" is not defined my requirements.txt => asgiref==3.5.2 backports.zoneinfo==0.2.1 certifi==2022.6.15 charset-normalizer==2.0.12 Django==3.2 django-cors-headers==3.13.0 djangorestframework==3.13.1 djangorestframework-jwt==1.11.0 djangorestframework-simplejwt==5.2.0 idna==3.3 psycopg2-binary==2.9.3 PyJWT==1.7.1 pytz==2022.1 requests==2.28.0 sqlparse==0.4.2 urllib3==1.26.9

iron magnet
#

Is there any way to get better logging from FastAPI? I have an endpoint that receives a fairly complex JSON object (a push webhook from GitHub) and sometimes my server just logs 422 Unprocessable Entity and nothing else. This would indicate that the data could not be deserialized into an instance of my Python class, but the error isn't exactly helpful in tracking down what it is.

#

Oh darn. I've googled this several times in the past, but now I stumbled upon the docs for how to handle errors. Never seen them before, so no wonder it's been a bit hard.

#

Basically I seem to want:

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    exc_str = f'{exc}'.replace('\n', ' ').replace('   ', ' ')
    logging.error(f"{request}: {exc_str}")
    content = {'status_code': 10422, 'message': exc_str, 'data': None}
    return JSONResponse(content=content, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY)
#

Let's deploy that and see.

next comet
#

Yo guys, as web developers do you learn Wordpress or do you think it could be beneficial to learn WP

iron magnet
#

They are the same?

grizzled depot
#

Does anyone know why I can't set my chrome window height any larger than 1331px with selenium? It works fine with Firefox

from selenium import webdriver


firefox = webdriver.Firefox()
chrome = webdriver.Chrome()

firefox.set_window_size(1200, 2000)
print(firefox.get_window_size()) # {'width': 1200, 'height': 2000}

chrome.set_window_size(1200, 2000)
print(chrome.get_window_size()) # {'width': 1200, 'height': 1331}

edit: It does work if I start chrome with the --headless argument, but that will cause problems elsewhere.

mystic wyvern
native tide
#

I'm getting a error from ASGI when I visit the page, how do I fix this?
I'm using FastAPI, and this error seems internal...

Error:

INFO:     127.0.0.1:53735 - "GET /static/styles.css HTTP/1.1" 500 Internal Server Error
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/uvicorn/protocols/http/httptools_impl.py", line 401, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 78, in __call__
    return await self.app(scope, receive, send)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/fastapi/applications.py", line 269, in __call__
    await super().__call__(scope, receive, send)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/starlette/applications.py", line 124, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/starlette/middleware/errors.py", line 184, in __call__
    raise exc
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/starlette/middleware/errors.py", line 162, in __call__
    await self.app(scope, receive, _send)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/starlette/middleware/base.py", line 69, in __call__
    await response(scope, receive, send)
TypeError: 'tuple' object is not callable
manic crane
mystic wyvern
manic crane
mystic wyvern
manic crane
#

oh like its the up to date version

jade dawn
#

hey guys

#

so a group of friends and i wanna set up this website for us that basically holds world cup score predictions and automatically scores points for correct guesses in a leaderboard type of formatt
i would like your advice on where to learn to do this and what video tutorials i should look up 🙂
thanks

viscid valley
#

When running the following process_view inside middle ware, it's recording two visiting, not sure why https://dpaste.org/pgVcQ

#

This actually only appears to happen on certain pages.

icy ember
#

I'm not sure whether this is the proper place to raise this question. Actually I'm trying to use flask backend to implement sign in with Apple, but I receive this error on running my script.
Could someone please assist me?

        headers = {
            'kid': AppleApiProvider.KID,
            "alg": "RS256"
        }
        now = datetime.datetime.utcnow()
        date = datetime.datetime(now.year, now.month, now.day, 0, 0, 0)
        exp_date = date + datetime.timedelta(weeks=8)
        payload = {
            'iss': AppleApiProvider.ISS,
            'iat': date,
            'exp': exp_date,
            'aud': 'https://appleid.apple.com',
            'sub': 'com.APP.staging.signin',
        }

        client_secret = jwt.encode(
            payload,
            AppleApiProvider.PRIVATE_KEY,
            # algorithm='ES256',
            algorithm = "RS256",
            headers=headers
        ).decode("utf-8")

        return 'com.APP.staging.signin', client_secret
remote pendant
#

remind me what does model.manager() does?

ionic raft
# next comet Yo guys, as web developers do you learn Wordpress or do you think it could be be...

TLDR; If you have time it won't hurt. Learning WP on your journey into web development can give you access to a *swiss army knife * web dev toolkit.

On my journey of becoming a web dev I started with WP. It has solid use cases, and some great solutions can emerge. It has a really broad community and plug in options to extend functionality. Is it beneficial to learn WP? That really depends on the use cases you're developing for.

However, WP comes down to how big the compromise needs to be to deliver on use cases and requirements. The three most pressing limitations for me were: 1. it is based on a framework that can make changes that can break your solution (WP Core - beyond your control). 2: It comes with performance overhead because it trying to be many things to many people. 3: Any changes to plugin functionality can also break the application (beyond your control). These limitations come down to a trade off of pros and cons. And perhaps the greatest one is that because WP is so popular as a CMS (Content Mgmt System) it comes with known vulnerabilities, attack vectors, that are rampantly exploited.

I found myself drawn to Python-Django because I wanted a much greater level of control for developing web applications on all three layers (DB, Application and Front-end). Understanding both WP and Django helps me qualify which use cases are better suited to which stack.

Good luck.

ionic raft
# jade dawn so a group of friends and i wanna set up this website for us that basically hold...

Interesting. I'd start by getting really clear on what I want to accomplish:

  • It sounds like you will need user account functionality. Users will make their predictions and be scored based on the variance between their prediction and what happens. You want data related to users to persist and always be available. Needs will evolve as you delve into the user's experience and what you're trying to accomplish (such as leaderboards for world cups every 4 years)
  • You will need login, logout and password reset functionality.
  • You need to design a data model along with what the web application will do (application logic)
  • You will also need to determine how you want to front end (the web pages themselves) to present and support this experience.
  • That then informs how to design the data model, application logic and web page layout

On one hand, Flask is simpler to get started (for your first project). But based on the real need for account login, Django may end up saving you time overall (it's more complex to learn, but it has built in tools for things like administration and user-authentication).

Advice on where to learn how to do this really depends on how technically comfortable you are with Python and coding in general. I recommend Corey Schafer's YouTube tutorials for both Flask and Django. I spent about 1.5 months learning Flask before I shifted to Django because the projects I build are complex. However, that time with Flask introduced me to web development fundamentals that served me well when stepping up to Django (where I got the bells and whistles). I only code Django web apps now.

jade dawn
#

ill get started with tutorials then

ionic raft
# jade dawn ill get started with tutorials then

Welcome to the journey into web application development. I started with an idea to build a web app to store information and automation steps for the process improvement methodology I train businesses on. Having a clear idea to drive your development is VERY helpful. Do you have much experience with Python?

jade dawn
ionic raft
# jade dawn mainly my experience comes initially being a mechanical engineer and working wit...

that will be helpful. You likely have a number of programming concepts down in Python. However, you might be well served by taking a deeper dive into something like a python web dev boot camp. You will use libraries with Django (as you have with matlab for example). And you will lean heavily into many Python programming concepts. Your grasp of programming logic patterns will be helpful too.

And yes, I'm on my third deployed project now (my profile has a couple of links). Building a fun project on an idea you really get is a fantastic way to get experience.

At a guess you're going to find Django very compelling to meet your requirements thoroughly. User authentication in Django is top-notch. In Flask you have to do a lot more heavy lifting.

#

Disclaimer: I am a HUGE fanboi of Django. I think it's an astonishingly good framework to build a web app on.

jade dawn
#

how would it compare to js?

ionic raft
# jade dawn hopefully i can easily understand some of the new concepts that django might bri...

Django is built on Python.
You'll use Python to build the data model (tables and relationships in the DB), and the application logic (the views that get things done). You'll use html to structure web pages, css to style web pages and Django's implementation of Jinja to build those web pages by the web server. And you'll find js will help you with managing web page behaviour. I use js sparingly (because browser based computation is slower than back-end server computation). You will have the option to delve into using a js framework (such as React) to make the most of sophisticated behaviour functionality built to solve front-end requirements.

jade dawn
ionic raft
manic crane
#

getting this error anyone know why => return [auth() for auth in self.authentication_classes] TypeError: 'type' object is not iterable my code => ```class OccupierLoginView(APIView):
serializer_class = LoginSerializer
authentication_classes = (TokenAuthentication)
permission_classes = (AllowAny)

def post(self,request):
    username = request.data.get('username',None)
    occupier_password = request.data.get('password',None)

    if not occupier_password:
        raise AuthenticationFailed('A password is needed')
    
    if not username:
        raise AuthenticationFailed('A username is needed')

    occupier_instance = authenticate(username,password=occupier_password)
    if not occupier_instance:
        raise AuthenticationFailed('occupier not found')

    if occupier_instance.is_active:
        occupier_access_token = generate_access_token(occupier_instance)
        response = Response()
        response.set_cookie(key='access_token',value=occupier_access_token,httponly=True)
        response.data = {
            'access_token':occupier_access_token
        }
        return response

    return Response({
        'message': 'something went wrong'
    })````
dapper vigil
valid void
#

Hello everyone here ! I tried multiple times to install django and djangorestframework from pip3 on my environment on PyCharm, but it's not working at all. When in my installed apps I'm adding 'rest_framework', i'm having an error : ModuleNotFoundError: No module named 'rest_framework'.
Everything I tried didn't work. With "pip freeze" I got this :

asgiref==3.5.2
Django==4.0.5
djangorestframework==3.13.1
pytz==2022.1
sqlparse==0.4.2
tzdata==2022.1

Do you have an idea about what is happening ? Thanks 😦

#

(In my venv/lib/site-packages I have a folder called 'rest_framework')

bronze dock
#

can anyone help me my html image wont load

#

<!DOCTYPE html>
<html lang="eng">
<head>
<title>Image</title>
</head>
<body>
<img src="file:///C:/Users/####/OneDrive/Pictures/85246.jpg" alt="85246.jpg">
</body>

</html>
native tide
#

what is the best way to automate a task of deleting reports on a website
would selenium be good for that?

elder verge
sage garden
#

Hello. I have a discord bot that uses a web scraper. Recently the website we use decided it would like to confuse us all by randomizing the class we draw from? What is the best way to have a wildcard or something for the class. My part of my bot looks something like this currently.

answerBody = soup.find(class_="answer-given-body")
However now they have the classes like this
class = "styled__QnaHtmlContent-oj1dsq-41 duUzTZ"
where those last digits are random based on the particular page.

scarlet kite
#

Hello everyone, I started learning microservices and currently I'm using FastAPI, to implement it I should with Celery package?

queen leaf
#

Hi everyone,

We are planning on developing an app which will have a facial recognition aspect and some machine learning aspects. This is a senior design project for our class so none of us are exactly experts. But we are trying!

I have done many ML projects but never an app using python. Our professor suggested using Flutter as its cross platform. But from what I am reading it may not be the best option for python APIs.

Could you let me know what your thoughts are for mobile development what should we use if we are decided on python APIs already?

manic crane
#

does anyone see anything i try to run it and i get "occupier not found" => ```class OccupierLoginView(APIView):
serializer_class = LoginSerializer
authentication_classes = (TokenAuthentication,)
permission_classes = (AllowAny,)

def post(self,request):
    email = request.data.get('email',None)
    occupier_password = request.data.get('password',None)

    if not occupier_password:
        raise AuthenticationFailed('A password is needed')
    
    if not email:
        raise AuthenticationFailed('An email is needed')

    occupier_instance = authenticate(username=email,password=occupier_password)
    if not occupier_instance:
        raise AuthenticationFailed('occupier not found')

    if occupier_instance.is_active:
        occupier_access_token = generate_access_token(occupier_instance)
        response = Response()
        response.set_cookie(key='access_token',value=occupier_access_token,httponly=True)
        response.data = {
            'access_token':occupier_access_token
        }
        return response

    return Response({
        'message': 'something went wrong'
    })```
inland oak
inland oak
inland oak
#

Choosing Frontend (mobile one) is usually best in the most compatible option with provided ecosystem. If u use Kotlin for Android, and Swift for iOS, u should be fine.
About framework details I don't know

zenith hound
#

Is it possible to reuse html filenames when using multiple blueprints?
Eg. I have Homepage blueprint and admin page blueprint, with their appropriate /templates directories. Is it possible to have index.html in both directories?
Right now, for some reason the admin blueprint always loads in the index from homepage

#

app/
├─ ui/
│ ├─ admin/
│ │ ├─ templates/
│ │ │ ├─ index.html
│ │ ├─ admin.py
│ ├─ home/
│ │ ├─ templates/
│ │ │ ├─ index.html
│ │ ├─ home.py

worn aurora
#

because both app are different

zenith hound
#

In the main file i got

app = Flask(__name__)
app.register_blueprint(main_bp)
app.register_blueprint(login_bp)
app.register_blueprint(admin_bp, url_prefix='/admin')

The home BP is:

main_bp = Blueprint('main_bp', __name__, static_folder=Paths.main_static, template_folder='templates')
@main_bp.route('/home')
@main_bp.route('/')
def home_page():
    try:
        return render_template('index.html')
    except TemplateNotFound:
        abort(404)

The admin BP is:

admin_bp = Blueprint('admin_bp', __name__, static_folder=Paths.main_static, template_folder='templates')
@admin_bp.route('/home')
@admin_bp.route('/')
def admin_page():
    try:
        return render_template('index.html')
    except TemplateNotFound:
        abort(404)
worn aurora
#

where is /admin route ?

zenith hound
#

Wdym by that?

worn aurora
#

is
@admin_bp.route('/admin') not required ?

zenith hound
#

Its from the url prefix right?

#

When you register the blueprint

zenith hound
#

If i change the admin index to index2 or whatever else, it works fine.

swift wren
#

what is a complexity/logic limit on an api-endpoint from a performance/reusability . I'm asking because one of my endpoints is doing about 3-4 things. Should endpoints follow the same principle as functions for example functions should do one thing or 2.

meager sand
#

difficult question - if you tell us what 3 - 4 things your endpoint is doing, it'd be easier to tell whether it makes sense

olive hazel
#

guys literally tell me what are the things and skills needed for making and publishing a portfolio website
i know the html and css part

#

do i need aws or heruko?

#

do i beed mango dbl

#

or sql

inland oak
olive hazel
#

whole stuff mate

#

it certainly doesn't need Javascript i know that for sure

inland oak
#

the backend road is awfully missing a lot of things though

olive hazel
#

no i need .com domian

olive hazel
inland oak
inland oak
inland oak
# olive hazel do i need aws or heruko?

you will need something to host it definitely. Anything that you wish fill it. Even github pages can host a staticly built website. So kind of you can go without aws/heroku

inland oak
# olive hazel do i beed mango dbl

mongo db is for backend path. if you wish to build a cool server side stuff, and having frontend is just secondary/non important thing for you, then mongo can be important, otherwise not. Although as average tool, we all use SQL database first. fifty shades of NoSQL databases come later after that, once you understood what for SQL and when could be needed no SQL

olive hazel
#

yeah realated database and un related database

#

so what i need is angular and Javascript

#

i didn't get the part where u said github

#

can it host a website?

#

what will the domain in that case

frank shoal
inland oak
frank shoal
#

You can also configure a CNAME to use your own domain

olive hazel
#

can i change the domain and do i need to pay for service

frank shoal
#

note: changing the domain means you won't get free ssl/tls

frank shoal
#

yes, but you have to own it

olive hazel
#

10 cents lol

olive hazel
inland oak
frank shoal
#

own the domain from a broker.

inland oak
#

No point in paid certs

frank shoal
#

free as in effort

inland oak
#

Cloudflare is no effort

rigid laurel
#

You don't need Cloudflare for TLS on Github pages

#

and there's not really any reason to use it

#

at that point - just use Cloudflare pages

olive hazel
olive hazel
frank shoal
#

Yeah. I use amazon

olive hazel
#

aws

#

is there any extra skil required for Github

#

why go daddy isn't good?

#

git is a lang?

inland oak
olive hazel
inland oak
#

Domain matters
Certs are auto provided for free

olive hazel
#

namecheap isn't?

#

how much does that cost

#

what your website melio lemme check it

#

yup empty

#

did u do any backend work on that

#

wow

#

u didn't do any html or css or any front end at all right

#

i bet u can't do like 3d stuff and like that

#

with it

#

so theres no point in freelancing

#

anyone can do that right

#

what do u call this aws and heruko and github server side?

#

hugo?

#

aah

#

alr lets just hope right

#

what makes me compete with a website generator is that i can think. shortly that will be done as well

#

i mean client can't think creativity and thats why im there

#

anyways thank you all very much

queen jackal
#

Hey! could someone help me out here? Please direct me to the right channel if I'm not in the right place.

I've built an application in flask, and it works perfectly fine in the production flask server.
I'm trying to deploy it using gunicorn. I've setup a gunicorn_config.py file, and I'm running with the command bash sudo gunicorn -w 4 'app.main:create_app(testing = False)
But here it suddenly tells that worker failed to boot, and it appears the reason is ```line 3, in <module>
from flask import Flask, request, render_template, send_file
ModuleNotFoundError: No module named 'flask'

I've run pip list and Flask is available in the environment, pip install flask is showing requirement already satisfied, and I've rechecked to make sure it works on it's own without gunicorn.

Could someone help me figure out how to debug the issue here?
lilac root
#

After a very Hard work on a how to pass python list to C function for test and fun ( i create a prime number function in c and using Ctypes I import So file in python ) it take 0.70 second for finding prime number between 0-500K 💪 dame power of C api

cinder gull
#

Hey who know flask write me in DMS pls!

#

(I need a help with creating global server, in webhook (local server working)

quick cargo
# lilac root After a very Hard work on a how to pass python list to C function for test and f...

Unfortunately this:

import numba
import time


@numba.njit(cache=True)
def sieve_python_jit(limit):
    is_prime = [True] * limit
    is_prime[0] = False
    is_prime[1] = False
    for d in range(2, int(limit ** 0.5) + 1):
        if is_prime[d]:
            for n in range(d * d, limit, d):
                is_prime[n] = False
    return is_prime

start = time.perf_counter()
sieve_python_jit(500_000)
stop = time.perf_counter() - start
print(f"Took {stop * 1000}ms")

Takes about 150ms - 200ms if you include the JIT warmup.
Otherwise it takes about 5ms 😅

😉 Smarter algorithms and numba will get you a long way

lilac root
#

And import so file

lilac root
swift wren
# meager sand difficult question - if you tell us what 3 - 4 things your endpoint is doing, it...

like i have a video upload endpoint, it does

  • receives multiple video files and iterates through them
  • inside the iteration it checks to see if Redis has cached it
  • checks to see if the video exists in the db
  • saves the file
  • compresses the video (takes 5-10 seconds)
  • writes to db
  • then it dispatches the video to another processing endpoint
    and repeat until there are no more videos received from THAT request.
#

is that too convoluted? or is that okay

native tide
#

is there anyone who can help me in deploying flask app on heroku ?

swift wren
#

these 3 files need to be in the root of your project also where the main.py file should be

onyx turtle
#

can anyone help me regarding mongo db

dense skiff
#

my current issue is TypeError: 'ImmutableMultiDict' object is not callable since i changed request.form.get to just .form (again)

#

to answer your questions; no, i'm not going to store passwords in plaintext; it's a placeholder for now

native tide
#

When creating a custom user model, is there a difference between these two

from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
  pass

.

from django.contrib.auth.models import User 

class CustomUser(models.Model):
  user = models.OneToOneField(User)

?

lapis spear
#

yo some pal shared me an account with codewithmosh django tutorial was it good? for beginner to job ready?

dusk portal
#
STATIC_URL = 'static/'
'''
STATICFILES_DIRS= [
    os.path.join(BASE_DIR,'static')
]
'''
STATIC_ROOT=os.path.join(BASE_DIR,'static/')```
#

when i turn off debug

#

even tho i run collectstatic

#

even if i add whitenoise

#

still

#

it doesnt load static files

#

i mean wtf

#

why

inland oak
#

Syntax coloration already shows you tips

#

U use different ways to declare strings

#

You make part of your code being strings too

#

No code, just strings

#

Variables aren't declared, they are part of strings

ocean mango
#

hello guys anybody worked with transaction here?

ocean mango
#

well, ok. I have a problem where I want to display all the transactions that takes place between two people in the order of latest updated time. Basically I want to show how to implement a receipt

daring isle
#

What db are you guys using for your stack ?
Django / React.

I usually use jawsdb over postgres for regular django . There’s 101 videos arguing benefits for all of them though

opaque rivet
#

so, JWTs are often used because they are stateless and don't need storing on the db. But, refresh tokens have to be stored on the db no? so JWTs are not really stateless?

inland oak
#

If u use JWT with validating it by secret key and not using dB request. Then it is without dB

#

JWT can contain additional token that is stored in dB, that can be deleted

#

Then it will require dB

#

We have a free reign for everything

#

Although in second case usually JWT is not used I think. We can transmit directly token in cookie without JWT that we will verify in dB

#

I think it is called Session token/Auth or something

#

The point of JWT is technically zero, if we already use session token

#

So let's consider JWT as thing only without db

#

Or wait

#

We can combine both

#

Let's have JWT storing session token

#

If JWT is not expired, then allowing request

#

If time expired or more sensitive request, then verifying session token

opaque rivet
#

sure, but if I'm wrong, people look to use JWTs over sessions so they don't have to store the tokens in the db. There would be no reason to use JWTs + session cookies for that reason

#

but learning about JWTs and refresh tokens I thought that the refresh tokens had to be stored in the database

#

but I suppose they do not have to be

#

can make the refresh tokens JWTs made from my secret key, and some user info (e.g. user_uuid) to make the refresh token specific to that user

#

so no tokens have to be stored in the db, that's great 👍

opaque rivet
#

so a refresh token is just a JWT with a longer expiry date?

raven apex
#

hey, i need help with pyscript is this the correct channel?

#

is it possible to run a ascii game in pyscript?

#

like i made hangman

#

and i would like for there to be some terminal where i can run the game where the user can enter input and whatever else i need to

#

ping me when you reply. thanks a lot

viral hawk
daring isle
novel holly
#

I am using flask with this code:

from flask import Flask, request, render_template

app = Flask(__name__)

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

if __name__ == '__main__':
    app.run(debug=True, port=8000)```

```html
<form method="GET">
        <p>Phone number:</p>
        <input name="phone_number" type="number">
        <br><br>
        <input type="submit">
    </form>```

I want to be able to use the inputed phone number text as a variable in my python code when it is submitted. How do I do that?
frank shoal
#

you need to make a POST route

#

i.e. @app.route("/", methods=["POST"]) then use the request.form variable to get the post data

#

actually, you're already using get, so you can just do request.form

analog crest
#

Hello, I'm a little stuck on the Django framework. I have a mockup (a form in my templates) that a user dynamically creates by clicking a (+). The problem is that I don't know how to recover its data.

plucky wadi
#

Any ideas on solving this error :
Refused to apply style from '<URL>' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Tech stack :
web server (reverse proxy) : nginx , application : django , application server : gunicorn & Docker.

inland oak
#

well, and mind the language

native tide
#

mimimi

agile gyro
#

what are some good tools to develop a website quiet fast

#

im using webflow for the frontend

#

but it feels like it would be a pain to link the frontend with a django framework

opaque rivet
#

hey guys - I've got a set-cookie header in my response but it's really bugging me that the cookie isn't being set. (doesn't show up in devtools)

set-cookie: access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmYmJkY2EyNWEwMTk0NmFiYTkxM2MzOWI5MTliNzRkYyIsImV4cCI6MTY1Njg4NzY2NH0._v2dp5VMC0CSLSuc8b1IUKqCJn2rSP_o_eL8pQp9a34; Path=/; SameSite=lax

is there any reason as to why this won't show up in devtools? it's in the response, just not being set in the browser!

inland oak
agile gyro
#

im tryna use django

inland oak
#

Or even just rendering in Django templating language

inland oak
agile gyro
#

oh rly

inland oak
#

Sure.

#

Vue.js + Axios requests to Django Rest Framework endpoints in json format

#

and voila

#

Tbh, you can even statically link-insert Vue.js into being rendered from Django templating language 🤔

#

but that's a pervert way. Better linking in a normal way

agile gyro
#

sheesh

#

ok i dont even know how to link

inland oak
agile gyro
#

im not good with websites jsut fyi

inland oak
#

It just gives away your statically compiled vue.js web site to user

#

It is at his client side in browser

#

There(from user browser) u can make http requests with Axios, in GET/POST and etc way to your hosted Django application

#

Django application in a simple Rest API way accepts JSON inputs and answers results in JSON too

agile gyro
#

ok i get it

#

makes sense

#

have u hearda webflow

#

@inland oak

obtuse robin
carmine cipher
#

Hello guys, assume I am a web developer for 2 years , how long can take me to learn WordPress?

inland oak
#

Except learning curve of react more complicated than Vue.js

native tide
# worn aurora **User** is used to extend the already defined user user class, **AbstractUser*...

Thanks for answering. I have 2 more questions.

  1. Once I make a new user class(using abstractuser), does it automatically override the existing user class to be considered as the user class for the project?
  2. Is there a big difference between the extending the pre-defined user class or creating our own user class in terms of practicality? What's the benefit of one over the other on a website?
worn aurora
native tide
#

So I hosted my flask app in railway.app but in the logs it starts the gunicron worker and it says connection in use it says retrying in 1 sec and then it says cant connect and exits anyone help?

uneven bloom
#

Has anyone worked with whatsapp Webhook and flask

dusk sonnet
#

Hi, im tryna deploy my app however im getting a ValueError: Required parameter not ste for the following:

<img src="{{ request.user.profile.picture.url }}" class="rounded-circle" alt="Profile Picture">
#

i dont understand why im getting this since i have all the environment variables set properly

versed ivy
dusk sonnet
#

the website currently works fine on my local machine however the deployed version doesnt work due to the above error

versed ivy
# dusk sonnet

maybe try user.profile... instead of request.user.profile... 😐

dusk sonnet
#

i changed it to request.user... to see if it worked but same thing

versed ivy
# dusk sonnet i changed it to `request.user...` to see if it worked but same thing

the user object gave no error! because the user.is_authenticated works fine.
so, the problem should lie inside the user.profile or user.profile.picture or the url of the profile class.
try checking the attributes of the user in your terminal.
before rendering, print the user.profile.picture.url and see if the error is coming from the user.profile attributes.

dusk sonnet
versed ivy
dusk sonnet
#

im gonna delete all the environment variables and set them again once again lol

dusk sonnet
native tide
#

django

floral thicket
#

in flask how can i get the full route with paramaters

#

ex : /completed?token=xxxxx-x-xx-xx&lang=xx

orchid olive
#

good morning

#

someone know where is the sites-available file in windows10-apache2.4?

#

found ir!!, thanks

main jasper
#

Flask. Paths, Saving files.

def write_sample_file(save_to_path):
with open(save_to_path, 'w') as f:
print(f'Saving to path: {save_to_path}')
f.write('Great success')

On route:
root_path = current_app.root_path
instance_path = current_app.instance_path

save_to_path_1 = os.path.join(root_path, 'static', 'sample.txt')
save_to_path_2 = os.path.join(instance_path, 'static', 'sample2.txt')

Second call fails (naturally?!)

But stackoverflow (https://stackoverflow.com/questions/36649703/get-root-path-of-flask-application/36651006#36651006 )insist people use instance path instead of root. WHY? HOW?

#

root_path: /home/[PCNAME]/Coding/flask_path

instance_path: /home/[PCNAME]/Coding/flask_path/instance

#

flask docs have:
UPLOAD_FOLDER = '/path/to/the/uploads'

which is not useful and seems like hard-coding path to config.

native tide
#

Can I get selenium help here

main jasper
#

Correction to question above: I did not paste calls to functions:
write_sample_file(save_to_path_1)
write_sample_file(save_to_path_2)

second one (using current_app.instance path) - fails,

onyx lava
#

Hey guys, is it smart for me to rather use client sessions or just return the html file once the user logged in

loud ember
#

Hey I got this error in postges sql .. how to solve this ?

viscid valley
#

Anyone have any links on best practices to interface Discord with Django?

worn aurora
viscid valley
# worn aurora using webhooks ?

I'm not quite sure, I've done it before just using the Discord library living inside an app called discordbot, was a mess.

worn aurora
#

as django does not fully support async its not generally used to bridge, it would be much better/eaiser if u use FASTApi and such

viscid valley
#

@worn aurora Thanks, could you provide some material so I can start on the right path? Thanks for the help 🙂

worn aurora
#

so u do this on global level

        app = FastAPI()
        discord_client = DiscordOAuthClient(client_id, client_secret, redirect_uri,
                                            scopes=("email", "identify", "guilds"))

        dashboard_root = project_base_path / "dashboard"
        static_path = dashboard_root / "static"
        app.mount(str(static_path), StaticFiles(directory=static_path), name="static")
        templates = Jinja2Templates(directory=dashboard_root / "templates")

        from bot.bot import Ranger

        if os.getenv('DEBUG_SERVER', '').lower() != 'true':
            bot = Ranger(debug_guilds=[
                int(os.getenv('GUILD_ID'))
            ])
            ensure_defaults()  # blocking call
            bot.load_custom_cogs()

then

        @app.on_event("startup")
        async def startup():
            logger.debug("Starting Bot....")
            if os.getenv('DEBUG_SERVER', '').lower() != 'true':
                asyncio.create_task(bot.start(os.getenv("DISCORD_TOKEN")))
            else:
                logger.debug("Server Debugging turned on... skipping starting bot")
#

this also has code for Oauth, so u can skip it if u like

#

template serving in fastapi is a bit slower than django but it makes up for it by making it easy to develop

#

btw what is your end goal ?

loud ember
worn aurora
#

like this is wrong, look at the where clause

SELECT * from table1
where "column1"="value"
solar heath
#

Hey

#

Does someone know how to get form information with Flask?

#

I am trying this

#
    <form>
        <input type="text" placeholder="Nombre">
        <input type="text" placeholder="Apellido/s">
        <input type="text" placeholder="DNI/NIE/NIF">
        <input type="email" placeholder="Correo electrónico">
        <input type="password" placeholder="Contraseña">
        <input type="password" placeholder="Confirmar contraseña">
        <button>REGISTRARSE</button>
    </form>
#
@app.route("/cliente")
def clientes():
    return render_template("cliente.html")

@app.route("/cliente", methods=["POST"])
def clientes_post():
    print("ASD")
obtuse robin
#

and put the attribute method=“POST” on the form tag

#

you also need to put an id on the form tag to later distinguish it in python

solar heath
#

how do I get form answers by form id?

obtuse robin
#

on the function do


if request.method == "POST":
  form_information = request.form['form_id']
#
@app.route("/cliente")
def clientes():
  if request.method == "POST":
    form_information = request.form['form_id']
  return render_template("cliente.html")

@app.route("/cliente", methods=["POST"])
def clientes_post():
    print("ASD")
#

should be here

#

also youre using the same app routes

#

that wouldnt work

#

they all go through the same one

solar heath
#

like this?

obtuse robin
#

sure

#

but if you want information to be pulled from the post youd need to use request and access the form

solar heath
#

I get an error

obtuse robin
#

what is it

solar heath
worn aurora
solar heath
#

Like this?

worn aurora
#

ohh flask, i though we were on fastapi

#

and

you should close the help channel if your asking for help here

obtuse robin
solar heath
#

yeah

#

no

obtuse robin
#

you need to move everything and put your if request.method == post there

solar heath
#

it's in cliente.html

obtuse robin
#

oh

solar heath
#

(I am accessing through /cliente)

worn aurora
#

its
flask.request.method == 'POST' for flask

native tide
#

How much django would one need to know to be able to build a website similar to this? https://www.erepublik.com/ (basically a social network disguised as a "game")

I have the basics of django down(models, fields, databases) but I don't know stuff like property decorators, signals etc. Should I learn those before trying to build a website like this? or can I build it with just knowing the fundamentals

obtuse robin
#

ive done request.method and it works

worn aurora
#

u can remove the param from the function def

solar heath
#

kk

#

now it works

obtuse robin
# solar heath

arent what you did flipped? shouldnt it show the cliente html if you did not get a post request

#

hm

native tide
#

@worn aurora thoughts?

obtuse robin
#

okay glad it works

solar heath
#

now it works

#

now how to get form inputs

#

id from form is "register"

worn aurora
#

as i cant see the acctual game cant really say much

native tide
#

the main thing would just be the same functionality as a social network website(like a really watered down facebook)

worn aurora
#

ahh then i guess above mentioned things will be enough

solar heath
#

How do I get the form inputs?

solar heath
#

is there a way to get all of the inputs inside a form at once=

#

I can manage to get one by one

#

but not all at a time

native tide
#

Let's say I have a currency model for my application(shown below). the application will have multiple currencies.

How would I go about implementing it so that each user can have a certain quantity of some currencies? and with methods that can increase/decrease currency in someone's account

This is what I've written so far:

class Currency(models.Model):
    name = models.CharField(max_length=100)
    symbol = models.CharField(max_length=100)
    country = models.ForeignKey(Country, on_delete=models.CASCADE, default='')

Should I create a foreignkey field within the user profile? but how would I implement quantity of currency then?

native tide
#

tell me how to host a Quart app, im using Hypercorn but i really dont know how to host it on a specific domain PB_peepo_cry it says the app is listening on "0.0.0.0:8000" :P

solar heath
#

Can I use js methods in flask?

#

like alert() ?

chilly bridge
solar heath
#

Can I detect where form is being sent?

#

I have two forms in my web and I wanna know which one is being sent

agile gyro
#

I need help making a website

#

I want to have two different sites that are linked together

#

but im not sure what to use

#

my main issue is front end

#

but I'm here to ask if there is something out there that will help me build a digital product store

#

I've seen webflow but it feels like people can just right click download

#

and the other site is when i want to upload products then later on package them

native tide
#

Something out there as in only for the frontend, or backend as well? @agile gyro

agile gyro
#

both

#

would be nice

#

its this shit that sketchs me out

#

i think i will just make a unique link api

#

the major thing im worried about is how to prevent shared download links

#

im not sure how to do that

#

for example i want to be able to send a link for them to download

#

but they would have to sign in

#

for it to work

#

do u think i can do thisin wordpress

native tide
agile gyro
#

ya ive only heard good things about it never used it either

native tide
#

hey guys I'm trying to learn how to get requests, ur lib to automate stuff on websites. I feel completely ignorant on the topic, does anyone know where should I start to learn the network tab, understand how to make requests etc.. Most of youtube videos just show how to do it but not the actual science behind it so If someone could tell me where to look would be greatly appreciated.

dusk sonnet
native tide
#

My userprofile model has a function to increase the user's experience points by 5.

Is there a way to implement a button on an HTML page so that each time someone clicks that button, their XP goes up by 5(by calling the model method)?

ivory kiln
#

Its also perhap scaled a bit too large for mobile

dusk sonnet
dusk sonnet
#

it might be slow because of the pictures because i dont resize the pictures since i dont know how to create a lambda function for it

spring oriole
#

It’s been a while since I used it but I think it’s possible to right click and ask for Python code. It’s basically a proxy that sits between the backend and your browser when you use websites. That could probably help you learn. Also curl

manic crane
#

hey could somone help me with this error => django.core.exceptions.ImproperlyConfigured: Field name `token` is not valid for model `Occupier`. my code => ```class Occupier(AbstractBaseUser,PermissionsMixin):
#occupiers can join several cliques
#all posts must go to a specific clique
email = models.EmailField(verbose_name='email',max_length=59, unique=True)
username = models.CharField(max_length=30,unique=True)
occupations = models.CharField(max_length=200,null=False) #amount of occupations user does
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
dob = models.DateField(blank=True, null=True,unique=False)
password = models.CharField(unique=True, max_length=200)
first_name = models.CharField(max_length=200,null=True)
last_name = models.CharField(max_length=200,null=True)

objects = OccupierManager()

USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email','occupations','password','dob']

def str_(self):
return self.username

def has_perm(self,perm, obj=None):
return self.is_admin

def has_module_perms(self,app_label):
return True

@property
def token(self):
token = jwt.encode({'username':self.username,'email':self.email,'exp':datetime.utcnow() + timedelta(hours=24)},
settings.SECRET_KEY,
algorithm='HS256' )

return token```
fossil idol
rocky epoch
#

So im making a little flask project where i enter a city name in a stringfield and then click on the submit button and then it shows me the weather of that particular city in a html card
the problem im facing is that i am unable to find a way to display the card once the form has been submitted.
i think i shud be using an if statement using jinja templating but i am having a hard time figuring out how to get it working

#
<body style="background-color:rgb(91, 94, 166);">
  <div style="text-align:center; padding:20px;padding-bottom:50px; color: whitesmoke;">
    <h1 class="display-3">TheWeatherApp</h1>
  </div>
  <div style="width: 40%; background-color: whitesmoke;padding: 12px;margin:auto;border-radius:20px;">
    <div style="text-align: center">
      <div class="col-auto">
        <form method="post" action='{{url_for("index")}}'>
          {{form.hidden_tag()}}
          <h1 class="display-6">Enter City Name</h1>
      </div>
      <div style="width:70%;margin:auto;padding-bottom:10px;">
        {{form.city(class="form-control")}}
      </div>
      <div class="col-auto">
        {{form.submit(class="btn btn-outline-secondary")}}
        <!--<button type="submit" class="btn btn-outline-secondary">Search</button>-->
      </div>
      </form>
    </div>
  </div>
  {% if form.city.data is not none%}
  <div class="card" style="width: 18rem;">
    <img src="..." class="card-img-top" alt="...">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
      <a href="#" class="btn btn-primary">Go somewhere</a>
    </div>
  </div>
  {% endif %} 
</body>```
#

heres the html

#
@app.route("/",methods=['GET','POST'])
def index():
    form = CityForm()
    if form.validate_on_submit():
        print(form.city.data)
        return redirect(url_for('index'))
    return render_template("index.html",form=form)```
#

and heres the flask function

hushed crow
#

any idea why webssh throws these?

unkempt arrow
#

Hello, I already tried two times to get help from regular channels so I am trying here. I have this in my function to generate html :

data = """var script = document.createElement("script");..."""
postfix.append(html.script(data))

but then it generate this <script>var script = document.createElement(&quot;script&quot;);...</script>
How can i handle with this to force to don't escape in my string ?
html come from py.xml import html.

red moon
#

Try to use "

graceful cloak
#

Hey there,
I am converting the MongoDB Cursor() object I get from performing a query in pymongo to a list using the list() operation. This conversion typically takes about 0.5 seconds for only 32 documents that are not very large in size at all. How could I speed up this type conversion?

solar heath
#

How do I deply a Flask app (ubuntu server)

#

I have it deployed but it might be causing conflict with my other website

rigid laurel
#

You probably need to put it behind a reverse proxy such as Nginx or Caddy - or if you already have one, you might need to reconfigure it

solar heath
#

I am using nginx

#

@rigid laurel

rigid laurel
#

It looks like you're running it with the flask dev server - that's usually a bad idea - here's a DigitalOcean article walking you through the whole setup of using Nginx + Gunicorn which I'd suggest trying to apply to your specific app. https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-18-04

solar heath
#

I am already looking a video tutorial

#

before continuing I want to know how to host two websites at the time

rigid laurel
#

once you've set up one app, adding another is fairly easy. I haven't used Nginx in years, I've used Caddy instead, but iirc you just add another location section to your Nginx config

solar heath
#

no flask

atomic sinew
#

How to apply css on imagefield in django models ? When I put that in html: img tag, only inline css works, niether internal, nor external.

worn aurora
agile gyro
#

how do i determine how many vCPUs i need and Ram ?

#

it is a digital ecommerce store

#

i think will have 50 active users at once

#

but at launch would probably have 200+

atomic sinew
#

Now it works fine

autumn veldt
#

how can i hide from website that im using chromedriver ?

echo cloak
#

ensure that $cdc_ doesn't exists anymore as a document variable

autumn veldt
#

umm

#

how do i do this ?

#

@echo cloak

echo cloak
#

download chromedriver source code, modify chromedriver and re-compile $cdc_ under different name. @autumn veldt

autumn veldt
#

i get an error

#

look

#

OSError: [WinError 216] This version of %1 is not compatible with the version of Windows you're running. Check your computer's system information and then contact the software publisher

#

but it worked before the change

echo cloak
#

with what name did you changed the $cdc_ ?

autumn veldt
#

abc

#

$abc_

echo cloak
#

you have to make sure that the replacement string (e.g., dog_) has the same number of characters as the search string

echo cloak
#

its the same no. of char

autumn veldt
#

$abc_asdjflasutopfhvcZLmcfl_

autumn veldt
echo cloak
#

You have to change the jdk location in project structure

Follow those steps

Go to file -> project structure -> sdk location

Unselect Use embedded jdk(recommended)

Then Change the jdk location to C)Program Files/java/jdk1.x.x_xxx

Where x is dependent on the JDK version you have installed locally.
autumn veldt
#

wait i think i know why is that

#

one min

tight knoll
#

Hello

late stone
#

anyone familiar with django models

#

?

muted walrus
#

Hey All, I am trying to re-direct a url from a function in views.py, but upon running the api
I get "function at 0xxx14" some mem Location .
I am using return redirect (url) . Can anyone suggest something here .(Django)

versed ivy
# late stone anyone familiar with django models

Ummm... can't explain properly in text! but you may take a look at this video which I followed for my django tutorial (https://youtu.be/5zNR3E6WRLE?list=PL4cUxeGkcC9ib4HsrXEYpQnTOTZE1x0uc&t=50).

Then it is highly recommended that you read through the docs for sometime and if you have any specific problem understanding some parts, ask here again.
Don't be discouraged to ask.

Django Models Docs: https://docs.djangoproject.com/en/4.0/topics/db/models/

muted walrus
#

@inland oak Thanks Buddy, I did refer this, wanted to know if we can also call a function in redirect? 🤔

inland oak
#

I would recommend using reverse url function though

muted walrus
undone canopy
#

i want a proper manual for python like the understanding of every code like print(),"",# etc

brisk creek
#

hey, does anyone know why two sub folders get created inside the project folder if I'd like to make an HTML/CSS file?

#

blog is the app, but I have a subfolder within templates called blog. Anyone know why? Why would I not just have the html file in templates

daring isle
remote pendant
#

is there a way to change the name of object list inside the admin page of django instead of just object 1, object 2, etc?

tight pike
#

It's simply a standard set by Django community and Django framework, made to avoid confusion and some type of future problems

#

try to add this in your models.py file in your class:

def __str__(self):
        return self.****

swap the 4 'stars' with a variable which contains the name of your object

#

example: if you got a class Post which contains many posts, you'll definitely have a 'title' variable, so you simply return self.title. Obviously after having modified your models.py file, then you gotta do python manage.py migrate & python manage.py makemigrations

remote pendant
formal swift
#

Anyone know what a 'OPTIONS' request is?

#

I am sending an API on iPhone and instead of a POST like my desktop does, it is sending OPTIONS

rigid laurel
#

typically used for a CORS preflight

#

it gets sent out ahead of CORS enabled requests by your browser

#

if you control the server - you probably want to handle it

#

not necessarily writing code to handle it - just respond to the preflight at the reverse proxy level, or with some middleware type thing like Flask-Cors

formal swift
#

Okay thank you

#

Just figured out why it is sending the CORS preflight. It is because I was on HTTP and sending the request to the HTTPS version of my website

native tide
#

is there a way to use python with html

#

I've made most of my website with html

#

but I want to add some functions to it that I think I can only do with py

#

such as selection

remote pendant
#

how to give permission to certain users to view certain pages?

rigid laurel
#

there is no good way to do it, no. JavaScript is pretty much the only way @native tide

native tide
#

Maybe using MySQL

#

Find the user and set a column "allowed" to True

native tide
remote pendant
#

i mean django, what i want is when my user login, they can only view certtain pages.

native tide
#

oh I wouldn't have a clue then xd

#

still need to learn django

rigid laurel
#

JS isn't too difficult to pick up. You can either just jump into it with trial and error, or work through a tutorial. The Mozilla tutorial is a little dry but fairly good if you go that way https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps

In our first JavaScript module, we first answer some fundamental questions such as "what is JavaScript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing JavaScript. After that, we discuss some key building blocks in detail, such as variables, strings, numbers an...

#

(I'm not actually 100% sure that's the right Mozilla tutorial, but Mozilla is definitely the place to go to)

native tide
#

so this will basically allow me to add logic based stuff to my website?

#

if u know what I mean

#

not just text and pics etc

rigid laurel
#

Yeah

remote pendant
#

for now, i just do an if statement in the html file that says you cant view this page.

late stone
daring isle
late stone
#

understandable, Ok so heres my question:

late stone
# daring isle im not ready for that level of commitment lol, whats your question?

I am building an employer admin program.

Within my user management app, in my models.py file, I have a Profile class pointing to Company class using models.OneToOneField. The company class points to an Employee class via models.ForeignKey.

When I create a company profile and I create a company along with and it works just fine, but when i make more than one employee in relation to the company and works fine, but when I retrieve that employee, I get a just one employee. How can i make it to like whenever i call the employees by doing: obj.company.employee i get all the employees instead of the latest employees saved in the db

heres the models.py file with the models describe above: https://github.com/AngelM512/hr_program/blob/master/userMgt/models.py

GitHub

Contribute to AngelM512/hr_program development by creating an account on GitHub.

#

i am very new to django so i am very thankful for your help

daring isle
#
class Company(models.Model):
    name    = models.CharField(blank=True, max_length=45)
    address = models.CharField(blank=True, max_length=255)
    employee = models.ForeignKey(Employee, 
                                on_delete=models.CASCADE,
                                blank=True,
                                null=True)

in your company obj you have an employee field, that will have one employee per company or a list of identically named companies with one employee each

#

is this intentional?

late stone
#

no, i want the company to have many employees but each employee can only work for a company

daring isle
# late stone I am building an employer admin program. Within my user management app, in my m...
class Employee(models.Model):
    first_name    = models.CharField(max_length=20,blank=False)
    last_name     = models.CharField(max_length=20,blank=False)
    prefered_name = models.CharField(max_length=20,blank=True)
    birth_date    = models.DateField()
    gender        = models.CharField(max_length=1)
    salary        = models.IntegerField()
    hired_date    = models.DateField()
    department    = models.CharField(max_length=45)
    company = models.Foreignkey(Company, on_delete=models.Cascade, blank=True,     null=True)

    def __str__(self) -> str:

        return (self.first_name +' '+ self.last_name)

add the company as a foreignkey to the employee model

#

remove the employee field from the company

#
obj = Employee.objects.filter(company='put company id here').all()
#

then you can query your employees like this

#

then obj will be an array of all employees with specific company

late stone
#

dude you are the best thank you so much. program is working the way i want it now

#

@daring isle

daring isle
spare iris
#

does this mean i can scrape hertz?

#

i'm very new to webscraping

remote pendant
#

django.db.utils.OperationalError: (2006, 'SSL connection error: unknown error number') I got this error when I try to migrate my database to mysql. I've looked up the internet and found no solution. Can anyone help me?

remote pendant
#

nvm, i use posgresql now

cinder gull
#

Hey who know flask web hooks write me in DMS pls!

subtle drum
subtle drum
rugged bane
#

How do you change width of image in a carousel?

dark snow
#

Hi,
What library do you recommend for rest api?
Exactly what framework is usually used for large commercial projects?
I would like to learn a framework that I can use in the future at work

versed ivy
inland oak
undone canopy
#

CAN I GET A REPLY HERE IAM NEW HERE BTW....HI!

dark snow
spare iris
#
from bs4 import BeautifulSoup
import requests

url = "https://www.hertzcarsales.com/used-cars-for-sale.htm?geoZip=73301&geoRadius=0"

page = requests.get(url)

soup = BeautifulSoup(page.content, "html.parser")

price = soup.find(class_ = "text-right portal-price").get_text()

print(price)
#
Traceback (most recent call last):
  File "/Users/rahuldas/Desktop/web scraping hertz/web_scraping_hertz.py", line 10, in <module>
    price = soup.find(class_ = "text-right portal-price").get_text()
AttributeError: 'NoneType' object has no attribute 'get_text'
#

i'm trying to scrape the price, but it doesn't seem to work

spare iris
#

oh that's what they were asking

astral pine
#

the terminal didn't help me at/ all

spare iris
#

what

astral pine
#
import discord
import random


TOKEN = "sike you thought"

client = discord.Client()

@client.event
async def on_ready():
    print("We have logged in as {0.user}".format(client))

@client.event
async def on_message(message):
    username = str(message.author).split("#")[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f'{username} : {user_message} ({channel})')  

    if message.author == client.user():
        return
    

    if message.channel.name == 'testing-2':
        if user_message.lower() == "hello":
            await message.channel.send == (f'Hello {username}!')
            return
        if user_message.lower() == "bye":
            await message.channel.send == (f'See ya later {username}!')
            return
#

this is the command

#

the bot isn't responding

#

and the terminal says

#

man i can't copy the terminal

spare iris
#
from bs4 import BeautifulSoup
import requests

url = "https://www.hertzcarsales.com/certified/Ford/2019-Ford-Fiesta-7406eaed0a0e0a905aaa0f8910f96833.htm"

page = requests.get(url)

soup = BeautifulSoup(page.content, "html.parser")

soup_2 = BeautifulSoup(soup.prettify(), "html.parser")

#print(soup_2)

title = soup_2.find(class_="text-muted font-weight-bold BLANK").get_text()

price = soup_2.find(class_="price-value").get_text()

transmission = soup_2.find(class_="mr-3").get_text()

print(title)
print(price)
print(transmission)
#

i don't get how the class tag says it's automatic

#

i use .get_text

#

and still it doesn't give me the "Automatic"

#

yeah i'm not so sure

#

i specify the class name just like i did w the other ones

spare iris
#

still don't know

formal swift
#

I am trying to work out task management with flask. So, say on a dashboard they submit a form and the form sends an rest API to another part of my server to do a task. If the page is refreshed will the task still happen?

#

Or if at the same time, another task is sent, does flask automatically handle it all?

chrome belfry
#

or like a lambda?

spare iris
golden bone
spare iris
#

i am so lost

patent glade
#

Does anyone know how I can see the actual implementation of the DOM?

#

The actual classes for Node, EventTarget, Document, and so on, in code form?

proper hinge
#

You'd have to pick a browser and look at its source code

patent glade
#

Guhhhhhhhh

#

Chromium is massive

proper hinge
#

Yes the major browsers are all big code bases

patent glade
#

I've tried to find the relevant parts a few times, but its all distributed

#

My task is to write a faithful implementation of the dom protocol (since technically its an interface designed to be implemented in any language) in python

proper hinge
#

You could try to search a browser engine's bug tracker for the classes you're interested in

#

Usually the issues link to diffs for fixes and whatnot

#

That should give you an idea of where things are located

patent glade
#

There's this document

#

Which I think is basically the recipe. But the tendrils of the DOM extend minutely, in every direction, throughout the mechanics of the browser itself that it's hard to know what I need to emulate

#

What I think I need is a base EventTarget class and a base Node class

wise nest
#

Hello!

#

I have a question. So I am trying to return a different html template with flask but when I click the button to do it, it doesn't work

patent glade
#

I need a bunch of node subclasses which act as mixins, and those are mixed together in various combinations to create elements, documents, document fragments, concrete text node classes of various types

wise nest
#
import os
import openai

openai.api_key = os.getenv("API KEY")

app = Flask(__name__) # Create an Instance

@app.route('/') # Route the Function
def main(): # Run the function
    return render_template('index.html') # Render the template

@app.route('/generate', methods=["POST", "GET"])
def generate():
  return render_template("generate.html")
    
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, debug=True) # Run the Application (in debug mode)```
#
     <input type="button" name="submit" value="Run Script">
    </form>```
I don't have anything in the generate html for the button
patent glade
#

In Javascript

#

What is a "namespace"?

proper hinge
#

Are you referring to when you do an import like import * as namespace from "module"?

patent glade
#

No, no, I'm talking about javascript

proper hinge
#

Yes, that is JavaScript code.

patent glade
#
1.4. Namespaces
To validate a qualifiedName, throw an "InvalidCharacterError" DOMException if qualifiedName does not match the QName production.

To validate and extract a namespace and qualifiedName, run these steps:

If namespace is the empty string, then set it to null.

Validate qualifiedName.

...```
patent glade
#

Oh

#

Cool, okay

#

I guess I am...?

proper hinge
#

Is your question in the context of the JS language itself or in the context of the DOM standard?

#

Seems to be the latter

patent glade
#

Yeah, the DOM standard

proper hinge
#

I'm not sure then

#

Perhaps related to XML namespaces? I dunno

#

Yes, that actually seems to be the case after looking at the DOM standard

inland oak
wanton compass
#

where could I look to get help in reading webpages for updated text? is this the channel or somewhere else?

modern wharf
#

hi guys this is my website created by me

#

Can u guys give me some feedbacks?

spare iris
#

bs4 is so irritating

native tide
#

How so?

#

Only issue I have is finding the tags.

golden bone
wanton compass
remote pendant
#

AttributeError: 'NoneType' object has no attribute 'split' Why im always getting this error?

native tide
#

Sending your code will be much appreciated.

remote pendant
#
  File "D:\Anaconda\envs\Web3\lib\socketserver.py", line 647, in process_request_thread
    self.finish_request(request, client_address)
  File "D:\Anaconda\envs\Web3\lib\socketserver.py", line 357, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "D:\Anaconda\envs\Web3\lib\socketserver.py", line 717, in __init__
    self.handle()
  File "D:\Anaconda\envs\Web3\lib\site-packages\django\core\servers\basehttp.py", line 171, in handle
    self.handle_one_request()
  File "D:\Anaconda\envs\Web3\lib\site-packages\django\core\servers\basehttp.py", line 194, in handle_one_request
    handler.run(self.server.get_app())
  File "D:\Anaconda\envs\Web3\lib\wsgiref\handlers.py", line 144, in run
    self.close()
  File "D:\Anaconda\envs\Web3\lib\site-packages\django\core\servers\basehttp.py", line 111, in close
    super().close()
  File "D:\Anaconda\envs\Web3\lib\wsgiref\simple_server.py", line 35, in close
    self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'

I think the problem is with this wsgi file.

#

it doesnt affect my web, but the error always shows up

native tide
native tide
#

Django question: How can I make URLs in my urls.py be case insensitive?

#

That solution doesn't work anymore, Django deprecated it

subtle drum
#

Hi, im using datatables.
Anyone know how to resize this?
somehow the search box over rides my columnDefs option.

ionic raft
# modern wharf https://tanvoontao.github.io/AllAboutVoonTao.github.io/

That's quite good for a single-page exploration of a number of well laid-out design elements. I like the overall design language. My personal preference is for more white space. Given the focus of the landing page, maybe greater padding for elements while continuing to use a screen-width container.

ionic raft
modern wharf
ionic raft
# modern wharf Thanks greate feedback! Have a nice day

I definitely appreciate the depth of research thru your comp sci degree, along with techniques you must be exposed to. For example, the loading rocket that then gets used for the top of page icon...

...that's sweet design language. Definitely talent there 🙂

#

Creative 🙂

modern wharf
#

Thanks! I was thinking so hard to make it as perfect as I want since I gonna use this for my future workpath to showcase my projects