#web-development

2 messages · Page 217 of 1

glacial kelp
#

what is the problem of this

white glacier
#

Replit?

native tide
#

Anyone has experience building small real-time web apps and has suggestions for libraries to use when async operations are needed + with a mix of API's ? Am I good to go with FastAPI + python-socketio + asyncio ?

alpine nacelle
#

Got a Selenium project I'm working on but after a while the webpage decides to hang and needs the driver resetting. What's the best way of handling it, just a try except catching a TimeoutException and calling a method from there to reset the driver?

river tulip
#

hey y'all if someone of you knows a little bit about APIs, could maybe have a quick look at #help-grapes ?

#

I do not understand why my code enters the if statement even though the response code is 200?

river tulip
fervent jungle
#

Have a issues with celery+flask
I have celery work fine on its own but when I add it to a flask app. it does not parse the url correctly and tries to connect to localhost.
The only way I was able to get it working was to call Connection directly.

from flask import Flask
from celery import Celery, shared_task
import ssl

app = Flask(__name__)

url = 'amqps://user:pass@host:5671'

app.config.update(
    CELERY_BROKER_URL=url,
    CELERY_RESULT_BACKEND='rpc://',
    BROKER_USE_SSL={'cert_reqs': ssl.CERT_NONE},
    CELERY_TIMEZONE='UTC',
    CELERY_DEFAULT_QUEUE='TEST'
)

def make_celery(app):
    celery = Celery(
        app.import_name,
        backend=app.config['CELERY_RESULT_BACKEND'],
        broker=app.config['CELERY_BROKER_URL']
    )
    celery.conf.update(app.config)

    class ContextTask(celery.Task):
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return self.run(*args, **kwargs)

    celery.Task = ContextTask
    return celery

celery = make_celery(app)

@shared_task(task_ignore_result=True)
def addCall(a, b):
    return

def my_ext_caller(a, b):
    from kombu import Connection
    with Connection(hostname=url,
                    ssl={'cert_reqs': ssl.CERT_NONE}, default_channel='test_ext') as conn:

        result = addCall.apply_async((a, b), queue='TEST', connection=conn)
        # result.wait()
        conn.close()
        return result

@app.route('/works', methods=["GET"])
def test1():
    my_ext_caller(1, 1)
    return 'test'

@app.route('/not_working', methods=["GET"])
def test2():
    addCall.delay(1, 1)
    return 'test'

if __name__ == "__main__":
    app.run(debug=True)
#
  File "/Users/jre/py39/lib/python3.9/site-packages/kombu/utils/functional.py", line 30, in __call__
    return self.__value__
AttributeError: 'ChannelPromise' object has no attribute '__value__'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/jre/py39/lib/python3.9/site-packages/kombu/connection.py", line 447, in _reraise_as_library_errors
    yield
  File "/Users/jre/py39/lib/python3.9/site-packages/kombu/connection.py", line 434, in _ensure_connection
    return retry_over_time(
  File "/Users/jre/py39/lib/python3.9/site-packages/kombu/utils/functional.py", line 312, in retry_over_time
    return fun(*args, **kwargs)
  File "/Users/jre/py39/lib/python3.9/site-packages/kombu/connection.py", line 878, in _connection_factory
    self._connection = self._establish_connection()
  File "/Users/jre/py39/lib/python3.9/site-packages/kombu/connection.py", line 813, in _establish_connection
    conn = self.transport.establish_connection()
  File "/Users/jre/py39/lib/python3.9/site-packages/kombu/transport/pyamqp.py", line 201, in establish_connection
    conn.connect()
  File "/Users/jre/py39/lib/python3.9/site-packages/amqp/connection.py", line 323, in connect
    self.transport.connect()
  File "/Users/jre/py39/lib/python3.9/site-packages/amqp/transport.py", line 113, in connect
    self._connect(self.host, self.port, self.connect_timeout)
  File "/Users/jre/py39/lib/python3.9/site-packages/amqp/transport.py", line 197, in _connect
    self.sock.connect(sa)
ConnectionRefusedError: [Errno 61] Connection refused
native tide
#

Also change the port at the top to 5672

to run rabbit in docker:
docker run -d -p 5672:5672

or if you don't have docker installed then:
sudo systemctl start rabbitmq.service

steel night
#

hmm

#

could my_ext_caller not be collecting the promise and so you don't see it's error?

#

I'm not 100% on the behavior of apply_async in kombu

#

but that implies it's returning a promise. and then you immediately close without collecting it

#

whereas the decorated task is actually getting the result?

#

so they're both failing but you only see one of them failing?

#

o nvm I missed task_ignore_result=True in that decorator

native tide
#

need someone who is good with cookies/requests/headers, if you can do a job for me im paying btc

#

dm ^

steel night
#

!rule 9

lavish prismBOT
#

9. Do not offer or ask for paid work of any kind.

fervent jungle
steel night
#

hmm

#

does task.delay() ignore the ignore_result=True setting?

#

the documentation I linked up there implies that task.delay does not allow extra execution options

#

possibly including ignore_result=True

#

if you change delay to apply_async do you still see the error?

#

and/or the other way around

#

that's the only difference b/w the endpoints I can see

#

they're calling the task with different methods

fervent jungle
#

it never get to that part. It was throwing this before
WARNING: No hostname was supplied. Reverting to default 'localhost'

#

with the .delay

fervent jungle
steel night
#

idk. perhaps your CELERY_BROKER_URL is malformed

#

I'm not familiar with amqps

fervent jungle
#

it works out side of flask

steel night
#

I've always used something like CELERY_BROKER_URL = "pyamqp://user@host"

fervent jungle
#

that was introduced in 4.0 i think

steel night
#

hmm

fervent jungle
steel night
#

looks nice

native tide
#

Setting my DEBUG variable to false in django throws 500 error, i already looked at stack but setting ALLOWED_HOSTS to ['*'] does not work

#

i'm pulling an all nighter because i can't have debug enabled in production, any help is appreciated

inland oak
# native tide Setting my DEBUG variable to false in django throws 500 error, i already looked ...
pip install django-cors-headers
CORS_ALLOWED_ORIGINS = [ # your frontend addresses of the web site. I added additional localhosts for access from testing applications
    custom_allowed_origin,
    adding_www(custom_allowed_origin),
    "https://localhost:8080",
    "https://localhost:8000",
    "https://localhost",
    "http://localhost:8080",
    "http://localhost:8000",
    "http://localhost",
]

INSTALLED_APPS = [
    "corsheaders",
    ...
inland oak
#

forgot, plus here

native tide
#

i'm not using a frontend, i'm using class based views as generics @inland oak

#

if that makes a difference

inland oak
#

if it is CORS problem, it will be shown in console/network tab by some specific msgs, or by failed OPTIONS requests. OPTIONS are important for preflight CORS thingy

thin dome
#

guys i have a url
http://127.0.0.1:8000/home/name/name?q=Hello
and code
q = urlparse(request_path).query
but its not working, it is a empty str any solutions?

native tide
forest copper
#

PythonAnywhere is like a cloud for python based web applications?
What if I learn AWS technologies instead? 3 birds one stone or something?

native tide
#

@inland oak still not working btw

inland oak
#
MIDDLEWARE = [
    ...,
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    ...,
]
inland oak
#

get more logging msgs to find where it went wrong

native tide
#

i already tried it numerous times

fallen path
#

hey

#

Django messages multiple tags
I was trying to pass multiple extra tags in the messages.add_message() as a list. It seemed to work fine while using render, but when I'm trying to use redirect, it passes the extra_tags as a string and I can't get my objects by indexing as it considers the whole list as a string. Is there a way to solve this or pass multiple extra tags? Here is the code-

def handleSignup(request):
    if request.method == 'POST':
        username = request.POST['signup_username']
        name = request.POST['name']
        password = request.POST['signup_password']
        email = request.POST['email']

        if User.objects.filter(username=username).exists():
            messages.add_message(request, messages.INFO,
                                 'Please try another username.', extra_tags=['danger', 'Username already taken!'])
        elif User.objects.filter(email=email).exists():
            messages.add_message(request, messages.INFO,
                                 'An account with the email already exists.', extra_tags=['danger', 'Email already in use!'])
        else:
            user = User.objects.create_user(
                username=username, email=email, password=password)
            user.name = name
            user.save()
            messages.add_message(request, messages.INFO,
                                 'Account created.', extra_tags='success')
    else:
        return HttpResponse('404 -  Not Found')
    return redirect('/')
#

can someone help me out with this

inland solar
#

f = open('config.json','r+')
param = json.load(f)["param"]

@app.route('/')
def main():
return render_template('index.html', param=param)

#

am i doing this right

fervent jungle
# steel night hmm

so - I rebuilt everything. I have this working in an other env. the only thing different was the python version on my systems is 3.9.9 - my server is build on docker python:3.10.2-bullseye

#

so down the version to 3.8.12 and works now

inland solar
#

hlo

#

can anyone help me

fervent jungle
#

missing a }

elder jackal
#

hi anyone saw a fastapi + dependency injection + multiple databases project?

pure nimbus
#

I had an issue with my django form coming up as unbound after passing request.POST to populate its fields. my init contained an argument list, and I appear to have resolved the issue by removing the argument list and setting it to just (self, *args, **kwargs) then calling super().init(*args, **kwargs). Does anyone know why that is?

weary gull
#

any website for good bootstrap templates?

fervent jungle
inland oak
agile pier
#

how do I upload data from json file in django?

timber crystal
#

Hey guys, I'm not a web developer at all, so I apologize if this seems pretty basic but, in a website if I see:

#A bunch of code then:
    </div>
<script type="text/javascript">
#a function
</script>
</div> 
#end of the greater block I'm referring to in my question

Does that mean that that function only applies to the information within that greater <div> </div> block?

reef siren
#

how do i upload a project to github using the desktop app

frank shoal
#

github for windows?

#

not really web-related but w/e

trim spire
hot valley
#

Hello,
What are thé best free courses to learn web dev with python ? ( Complete newbie in web dev but experienced with python)

rugged osprey
# hot valley Hello, What are thé best free courses to learn web dev with python ? ( Complete ...

If you want to try Django I kinda liked https://www.youtube.com/watch?v=Z4D3M-NSN58&list=PLzMcBGfZo4-kQkZp-j9PNyKq7Yw5VYjq9 from
Tech With Tim after that I had my own similar project in mind I built with the help of these videos and continued searching elsewhere. But Django can be little bit tricky from the beginning to get used to. And its often recommended to start with Flask I guess

Welcome to the first python django tutorial on my channel. Django is a full stack web framework that allows for rapid development of websites. In this tutorial I will be showing how to setup and install django and talk about how to navigate between different pages.

Source Code: https://techwithtim.net/tutorials/django/setup/

Playlist: https://...

▶ Play video
pure nimbus
hot valley
native tide
#

Hi, I’m making a project and found YouTube videos that do exactly it. Is it bad to look at the tutorials and make it that way?

graceful igloo
#

nvm i found it

inland oak
cyan valley
#

idk if this is the right server to ask.
is it possible to list service workers in web app?

cerulean thicket
#

hello i have a code , in which when i send request through postman post method is not getting called

#

can anyone look into this ?

#

ping me whn replying

cyan valley
#

Like this

    @app.route('/', methods=['POST'])
    def post(self):
vernal plover
#

I’m having trouble with pip

#

I need help

cerulean thicket
#

@cyan valley please check this

cerulean thicket
cyan valley
#

wait

cyan valley
cerulean thicket
cyan valley
#

error?

cerulean thicket
cyan valley
#

you getting error code 400. which means Bad Request

cerulean thicket
#

but i am not able to understand becoz of which part of code i am getting this error?

cyan valley
#

make sure you sending json request from postman. check if content-type header is correct

cerulean thicket
#

now i am getting another thing

#

previous was fixed

cyan valley
#

found the problem. line 59. server looking for data["batch_size"] but you sending batch_size_val

#

you are looking for key that does't exist. either change in code or change in postman

#

@cerulean thicket

cerulean thicket
# cyan valley you are looking for key that does't exist. either change in code or change in po...

i tried this way python data = request.get_json() print('data=/n', data) json = ({ "status": "failed", "message": "ALL fields are mandatory" }) # in the below try catch we are accepting values from request try: country = data["country"].upper() print('country=', country) batch_size_val = (data["batch_size_val"]) epoch = data["epoch"] epoch_val = epoch except KeyError: print(json) logger.debug(json) return(json)

#

see this also

#

then also it is not working

cyan valley
#

well. only print statement debugging can help.

cyan valley
cerulean thicket
cyan valley
eternal kestrel
#

Hi, I'm trying to use flask and render_template to render a table from json

#

the for loop i use to loop over the json does not iterate

#

i have checked the json it is valid

#

can someone assist me

#
        {% for row in json_data["data"] %}
          <tr>
            <td>{{ row['col1'] }}</td>
            <td>{{ row['col2'] }}</td>
          </tr>
        {% endfor %}
        
#
{
    "count": 1,
    "data": [
        {
            "col1": "sample1",
            "col2": "sample2",
        }
    ]
}
#

this is my template, and json

#

no iterations

cerulean thicket
cyan valley
# cerulean thicket when i remove try catch then it works

(o_O) okay. then try:

        data = request.get_json()
        print('data=/n', data)
        json = ({
            "status": "failed",
            "message": "ALL fields are mandatory"
                })
                # in the below try catch we are accepting values from request 
        try:
            country = data["country"].upper()  
            print('country=', country)
            batch_size_val = (data["batch_size_val"])
            epoch = data["epoch"]
            epoch_val = epoch
        except KeyError as error:
            print(error)
            print(json)
            logger.debug(json)
            return(json)

see what error it's printing

cyan valley
cerulean thicket
#

see in this

cyan valley
#

wait second

#

how it's even working

cyan valley
cerulean thicket
#

when i try python country = data["country_code"].upper() print('country=', country) this way then i am getting python data= {'country_code': 'ind', 'batch_size_val': 2, 'epoch': 10, 'epoch_val': 10} country= IND {'status': 'failed', 'message': 'ALL fields are mandatory'}

cyan valley
#

why it's not printing error?

cerulean thicket
inland oak
#

or reading server console

cerulean thicket
# inland oak have u tried enabling debug

i gone throughpython <title>500 Internal Server Error</title> <h1>Internal Server Error</h1> <p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>.

cyan valley
# cerulean thicket on postman i am getting this

it's hard to debug the code in it's current state because it's failed somewhere in function.

you are using data keyword even after extracting data from it. gotta replace the use use of data variable after the first try catch and use they variables you created in the try catch.

inland oak
cerulean thicket
cerulean thicket
cyan valley
# cerulean thicket can u explain in other words bhai

so this

        try:
            country = data["country_code"].upper()  
            print('country=', country)
            batch_size_val = (data["batch_size"])
            epoch = data["epoch"]
            epoch_val = epoch
        except KeyError:
            print(json)
            logger.debug(json)
            return(json)


        # in the below try catch we are validating country name with country code
        try:
            country = pycountry.countries.get(alpha_3 = data["country_code"].upper()).name.lower()
            logger.debug(f'country1 : {country}')
            country = country.split()
            country =("_".join(country))
            logger.debug(f"country : {country}")
            alpha_2 = pycountry.countries.get(alpha_3 = data["country_code"].upper()).alpha_2
            logger.debug(f"alpha_2 : {alpha_2}")
        except AttributeError:                
            jsonify1 = {
                        "status": "invalid",
                        "message" : "Invalid country_code"
                        }
            print("invalid country_code")            
            logger.debug(jsonify1)
            return jsonify1        
        
        try:

            batch_size_val = int(data["batch_size"])
        except ValueError:
            jsonify1 = {
                "status": "invalid",
                "message" : "Invalid batch_size"
                }
            logger.debug(jsonify1)
            return jsonify1

you see you're getting data from the data variable in first try catch so use those variables from first try catch in following try catch instead of using data variable again. it will make the code easier to work with and easier to debug.

cerulean thicket
cyan valley
cerulean thicket
cyan valley
cyan valley
cerulean thicket
#

i am using pycountry library to to get country name , in that i need country code

cyan valley
#

you can do country = pycountry.countries.get(alpha_3 = country).name.lower() because you already created a country variable in first try catch which has that data.

#

i mean you don't need to do like this. this just makes the code easier to debug

cerulean thicket
#

thank u so much. let me debug more , if i need anything can i ping u ?

cyan valley
cerulean thicket
inland solar
#

can anyone plz help me

cyan valley
inland solar
#

it started working

#

names of the function and posts.query were matching............

cyan valley
#

Wait nevermind. Yeah

atomic ermine
#

I have a html page with multiple input images like this:

<form method="POST">
{% for (card_path, card_name) in cards %}
  <input type="image" src="{{ card_path }}" name="{{card_name}}" alt="{{ card_name}}" style="width:100%">
{% endfor %}
</form>

But in my flask app i cannot see which one of the image inputs were pressed. Normally with an input type submit you can specify the value of the button, then see what the value of the pressed button is. But it seems you can't set a value for an input type image.

How can i figure out which one of the images has been clicked?

ivory lotus
#

my static directories are weird, C:\Users\[____]\PycharmProjects\the-doge-net\thedogenet/static is happening. However idk why it's doing /static, and i can't seem to find the root of the problem

eternal kestrel
cyan valley
eternal kestrel
#

but what doesnt make sense is

#

there other item in my json is there

#

there is json["data"]

#

but thjeres also

#

json["count"] which is an int

#

it works

cyan valley
#

Check if you are sending data to the template

eternal kestrel
#

data is an array of dictionaries

cyan valley
eternal kestrel
#

json_data["data"] is the array in the json that contains the items im iterating over

#

I guess I'm not accessing the json properly?

#

or my loop

#

{% for row in json_data["data"] %}

#
{
    "count": 1,
    "data": [
        {
            "col1": "sample1",
            "col2": "sample2",
        }
    ]
}



          {% for row in json_data["data"] %}
          <tr>
            <td>{{ row['col1'] }}</td>
            <td>{{ row['col2'] }}</td>
          </tr>
        {% endfor %}
        
        
#

How can I modify this to work

#

the full json data prints to the page now

#

but cant access "data"

eternal kestrel
#

funny one

#

thanks

ornate flame
#

https://forum.djangoproject.com/t/request-to-join-hindi-translation-team/12214 please help 😦 i cannot join the team as it shows language does not exist but it does!

native tide
#

Hi I’m curious why are there classes created in the views.py file of a Django project?

unique shore
#

They are functions that take and return web requests

native tide
#

Thanks. I’m trying to figure this first step. What does it mean and what am I doing?

#

This is from tutorial

unique shore
#

must be new

native tide
#

What does the context part mean?

unique shore
#

It should work the same way

#

Prolly has to do with the current thing you are editing

#

You can add your own implementation of get_context_data

#

But by default it adds the object being displayed

native tide
#

So I’m calling the function out when I mention m “RED” in the base.HTML file in the case mentioned above.

unique shore
#

Well look at the comment to the side

native tide
#

I wrote those look

#

Lool

#

Oh yea it does so RED is a variable name to call the function

unique shore
#

mhmm

weary spear
#

Hey! Is there any resource that would help me to build an update system?
I mean I'm updating the github repo and app is detecting newer version it will ask user to update and eventually update the app?

trim spire
#

I am using Flask.
I want to create a system similar to Kahoot, where one can generate a room (which will generate an ID). How can I make that room joinable by using <url>/ID

Should I generate a new HTML page for each room?

unique shore
#
@app.route(“/rooms/<id>”)
def rooms():
    pass
#

you are looking for dynamic routes. You can find many things about these online

agile pier
#

Is there a way I could have 2 options for adding data to django models? one is manually enter the data in the fields or another option is to upload the csv file
Like a OR option type of thing?

cerulean thicket
#
    images= cv2.cvtColor(images, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'``` how to fix this error ?
agile pier
wet meadow
#

My js code as below =

var listOfItems = ["images/dice1.png", "images/dice2.png", "images/dice3.png", "images/dice4.png", "images/dice5.png", "images/dice6.png"]

var randomNumber1 = Math.round(Math.random()*5+1)
var randomNumber2 = Math.round(Math.random()*5+1)

var dice1RandomImages = listOfItems[randomNumber1 - 1]
var dice2RandomImages = listOfItems[randomNumber2 - 1]

function winner() {
  document.querySelectorAll(".img1").setAttribute("src", dice1RandomImages)
  document.querySelectorAll(".img2").setAttribute("src", dice2RandomImages)

  if ((randomNumber1 > randomNumber2) == True) {
    document.querySelectorAll("h1").innerHTML = "Player One Wins!"
  }
  else if ((randomNumber1 < randomNumber2) == True) {
    document.querySelectorAll("h1").innerHTML = "Player Two Wins!"
  }
  else {
    document.querySelectorAll("h1").innerHTML = "Draw, Roll again"
  }
}
winner()

And in my html code i put the js script code link near the bottom of body like

<head>
<!-- Code -->
</head>
</body>
<!-- Code -->
<script src="index.js" charset="utf-8"></script>
</body>

And there are 6 dice images so why isnt my code appearing?

golden bone
native tide
#

I’m getting a 404 error. Django tried to use URL patterns admin/ and Calc/ and didn’t match any of these. What could be the reason?

#

What is the main reason for 404 error?

unique shore
#

404 not found means that the page wasn’t found

dim rover
#

what page are you trying to get to?

native tide
#

Interesting I looked at urls and doesn’t seem to find no error in what I type

#

To a page calcs.html

#

Surely admin.html will work. That’s standard?

unique shore
#

Doesn’t seem like you saved the file

native tide
#

Saved and retried.. same response

unique shore
#

do you have a view for calcs/

native tide
#

Yes

#

I will show you

dim rover
#

and whats in calc/urls.py

unique shore
#

^

native tide
#

And my calc.html

#

Calc/urls.py file

lavish prismBOT
#

Star / Wildcard imports

Wildcard imports are import statements in the form from <module_name> import *. What imports like these do is that they import everything [1] from the module into the current module's namespace [2]. This allows you to use names defined in the imported module without prefixing the module's name.

Example:

>>> from math import *
>>> sin(pi / 2)
1.0

This is discouraged, for various reasons:

Example:

>>> from custom_sin import sin
>>> from math import *
>>> sin(pi / 2)  # uses sin from math rather than your custom sin

• Potential namespace collision. Names defined from a previous import might get shadowed by a wildcard import.
• Causes ambiguity. From the example, it is unclear which sin function is actually being used. From the Zen of Python [3]: Explicit is better than implicit.
• Makes import order significant, which they shouldn't. Certain IDE's sort import functionality may end up breaking code due to namespace collision.

How should you import?

• Import the module under the module's namespace (Only import the name of the module, and names defined in the module can be used by prefixing the module's name)

>>> import math
>>> math.sin(math.pi / 2)

• Explicitly import certain names from the module

>>> from math import sin, pi
>>> sin(pi / 2)

Conclusion: Namespaces are one honking great idea -- let's do more of those! [3]

[1] If the module defines the variable __all__, the names defined in __all__ will get imported by the wildcard import, otherwise all the names in the module get imported (except for names with a leading underscore)
[2] Namespaces and scopes
[3] Zen of Python

dim rover
#

so calcs/* is supposed to go to this one thing ?

unique shore
#

import the specific view

#

the urls.py for calc should be something like:

urlpatterns = [
    path(‘calcs/something/‘, views.your_view).
]
#

you can change the import to from . import views and prefix your views in the path with views.

native tide
#

Surely import * will just import everything

#

I don’t have to specific

dim rover
#

oh dont you need a default route

unique shore
#

^

#

there is no default

#

so maybe do /calcs/ in the url

native tide
unique shore
#

Because it seems like you are on what would be the index

#

And there is no index route from what it seems like

dim rover
# native tide

seems like empty string
path("", CalcView.as_view ... might have been right, there

native tide
#

The tutorial made it empty

#

I followed it and I have done it while empty before

unique shore
#

put a / in the quotes

native tide
#

Ah might be that

#

Let’s see

#

Nope

unique shore
#

something must be fucked up with your routes then

native tide
#

Within command line?

unique shore
#

wdym

native tide
unique shore
#

trailing /

native tide
#

What will do follow the tutorial step by step and see if I missed anything

unique shore
#

Ok

#

Come back if you need help

native tide
#

Sure thanks moai 🙂 and greyblue

native tide
#

I changed some of it like static ended with / shown in video.

#

I still get the ‘/‘ error

native tide
#

At the bottom of the page, it tells you how to do it. I think you have to change your settings file

unique shore
#

anchor tag in html?

#

oh proper error web page

#

didn’t see the error thing

#

that’s only there because you are in debug mode

#

you can specify the error and render html templates for it in views file for the app where you wanna do that

#
def error_404(request, exception):
    data = {}
    return render(request, ‘path_to_html_file’, data)
#

And you have to specify them in the projects urls

#

You’d have to change DEBUG to false also

#

in urls.py: handler404 = 'myappname.views.error_404'

native tide
#

I'm using selenium to do a automated login, the website has cloudflare, I have bypassed the cloudflare, but when trying to get a element I feel like the website is not loading in time to get the element
[3:29 PM]
I have tried time.sleep and 'wait' in the selenium docs and both hold cloudflare would anyone have a solution for this

golden bone
#

But if it's really a Cloudflare issue, can't help you there

ocean raft
#

ayo

#

any django peeps here?

jolly cosmos
#

Hi ı have one question

simple garden
#

what does new Date(userinput) do?```js
var userinput = document.getElementById("DOB").value;
var dob = new Date(userinput);
if(userinput==null || userinput=='') {
document.getElementById("message").innerHTML = "**Choose a date please!";

native tide
#

Ok I just made a todo list app

#

Now I want to input a script into so when an input of an integer is entered, a calculation will be made and answer will come out. Is there resources to look at to do this?

gray spire
#

Hiii, does anyone have any experience in making web applications on spring boot?

golden bone
dull cargo
#

Hi guys! I have a small project that needs like/unlike API using flask restx api. My endpoint is "/int:post_id/like". I use POST method to like/unlike a post but it is not relevent in POST (i mean we do not pass an argument in POST). Could someone give me an idea? Should i change to PUT?

golden bone
# dull cargo Hi guys! I have a small project that needs like/unlike API using flask restx api...
sinful flare
#

anyone can explain to me what flask app_context means please

#

with app.app_context()

mint spear
#

I have seen this syntax first time in my life in python which appears to be C-like: print ("Second element = %d" %(a[1])) please someone explain it to me because it doesn't have a comma to separate string and format specifiers. It's weird.

inland oak
inland oak
#

!e

a = [2, 3]
print("Second element = {:d}".format(a[1]))
lavish prismBOT
#

@inland oak :white_check_mark: Your eval job has completed with return code 0.

Second element = 3
inland oak
#

although I prefer f strings

coarse torrent
lavish prismBOT
#

@coarse torrent :white_check_mark: Your eval job has completed with return code 0.

Second element = 3
inland oak
#

👆 f-strings

native tide
#

btw the info stored in a session is destroyed as soon as we leave the site right? and session is used to store sensitive info like usrname and pass , so if we click on save username and password option then is our usernme and pass stored in cookies ??
coz cookies remember the info for a long time? like a cookie with a long time to expire ?

inland oak
#

usually

native tide
inland oak
#

xD, not really the best place to ask about it

native tide
#

oop sorry

queen snow
#

how can python be used for web dev?

sinful flare
#

anyone here good with flask i need help

rigid loom
#

I'm afraid we don't allow any form of recruitment here, as per our #rules.

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied ban to @reef cave until <t:1645957501:f> (6 days and 23 hours).

agile pier
#

how do make organisation field compulsory and then have an option to either upload csv file or enter the data manually

lilac gate
#

I'm trying to add a table that's within a form to a <details> tag in HTML5. The table looks normal, but when I add the details tag it then causes this disaster. Any ideas?

mint spear
#

but it is working in python3 shell as well

#

@inland oak @coarse torrent are both of your formats same? I am confused now.

coarse torrent
# mint spear <@!370435997974134785> <@!854125488707993650> are both of your formats same? I a...

My format is f-strings:

f"3 + 2 = {3 + 2}"

In f-strings, you can insert any expression that does not contain the same type of quotes as your enclosing string (here ") between curly braces to have it evaluated, then turned into a string via str.

The other format is using str.format():

"{:d} {:s}".format(20, "test")

In this way of using format, the letters after the colons specify how it will be displayed. Some options:
:d Number
:s String
:x Hexadecimal
:n Number, but with localized digit separators
:b Binary
:o Octal

#

!d str.format

lavish prismBOT
#

str.format(*args, **kwargs)```
Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces `{}`. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

```py
>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
```  See [Format String Syntax](https://docs.python.org/3/library/string.html#formatstrings) for a description of the various formatting options that can be specified in format strings.
hidden sentinel
#

Help!!

#

Pls

mortal grotto
#

can i know why we need django or other framewark to create web applications if we can do this with javascipt and why some people use both instead of one and what's the different between them

unique shore
#

mostly because people hate working with JavaScript afaik

#

and WebAssembly exists too

mortal grotto
#

so it means we can use javascript in backend

unique shore
#

you can, with node.js

#

javascript is both frontend and backend'

mortal grotto
#

and why pepole prefer python over java at backend

unique shore
#

python is mainly backend

#

java or javascript?

mortal grotto
#

and can i know why we can not use python in front end

#

is there any way creating dynamic website using only python

unique shore
#

well, web browsers can only read JavaScript. But, WebAssembly exists now so I guess you can create the frontend in languages other than JS

mortal grotto
#

what is webAssembly

#

i have heard about it

unique shore
#

you cna probably use a preprocessor to convert python to js and back

mortal grotto
#

and should we?

unique shore
#

its a binary instruction format that allows you to create web apps in languages other than JS

#

ehh idk

#

i would still learn and use JS if you are doing any web dev'

mortal grotto
#

ohh

#

thnx for clearing

#

my doubts

unique shore
#

once you learn JS though, use TypeScript instead

#

its a superset of JS

#

with type system

mortal grotto
#

ok i will see

unique shore
mortal grotto
#

but i'm confuse right now if i should go for web development

#

i am beginner and know python and tkinter

unique shore
#

also WASM supports:

  • C/C++
  • Rust
  • AssemblyScript
  • C#
  • F#
  • Go
  • Kotlin
  • Swift
  • D
  • Pascal
  • Zig
  • Grain
#

@mortal grotto well think about why you want to program. what do you want to make?

#

don't just do web dev because everyone else does it

mortal grotto
#

idk but i want to go into ML

#

but not confident enough right now

unique shore
#

well then do ML

mortal grotto
#

so i 'm thinking first i should clear some concepts of math and get grasp at programming logic

unique shore
#

yeah prolly

mortal grotto
#

then should jump into ML and stuff

stuck trout
#

@mortal grotto Confidence comes after action, not beofre

unique shore
#

^

stuck trout
#

if that's helpful...

unique shore
#

python has many good machine learning libs like TensorFlow, NumPy, and PyTorch

mortal grotto
unique shore
#

but we should prolly move to an ot channel as this channel is for webdev

#

!ot

lavish prismBOT
mortal grotto
unique shore
#

we can move to the OT channel though

mortal grotto
#

and how?

unique shore
#

!ot

lavish prismBOT
unique shore
#

just press that blue thing next to off-topic channel

drowsy fossil
#

Hey can some suggest me content to understand rest framework in django

inland solar
#

is developing an ecommerce website a good idea?

deft willow
#
 The page at 'https://dashboard.breadbot.me/server/744176742540771368?sidebar=levels' was loaded over HTTPS, but requested an insecure resource 'http://dashboard.breadbot.me/change/rewardadd/744176742540771368/'. This request has been blocked; the content must be served over HTTPS.

why is this happening to me when i use fetch in js?

agile pier
agile pier
#
class asset_inventory(models.Model):
    organisation = models.ForeignKey(organisation, on_delete = models.CASCADE, null = True)
    Upload_CSV = models.FileField(null = True, blank=True)
    asset_name = models.CharField(max_length = 20, null = True, blank=True)
    asset_type = models.CharField(max_length = 255, null = True, blank=True)
    technology = models.CharField(max_length = 255, null = True, blank=True)
    ports = models.CharField(max_length = 255, null = True, blank=True)
    services = models.CharField(max_length = 255, null = True, blank=True)
    first_discovered = models.DateTimeField(editable=False)
    last_discovered = models.DateTimeField(editable=False)
    status = models.CharField(max_length = 20, choices = choices, null = True, blank=True) # remove this?
    
    def save(self, *args, **kwargs):
        filename = self.Upload_CSV.url
        # filename[6] += "csv/"
        print("C",filename)
        with open(filename, 'r') as f:
            readerr = csv.reader(f)

            for i, row in enumerate(readerr):
                if(i == 0):
                    pass
                else:
                    # row = "".join(row)
                    # row = row.replace(";", " ")
                    print(row)
        ''' On save, update timestamps '''
        if not self.id:
            self.first_discovered = datetime.datetime.now()
        self.last_discovered = datetime.datetime.now()
        return super(asset_inventory, self).save(*args, **kwargs)  
#

the error is in with open(filename, 'r') as f:

molten token
#

Not so infosec anymore ;p

#

Check path, permissions

surreal jungle
#

How do we start with web dev

cursive rampart
#

I've got a question, I am creating a "program" wich tells you if ur password is strong or not, just a simple program but I'd like to combine my python low skills with my HTML low skill, how can I create an interface in HTML for my python project?

deft willow
#
 The page at 'https://dashboard.breadbot.me/server/744176742540771368?sidebar=levels' was loaded over HTTPS, but requested an insecure resource 'http://dashboard.breadbot.me/change/rewardadd/744176742540771368/'. This request has been blocked; the content must be served over HTTPS.

why is this happening to me when i use fetch in js?

mystic wyvern
native tide
#

Can I please have a pytest guide?

native tide
#
        Q(topic__name__icontains=q),
        Q(name__icontains=q),
        Q(description__icontains=q)
        )```
#

why is this not filtering by description and name??

native tide
#

Hi I tried to deploy an app and I received a “no matching host key type. Their offer: ssh-rsa” error. Any ideas what I should do?

sinful flare
#

hello i want to know what does it mean the word "contexts" in flask or python

unique shore
misty swan
#

basically this is how I would want it to work

#

Seems like a simple task, but I'm not sure what I'm doing wrong

harsh zinc
#

anyone know how i could store user data with a post request on nextJS?

agile pier
#

why is this error coming while adding a django model data

#
class asset_inventory(models.Model):
    organisation = models.ForeignKey(organisation, on_delete = models.CASCADE, null = True)
    Upload_CSV = models.FileField(upload_to ='csv', null = True, blank=True)
    asset_name = models.CharField(max_length = 20, null = True, blank=True)
    asset_type = models.CharField(max_length = 255, null = True, blank=True)
    technology = models.CharField(max_length = 255, null = True, blank=True)
    ports = models.CharField(max_length = 255, null = True, blank=True)
    services = models.CharField(max_length = 255, null = True, blank=True)
    first_discovered = models.DateTimeField(editable=False)
    last_discovered = models.DateTimeField(editable=False)
    uploaded = models.BooleanField(default=False)
    status = models.CharField(max_length = 20, choices = choices, null = True, blank=True) # remove this?
    
    def save(self, *args, **kwargs):
        ''' On save, update timestamps '''
        if not self.id:
            self.first_discovered = datetime.datetime.now()
        self.last_discovered = datetime.datetime.now()
    
        super(asset_inventory, self).save(*args, **kwargs)
        print("F", self.Upload_CSV == None)
        if self.Upload_CSV != None:
            filename = self.Upload_CSV.path
            with open(filename, 'r') as f:
                readerr = csv.reader(f)

                for i, row in enumerate(readerr):
                    if(i == 0):
                        pass
                    else: 
                        print(row[0])
                        asset = asset_inventory.objects.get(id=self.id)
                        print(asset.id)
                        asset.asset_name = row[0]
                        print("C", asset.asset_name)
                        asset.save()

        return super(asset_inventory, self).save(*args, **kwargs)
native tide
#

Hiii

#

anyone please send me some cool django projects

willow root
willow root
#

for the first step I would recommend making some random websites ideas like online shop, streaming platform etc..

#

with just html and css

#

and then make some simple projects like calculator or todo with javascript (also using your skills with html and css)

#

to learn anything first just watch videos on youtube, when you are experienced enough you can try reading documentation

native tide
#

?

nova eagle
native tide
#

guys i need help desperately

#

when i fetch an api with js how do i return the result of the fetch

#

mine's returning the promise object (telling me that it's pending)

golden bone
native tide
#

i made it

#

the api i mean

#

i have some troubles dealing with the fetch method

bright spindle
#

is there a way to tell django not to load fixtures when testing

#

it's literally taking too long to load for every test

trim spire
#

Using flask, how can I display Yes and No instead of True and False for boolean values on the site?

unique shore
#

booleans can only be True or False, so not sure

#

Whatever you are returning True or False on, prolly return Yes or No?

native tide
steel night
uneven radish
#

I have a form in Django like this and all these SELECT inputs are overflowing the width of my table layout.

I'm just using the form.as_table in Jinja.
This isn't exactly Python Web Dev related (more of Front-end issue)

#

Do I have to loop across the form fields and specify the max width something like that? Any help is appreciated.

ocean raft
#

Hey guys , Im trying to create 2 models in which you can post images and comment on them

#

'''

#
class Pizza(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE,null=True,blank=True)
    title = models.CharField(max_length=50)
    image = models.ImageField(null=True, blank=True,upload_to="images",default="white.jpg")
    description = models.TextField(null=True,blank=True)

    likes = models.IntegerField(blank=True,null=True,default=0)
    dislikes = models.IntegerField(blank=True,null=True,default=0)

    def __str__(self):
        return str(self.user)

class PizzaComment(models.Model):
    post = models.ForeignKey(Pizza,on_delete=models.CASCADE)
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    comment = models.TextField(null=True,blank=True)

    likes = models.IntegerField(blank=True,null=True,default=0)
    dislikes = models.IntegerField(blank=True,null=True,default=0)

    def __str__(self):
        return str(self.user)```
#
class PizzaCommentCreate(CreateView):
    model = PizzaComment
    context_object_name = "comment"
    template_name = "sky/pizzaCommentCreate.html"
    fields = ["comment"]

    def get_success_url(self):
        return reverse_lazy('pizza')

    def form_valid(self,form):
        form.instance.user = self.request.user
        return super(self,PizzaCommentCreate).form_valid(form)
ocean raft
#
  path('PizzaHub/',PizzaList.as_view(),name = "pizza"),
    path('PizzaDetails/<int:pk>',PizzaDetail.as_view(),name='detail'),
    path('PizzaCreate/',PizzaCreate.as_view(),name = "create"),
    path('PizzaUpdate/<int:pk>',PizzaUpdate.as_view(),name='update'),
    path('PizzaDelete/<int:pk>',PizzaDelete.as_view(),name="delete"),
    path("PizzaCommentCreate/",PizzaCommentCreate.as_view(),name="commentCreate")
#

the urls

ocean raft
#

im kinda stuck if anyone has resources or advice it would bee really cool

#

Django btw

trim spire
#

Using Flask, how can I toggle between asc and desc using /sort ?

@app.route('/sort')
def sort_list():
    places = Place.query.order_by(Place.name.asc()).all()
    return render_template("index.html", places=places)
bright spindle
#

also its rather tedious doing this for all tests

#

isnt there a way to set default no fixtures

native tide
steel night
# bright spindle It doesn't quite work if i just set all to []

You maybe can try out SimpleTestCase or TransactionTestCase? If you’re careful using them your tests will run much faster since it won’t recreate the entire test database between tests. However this means you have to be more careful not to introduce contamination of state between tests

celest hedge
#

guys, can anyone here help me solve this error?

TypeError: The view function for 'slow' did not return a valid response. The function either returned None or ended without a return 
statement.

i'm using flask

bright spindle
steel night
bright spindle
#

might be handy for v2, doe v1 is almost at its EOL

#

so rewriting tests is not worth the effort

#

thanks for the reference doe

forest sonnet
#

is rhere anything similar to this for django

#
#

i want to build a leetcode clone of sorts but im not sure how i can go aboit running submissions

steel night
#

Uhhh do you care if the result is secure

forest sonnet
#

no

#

i just wanna see it work

steel night
#

Because if no, you can just use ‘eval’ on strings your users submit. If yes, then you’re in for a large amount of complicated engineering effort

forest sonnet
#

not gna be using this for anything other than tht

#

oh wtf

#

i can eval

#

a whole python script?

steel night
#

As long as it’s valid in the current namespace

forest sonnet
#

so if i just ran

#

eval("def solve(i):
return i+1")

steel night
#

Or you could write the script a user submits to a temp file, then run via subprocess ‘Python temp file.py’ and capture the output

forest sonnet
#

itd actually work?

#

ohhhh

#

alr i'll put that into thought

#

that seems like an idea

#

alr tyty

#

can eval run functions or is thst not a thing

#

i dont have my editor with me rn :(((

steel night
#

See the section on “nested locals”. Executing a tempfile may be a more general solution

forest sonnet
#

hmmm i see

#

maybe the tempfile is the way to go

#

is it difficult to run a subprocess

#

im new w django and i honestly have no idea what im doing

steel night
sacred crane
#

gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> i am having this error while deploying fastapi in a docker

agile pier
#

how do i add data from csv file to django models?

#

I have created a function to read the csv file

deft willow
#
fetch(`/change/rewardadd/${format}`, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        "Accept": "application/json",
                        "Access-Control-Allow-Origin": "*"
                    },
                    body: JSON.stringify({newValue: {level: levelint, role: roleid}})
                });
 The page at 'https://dashboard.breadbot.me/server/744176742540771368?sidebar=levels' was loaded over HTTPS, but requested an insecure resource 'http://dashboard.breadbot.me/change/rewardadd/744176742540771368/'. This request has been blocked; the content must be served over HTTPS.

why is this happening to me when i use fetch in js?

summer kernel
#

Does anyone knows about website making ?

#

Send me dm pls

inland oak
#

Does anyone knows about website making ?

candid cradle
#

Who can help me with smoke test in django rest framework?

old hound
#

I have an application that runs asynchronously to my uwsgi app. Though when I hit the root directory, I want to be able to pull certain stats from that app (on the same system). What's the best way to implement this?

#

Would this be an instance where BaseManger would work?

manic crane
#

im trying build search functionnality in my django app i installed django filters but when i go to add it to installed apps i get : ModuleNotFoundError: No module named 'django_filterrest_framework'

native tide
#

Awesome I created ssh key and I see it in my user ssh file.

I did git push heroku master but I still get a “no matching host key type found”

old hound
#

@native tide what's the question? Just because you add a key to a repo doesn't mean it's used. You need to load and call it.

brisk creek
#

Hi. I have beginner experience in html/css + javascript. wanted to learn python and unfortunately have to make a website + a mobile app - what language would you guys recommend for the front-end?
I'm going into ML hence needing to use Python, but I've heard linking Python to html is not a good idea. I'm also not sure what the best lang would be for mobile dev w/ Python
I'm also going to incorporate NLP and an ML algorithm I don't know yet if that influences the recommendation at all

native tide
steel night
sacred crane
#
During handling of the above exception, another exception occurred:


Traceback (most recent call last):

File "/usr/local/bin/gunicorn", line 8, in <module>

sys.exit(run())

File "/usr/local/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 67, in run

WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run()

File "/usr/local/lib/python3.8/site-packages/gunicorn/app/base.py", line 231, in run

super().run()

File "/usr/local/lib/python3.8/site-packages/gunicorn/app/base.py", line 72, in run

Arbiter(self).run()

File "/usr/local/lib/python3.8/site-packages/gunicorn/arbiter.py", line 229, in run

self.halt(reason=inst.reason, exit_status=inst.exit_status)

File "/usr/local/lib/python3.8/site-packages/gunicorn/arbiter.py", line 342, in halt

self.stop()

File "/usr/local/lib/python3.8/site-packages/gunicorn/arbiter.py", line 393, in stop

time.sleep(0.1)

File "/usr/local/lib/python3.8/site-packages/gunicorn/arbiter.py", line 242, in handle_chld

self.reap_workers()

File "/usr/local/lib/python3.8/site-packages/gunicorn/arbiter.py", line 525, in reap_workers

raise HaltServer(reason, self.WORKER_BOOT_ERROR)

gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>

I am trying to run fastapi in docker but i am getting error. I am using docker run -d -p 8080:8080 onetest to run the container. I was unable to rectify this error. When i run the application without docker locally i am not facing any problem. I am having this problem with running fastapi with docker.

#
bind = "0.0.0.0:8080"
workers = 4
timeout = 300
worker_class = "uvicorn.workers.UvicornWorker"
``` gunicorn_config.py
sudden gulch
#

need help with django rest framework

#

i have a player model in which there is data of players including country they belong to

#

i have to create an api with return players grouped by country in json

#

{"japan":[list of player],"taiwan":[list of players]}

#

how can i create a serializer which can do this

inland oak
native tide
#

hey

#

i taught myself python

#

and wondering about web dev

#

do i need to get my hands into html, css, js or any other framework

lavish prismBOT
#

Hey @native tide!

It looks like you tried to attach file type(s) that we do not allow (.pdf). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.

Feel free to ask in #community-meta if you think this is a mistake.

native tide
#

also if you know the book beloiw is good or not

#

"Web Development with Django by Ben Shaw, Saurabh Badhwar, Andrew Bird"

still jay
#

I'm making an api using drf and using session authentication for the endpoints. While testing the PUT request I noticed that the url was making 5 queries. 1 of them was duplicate.

#
1. SELECT `django_session`.`session_key`, `django_session`.`session_data`, `django_session`.`expire_date` FROM `django_session` WHERE (`django_session`.`expire_date` > '2022-02-22 10:02:16.956277' AND `django_session`.`session_key` = 'y4o67bixcdql4slxtjq2d9yfkp11xm8s') LIMIT 21
2. SELECT `accounts_baseuser`.`id`, `accounts_baseuser`.`password`, `accounts_baseuser`.`last_login`, `accounts_baseuser`.`is_superuser`, `accounts_baseuser`.`first_name`, `accounts_baseuser`.`last_name`, `accounts_baseuser`.`is_staff`, `accounts_baseuser`.`is_active`, `accounts_baseuser`.`date_joined`, `accounts_baseuser`.`email`, `accounts_baseuser`.`id_number` FROM `accounts_baseuser` WHERE `accounts_baseuser`.`id` = 1 LIMIT 21
3. SELECT `accounts_baseuser`.`id`, `accounts_baseuser`.`password`, `accounts_baseuser`.`last_login`, `accounts_baseuser`.`is_superuser`, `accounts_baseuser`.`first_name`, `accounts_baseuser`.`last_name`, `accounts_baseuser`.`is_staff`, `accounts_baseuser`.`is_active`, `accounts_baseuser`.`date_joined`, `accounts_baseuser`.`email`, `accounts_baseuser`.`id_number` FROM `accounts_baseuser` WHERE `accounts_baseuser`.`id` = 1 LIMIT 21
4. SELECT (1) AS `a` FROM `accounts_baseuser` WHERE (`accounts_baseuser`.`email` = 'test@email.com' AND NOT (`accounts_baseuser`.`id` = 1)) LIMIT 1
5. UPDATE `accounts_baseuser` SET `password` = 'pbkdf2_sha256$320000$9RfVbFcF0TMLB9CY8beowq$J5DuRZEXAvzC21T7u7AtHf9UQCsMW8R63shQQg/ePkY=', `last_login` = '2022-02-22 10:02:16.947069', `is_superuser` = 0, `first_name` = 'Test', `last_name` = 'Update', `is_staff` = 1, `is_active` = 1, `date_joined` = '2022-02-22 10:02:16.539777', `email` = 'test@email.com', `id_number` = '111111' WHERE `accounts_baseuser`.`id` = 1
#

I used RetrieveUpdateDestroy api view for the endpoint.

#
class UserView(RetrieveUpdateDestroyAPIView):
    permission_classes = [IsAdminUser]
    queryset = models.BaseUser.objects.all().order_by("id")
    serializer_class = serializers.UserSerializer
still jay
inland solar
#

can anyone plz help me

native tide
#

hey guys me and my friends re making a web application, if anyone interested pls dm me personally. we originally need people who are good at Html5, CSS, Python and anyone good at vue.js framework(this is not a paid job, no one is getting paid)

golden bone
# inland solar

It says there is a problem with the package, so look into that. Also, you want to use a virtual environment... in addition to protecting.yourself from other disasters, it may potentially resolve the error

coarse ivy
#

Can anyone tell me best resources to learn django?

warm cove
#

lmao if u wanna be a web dev use js and actual web dev languages

mental summit
lavish prismBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

mental summit
#

You’ll need to filter it to web development and look for the ones on Django

surreal shuttle
agile pier
#

i have this model field with 3 choices

#

how do I display all those 3 choices on the client side and also let them update it?

jaunty magnet
#

how old is too old for a backend package? For instance, flask-login hasn't had a single commit for the last 8 months. Is that bad?

atomic horizon
#

i have a slightly dumb question -- I am just getting started with django and have built a basic blog with a login, registration, password reset, etc. I'm really enjoying the django interface and would like to use it as my back-end for a web app. I will likely be using React for the front-end design.

However, when someone goes to my website, I want it to first have a typical marketing approach: homepage, about us, FAQ, about us, etc. Then the subscribe/login/get started attached.

For those who have built web apps, but also have a project site built like a regular website -- do you still use django for the whole thing? Or do you, for example, build the site separately and then have it link to the web app django project when users register and login?

For either option: What would you recommend?

inland oak
inland oak
#

No problem to link custom login form from react to Auth in Django

atomic horizon
atomic horizon
#

whoops, meant django rest

inland oak
#

Not getting last question too

atomic horizon
#

need another coffee lol

inland oak
atomic horizon
#

Like this? @inland oak Roadmap:

Create project using Django + Django React API ▶️ Build web app inside django project

Using the same back-end, build the company site within the project under its own separate folder directory to hold css templates, pages, etc

atomic horizon
#

So you create a django project as usual, then essentially add django react on top of it -- or integrate it

inland oak
#

Yes

native tide
#

ik this is dumb but anyone know how to get a discord server id using a api if you know the api pls tell me

jaunty magnet
atomic horizon
# inland oak Yes

Then Django Rest API takes care of the hooks to essentially link the company site with the web app as one functioning environment?

inland oak
native tide
#

ik this is dumb but anyone know how to get a discord server id using a api if you know the api pls tell me

jaunty magnet
agile pier
atomic horizon
steel night
#

django-rest-framework has pretty great documentation on setting up REST APIs in django

#

see @inland oak 's link above

inland oak
atomic horizon
#

brilliant, thank you both!

inland oak
#

YouTube learning is a waste of time to me

#

Really bad quality and full of water

#

Docs and books are superior by magnitude

atomic horizon
#

Agree with books for sure, I finished automate the boring stuff recently and loved it.

#

Thanks again for your time.

inland solar
karmic robin
#
import * as React from 'react';
import { Text, View, StyleSheet, Button, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';
import AssetExample from './components/AssetExample';
import { Card } from 'react-native-paper';
import { useState } from 'react';
export default function App() {
  const [subtotal, setSubtotal] = useState(0);
  const [numDiners, setNumDiners] = useState(0);
  const [tipPercentage, setTipPercetnage] = useState(0);
  const [result, setResult] = useState({});
  const styles = StyleSheet.create({
    screenContainer: {
    flex: 1,
    justifyContent: "center",
    padding: 16
  }
});
  const submit = (e) => {
    e.preventDefault();
    if (+subtotal <= 0 || +numDiners <= 0 || +tipPercentage <= 0) {
      return;
    }
    const total = +subtotal * (1 + +tipPercentage);
    setResult({ total, totalPerDiner: +total / +numDiners });
  };
  return (
    <div className="App">
      <form onSubmit={submit}>
        <fieldset>
          <label>Subtotal: </label>
          <input
            value={subtotal}
            onChange={(e) => setSubtotal(e.target.value)}
          />
        </fieldset>
        <fieldset>
          <label>Amount of People Sharing Bill: </label>
          <input
            value={numDiners}
            onChange={(e) => setNumDiners(e.target.value)}
          />
        </fieldset>
        <fieldset>
          <label>Tip Percentage: </label>
          <select
            value={tipPercentage}
            onChange={(e) => setTipPercetnage(e.target.value)}>
            <option value="0">0%</option>
            <option value="0.05">5%</option>
            <option value="0.1">10%</option>
            <option value="0.15">15%</option>
            <option value="0.2">20%</option>
          </select>
        </fieldset>
        <View style={styles.screenContainer}>
      <Button title="Calculate Tip" 
              type="submit"
              onPress={() => this.handleButtonPress()} 
              />
    </View>
      </form>
      <p>Total Amount: {' $'} {result.total && result.total.toFixed(2)}</p>
      <p>
        Total Per Diner:{' $'}
        {result.totalPerDiner && result.totalPerDiner.toFixed(2)}
      </p>
    </div>
    
  );
 
  
}
#

could anyone help me figure out why my button wont submit the form?

indigo kettle
#

I don't think you need an event handler from on your button

#

also is this.handleButtonPress defined somewhere?

#

what is that

still jay
karmic robin
# indigo kettle what is that

I'm supposed to make this look better..
https://thewebdev.info/2021/01/26/create-a-tip-calculator-with-react-and-javascript/

I honestly don't know what I'm doing so I need to go learn some stuff haha

Spread the love Related Posts Create a Tip Calculator App with Vue 3 and JavaScriptVue 3 is the latest version of the easy to use Vue JavaScript framework that… Create a Tip Calculator with Vue 3 and JavaScriptVue 3 is the latest version of the easy to use Vue JavaScript framework that… Create a Counter […]

still jay
karmic robin
still jay
#

Try this.

  1. use a custom hook to handle input
    const [value, setValue] = useState(initialState)

    function handleChange(e) {
        setValue(e.target.value)
    }

    return [value, handleChange]
}```
#
  1. Use the custom hook like this
const [name, setName] = useInput('')
  1. In the form fields
onChange={setName}
#

just make sure you have your button as type="submit in the form

#

I don't think you need to handle onClick directly for submit buttons

#

I could be wrong though

#

in your onSubmit

const dispatch = useDispatch()
const onSubmit = (e) => {
        e.preventDefault()
        const obj = { name, ... } //  Your states
        dispatch(yourFunc()) // if you're using redux you'll need to use useDispatch
    }
karmic robin
#

I will try this, thank you so much!

still jay
still jay
karmic robin
still jay
karmic robin
#

real world experience lol

silent wave
#

Hola, since you're Web Devs^^ i think you could help me with a Webscraping problem

Does someone of you know if it would work, when i load the Values of my Mozilla Cookie into my Script and then run the same Webpage with that Script?

Because i'm struggling with a JS Login on my Python Script and i thought that could be one way, but i havent tried it and nobody could tell me if it would work

agile pier
#

anyone worked with ajax?

frank shoal
lament copper
#

Can someone point me to some good resources for web dev/hosting?

proper hinge
#

I am writing a custom migration in Django. In my operations, I first have an AlterField and second a RunPython which also has a function for reverse_code. When Django reverses this migration, does it run the RunPython operation first?

#

The AlterField is adding a unique constraint. When I revert the migration, I get a unique constraint violation from my RunPython. Thus, it seems RunPython goes first, but it relies on the unique constraint being removed before running.

#

I may try to split AlterField into two operations - one that allows nulls and another that removes the constraint. Then my RunPython should be able to go between I think. Not sure if there is a better way.

steel night
#

What does the the RunPython command do? nvm actually read the snippet

#

But anyway in my experience Django does run the migration operations in the order listed, and in reverse order when running a reverse migration. So I think what you proposed makes sense.

proper hinge
#

Thanks. It turns out I would have had to split it up anyway for other reasons.

#

I needed to implement this as well https://stackoverflow.com/a/1934764 and as per the comment, I need to set null=True and change the field type separately. So I can just apply the null constraint when I change the field type. This has worked for me.

glass island
#

I am kinda good at flask I know how to use it but I want to know about backend web dev and indepht

#

what should I learn?

inland oak
#

So, it begins from
System analysis and design to plan your backend

And continues with
OOP, Design patterns, clean code, TDD, DDD and different Robert Martin books

Optionally getting to know Infrastructure as a code at least at minimal level or higher

#

Because backend is quite merged with DevOps/infrastructure
CI CD is included into it

unique shore
#

CI/CD

#

you should also know how to make APIs, use cloud services, mess with databases, linux proficiency, etc

glass island
#

I'm good:
clean code

need to learn more:
design
design patterns

to learn:
system analysis
tdd ddd

inland oak
inland oak
#

It makes biggest jump in code quality, by ten times
And with minimal effort

glass island
warped kernel
#

I'm not gonna make a call on that, since I'm never active in this channel and not very informed on web development. Link to the message in #community-meta and ask for it to be pinned, and someone more knowledgeable can make the call.

glass island
#

alright!

inland oak
glass island
#

you really pulling me down into the rabbit hole

inland oak
velvet yew
#

Can someone recommend an API documentation solution (for Django) that comes with code examples? I don't like Swagger UI nor ReDoc

inland oak
#

It is universal documenting tool for Python, that as a result compiled into static html,CSS,js files

#

Not just for APIs

velvet yew
#

I'm looking for an API one

#

That doesn't look like absolute garbage like that does

#

Stoplight is what I'm considering currently, just trying to see what people are using

#

(a lot of big names use that so it's promising but still looking for alternatives just in case)

agile pier
frank shoal
#

Just use fetch

inland oak
#

Fitting to be used as a heavy artillery against any type of problem

#

At the cost of higher CPU and RAM consumption

inland oak
#

Be lazy, steal it from bootstrap

#

And? Bootstrap can be still used

#

If u need range spider

#

Or I did not understand what do u mean by range slider

#

Looks like regular slider
Which u can implement
With any frontend means.
On your own
Or by taking from bootstrap

#

It would be easier to implement custom slider in frontend framework

#

But bootstrap should work in backend as alternative

#

Or any other CSS framework

#

Mine too

#

So what is the problem then

#

And

inland oak
#

I have a feeling like u a just missing html/CSS/js basics

#

Perhaps to read it first

#

Then learn js

#

I am lazy to read your code.

I can just say that general idea what u need to do in

Making slider custom or bootstrap.
Attaching yourself with JavaScript event to listen to value of slider changes or drop down mouse thing to finish.

When necessary event happens, u fetch/Axios whatever js request to your API.
Using data u update DOM values.
Client side in backend is painful, u should consider making just post request with full rerender of page (instead of js requests)

Or it can be done in a nice way with frontend framework, which should be needed here to scale the code

#

U have an option to make it almost without js by just making post request for full rerender, but this solution is bad because requires full page rerender

#

And it will be just bad to scale

#

In reality you need frontend framework here, like react/Vue to make it beautifully easy

#

It will be brain dead simple to implement there

#

U can implement what u wish with just vanilla js/jQuery but in my opinion those tools should not be used in 2022 year unless absolutely necessary

#

U will need to learn vanilla js anyway, in order to understand what u a doing in frontend framework

#

At limited level sufficient to use frontend framework for small projects

#

With Vue.js and Django as rest API

#

I used opensource VPN protocol wireguard under the hood

slow flint
#

Has anyone worked on augmented reality ? I need some help

native geode
#

ok

graceful igloo
#

Hi guys. What are some free ways to host a static website? If any.

unique shore
#

But the domain cost money

open crag
#

message2 = render_to_string('email_confirmation.html',{
'name': myuser.first_name
'domain': current_site.domain
'uid': urlsafe_base64_encode(force_bytes(myuser.pk))
'token': generate_token.make_token(myuser)
})

#

is here any syntax error..?

inland oak
graceful igloo
#

Is it possible to keep everything at 0$? I’m not good with money stuff irl. And I want to do this to show off to employers

inland oak
#

if it will be python application? it would be more challenging.

graceful igloo
#

It would be a Python application. With HTTML and CSS

#

Why is that more challenging?

inland oak
#

you need to use Linux machine instance or some sort of bastardized python application service like Heroku

#

AWS gives free Linux instance to use up to 1 year from your first registration

graceful igloo
#

I have a Linux machine virtualized? Also I think my friend used Dockers to do hers.

graceful igloo
#

Well. I guess my virtual machine can’t serve yeah

inland oak
#

it would not be public though 😉

#

since it is within only your local dev machine

graceful igloo
#

I see. I guess it’s Heroku or GitHub pages then?

native tide
#

I am trying to make a website called quipswap. Basically the functionality is that you can create a quip which is a small image and you can send that to someoen on your friends list, so basically in the app, everyone has a list of quips they created, a list of quips they can see because it was shared to them, and a page to make a quip

#

how would I set up the database for this?

inland oak
#

while your machine is online

inland oak
#

Google for half of a year

#

AWS a year

#

Azure dunno

native tide
#

the page to make a quip would allow them to add an image, and a multiple select element to select the friends they want to send the quip to

graceful igloo
#

If possible Darksind can I DM you about this? I don’t want to keep talking about it because others want to post there questions

inland oak
#

DMs are quite rude to other people's time

#

when you ask in public, you are answered by any willing free person that has time at the moment

#

with DM you are occupying and pestering particular person

graceful igloo
#

Sorry Dark. I’m still getting used to the world

#

But anyways. I think I’ll keep working on my flask

inland oak
#

Ask right questions, you will get the answers 😉 Nice of you at least to ask before trying DM

graceful igloo
#

And then maybe pray I can get something going with one of the pre IOU’s let mentioned things

native tide
#

ok so I'm working on a website that allows for users to share images to people in their friends list, the functionality to share images, is that you have a form that takes in an image and you have an element where you select all the friends you want to share it with.

#

how would I store this in the database so for any given user, I can query all the posts that they have created and all the posts that have been shared to them

inland oak
#

Feel free to create any other alternative schemes, that's just as first suggestion

native tide
#

so if I created a post and shared it with 3 friends, we would have to create three sharing_links "objects" if you will

inland oak
#

Feel free to send Queries in Bulk method, so you could send it in one request to database instead of multiple ones

native tide
#

Helpppppp!

inland oak
#

Runs away in a fear of unknown

native tide
#

If someone click on button so the page refresh and give another button without changing the url

manic crane
#

im trying to add search functionality to my django backend i have 'django_filters' in my installed apps and i keep getting this error ModuleNotFoundError: No module named 'django_filters'

violet ice
#

How we can identify user devices for every login and for new device send alert as google do
How we can identify user devices as google do

if we do log in with a new device, then google sends an email alert..

I am using custom login with email/password

I tried user-agent but that is not working..

I want to save the user device in DB and every login wan to check the device if same that is ok or if new then will send the mail

Any suggestion/example

I am using flask for my all APIs

weary spear
#

Hey guys! I'm working on a simple API to learn how to work and develop it. This is a no-name restaurant order and I'm not sure how to build the json array correctly:

    "products": {
        "product":{
            "_id": "asdf1",
            "name": "Burger menu",
            "addons": "",
            "price": 12.99,
            "currency": "EUR"
        },
        "product":{
            "_id": "asdf1",
            "name": "Chicken burger",
            "addons": "Spicy sauce",
            "price": 6.99,
            "currency": "EUR"
        }
    }
}```

For sure I have duplicate `product` key in here + how could I get all prices from here to sum it up?
#

I have idea for products

{
    "products": {
            "ids": 
                {
                  "asdf1",
                  "asdf2",
                  "asdf3"
                 },
        }
}

But I'm not sure how to add here the rest of the details like name, price etc in here

smoky skiff
#

Hi! I'm trying to learn Flask so I've been playing with it and reading about the last couple of days. Now I'm doing a personal project to get my hands dirty. My ideas is to make something similar to smallpdf.com. A site that lets you upload stuff, process it, and then serves it back.

I can already let the user upload the files and I know how to serve them, but I’m wondering if I’m building it in the correct way.

My idea was to give the user a session id so I can serve them back their own processed file and not mix them up (if someone else is using the webapp at the same time) then deleting both files so as to not run out of space.

I wonder if anyone has a video or a guide that builds a site kinda like that so I can compare. I feel I would build it in a way that’s not flask-y

#

I don't know if I can link to a pastebin to give a better idea of how I've been building it so far

native tide
#

How i make button which refresh page and give a new button without redirect in flask

native tide
agile pier
#

i also don't know much but u can look more about ajax

#

it may do the work which u need

native tide
dense slate
#

You need javascript to do what you want.

native tide
urban ridge
#

hi guys, quick question: how do files get uploaded to s3? Im using django storages and facing problems uploading large files. do the files go to the server first them s3? or directly from client to s3?

inland oak
#

So obvious thing to do would be, uploading to server first and from it to S3 bucket

#

But at the same time, this creates doubled traffic and the biggest concern about it is TRAFFIC LIMITS which are charged for you

#

I know that DigitalOcean is not charging for transfers to S3 bucket from servers located in the same LOCATION as S3 bucket

#

which eliminates the problem

twin kestrel
#

could someone help me create a flask application which can be used with a tensorflow/keras model

topaz widget
#

Not exactly Python-related, but does anyone know of a trutstworthy ad-blocker extension?

inland oak
#

for super sensitive stuff I operate without all extensions in incognito pages just to be sure though

vivid canopy
autumn veldt
#

i need to run this flask code:

import flask

from flask import *


app = Flask(__name__)


@app.route("/")
def index():
    return "hello"

on my network so i can go to this from my phone for example when i run this command:

flask run -h 0.0.0.0 -p 80

its not working on my phone but it dos work on my own pc why is that ?

#

please help me

amber zephyr
#

hello
not sure this is the best channel for this question, but:

I'm trying to retrieve the url to an image from the COCO dataset (for instance, https://cocodataset.org/#explore?id=216739)
the issue is that this image is loaded dynamically/takes a while to load (javascript? dunno!);

I've tried using urllib and requests, but cannot get the HTML with the full content (or, at least, the url of the image, http://farm3.staticflickr.com/2794/4190008256_fb66764971_z.jpg)
I've checked for solutions online, nothing worked; I don't want to use selenium
suggestions?

surreal shuttle
autumn veldt
worldly furnace
topaz widget
amber zephyr
# topaz widget Why don't you want to use selenium? This is the tool for the job.

unnecessarily complicated for what I need
I'm able to use the cocoapi that has been written in Python, but for that I need to download a 240MB ZIP file with the image annotations
unfortunately they didn't write an API where I can simply input 'image ID' (an integer like 216739) and get the image back
I also saw that the package 'requests-html' exists... but not for Windows

zenith sand
#

How do I change text in a HTMl file after I already rendered the template in flask?

#

like if i render template, how do i change the text in it after 5 seconds for example

native tide
#

hi

#

ok question

#

if I pass a multiform data to a python backend

#

(like this react example)

#
  const createUploadForm = () => {

    console.log('value of uploadFile: ', uploadfile)

    var formData = new FormData();
    formData.append("image", uploadfile)
    const obj = {title: postcomment.title, content: postcomment.content}
    const json = JSON.stringify(obj);
    const blob = new Blob([json], {
      type: 'application/json'
    });
    formData.append("document", blob);
    return formData
  }

  useEffect(()=>{
    var formdata = createUploadForm()
    if(postcomment.submit){
      // axios.post(
      //   "http://localhost:8000/lightone/comment/1/", 
      //   {title: postcomment.title, content: postcomment.content}
      // )
      axios({
        method: 'post', 
        url: "http://localhost:8000/lightone/comment/1/", 
        data: formdata
      })
#

how would I decode this on a python backend?

#

there are a bunch of mediocre solutions I found on the net that might work, but there should be a straightforward solution

#

is there anybody here?

native tide
#

django

#

im using django

#

whats the answer

#

im not going to use that

#

i want to parse an incoming form

#

there is absolutely no reason to need a framework on top of another framework

#

zero

stark crow
deft willow
#

my room light dashboard

silent nexus
#

are you using flex or grid?

unique shore
#

looks like grid

topaz widget
silent nexus
#

I think it needs more side padding and some gap

#

but otherwise it looks fine

#

maybe a single submit changes button for all the buttons?

naive rock
#

A REST API doesnt necessarily have to return a response in json?
A REST API could also return response in XML?

rigid laurel
#

Technically yes, but at this point rest is pretty synonymous with JSON over http

naive rock
#

Yeah that's what I thought too that JSON is synonymous with REST.

We utilize a third party API and they said they were changing API from SOAP to REST and I was relieved that I wont have to deal with XML anymore. I can directly with json. I made request to their new API and it still returns XML lol.

But I understand a lot of people have XML in their codebase, so they likely didnt want that to get effected.

rigid laurel
#

If someone said they were moving from soap to rest but still had most everyone returning xml I would feel thoroughly cheated

native tide
naive rock
#

I dont know why I never thought of this before, but XML looks a lot like HTML.

steel night
#

just knowing how to work with networking protocols (TCP, UDP, HTTP, etc) and sockets would get you 80% of the way there

native tide
#

I'm new to python web development. How would I make a input, so they can input a string, send it to my server, and I return the string, after processing it with my already written code to modify the string?

golden bone
#

If you only need to process one string at a time, a single GET endpoint should do

stoic marsh
#

Is it possible to write code for a dynamic website in 5 days?

#

Only front-end code

inland oak
#

Is it going to be one page of content, with something like 4-5 blocks of unique stuff? All right, possible.

#

Is it going to be 2 pages, out of 2-3 blocks? All right still possible

storm stag
#

no

#

use your own web framework, nah

inland oak
storm stag
#

use others web framework, hell yeah

#

😎

inland oak
#

if blocks are reusing same CSS, then they can be considered as the same

#

we count only UNIQUE CSS blocks

#

blocks with same applied CSS, can be not counted

#

if you have 6 pages with 2 blocks out of ALL of them UNIQUE. You are highly likely will not be able to do it in 5 days. At least 3 times more better to ask time

stoic marsh
#

Okay thanks got it

inland oak
# topaz widget Alright, thanks.

Btw, great idea.
Main account for any github/gitlab/banks to use STRICTLY WITHOUT plugins at all 😉

Chrome gives feature to have multiple users.
To use UBlock Origin (and optionally other plugins) for youtube and e.t.c. in a separate special user for watching stuff 😉

#

I think i can get used to it. I already did it for ticktock anyway

native tide
#

which front end framework would you recommend to use with django as back end and how do the two interact with each other ?

inland oak
#

if you are ready to jump to TypeScript and wishing Google ecosystem, with hard learning curve: Choose Angular

#

if you are ready for Facebook ecosystem, the most popular frontend framework in the world, starting from just Javascript, choose React

#

if you are wishing the most simple to learn frontend framework, with ecosystem more or less rich as Angular, but not afraid that it came from China. Choose Vue.js

#

I tried Vue.js so far pithink

#

I would not mind trying React in the future

#

And at the same time keep in mind that scaling code is a bit difficult thing to do. If you are in Vue.js, make sure your project is relatively small. Or otherwise you could out grow your State management system

#

for bigger in code projects perhaps React or Angular could make a better choice

#

Vue.js is nice and simple choice for small projects

native tide
#

So all of these are usable with django without an issue ?

#

Sorry if this is a dumb question

#

but the way we are being taught is basically, they give us computers and a project and tell us : Do it, you have 6 months

inland oak
inland oak
#

so it is not for serious production?

native tide
#

yes basically but it is actually a serious production

inland oak
#

erm. okay. Then React or Vue.js if it is intended for serious production. Angular is an option too, but I would exclude due to harder learning curve.

native tide
#

I think we'll use react then, seems straightforward enough for our current level

inland oak
#

i would look first at getting Router and State management
And thinking, do I need Internationalization tool?

#

Oh, and how to have Unit Testing

#

Since i am newbie to it, I would have checked those tools that make initial setup to add all tools for me (Create React App? pithink )

#

of course I could not live without SCSS, CSS without SCSS is plainly horrible

#

I would learn as first thing, how to DRY/split/reuse my code into smaller components of course

#

Due to me being a book person, I would be tempted to get a book pithink

inland oak
#

I was asked to do insane at my level too. Time flew and I adapted to actually finish the project

#

people adapt to meet the requirements.

#

As long as they are interested to meet them

#

I was interested, because learning all this stuff was super beneficial to my career

cerulean badge
#

django

request.user.student = None
request.user.save()

I have a Student model with o2o nullable field to user, but it doesn't detach with the above code, why?

agile pier
#

i have these choices in my model field

choices = (
    ("Fixed", "Fixed"),
    ("Open", "Open"),
    ("InProgress", "InProgress"),
)
#

status = models.CharField(max_length = 20, choices = choices, null = True, blank=True, default='Open')

eternal kestrel
#

Hi

agile pier
#
<td><select id="ab" data-item = {{vulnerability.id}} qty-item="{{vulnerability.status}}" class="update" onchange="if (this.selectedIndex) doSomething();">
            {% if vulnerability.status == 'Open' %}
            <option value="{{ vulnerability.status }}">{{ vulnerability.status }}</option>
            <option value="InProgress">InProgress</option>
            <option value="Fixed">Fixed</option>
          </select>
          {% elif vulnerability.status == 'InProgress' %}
          <option value="{{ vulnerability.status }}">{{ vulnerability.status }}</option>
            <option value="Open">Open</option>
            <option value="Fixed">Fixed</option>
          </select>
          {% else %}
          <option value="{{ vulnerability.status }}">{{ vulnerability.status }}</option>
            <option value="InProgress">InProgress</option>
            <option value="Open">Open</option>
          </select>
          {% endif %}
#

how do make a dropdown on the user interface to show the current selected choice and also the other 2 choices to change it?

agile pier
eternal kestrel
#

Hi, Im using flask. I want to accept JSON and files in one HTTP request with mutlipart/form-data.

#

Please help

delicate ore
#

hi

eternal kestrel
#

Hi

delicate ore
#

do you want to give data?

#

or receive it

eternal kestrel
#

im posting it with requests library and receive with flask.request

#

two python apps

delicate ore
#

so an API?

eternal kestrel
#

yes

#

forwarding the request

delicate ore
#

ok what do u want

eternal kestrel
#

from user to site to api

#
r = requests.post(API_URL + route, data=data, files=files, headers = {'Content-type': 'multipart/form-data'})
#

I have this

#

data is a dict

#

json

#

files is a dict of the file upload

#

so { filename : file }

#

theres 2 in it

#

it works fine i think

delicate ore
#

is it working?

eternal kestrel
#

the issue is data

#

heres the problem

#

on the API side when receiving

#

if I use

#

request.get_data()

#

it says

delicate ore
#

maybe try request.data, and print it to see what happens

eternal kestrel
#

same as get_data but

#

json.loads(get_data()) returns: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 1108: invalid start byte

#

well request.get_data()

#

and

#

request.get_data() without json.loads gives this error:

#

TypeError: byte indices must be integers or slices, not str

#

when I try to access an item in the json

#

with data["item"[

#

]*

#

when I do

data = request.get_data()
print(data)
#

its a massive byte array

#

OH

#

I see

#

my json is there at the top

#

after the json its the file data as bytes

#

i thought flask seperated that

#

the problem here is request.files is in request.data after my specified data

#

how can i get around this

delicate ore
#

request.data.data

eternal kestrel
#

no way

#

let me try

agile pier
eternal kestrel
eternal kestrel
#

hmm, youre right

delicate ore
#

decode(request.data, "utf-8")
Then to str

eternal kestrel
#

Right, the problem with decoding

#

same problem as get_json

#

it decodes as utf8

#

invalid bytes

#

on the file data

#

its not a string

#

its filestroage

#

not json

#

darkrex

eternal kestrel
#

its not pretty though

delicate ore
#

also ping me when u reply

#

use request.files

eternal kestrel
#

@delicate ore hello

#
    my_data = {
        'json_data': ('json_data', json.dumps(my_json), 'application/json'),
        'photo1': ('photo1', photo1.stream(), 'application/octet'),
        'photo2': ('photo2', photo1.stream(), 'application/octet'),
    }
#

or the exact same without .stream()

#

photo1 and photo2 are the user uploaded files from flask request of type FileStorage

#

req_json = request.files.get("json_data") server side

#

with stream() TypeError: 'SpooledTemporaryFile' object is not callable

daring meteor
#

Hello

#

I got kinda off topic
BUt I'll be really GRaTefull if someone helps me by answering

eternal kestrel
#

without stream() TypeError: 'FileStorage' object is not subscriptable

daring meteor
#

these are some shits I found on my school websites <head><style type = text/css>
like these are some random fake porn sites and vpn ads
what are they doin here?

errant ledge
#

That's how the officials are taking care of money from your taxes 🤷

native tide
#

I am using the exact font and colors they give, yet my fonts look nothing like theirs

#

why

#

How do I only connect to a io socket once? Everytime i reload the page, it just adds another event listener instead of replacing the existing one

native tide
slim sapphire
#

Hello, I am currently working on an API using Flask, flask-resplus, Werkzeug, and a couple other less relevant packages. So flask-restplus is a little outdated and the newest version of Werkzeug breaks it: https://github.com/noirbizarre/flask-restplus/issues/777 so I downgrade it to what it should be, 0.16.0 or something like that right. And now the program gets broken again because Flask wants the current version of werkzeug: https://github.com/pallets/werkzeug/issues/2324. What is the work around for this? I've never had dependent dependency issues such as this one lol

GitHub

Sorry, I am an Ops guys and not a developer but I hope this helps.. Error Messages/Stack Trace If applicable, add the stack trace produced by the error | Traceback (most recent call last): | File &...

wheat verge
#

what python libraries are a must for a python web developer

slim sapphire
#

I think you should be asking more about functionality vs. which specific libraries. Lots of libraries do similar stuff

wheat verge
#

well what i am trying to ask is what does one expect a python web developer should know

frank shoal
#

django, flask, fastapi are the big 3 web frameworks

#

django is a jumbo-framework. It has pretty much everything.

#

flask is slimmed down without as many features, but still useable.

#

fastapi is the minimal required for making a REST api, but also supports other features if additional libraries are installed. Templates are supported if jinja2 is installed. Static files can be used if aiofile is installed. etc

#

flask uses werkzeug, while fastapi uses starlette as a wsgi/asgi implementation

prime elk
#

Can anyone help me out? I have no idea if this is the right place..

native tide
#

I think FASTApi is exactly what I need. Much appreciated.

prime elk
#

I checked out the help channels, but I don't have a problem with code, rather just questions.

frank shoal
#

ask your question

prime elk
#

Yeah, this isn't the right place but ok

#

How do I start learing? Python..

#

Damnit I'm going to get banned for this

warm aurora
#

Yoo

#

Can someone help me real quick

#

My images wouldnt show up on the website

#

Im assuming it has to do with the path?

frank shoal
lavish prismBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

prime elk
frank shoal
# warm aurora Im assuming it has to do with the path?

How to debug things in the browser: Open the page and press Ctrl+Shift+I to open the inspector. Click the console tab and look for errors. If none are found, go to the network tab and refresh. Look for any 4xx status codes.

warm aurora
#

Can we get in a call??

#

Thats what i get

frank shoal
#

click Network to inspect the full path of the file

#

you may need to refresh

warm aurora
frank shoal
#

You can press Win+Shift+S to take a screenshot

warm aurora
#

U want a better picture?

frank shoal
#

Did you refresh?

warm aurora
#

No