#web-development

2 messages ยท Page 144 of 1

marble spade
#

xd

#

can you explain what you mean

#

return render(request, "main/home.html", {}) do you mean to add this/

tribal pewter
#

Let me see your forms html

marble spade
#

{% block content %}
<!-- This is how I edit custom things on top of the base HTML page.  -->
<h1>HOME PAGE</h1>
<html>
<body>
<span>Hello, {{request.user}}</span>
<span> <a href="logoutpage"> Logout </a></span>
<br><br><br>
<form method="POST" action="">
    {% csrf_token %}
<input type="text" name="stock_type" placeholder="Stock please..." class="username_class"><br>
<input class="submit" type="submit" name="UserCreate"><br><br>
</form>
<h2> OPEN ${{ open_data }}</h2>
<h2> CLOSE {{ close_data }}</h2>
<h2> HIGH {{ high_data }}</h2>
<h2> LOW {{ low_data }}</h2>

</body>
</html>

{% endblock %}
tribal pewter
#

So when you are submitting this form the info are being sent to the same url of the page you're at because action is empty

marble spade
#

right so what do I change the action to

#

oh

tribal pewter
#

In your urls file create a new path to the view yeetman

#

And puth that path in action

marble spade
#

but yeetman is simply a function

#

why would I need to add a path?

#

it's not a wepage

#

web

tribal pewter
#

And how do you trigger that "function"

marble spade
#

tbh I got no clue

#

it just does

#

xd

swift wren
#

hey guys, i want to know how i can make bootstrap cards move on their own. so basically i have these cards right, and im using django to have a for loop and the amount of things Django returns is th amount of cards that are created right. so basically, if my database has 3 items, Django is going to create 3 cards, but right now it will only be created by going down. how can i set parameters to where the cards are pushed. because i want to first: check if the cards are approaching the bottom of the screen and then secondly: check if the cards are overflowing to the right. how can i add those 2 parameters to the the html so that the card divs can be placed appropriately to the resolution of the window
can you please ping me if you have a input, thank you

tribal pewter
marble spade
#

like nested?

tribal pewter
#

Nono

marble spade
#

or just remove the function

#

not needed

tribal pewter
#

Yes just remove it

marble spade
#

ok

#

I removed it

#
@login_required(login_url='/loginpage')
def home(request):
    stock_has_been_selected = False
    if request.method =='POST':
        stock_type = request.POST.get('stock_type')
        

    #Code for open, simplifed and cut down to 8 decimal places and no brackets.
    if stock_has_been_selected == True:
        my_share = share.Share('TSLA')
        symbol_data = None
        data = my_share.get_historical(share.PERIOD_TYPE_DAY,0,share.FREQUENCY_TYPE_DAY, 1)
        open_price = str(data['open'])
        open_price = (open_price.replace('[', '').replace(']', '')[0:8])
        close_price = str(data['close'])
        close_price = (close_price.replace('[', '').replace(']', '')[0:8])
        high_price = str(data['high'])
        high_price = (high_price.replace('[', '').replace(']', '')[0:8])
        low_data = str(data['low'])
        low_data = (low_data.replace('[', '').replace(']', '')[0:8])

        context= {
            'open_data': open_price,
            'close_data': close_price,
            'high_data': high_price,
            'low_data': low_data,
            }
        return render(request, "main/home.html", context)
    return render(request, "main/home.html", {})
#

this is what we are working with now

tribal pewter
#

Try submitting now and I'll be right back in abt 15 min

marble spade
#

allr

#

;O

#

god knows how

#

but it works

#

you genius ๐Ÿ™‚

#

!close

#

oh

#

oops lol

opaque rivet
#

could anybody help me with a design question?

my user connects to my server via websocket and receives intraday stock information. I want short-term storage of stock prices and other information - cached data for the day. is redis suitable for this?

ionic cipher
#

!resources

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.

ionic cipher
#

!kindling

lavish prismBOT
#

Kindling Projects

The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.

ashen vigil
#

Q) What do y'all think about Serverless Flask? Is it a good implementation?

opaque halo
#

Hi guys! I was wondering if either of you could point me in the right direction as my current project isn't in my area of expertise.

I store my (anime)series' ratings on an online database (and have access to their API) -I need to re-rate most of the series as most of my tastes have changed over the past 3 years.

I wanted to build an web/or any other interface to help me rate these at speed (using my keyboard only). I was initially thinking of doing this using pygame? Since that's the only GUI library that I have somewhat experience with.

But I was wondering if you guys knew of any other "easier" or elegant way I could get this interface setup quickly.

My main area of comfort in Python is data science, so this just feels quite daunting to me :S

past cipher
#

Would you say its quicker to loop over 10,000 rows than delete 10,000 rows from a database ?

#

the row contains two columns: ID, Item

#

The problem I'm facing is user can create a product, and sell items. they could add 10,000 items for example. When they update the items, I need to compare the new items vs the old items, and update the items inside the db

#

i'm stuck on whether to just delete all the rows, and then add the new items

#

or compare the two lists, and then add rows to the table that don't exist already

native tide
#

any one have a fix for this?

#

I am trying to push it to heroku

past cipher
#

check the log

opaque rivet
past cipher
#

thats not the full error

opaque rivet
native tide
#

oh no

#

help

past cipher
#

that doens't tell us anything other than the status log

#

paste your log

#

!paste

lavish prismBOT
#

Pasting large amounts of code

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

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

native tide
past cipher
#

ModuleNotFoundError: No module named 'django_project.wsgi'

native tide
#

?

past cipher
#

thats your error

native tide
#

uhh

#

where is it usually located?

past cipher
#

not sure, I use Flask not Django

#

check SO if you still can't fix it

native tide
#

I reference it wrong it think

#

web: gunicorn PROJECT_NAME.wsgi --log-file -

weak mesa
#

I have an issue linking my react app to my AWS DRF API while fetching data : on chrome, cors is allowed and data fetched, but on firefox, I have a CORS failed, can't find jack on the internet, does anyone have an idea?

native tide
#

I got a new error using heroku ERROR: Could not find a version that satisfies the requirement ltgraph==0.17 (from -r /tmp/build_0d89645f/requirements.txt (line 1)) (from versions: none) remote: ERROR: No matching distribution found for ltgraph==0.17 (from -r /tmp/build_0d89645f/requirements.txt (line 1)) remote: ! Push rejected, failed to compile Python app.

opaque rivet
opaque rivet
#

๐Ÿค” , what's the exact error in the server / client sonsole?

opaque rivet
#

I don't understand French ๐Ÿฅด , but I guess it's saying there is no same origin header from CORS?

weak mesa
# weak mesa

Sorry this is in French but I am sure you can identify which error it is in english

#

yes correct

#

by the way, I am on "Strict mode" for Firefox, could it be the issue?

opaque rivet
#

not sure - but that error is due to your CORS enforcing the same origin policy, the origin of that request is not included in the CORS settings. (which is strange, as you've specified the settings are fine).

weak mesa
#

Yes, considering it is working on chrome and edge, this is quite strange indeed

weak mesa
opaque rivet
#

is your origin http?

#

or https?

weak mesa
#

http

#

it is written https on the error though

opaque rivet
#

hmm... I sense that may be an issue that trips CORS, since they're different protocols & therefore different origins.

#

you could try use ngrok to quickly get https for your site (if it's running on localhost) then retry

weak mesa
#

React app is running on my machine (localhost) and the DRF API is running on aws ubuntu server

#

I will check on aws how to get https protocol for my instance

opaque rivet
#

it will be your frontend which will have to utilize https, i'd recommend ngrok for that. I'll admit that's a strange error though ๐Ÿฅด

weak mesa
#

I will reset firefox settings and try again, might be the issue too

weak mesa
#

Ok found the error ! in my firefox settings : "activate https only" was ticked, I switched to "Do not activate" and now it works like clockwise. Phew....

idle apex
#

when i run my flask app, request.values.get immediately returns None in the console, so i get a keyerror when it tries to retrieve the value of None in the dictionary

#
from flask import Flask, render_template, url_for, redirect, request

app = Flask(__name__)


d = {
    "ๆˆ‘": {
        "eng": "I, me",
        "pin": "ng4"
    },
    "ไฝ ": {
        "eng": "you",
        "pin": "nyi4"
    }
}


@app.route("/", methods=["GET"])
def search():
    hanterm = request.values.get("term")
    print(hanterm)
    # if request.method == "GET":
        # return render_template(
        #     "results.html",
        #     title=hanterm,
        #     postdata=d[hanterm],
        # )
    return render_template("index.html", title="Search")


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

my html form:```html
<form method="GET" action="{{ url_for('search') }}">
<fieldset class="form-group">
<legend class="border-bottom mb-4">Search term:</legend>
<div class="form-group">
<input type="text" placeholder="Type here" name="term">
</div>
</fieldset>
<div class="form-group">
<input type="submit" value="Search" name="submit">
</div>
</form>

opaque rivet
native tide
#

Hello, I need some help. I get this error: `ImportError: cannot import name 'pathlib' from 'django.urls'
and I actually can't find pathilib in directory. I reinstall django but doesn't help

#
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('flowers/', include('flowers.urls')),
    path('admin/', admin.site.urls),```
#

any idea?

#

yea

#

I kwno where was a problem

sand glen
#
        <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
            <a class="navbar-brand" href="/">My Website</a>

            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar">
                <span class="navbar-toggler-icon">
                </span>
            </button>

            <div class="collapse navbar-collapse" id="navbar">
                <div class="navbar-nav">
                    <a class="nav-item nav-link" id="featured" href="/featured">Featured</a>
                    <a class="nav-item nav-link" id="sign-up" href="/sign-up">Sign Up</a>
                    <a class="nav-item nav-link" id="login" href="/login">Login</a>
                    <a class="nav-item nav-link" id="logout" href="/logout">Logout</a>
                </div>
            </div>
        </nav>```

hi! im using flask and i have this bootstrap navbar. i wish to make it so that the part of the website you are currently on gets highlighted on the navbar. 
on bootstrap's website, it says to do this:
#

but im confused on what to do

#

do i need to add front end code to add the attribute automatically

#

im using jinja btw

red roost
#

Doing a live video on django deployment from scratch, anyone interested ?

stone wren
#

[flask]

I really don't understand the db.session thing.

I wrote this method for my model

would this work in my case?

def set_customs_state_to_successful(self):
        self.declared_to_customs = DeclaredToCustoms.Succesful
        db.session.commit()
wooden ruin
wooden ruin
#
{% if condition %}
  <a class="nav-item nav-link active" id="featured" href="/featured">Featured</a>
{% else %}
    <a class="nav-item nav-link" id="featured" href="/featured">Featured</a>
{% endif %}
sand glen
#

yes thats what i was thinking

#

thanks

#

i was wondering if there was a more efficient way

#

or something

#

i wonder if i can do:

wooden ruin
#

ideally this could be implemented using a little bit of javascript, such as getting all anchor tags in the navbar, grouping them into some sort of array in javascript with a dataset of the url maybe, then compare the window.location. with the dataset of each one and highlight the one that matches

sand glen
#
<a class="nav-item nav-link{{ ' active' if cond else '' }}" id="featured" href="/featured">Featured</a>
#

is that valid

#

lemme see

wooden ruin
#

i dont think that will u might get a parsing error

#

because from my experience with template language i have to use and endif

sand glen
#

hm

#

lemme check

pale cosmos
#

I have a question about selenium

sand glen
#

wait

#

it actually works

#

@wooden ruin

sand glen
#

wdym

pale cosmos
#

code format

pale cosmos
#

bot my messages is normal

#

but*

sand glen
#

oh

pale cosmos
#

'''py
something
'''

sand glen
#

if you're not pasting python code then put the file extension of the code you're writing

sand glen
#

it should be in the top left of your keyboard

pale cosmos
#

ok

#

thx

quiet ridge
#

how can I take images input and store them sqlite db in flask

wooden ruin
sand glen
#

how do i make the short error (text below "404 not found") display on one line?

#
@errors.errorhandler(404)
def page_not_found(e):
    error_parts = str(e).split(": ")
    return render_template(
        "error.html",
        error_short=error_parts[0],
        error_long=error_parts[1]
    )
{% extends "base.html" %}
{% block title %}Error{% endblock %}

{% block content %}
<br>
<h1 align="center">{{error_short}}</h1>
<h4 align="center">{{error_long}}</h4>
{% endblock %}```
native tide
tribal sedge
#

What is DJANGO used for ?

#

Is it an API or what

quick cargo
#

It's a web framework

tribal sedge
#

Ah ok

mint hedge
#

It is hell to deal with when unchained ๐Ÿ˜‚

native tide
#

is there a way to set a custom error page for only some routes in flask?

grim tiger
#

@native tide You can set it on a blueprint.

tulip relic
#

is it possible to get the raw querystring values (as bytes, not str) from an aiohttp request

#

without reparsing it

#

I basically have a URL-encoded binary blob, and it's being interpreted as unicode

#

which may be the most unhelpful github issue I've ever seen

azure flax
#

Hello everyone, i am using pre_save signal to change the path of the files that saved into my database, and i am having a problem : here is my code if someone have an idea on how to fix it.i worked soo much on it but i am blocking please some help...
https://del.dog/hiwowyning
the error i got is : can't set attribute

dogbin

''' models.py '''
class Media(models.Model):
'''Defining the entries'''
title = models.CharF

azure flax
#

what do you mean please?

tulip relic
#

actually, what is the full error trace

azure flax
#

the code i put is here just to explain what i did!

#

well the error i got it on my debug mode

#

but can we juste do a setter on the "media" class to update the url attribute ?

#

of a ImageField ?

tulip relic
#

hmmm, I'm not really sure. I haven't used django that much
is there something like

Traceback (most recent call last):
  File "Z:\code\pytracker\pytracker\src\app.py", line 33, in announce
    peers = await peer_list.get_peers(peer, info_hash)
  File "Z:\code\pytracker\pytracker\src\storage.py", line 79, in get_peers
    if not (peer.info_hash == info_hash):
AttributeError: Cannot set attribute

in the logs?
It will look slightly different, but it tells what the error means

azure flax
#

how can i got the logs? (i am not too much used to use django since i use it just for the django-admin panel) all the logs i can have is from my docker

#

maybe i have to execute a command on the docker of admin?

opaque rivet
# azure flax what do you mean please?

What's your error message?

My guess would be that the error lies in the setattr functions (which I would avoid using, by the way) - but we're going to need the error message.

azure flax
#

where can i see the error message, because my runserver didn't return any error

#

i only got it with the interface on the debug mode

#

and my message error is "can't set attribute"

opaque rivet
# azure flax Hello everyone, i am using pre_save signal to change the path of the files that ...

oh, I found your error, here it is:

setattr(instance.picture,"url",'media/{}'.format(instance.picture.url))

and

setattr(instance.picture,"url",'media/{}'.format(instance.picture.url))

Firstly, I would not use setattr. The first line is equal to saying:
instance.picture.url = media/{}'.format(instance.picture.url) which is better in terms of readability.

the url of your picture is read-only, you cannot set it.

azure flax
#

so how can i set it? the problem is my media are in the folder media/.... and when i set it on the settings.py, so to save in the database the url as media/... not only the_path_to_picture that's why i am trying to do it like that

#

do you think there is a way to update the "url" on my database

opaque rivet
#

I don't know what you're trying to do. I would give instance a new picture and then use that url for whatever you're using it for...

azure flax
#

I will explain my problem, maybe there is a simple solution than doing it with 2 signals haha!
my problem is that i save my medias on the media/... folder i defined on the settings by MEDIA_URL = '/media/' , so everytime my Imagefield save a new picture it stores it to media/path_specified_in_Imagefield, but i would like to save the data on my database with directly the true path to my pictures and by that i mean media/path_to_picture

opaque rivet
#

I don't really work with media files that much, but could you change your picture's name to its url? Pretty sure the name is not read-only like url. That way your files will have their urls as their names - with some trimming down of the path that is

opaque rivet
candid ridge
#

Any beginner friendly tutorials I can watch or listen to?

opaque rivet
#

man... learning Celery and about RabbitMQ is really cool - I've been down a rabbit-hole today. It's got me wanting to write articles on it

chilly falcon
#

hello i am learning django any idea or road map to learn properly

#

??

stable hemlock
wooden ruin
#

Also look into courses for django in edx

#

Cs50 web goes into django as well

chilly falcon
chilly falcon
native tide
#

wtf

native tide
#

does anyone have a solution for this problem?

#

"This file is empty" in github , I was trying to upload my django project

native tide
slim beacon
#

Can someone help me set up the NGINX configuration for websockets? I have a server already set up for WSGI, but I need to change this to accept websocket connections.

chilly falcon
#

can anyone tell me diffrence in this two?
def signIn(request):
return render(request, 'signin.html')

def signIn(response):
return render(response, 'signin.html')

ashen vigil
#

How do y'all prefer to write tests for your Flask/Django applications?

quick cargo
#

depends whether it can be localised tests in the code or whether its unit tests via postman etc...

chilly falcon
#

i saw different ytber are using request and respose in there views

swift wren
#

hey guys, i want to know how i can make bootstrap cards move on their own. so basically i have these cards right, and im using django to have a for loop and the amount of things Django returns is th amount of cards that are created right. so basically, if my database has 3 items, Django is going to create 3 cards, but right now it will only be created by going down. how can i set parameters to where the cards are pushed. because i want to first: check if the cards are approaching the bottom of the screen and then secondly: check if the cards are overflowing to the right. how can i add those 2 parameters to the the html so that the card divs can be placed appropriately to the resolution of the window
can you please ping me if you have a input, thank you

ashen vigil
#

I think, maybe writing some custom css, to handle that can help

opaque rivet
#

same for flask, i guess

ashen vigil
#

What's the testing methodology?
Do you run all get/post requests with mock-data?
Do you check the response codes only or do you also check if the desired output is received? If yes, do you call an instance of the function that converts input to output, in the test to check if the response matches

opaque rivet
#

same thing goes for API endpoints, just test everything

sand glen
#

hi! i have this style code in base.css

#

i've imported it here in my <head> for base.html

#

but it doesnt seem to apply

#

if i add the CSS inline with <style> it works, but not if i <link> it

tribal pewter
#

cz you are not really linking to the CSS file

#

you should add the full destination

#

or

sand glen
#

ok

#

oh

#

{{ url_for('static', filename='style.css') }}

#

found that in flask docs

#

thanks

#

tf

#

still doesnt work

#

this is my file structure

tribal pewter
#

not sure how you do it with flask

sand glen
#

i figured it out

#
        <link rel="stylesheet" href="{{ url_for('static', filename='css/base.css') }}" />
#

also, this <h3> doesnt seem to be affected by my CSS

#

if i change it to an <h1> it works as expected

#
body { background: #2a2b2a; }
h1, h2, h3, h4, h5, h6 { color: white; }```
this is my CSS
storm roost
#

Hey guys

#

I have an integer field in my model with choices as:
COLLABORATORS_ROLES = ( ('', '-'), (0, 'Author'), (1, 'Co-Author'), (2, 'Editor'), (3, 'Peer Reviewer') )

#

Currently when I serialize my model, it returns the integer value of the roles (again since it's an integer) but is there a way to get the value like 'Author' instead of integer?

#

to serailize, I'm using the django.core.seralizers.serialize

opaque rivet
storm roost
#

parse it how?

storm roost
opaque rivet
#

i.e. you have a dictionary {integer: author}, you can use the integer returned to get the author you want

storm roost
#

alright

#

Thanks

rigid moon
#

Hey, I'm trying to create a database in flask, by importing db in the shell then calling db.create_all(), but it doesn't create any file in my directory

#

I can introduce items manually, like this, but after I quit the shell the item isn't there anymore

crimson peak
#

Looking nice

#

Is it a VS code theme?

rigid moon
#

Pycharm with material theme

crimson peak
#

Ohh niceee

serene prawn
sand glen
#

no

#

i fixed it

serene prawn
#

Ok, take care

serene prawn
rigid moon
#

yeah, I copied some code from github and it worked, idk why tho

serene prawn
#

๐Ÿ˜…

#

did you perhaps created your db in memory?

rigid moon
#

well the db was created, but it only worked in that specific session, if I closed shell and tried calling Item.query.all() I wouldn't get anything

#

and the file.db wasn't created either

serene prawn
#

So i guess it was in memory then

#

If you didn't have actual db file in case you use sqlite as your db

vestal hound
#

not in the browser

#

but

#

if you're running in a non-browser environment

#

e.g. Node on the backend

#

it's defo possible

serene prawn
#

I think majority of browsers provide same environment/api

#

Usually there's no specific stuff that you should care about i guess

#

Because js is usually used with some kind of framework at least in recent 2-3 years

native tide
#

Do you guys know how to fix this problem in heroku "Server Error(500)". I am using django

serene prawn
#

There's error in your django application

#

Run it locally and see what error is

#

Or check logs on heroku if there's any

serene prawn
native tide
#

ok I will try

thick sinew
#

I think it is a standard for entire web, any 400 error is client side error and every 500 means problem is on server side, zero can be any number

native tide
#

yep there is a problem in the web

#

not loading static files

#
C:\code\python\django_project\env\lib\site-packages\whitenoise\base.py:115: UserWarning: No directory at: C:\code\python\django_project\django_project\staticfiles\
  warnings.warn(u"No directory at: {}".format(root))```
thick sinew
#

It cannot find directory, double check your path first, you may have a typo in dir name

native tide
thick sinew
#

Do you have this line?

    os.path.join(BASE_DIR, 'static'),
)```
native tide
#

nope

thick sinew
#

Try it

native tide
#

still the same

thick sinew
native tide
#

I will try, thanks ๐Ÿ˜„

thick sinew
#

I would suggest you to google this, i am not master with heroku so this way it will be faster for you i think

tribal kettle
#

Hi, I'm using django and I'd like to know how to reproduce this form: https://paladinsdecks.com/nc/decks/new-deck/androxus/
Especially the card selector. I can do the other fields, but the card selector I've no idea how to do it, even though I've already googled how to make this.

This is behavior i want. thanks for helping.

native tide
#

is it okay if the admin looks like this? ๐Ÿฅฒ

quick cargo
#

are you by any chance running in production mode?

quick cargo
#

If it's in production mode Django wont server static files as by design thats left to something like Nginx or Apache to serve

#

as python is inherently slow at serving static content.

native tide
#

so it should not be this?

#

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

quick cargo
#

im not sure about the context on this one

#

its not anything todo with your code

#

it's todo with the fact that it's designed for deployment not development

native tide
#

rip, well time to switch to flask

quick cargo
#

when in debug mode for development the testing server will serve content

#

flask wont serve those files anyway

#

if you're just debugging use the debug / developing use the debug mode

#

if this is for deploying your app then the tutorial is taking you down the standard reverse proxy route with nginx protecting your python workers and serving static content

serene prawn
native tide
#

django and heroku is hard men ๐Ÿ˜ฆ

serene prawn
#

Maybe this would help though

#

Flask is harder to develop apps with

native tide
#

I should probably study more cuz I haven't mastered django yet ๐Ÿ˜ฉ lemon_sentimental

leaden lantern
#

Hello There,
So I was making a dashboard but I want to list all discord emojis to choose one from them. How I can implement this stuff, I have seen this same thing on many websites

wooden ruin
#

if you want an easy way to serve static files in production, look into whitenoise

native tide
#

Yep but I dont know the use gunicorn and whitenoise

wooden ruin
#

gunicorn looks for an application variable, so the most common way i run a WSGI django project is by doing gunicorn <my-project>.wsgi

#

and to be fair, i googled every error and managed to work things out

#

and when configuring whitenoise, add the middleware to settings.py:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    ...
]

and this is what i use
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'

mystic wyvern
#

greeting everyone, i want to know something I am really confused at it it is (api) please I want it in the simplest concept .

wooden ruin
#

@mystic wyvern lets say you have a SQL database full of all sorts of data

wooden ruin
#

you cant just access it by messing around, if you want to access it you have to write a sql command. sounds fair?

#

you can automate this by using flask, for example

#

you can write some code in python that will access the database and do whatever you want

#

but lets say someone else doesnt know any python or SQL

#

how would they get something from the database? well they could talk to you

#

if i tell you to get me a picture of a dog from a database, you could do that using flask, django, sql, etc. right?

#

i dont even need to know python, as long as you can take care of it for me

#

and you can "do your thing" and return to me the picture of a dog

#

i don't have to know anything that you are doing as long as i know how to talk to you

#

that how i like to think an api works

#

and if you can provide me with consistent pictures of dogs, then i can rely on you to build a dog website, for example

#

so if a user were to visit my website, i would "ask" you to give me dog pictures, and you would return pictures of dogs for my to display

#

did this clear anything up? @mystic wyvern

mystic wyvern
#

to some extent yes

wooden ruin
#

ok cool, this is how i like to imagine api's work

mystic wyvern
#

i think that was clear enough

wooden ruin
#

keep in mind an api can work with other things. have you used javascript before?

#

ok :)

mystic wyvern
#

I am currently learning it

wooden ruin
#

so you may or may not know that javascript supports game controllers as devices

#

all those features that javascript provides for the game controll is part of an API

#

the API can access each button press, and many other properties for you to access

naive sparrow
#

@mystic wyvern Api is basically an interface through which you can manipulate code written by someone else through your code. It can be
set of functions/methods
rest api

Or something else

mystic wyvern
#

@wooden ruin I appreciate that for you, thank you a lot

mystic wyvern
naive sparrow
#

Exactly

#

Api is what enable you to talk with someone else's code.

wooden ruin
#

yep, or you can make your own api

#

makes it useful when developing the backend and frontend independently

#

if an api is well documented, then its easy to use and understand

naive sparrow
rigid loom
#

Code:```py
def get_all_accounts(payload):
"""
Responds to a GET request to /api/v1/accounts
Reads all accounts from the database

:return:        JSON representing accounts or 403 if invalid token / insufficient permissions
"""
...
return [_account_to_json(acc) for acc in data]```swagger.yml```yml

/accounts:
get:
operationId: accounts.get_all_accounts
tags:
- "Accounts"
summary: Read all accounts from database
description: Read all accounts from database
parameters:
- name: payload
in: body
description: Auth token
required: True
schema:
type: object
properties:
token:
type: "string"

  responses:
    # ...

Curl request: py
curl -X GET 127.0.0.1:5000/api/v1/accounts -H "Content-Type: application/json" -d "{"token": "token"}"Error:py
TypeError: get_all_accounts() missing 1 required positional argument: 'payload'```why isn't the payload parameter getting passed to the function?

mystic wyvern
naive sparrow
#

It's redux store's api, i'm not sure but i guess replaceReducer accept a new reducer as argument and replaces the older reducer which is registered as rootReducer.

mystic wyvern
#

@naive sparrow @wooden ruin thanks for you guys โคโค

naive sparrow
#

you can't sent data through GET request, change method to POST @rigid loom

rigid loom
#

Which is for creating a new account

#

So I guess I'd have to move that?

naive sparrow
#

You can't sent request body along with get request

rigid loom
#

That works, thanks lol. I feel so dumb xD

#

Thank you very much ๐Ÿ‘

opaque rivet
#

does anyone know why my websocket isn't firing the onmessage function?

// js
const ws = new WebSocket("ws://127.0.0.1:8000/datastream/")

        ws.onmessage = (payload) => {
            const data = payload.data
            console.log("data received")
            console.log(data)
        }

The websocket is accepted by my server, and I send back a response (w/ key "text")

# consumers.py
    def websocket_connect(self, payload):
        self.send({
            "type": "websocket.accept",
            "text": db.get(all_keys=True)
        })

But my JS onmessage function isn't recognizing it. Can I not send data payloads when accepting websockets? I guess the connection is not yet established completely so I won't be able to send data like that?

naive sparrow
#

@opaque rivet did you include websocket cdn

#

Check console if there's any errors or warnings

opaque rivet
naive sparrow
#

Sorry can't help with Django, i'm javascript dev :)

opaque rivet
#

gotcha, I'll just have to read about them a bit more, I think I'm onto a workaround though, I'll see if it works ~5mins

#
ws.onopen = () => {
            ws.send(websocketEnum.Initialize)
        }

ok works now :),

  • websocket request is sent to server,
  • server sends a response accepting it,
  • client sends a request saying "I'm ready"
  • backend sends required data
    def websocket_receive(self, payload):
        if payload['text'] == 'initialize':
            self.send({
                "type": "websocket.send",
                "text": json.dumps(db.get(all_keys=True))
            })
#

thanks for the help ๐Ÿ™‚

wooden ruin
opaque rivet
#

but it leads me to another question

#

for RESTful APIs, you can have multiple functions in one (e.g. handling GET, POST etc.) - is it the same with websockets? it seems like each websocket endpoint can only do one function, unless my frontend is sending some sort of status message like "update", "initialize", etc. does that make sense? how is it done usuaully?

wooden ruin
#

since we are dealing with non-http here, it's difficult to imitate other methods. look into socket.io if you want to have more custom events such as emit. as for now, my go-to is to have 1 consumer method that receives any messages, looks for a status in the body and redirect to the appropriate function. it's not the ideal setup but it keeps things semi-organized, and i can always split the websocket into 2 separate routes if i need to

opaque rivet
#

ok cool, websockets are looking nice so far ๐Ÿ™‚

#

definitely going to use em for future projects

wooden ruin
#

absolutely! also, look into django signals as well. when paired with django channels, it's a really cool and powerful combo :)

opaque rivet
#

mhm, working on redis-specific signals atm and hopefully I'll be able to send frequent updates from the server

opaque rivet
wooden ruin
#

yep, to me it's a great usage for broadcasting events

#

so if a new user is registered you can display it live

#

so new users can kind of see how "active" it is? if that makes sense

#

it would also be a good idea in terms of web gaming or, more importantly, database verification

#

saves time instead of processing everything in one view per request

opaque rivet
#

ah I see. I haven't yet learnt about channel layers / groups, and I was trying to listen to redis updates within the syncConsumer itself ๐Ÿคฆโ€โ™‚๏ธ , but I think channel layers is what I need.

essentially just need the signal to push data to the client via the websocket, to all clients connected to the "channel". will channel layers solve this?

wooden ruin
#

channel layers allow you to group your consumers, such as with chat rooms: if youre in a chat room, you can't see the messsages of another one. for this one you won't even need channel layers. or, you can put every user into 1 big channel layer and broadcast to that layer whenever you recieve the signal

#

unless, you are grouping your clients somehow, maybe based on authorization/access or any factors really

opaque rivet
#

all my clients should be grouped together in one pot.
so by my understanding, I can register all the clients to a channel layer and then broadcast data to all of them at once?

wooden ruin
#

yep, using the self.channel_layer.group_send method

#

it's going to need a workaround, though, because you need a staticmethod to connect if you're using django signals

#
    def get_user_updates(sender, instance, **kwargs):
        try:
            name = instance.first_name + " " + instance.last_name
            i = UserConsumer.connected_users[0]
            async_to_sync(i.channel_layer.group_send)(
                i.name, 
                {
                    "type": "message",
                    "message": name + " has registered for an account!"
                }
            )
        except: pass

this was my implementation of this

opaque rivet
#

i wont be using the django signals, but something similar (for redis). I'll just need to broadcast based off a conditional:

  if i_need_to_update_client:
    layer.broadcast...

^ something like this

#

big thanks for the help!! I was trying to implement channel layers without knowing what they were, I really appreciate the explanation ๐Ÿ™‚

wooden ruin
#

no problem! i know this stuff was difficult for me when i first started, so i know how it feels

#

as a last note before i have to go, do note that the redis signal function you might be implementing can't really know whether to send it or not, such as if no users are connected. it's best to keep track who and which users are active, and I store them in a list, and remove them fromthe list when the client disconnects. that way i have all my users in a list ready to go, and i can message any one of them should i need too

elder nest
#

can someone help me to why this isnt working <button type="button" href="/dashboard/{{ guild['id'] }}" class="btn btn-success pull-right">Go To Dashboard</button>

#

its not rerouting it to that link

wooden ruin
elder nest
#

nope

#

here is whole thing @wooden ruin

#

{% block body %}
    <section id="main">
        <div class="container">
            <div class="row">
                <div class="col-md-9">
                    <div class="panel panel-default col-md-offset-3">
                        <div class="panel-heading main-color-bg">
                            <h3 class="panel-title">PLEASE SELECT A SERVER</h3>
                        </div>
                        <div class="panel-body">
                            <div class="well well-lg">
                                {% for guild in render_guild %}
                                    <h4>
                                        <img class="img-responsive" style="display:inline-block; height:30px; margin-top-5px" src="https://cdn.discordapp.com/icons/{{ guild['id'] }}/{{ guild['icon'] }}.png" />
                                        {{ guild['name'] }}
                                        <button type="button" href="/dashboard/{{ guild['id'] }}" class="btn btn-success pull-right">Go To Dashboard</button>
                                    </h4>
                                {% endfor %}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
{% endblock %}```
warm fractal
#

anyone aware of something that can load twittesrs bookmarks into something one constrolls oneself?

twilit thorn
#

guys can someone help me set up a virtual environment?

opaque inlet
#

It seems that I can't define a template, despite having the right location of my html template. I have my index.html file in msg/templates/msg/index.html
this is the code I am using ```py
def index(request):

return render(request, 'index.html')
#

It says that index.html cannot be found

umbral echo
#

msg/index.html

opaque inlet
#

no

#

am I supposed to have it like that?

#

this is django btw

umbral echo
#

This is the path you gave

opaque inlet
#

yeah

umbral echo
#

Render will look into templates directory, but you added a msg directory. Try it with msg/index.html to see what it says

opaque inlet
#

it still can't find index.html

#

TemplateDoesNotExist at /index/
msg/index.html

#

That's weird

#

It's looking here for my templates

#

AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\templates\msg\index.html

#

That's one of the places it looked for the tempalte

#

template*

shell heath
#

which onej

umbral echo
#

@opaque inlet what is your project tree ? Is template located in your app?

opaque inlet
#

Yeah, the template is located in the app

#

msg is the name of the app

umbral echo
#

It should be msg/index.html

#

But since you created a directory

#

Should it be msg/msg/index.html?

opaque inlet
#

I don't believe so

#

I went to the directory that django was looking for and I don't see a msg app there

#

Yeah, my templates aren't there

#

Maybe those could be the alternative templates that it would be looking for?

#

I believe django is also the right version

#

3.1.6

#

ok I fixed it

#

So basically, I defined DIRS and had the path to my templates folder

#

and it returned the index.html file that I was looking for

wooden ruin
elder nest
#

I am making it so the dashboard has myip/dashboard?code=accesscode&id=guildid

#

but I cant figure out how to get the guild stuff

wooden ruin
#

if you are able to get a guild's id within the function, then all u have to do is query your database for the guilds id

#

so something like SELECT * FROM guilds WHERE id = 1 or something like that

elder nest
#

ok so I have to make a database with guild info

wooden ruin
#

yes, assuming you want to store the info of each guild

elder nest
#

I already have a database but I mean a table

wooden ruin
#

yep

elder nest
#

I already have that but it doesnt have the guild name in there

#

so I will make a different section with the guilds name and some other info in there

wooden ruin
#

start by planning out your table - plan out every field per row, and what kind of fields they will be. then you can query a guild by its id, name, etc.

elder nest
#

I am using mongodb so I can edit it but yeah I want, id, name, amount of users, and maybe who the owner is

wooden ruin
#

you would likely want to create a user table then and use a foreign key in the guild table

elder nest
#

wdym

limpid halo
#

So I have an existing game engine package I've written for blackjack and want to use it to supply the logic for a javascript/css-based web interface, would flask be a good package to learn for this purpose?

#

I might do customizable rock paper scissors first because I have an engine written for that too

serene plover
#

some guy told me to get help here

#

it has no issues, i just want to somehow compare "test" to a string with an if statement but idk how

whole crow
#

@serene plover if test == "something":

serene plover
#

ik but like

limpid halo
#

wow flask is neato

serene plover
#

print(test) is

<div class="ac-logo"></div>
</div>]```
vestal hound
#

what kind of comparison do you want to perform specifically

vestal hound
#

it's a ResultSet

serene plover
#

i want to compare test to
[<div class="title-wrap"> <div class="ac-logo"></div> </div>]

#

with an if statement

whole crow
#

that seems like a strange thing to compare to. What are you really trying to determine?

serene plover
#

so like if the contents of the link has that html code:

vestal hound
#

why?

serene plover
#

im making a simple program

#

possible?

vestal hound
#

possible

#

but why

serene plover
#

wdym why

#

im practicing with this stuff

vestal hound
#

that's not something you would generally do

serene plover
#

rn im trying to compare the contents of the given link to that html code

vestal hound
#

and accordingly

serene plover
#

and its part of a simple small program

vestal hound
#

it's not easy

#

to do that with BS4

#

because

#

that's actually a BS4 object

#

that represents some HTML

#

it's not raw HTML

#

I mean

#

you could (though I don't remember the API)

#

presumably .html or something

#

then compare it to a string

#

but that's p weird

serene plover
#

if its hard with bs4 i can try using other scraping modules

#

but still i dont know how to compare the url contents to an html code

vestal hound
vestal hound
chilly falcon
#

in django auth_user of what type of user??

#

i mean auth_user table in django databases??

dusty sapphire
#

How do you guys save global variables in flask. I have used a dictionary to keep values that was inputted and the dictionary always omit some dictionary keys whenever it is deployed

#

in development, it's fine but when lots of people access it, it gets an error. I think it's because there's a lot of people accessing the same dictionary.

#

What would be an alternative of a global variable that doesn't get errors whenever it is being modified by different web browsers?

quiet ridge
#

How to store images in SQLite db with flask SQL alchemy

chilly falcon
solemn fractal
inland copper
#

how to add preloader to a webpage that will run until the page is loaded

native tide
#

Hey, i need complex help

#

Can someone?

#

i have this ```py
def add_values():
file = open("templates/index_graph.html","a")
file.write("<body>\n")
for name,key in difference.items():
file.write(f"<tr><td>{name}</td><td> {key} </td>")
file.write("\n</body>\n")
return render_template("index_graph.html")

#

why>:

opaque rivet
#

do file.close() after all of the changes

native tide
#

oh

native tide
#

site

#

@opaque rivet why?

opaque rivet
#

what is the output of difference.items()

native tide
#

its dict

native tide
#

this

opaque rivet
opaque rivet
#

and the reason you only see one cycle out of the 3 times you tried, is because you're wrapping it in <body> tags. Each HTML document can only have one pair of <body> tags.

#

don't you think it would be easier using jinja2 templates right now?

native tide
#

how?

#

i mean, thats the point, adding tables to that html

opaque rivet
# native tide how?

how what? using jinja2 templates? It would be much more readable & you should definitely use them, they give you more flexibility.

#

you don't want to have to be opening html files and writing stuff to the end of the file

#

that's not going to work in the long run

native tide
#

why>?

opaque rivet
#

what if you want to edit something at the top of your file? are you going to append huge chunks of HTML in your python views?

native tide
#

yeah

#

thats true

opaque rivet
#

with jinja2 templates you can have for loops, conditionals, and you can extend other templates... Overall it means you write much less HTML, and it allows you to easily communicate with your view

native tide
#

what u would recommend of doing this?

#

i mean, what way

opaque rivet
#

use jinja2 templates

#

watch a video on flask templates and you'll understand

native tide
#

thanks

twilit thorn
#

guys can someone help me set up my django sever

left crystal
#

How to preserve value of radio button on the page, after the form is submitted using flask?

opaque rivet
mint tangle
elfin bluff
#

Hello

#

how to execute an .exe from django webapp ?

ornate burrow
#

why does my modal not show its contents?

dbc.Modal(
            [
                dbc.ModalHeader("Header"),
                dbc.ModalBody("This is a modal "),
                dbc.ModalFooter(
                    dbc.Button(
                        "Close", id="close-centered", className="ml-auto"
                    )
                ),
            ],
        id="modal",
        is_open=True,
        centered=True)
distant trout
#

need some css help

#

want to put these panels inside of a container so they go side by side

#

instead of all stacked on top of each other

#

something like this

thick sinew
#

Try css grid containers

#

Or inline-block

distant trout
#

ahh thanks, let me try out both of those

native tide
#

Hey I am looking into deployment my first Flask app, if I choose to use PostgresQL do I need to host it on a different server from where I host the Flask app?

distant trout
distant trout
#

they give u a free postgresql database

#

and free 500 hrs worth of hosting time every month

native tide
#

Thanks! I'm guessing that Heroku is beginner friendly?

#

Don't know much about it.

quick cargo
#

often most thinks like this will run them together unless your a large company scaling across multiple servers

distant trout
#

In this video I'll show you how to push your Flask App to Heroku for Webhosting for free!

Webhosting apps can be tricky, but it doesn't have to be. In this video we'll install the gunicorn web server, create a requirements.txt file and a Procfile, set up git version control, install the free Heroku toolbelt, and then push our app to Heroku for...

โ–ถ Play video
native tide
#

Thanks.

#

I appreciate that

elder nest
#

this kind of goes here but also is database

    collectionfound = await collection.find_one(ping_cmm)
RuntimeError: Task <Task pending name='Task-40' coro=<ASGIHTTPConnection.handle_request() running at /opt/virtualenvs/python3/lib/python3.8/site-packages/quart/asgi.py:72> cb=[_wait.<locals>._on_completion() at /usr/lib/python3.8/asyncio/tasks.py:518] created at /opt/virtualenvs/python3/lib/python3.8/site-packages/quart/asgi.py:28> got Future <Future pending cb=[_chain_future.<locals>._call_check_cancel() at /usr/lib/python3.8/asyncio/futures.py:360]> attached to a different loop```
 I am getting that error with this code 
```@app.route('/dashboard', methods=['GET'])
async def dashboard():
  id = request.args.get('id')
  collection = app.db["main"]
  guild_id = id
  ping_cmm = {"_id":guild_id}
  collectionfound = await collection.find_one(ping_cmm)
  name = collectionfound["name"] 
  return await render_template('dashboard2.html', gname=name, gid=id)```
 and here is where I set up app.db 
```app = Quart(__name__)
mongo_url = os.environ.get("MONGO_URL")
cluster = motor.motor_asyncio.AsyncIOMotorClient(mongo_url)
app.db = cluster["discorddatabase"]```
quick cargo
#

are you running your bot and webserver together by any chance pithink

quick cargo
#

what server are you using to run quart?

#

uvicorn?

elder nest
quick cargo
#

no but i mean, what webserver

#

like gunicorn, uvicorn, etc...

elder nest
#

idk I just imported quart

quick cargo
#

okay, in that case you're using the debug server

elder nest
#

ok

#

any ideas on how to fix it?

quick cargo
#

i gotta check Quart RQ, if it's doing what i remember it does then i have an idea

#

Are you just running the file like you would normally

#

e.g.

elder nest
#

yes

quick cargo
#

can you send me your code where you run quart

#

presumably app.run somewhere

elder nest
#
import motor
from motor import motor_asyncio
import os
import dns
from routes.discord_oauth import DiscordOauth

app = Quart(__name__)
mongo_url = os.environ.get("MONGO_URL")
cluster = motor.motor_asyncio.AsyncIOMotorClient(mongo_url)
app.db = cluster["discorddatabase"]

@app.route('/')
async def home():
  return redirect(url_for("login"))

# Route for index page
# Provides user login capabilities
@app.route('/login', methods=['GET'])
async def login():
    return redirect(DiscordOauth.login_url)


# Route for dashboard
@app.route('/selectserver', methods=['GET'])
async def selectserver():
    code = request.args.get('code')
    access_token = DiscordOauth.get_access_token(code)

    user_object = DiscordOauth.get_user(access_token)
    user_guild_object = DiscordOauth.get_user_current_guild(access_token)

    id, avatar, username, usertag = user_object.get('id'), user_object.get('avatar'), user_object.get('username'), \
                                    user_object.get('discriminator')

    return await render_template('dashboard.html', render_user_avatar=f'https://cdn.discordapp.com/avatars/{id}/{avatar}.png',
                           render_username=f'{username}#{usertag}', render_guild=user_guild_object, code=code)

@app.route('/dashboard', methods=['GET'])
async def dashboard():
  id = request.args.get('id')
  collection = app.db["main"]
  guild_id = id
  ping_cmm = {"_id":guild_id}
  collectionfound = await collection.find_one(ping_cmm)
  name = collectionfound["name"]
  return await render_template('dashboard2.html', gname=name, gid=id)


if __name__ == '__main__':
      app.run(host='0.0.0.0', port=8080, debug=True)
#

theres just the whole file

quick cargo
#

what you can do that might work

#

is import asyncio

#

get a event loop at the top of your file just after the imports

#

e.g.

#

loop = asyncio.get_event_loop()

#

then pass app.run() loop=loop

#

so that it forces quart to use the given event loop rather than what it does by default which is create a new one

elder nest
#

ok

quick cargo
#

that should? fix it, otherwise you might need to give motor a explict loop kwarg

elder nest
#

ok now I am not getting that error

#

but now it is showing that nonetype object is not subscriptable but its not none

quick cargo
#

send the stack trace

elder nest
#

heres the database

quick cargo
#

can you send the full error aswell

elder nest
#
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/quart/app.py", line 1862, in handle_request
    return await self.full_dispatch_request(request_context)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/quart/app.py", line 1887, in full_dispatch_request
    result = await self.handle_user_exception(error)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/quart/app.py", line 1104, in handle_user_exception
    raise error
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/quart/app.py", line 1885, in full_dispatch_request
    result = await self.dispatch_request(request_context)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/quart/app.py", line 1933, in dispatch_request
    return await handler(**request_.view_args)
  File "app.py", line 48, in dashboard
    name = collectionfound["name"]
TypeError: 'NoneType' object is not subscriptable```
#

actually wait

quick cargo
#

your guild_id in that code is gonna be a string rather than a int

buoyant shuttle
#

any expereince react dev in here

#

need help

quick cargo
#

so your find_one is going to return none because mongo does str != int

elder nest
#

ok one sec

quick cargo
elder nest
#
async def dashboard():
  id = request.args.get('id')
  collection = app.db["main"]
  guild_id = int(id)
  ping_cmm = {"_id":guild_id}
  collectionfound = await collection.find_one(ping_cmm)
  name = collectionfound["name"]
  return await render_template('dashboard2.html', gname=name, gid=id)```
quick cargo
#

what's the url you're requesting?

buoyant shuttle
#
grabsEachSubmission(index){
        let miniState
        fetch("/reddit/api/stocks-hot-wallstreetbets")
        .then((response)=> {
            if (!response.ok) {
                alert("Something went wrong with http requests, try refresh the page")
            }
            else{
                return response.json()
            }
        })
        .then((data)=>{
            miniState = {
                index:             index,
                text:             data[index].title,
                author:         data[index].author,
                upvotes:         data[index].upvotes,
                comments:          data[index].comments,
                upVotesRatio:     data[index].up_votes_ratio,
                url:             data[index].url,
                dateCreated:     data[index].date_created,
                timeCreated:     data[index].time_created,
                length:         data.length,
                jsonData:          data
            }
        })

    }
``` this is the function
#

i want to return miniState, but when i call the function it says undefined(that was when i returned it) how do i return miniState then?

quick cargo
#

It's not quite that simple because it's a promise

buoyant shuttle
#
handleSubmission(){
        const props = this.state
        const obj = this.state.jsonData
        const array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
        // const keys = Object.keys(obj)

        if (this.state.text === "Loading Making Api call") {
            alert("Loading")
        }
        else{
            console.log(this.state)
        }        
        return(    
            <React.Fragment>
                {array.map( (x,index)=> 
                    console.log(this.grabsEachSubmission(index))
                )}    
            </React.Fragment>
        )
    }
``` this is the function that conosle logs the other function
quick cargo
#

so your grabEachSubmission is gonna return before the request comes back

buoyant shuttle
#

i see

#

how do i return it then?

quick cargo
buoyant shuttle
#

ty

quick cargo
#

but Tl;DR you basically need to update the react state after the promise has resolved

buoyant shuttle
#

Not found when i click the pafe

#

fixed it no worrie

night agate
#

whats the problem here ?

elder nest
#

how would I make it so there is an update button and whatever is in this box gets updated in my database

mortal pike
#

I need to build a status field in my model(DJANGO), however I can't decide whether to use a Charfield(Uneditable), foreignkey. It just needs to display one of three options depending upon a query query from the database. Any recommendations?

native tide
#

How to display graph on my website?

mortal pike
stable hemlock
opaque rivet
#

@native tide render matplotlib graphs or use d3.js

median ridge
#

I am trying to work with bs4 and I want to retrieve the number after </span> how can I do that?

serene prawn
#

Would try to help you

quick cargo
#

easiest method is just make the soup and then soup.text which will remove the tag and then let you strip off that $ if it doesnt already

serene prawn
quick cargo
#

it normally depends on the tags, but yeah i wouldnt expect it to strip an inline tag like that

#

would go against the behavior of html

serene prawn
#

Guess you can also remove that span from dom

html = "<div class='price-large'><span class='symbol'>$</span>57,917.91</div>"

soup = BeautifulSoup(html, features="html.parser")
soup.select_one(".symbol").decompose()
print(soup.find("div").text) #>>> 57,917.91
#

@quick cargo Can you help me a bit if you're not busy?

quick cargo
#

whats up?

serene prawn
#

How should i go about implementing authentication in my frontend and backend?

quick cargo
#

What sort of auth and what for?

#

like API auth, or general user login stuff

serene prawn
#

User login, but basically it would be an api auth too ๐Ÿ˜…

#

Because you need to access application api from frontend

quick cargo
#

Hmm, well i think the best sort of setup for that would probably be Oauth2

#

as it makes sure you follow a fairly secure setup and minimizes the risk of something going wrong

#

its basically the concept of

#

user sends a request with a given auth method, this can be username and password in cases

#

server validates this data

#

and returns a Token

#

and any interactions the user does go through the token

#

that token automatically expires after a given time unless it's renewed

serene prawn
#

I don't really want to use oauth because it looks complex though.

quick cargo
#

what framework / lib are you using for your backend?

serene prawn
#

I work with laravel and use django occasionally

quick cargo
#

Django has a really good Oauth lib pre made

#

that does all of the hard work for you

#

I imagine laravel will as well because it's the Django of PHP lol

serene prawn
#

Not really

#

I personally don't like it

median ridge
quick cargo
#

nice lib overall and makes it very easy

#

if you want something a little simpler you can go with the sort of default user name and password type deal but generally i recommend against it because it can be less secure

serene prawn
#

Btw is there application level middlewares in django?

#

Say for specific apps

quick cargo
#

Im not sure tbh

#

Generally the python framework eco system seems to not like doing that for what ever reason idk

serene prawn
#

I know you can decorate your view with middlewares tho

serene prawn
#

I didn't find anything in django docs

#

at least on that page

quick cargo
#

request is an HttpRequest object. view_func is the Python function that Django is about to use

serene prawn
#

So i'm just curious if there's such feature

quick cargo
#

that hook appears to be invoked just before a given view is invoked and gives you all the context for that

#

other than that idk

serene prawn
#

Btw did you try vue or any other js framework?

quick cargo
#

I mean i use both Vue and React

#

personally i prefer vue though

serene prawn
#

I don't like jsx because there's no directives and stuff that vue has

#

Otherwise i think i would use react though

#

Angular is also nice but i didn't like rxjs ๐Ÿ˜…

hardy cosmos
#

hey, i'm using flask and I'm having trouble returning json data to an ajax call without changing the page. when I return the json it just displays as text on the page. code screenshots to follow...

#

any help would be greatly appreciated, ive tried using different methods of returning the json but i cant get it working

quick cargo
#

i believe you can just return the dict as normal instead of jsonify now

hardy cosmos
#

that still has the exact same result ๐Ÿ˜ฆ

quick cargo
#

can you send a SS of the headers it's returning

hardy cosmos
#

yep

#

this is all its returning

#

so its like the json isnt being returned correctly its just being dumped as text

quick cargo
#

hmm

#

and ajax cant handle this using JSON.parse() ?

#

oh well looking at your ajax code it seems you're just reading the JSON as a string anyway

#

so it makes sense that it's displaying it like that

hardy cosmos
#

how do i parse it in not as a string?

#

sorry im a web design noob

quick cargo
#

you need to do let foo = JSON.parse(text) to convert it to a JSON object

hardy cosmos
#

thanks, one sec ill try that

median ridge
#

I am running this function on loop but every time it gives the same value is their any way I can refresh the request or something like that to update the value?

hardy cosmos
#

sorry what do I need to pass in as the argument to parse @quick cargo ? using the response argument from the anonymous function doesn't change anything and im not sure what else I can use

quick cargo
#

note that if you're just displaying this to some html element it's gonna look like text not json

slow junco
#

hello guys, Im a python beginner and im interested in learning Django for making Webapps but I also heard about Flask. Does someone know if Django and flask are made for different purposes ?

quick cargo
#

they both achieve the same goal just in diffrent ways

#

Django is what you would call a Full Framework meaning it has all the batteries included like Middleware, auth, database ORM etc...

native tide
quick cargo
#

Flask is what's called a micro framework, so it doesnt ahve so much of the bells and whistles

#

Flask is considered more flexible in terms of working style while Django is very opinionated

native tide
quick cargo
#

I mean start at which ever you want

hardy cosmos
quick cargo
#

literally doesnt matter which one you pick, both will teach you things

native tide
#

flask/fastapi is good to start

quick cargo
hardy cosmos
#

oh okay

#

i cant get it to work with json.parse either ๐Ÿ˜ฆ

quick cargo
hardy cosmos
#

same result

quick cargo
#

do you mean that it's still looking like a string?

hardy cosmos
#

yeah so my intention is to take the response and use it with javascript to modify text on the page, but instead flask is just sending me to a blank page with the json printed out as plaintext

quick cargo
#

what does console.log(text) do

hardy cosmos
#

same result

quick cargo
#

you should note that anything which isnt a direct JSON response from the server wont have the browser lint it

#

your browser will only pretty print json like that if it's the direct response

#

what you have going on is dynamic where the main webpage is HTML so the browser is going to display it like HTML

#

if you're just trying to display the returned json then it is going to look like text because the browser isnt going to pretty print it like you would expect from a direct JSON response

quick cargo
hardy cosmos
#

yeah sure, and i dont want to display the returned json at all i just want to store it as a variable

native tide
hardy cosmos
hardy cosmos
native tide
quick cargo
#

basically Curl but with electron

hardy cosmos
#

ill have a look at it

quick cargo
hardy cosmos
#

the console doesnt seem to even be printing the response so im not sure what thats about

quick cargo
#

What is the server logging?

#

also brb gotta do some jobs rq

hardy cosmos
#

these are the only server logs

distant trout
#

i love postman

#

makes working with api so much easier and later implementing in code

rugged charm
#

I am new to #Django-rest-Framework. I am trying to create a public POST api and on display it should also have the HTML form like it does with the class based views.

Here is my view.

@api_view(['POST'])
@permission_classes([permissions.AllowAny, ])
@authentication_classes([])
@renderer_classes([JSONRenderer, BrowsableAPIRenderer])
def lead_create(request):
    serializer = LeadSerializer(data=request.data)

    if serializer.is_valid():
        try:
           serializer.save()

        except Exception as e:
            return Response(
                str(e),
                status=status.HTTP_400_BAD_REQUEST
            )

        return Response(
            {'message': 'Lead Successfully Saved'},
            status=status.HTTP_201_CREATED
        )

My problem is the output is something like below:
https://i.stack.imgur.com/OKlUs.png

Why am I not getting the HTMLForm even when i have added the 'BrowsableAPIRenderer' renderer class

native tide
native tide
rugged charm
#

@native tide how to use post in the browser, In the browser this is how you view the apis

rugged charm
native tide
maiden tulip
#

After writing my first website with Django, I am looking into learning Node for a potential job. Only basic JS knowledge so far, but not new to programming. My idea was to create a tinder clone as my first project, but I am unsure about the technology to use.
MERN/MEAN/MEVN stack sound like what I should be heading for, with MERN>MEAN as Angular to me seems like it has a high learning curve. Not sure about Vue.
I am also unsure about the advantages of Mongo - being somewhat experienced in Postgre, PERN also seems like an alternative.

Also thinking about using Firebase, but I am unsure about GDPR regulations (and Tinder-Data is intimate data, so I guess GDPR applies more heavily?). For my Django Project I used Heroku and AWS S3 for deployment.

Thanks for your time

median ridge
serene prawn
#

So probably the price just didn't update?

median ridge
serene prawn
#

Well, that's strange, could you show the whole program?

median ridge
#

sure

#
from discord.ext import commands, tasks 
from discord.utils import get
import cryptocompare
import sys
import os
from bs4 import BeautifulSoup
import requests
import re

print(cryptocompare.get_price('BTC', 'USD'))

TOKEN = ''

PREFIX = '!BTC'

SERVER_MSG = '[BTC] '


# web scrape
async def retrieve_btc():
    URL = 'https://www.coindesk.com/price/bitcoin'
    with requests.get(URL) as page:
        soup = BeautifulSoup(page.content, 'html.parser')
        results = soup.find(id='__next')
        job_elems = results.find_all('div', class_='price-large')  #btc price 
        job_elems = str(job_elems[0])
        job_elems = job_elems.replace('<', '>')
        job_elems = job_elems.split('>')
        #print(job_elems)
        BTC_VALUE = str(job_elems[4] + job_elems[6])
        print(BTC_VALUE)
        page.close()
        page.cookies.clear()
        return BTC_VALUE


#with open('token.txt', 'r') as f:
#    TOKEN = f.read() 

client = commands.Bot(command_prefix = PREFIX)

@tasks.loop(seconds = 60)
async def update_crypto():
    btc_price = await retrieve_btc()
    act = discord.Activity(name = f'{btc_price}', type = discord.ActivityType.watching)
    await client.change_presence(status = discord.Status.online, activity = act) #24hr return
    #print(server_msg + "Bot Activity Updated")
    
    # changing the bot nickname
    guilds = client.guilds
    for guild in guilds:
        members = guild.members
        for member in members: 
            if member.name == client.user.name: 
                await member.edit(nick = btc_price)   #change the BTC price to the price


@client.event
async def on_ready():
    print(SERVER_MSG + 'The Bot is Online!')
    update_crypto.start()    





print(SERVER_MSG + 'Starting....')
client.run(TOKEN, reconnect = True)
print(SERVER_MSG + 'Bot Ended')```
#

@serene prawn

serene prawn
#

Can you actually check if that function is being called?

median ridge
#

yeah it prints out the value everytime

serene prawn
#

maybe that website is doing some caching though

median ridge
#

yeahh might be

#

to prevent the bots

#

:(

serene prawn
#

Can't you use some public api for that?...

median ridge
#

most of them are paid

serene prawn
#

Try to user cache-control header maybe?

elder nest
#

I cant figure out how to get rid of something out of a disctionary I get from a discordoauth object
someone helped me get this code
sharedguilds.pop(next(i for i, guild in enumerate(sharedguilds) if guild['id'] == strid))
but it doesnt remove anything from the dictionary
here is an example of one of the servers in the dictionary
{'id': '805225643734204416', 'name': ':sun_with_face:SunnySide:sun_with_face:', 'icon': '72288469be9cabeaff946a07fbeea98f', 'owner': True, 'permissions': 2147483647, 'features': ['WELCOME_SCREEN_ENABLED', 'PREVIEW_ENABLED', 'NEWS', 'MEMBER_VERIFICATION_GATE_ENABLED', 'COMMUNITY', 'INVITE_SPLASH', 'ANIMATED_ICON'], 'permissions_new': '8589934591'}

#

here is my full code

@app.route('/selectserver', methods=['GET'])
async def selectserver():
    code = request.args.get('code')
    access_token = DiscordOauth.get_access_token(code)

    user_object = DiscordOauth.get_user(access_token)
    user_guild_object = DiscordOauth.get_user_current_guild(access_token)
    print(user_guild_object)
    botguilds = []
    userguilds = []
    sharedguilds = user_guild_object
    collection = app.db["main"]
    for document in await collection.find().to_list(None):
      guildid = document["_id"]
      guildid = int(guildid)
      botguilds.append(guildid)
    for guild in user_guild_object:
      guildid = guild['id']
      guildid = int(guildid)
      strid = str(guildid)
      if guildid in botguilds:
        pass
      else:
        sharedguilds.pop(next(i for i, guild in enumerate(sharedguilds) if guild['id'] == strid))
    print(botguilds)
    print(userguilds)
    print(sharedguilds)
    id, avatar, username, usertag = user_object.get('id'), user_object.get('avatar'), user_object.get('username'), \
                                    user_object.get('discriminator')

    return await render_template('dashboard.html', render_user_avatar=f'https://cdn.discordapp.com/avatars/{id}/{avatar}.png',
                           render_username=f'{username}#{usertag}', render_guild=sharedguilds, code=code)```
#

I am trying to get it so it only shows the shared servers on my dashboard

#

but right now it still shows all of them

median ridge
sand glen
#

hi! i want to make a button that adds a new <entry> on the page. how would i do this in flask? do i need to use JS or can i use jinja?

#

my backend is written in flask

serene prawn
#

If you want to persist that data then you would have to save it on your backend

#

If you just want to add the element then just do that with js

sand glen
#

thing is

#

i dont know how

#

jquery?

serene prawn
#

If you're pretty new to js then learn how to insert new elements into dom

sand glen
#

i have never used JS before

#

in my project i have python, CSS and HTML only

serene prawn
#

You can either use native js or jquery but for anything more complex I would use js framework ๐Ÿ˜…

sand glen
#

like react?

#

can i use react with a python backend

serene prawn
#

You can

#

There's also vue and angular

#

They are more like frameworks when react is a library

#

But react and angular have better typescript support

sand glen
#

isnt typescript only useful backend

#

also

#

arent those JS libraries way better if you use JS backend

serene prawn
#

It's not

#

And you can use any backend

sand glen
#

oh

serene prawn
#

It doesn't really matter

sand glen
#

if im going to use react

#

should i ditch bootstrap

serene prawn
#

Plus typescript can be useful anywhere

#

Use bootstrap if you like it

#

There should be a react library with bootstrap components or you can just do that with classes

sand glen
#

so all i need to do is add react to my <head> and i can use it

serene prawn
#

Try create-react-app

buoyant shuttle
#

shey guys sorry again, back with another question

#
function callback (x, index){
            var text
            function handleTextProp(index){
                const xhr = new XMLHttpRequest();
                xhr.open("GET", "/reddit/api/stocks-hot-wallstreetbets?format=json")
                xhr.onload = () => {
                const data = JSON.parse(xhr.response)
                text = data[index].title
                }
                xhr.send()
            }
            console.log(text,index)
            return(
                <React.Fragment>
                {handleTextProp(index)}
                <Submission text="placeholder" key={index}/>
                </React.Fragment>
            )
        }
```  how do i make "text" variable public. When i make my get request and assign it to test, its only avaliable within that scope, once i move out of the onload event listener it isnt
sand glen
#

in flask

buoyant shuttle
#

how would i make text, a global variable like global in python

cedar cedar
#

Making request to yahoo website, after some point I get this error: {code: "internal-error", description: "offset and size is over threshold"} code: "internal-error" description: "offset and size is over threshold" result: null

opaque rivet
# median ridge yeahh might be

IEX cloud is a great API for that sort of thing, the rate limiting is quite loose so you can get away with making a request every minute on the free plan.

opaque rivet
# sand glen i already have an app though

if you're using React, the frontend is independent of your backend. You'll just use Flask as an API and have your React app as a SPA (single page application - this means that your server just renders 1 page and all of the future rendering of components is done by the client) - unless you use server side rendering but that's a bit more complex.

by doing create-react-app you will make a new folder where you can create your frontend.

sand glen
#

oh ok

buoyant shuttle
#

how do i access my state inside onload event listener of xhr?

#
    at XMLHttpRequest.xhr.onload (DemoBox.js:157)```
opaque rivet
# sand glen should i ditch bootstrap

also, you still have to write HTML with React, so bootstrap is can still be used - but you can also use UI libraries (ant design / chakra UI) to speed up your frontend development.

if you don't know JS you should learn it before learning react.

opaque rivet
#

are you trying to doXMLHttpRequest.xhr.onload.state?

buoyant shuttle
#

want to accss my component state

#
handleSubmission(){
        const props = this.state
        const obj = this.state.jsonData
        const array = [1,2,3]
        // const keys = Object.keys(obj)

        if (this.state.text === "Loading Making Api call") {
            alert("Loading")
        }
        else{
            console.log(this.state)
        }

        function callback (x, index){
            var text
            function handleTextProp(index){
                const xhr = new XMLHttpRequest();
                xhr.open("GET", "/reddit/api/stocks-hot-wallstreetbets?format=json")
                xhr.onload = () => {
                    const data = JSON.parse(xhr.response)
                    text = data[index].title
                    console.log(this.state) // gives error
                }
                xhr.send()
            }
            console.log(this.state, index,"test") // can access state
            return(
                <React.Fragment>
                {handleTextProp(index)}
                <Submission text="hello" key={index}/>
                </React.Fragment>
            )
        }        
        
        return(    
            <React.Fragment>
                {array.map(callback, this)}
            </React.Fragment>
        )
#

part that matters

function callback (x, index){
            var text
            function handleTextProp(index){
                const xhr = new XMLHttpRequest();
                xhr.open("GET", "/reddit/api/stocks-hot-wallstreetbets?format=json")
                xhr.onload = () => {
                    const data = JSON.parse(xhr.response)
                    text = data[index].title
                    console.log(this.state) // gives error
                }
                xhr.send()
            }
            console.log(this.state, index,"test") // can access state
            return(
                <React.Fragment>
                {handleTextProp(index)}
                <Submission text="hello" key={index}/>
                </React.Fragment>
            )
        }        
        
        return(    
            <React.Fragment>
                {array.map(callback, this)}
            </React.Fragment>
        )
native tide
#

In django, I'm trying to get one model in one app to be a foreign key for another model in another app, both of course in the same project. i can do this with User, but any app i make, i cant' sibling import? I've tried making the project a package but this is honestly like why in the world would django talk about reusable apps if you can't reuse them in such a manner>

native tide
daring cairn
#

new to flask, trying to build a basic web app that does media conversion and uploads to cloud. getting 404's as well as home() needs more than one argument but 0 passed can you help debug this plz? atm just trying to upload files to s3 storage nothing too fancy

lavish prismBOT
#

Hey @daring cairn!

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

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

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

https://paste.pythondiscord.com

daring cairn
#
    def __init__(self, hash_name):
        self.hash_name = hash_name

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

    def hash_username_fname_sname(fname, sname, username):
        to_hash = "{}{}{}".format(fname.lower(), sname.lower(), username.lower())
        hashed_name = hashlib.md5(to_hash).hexdigest()

        return hashed_name

    @app.route('/signup', methods=['post'])
    def signup(self):
        fname = request.form['fname']
        sname = request.form['sname']
        username = request.form['username']
        self.hash_name = self.hash_username_fname_sname(fname, sname, username)
        if request.method == 'POST':

            password = request.form['password']
            table.put_item(
                Item={
                    'first_name': fname,
                    'surname': sname,
                    'username': username,
                    'password': password,
                    'hash_key': self.hash_name
                }
            )

            msg = "Registration Complete. Please Login to your account !"

            return render_template('signin.html', msg=msg)
        return render_template('index.html')

    @app.route('/login')
    def login(self):
        return render_template('login.html')```
#
    def check(self):
        if request.method == 'POST':

            username = request.form['username']
            password = request.form['password']

            table = dynamodb.Table('rdy-user-credentials-table')

            response = table.query(
                KeyConditionExpression=Key('username').eq(username)
            )
            items = response['Items']
            name = items[0]['username']
            print(items[0]['password'])
            if password == items[0]['password']:
                return render_template("upload.html")
        return render_template("signin.html")

    @app.route('/')
    def home(self):
        return render_template("upload.html")

    @app.route('/upload', methods=['post'])
    def upload(self):

        if request.method == 'POST':
            img = request.files['file']
            if img:
                filename = secure_filename(img.filename)
                img.save(filename)

                s3.upload_file(
                    Bucket=BUCKET_NAME,
                    Filename=filename,
                    Key=self.hash_name
                )
                msg = "Upload Done ! "

        return render_template("file_upload_to_s3.html", msg=msg)


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

i introduced the class method and the error just happened

#

TypeError: index() takes exactly 1 argument (0 given)

opaque rivet
drifting wing
#

just curious if i should know how to make make things by hand in css and html or is it ok just to use bootstrap or something else. tks

naive oar
#

Hi all, does anyone have experience with uploading Django on Godaddy VPS?

dusk yoke
velvet crystal
#

is it possible to make a web site with python

#

or is html better for that

dusk yoke
#

@velvet crystal I think HTML is for front-end and Python for back-end, so you would need both.

twilit thorn
#

in the manage.py powershell i am creating new objects using the .objects.create command and it shows ive created them when i run .objects.all() however when i go onto the actual website i cant see that they have been created

#

does anyone know why this is?

silver sun
#

hey guys

#

I am running into CORS issues

#

i feel like i've tried somewhat everything

#

headings, flask-cors, tried running it on windows and linux

#

now that everything is on my linux computer i get 0 response back and it's not giving me a cors error but i feel sus about that. My last option is a proxy i suppose

#

if anyone has any good understanding to help me out, PLEASE DM ME. I'll show you my code

#

i am new to this, and could use all the help i can get

#

I'm using Flask and react. using the fetch api to call

silver sun
#

here is my stockoveflow post

trim geyser
#

does anybody know how to make a voting bot for online polls like polldaddy

gleaming mulch
#

@twilit thorn After you created the db objects did you run object.save()?

formal moth
#

Hi, does anyone know where I can host a Flask app online for free? I heard of Heroku and Netlify, do they work? Do they require any credit card details

mint hedge
#

I am writing a calculator flask app to calculate current draw for certain devices. Each has a set value but could change as updates to the devices occur (more or less current). I wrote a desktop version of this app and used a json file for all the values based on their settings (each device has about 5 different settings that determines the current draw).
I would like this easily editable by either a normal person or a simple IT person.
My question is, should I stick with json as my โ€œdatabaseโ€ or move over to something like SQLite?

mint hedge
formal moth
mint hedge
#

It is free for one site. They make the domain for you. Say you used you screenname, it would be www.donald@pythonanywhere.com or something like that

#

It is great for testing

formal moth
#

If I have a raspberry pi at home, would it be better if I hosted it there? Would there be any security risks? Such as ddos, my home network being hacked, etc?

mint hedge
#

Not production

mint hedge
#

And if you are afraid of being hacked, plug it in at the library ๐Ÿ˜‚

formal moth
#

Thanks! Do alternatives such as heroku or netlify work? I have seen people use those for hosting side projects

mint hedge
#

No idea.

#

I bug my sys admin at work with these questions

#

I am apparently on the IT deptโ€™s watchlist

#

Because โ€œlinux bad!โ€ And I know what a raspberry pi is and the furthest extent to the knowledge my IT manager has is by watching Mr. Robot

#

I am not too smart in networking. I know the basics. I am more a desktop guy myself.
My IT dept keeps making us watch videos from Kevin Mitnick's company and he shows how he can hack a mac to get the keychain password through an email. He never shows HOW he does it though (code or anything). I am not looking to hack people but i find the concept fascinating and want to see the methods used.......... yea, maybe i should be on the watch list

#

anytime someone at work leaves their computer open when they walk away, I open notepad and type "Thanks for the info"

#

I even got my IT manager one time. That was awesome

#

for him, i wrote "now I have the keys to the kingdom!"

native tide
#

@daring cairn have you tried adding <string:self> to the URL decorator so that it is like @app.route ('/<string:self>'). But why are you passing self? You don't seem to be using it in that function.

stable ledge
#

I want to have Javascript web clients connect to a Python server and send files and data from client to server and same for the reverse. How may I go about this?

native tide
#

does anyone know why i have been gettign this error i went inactive and left my site for 2 months then the header was messed up and theres this error

#

im not really good with web development i started in january

#

may I see your code?

#

get rid of the intergrety and try again

#

oh

#

thanks

#

it worked but idk why it suddenly stopped

#

before i left the site it was fine

#

the website stopped?

#

not like stopped but the navbar went really ugly

#

and had none of the bootstrap

versed python
native tide
#

is it possible to make the navbar one file with html

#

instead of putting it on the top of every pages code

#

it would make it easier to edit but im not sure if i can do it with html

#

you wouldn't want to do that what I would do is make an index with all of your basic stuff like navbar and text stuff and then use that as the base of your website

#

does that make sense?

#

not really to me

#

liek do u mean for the mains ite

#

because it has multiple pages

#

this is the main page

#

here what exactly are you working on? is this for school or for someone else or just personal

#

just for fun

#

its jsut a site im showing my friends and making it for fun

#

Dope I have been doing Web dev since I was 12 do you want me to become your tutor I could teach you all of this stuff

#

this is what i mean by maybe having the navbar as one file so if it breaks i dont have to edit the pages

#

if you want

#

ive been messing with sites and jsut code stuff since 2018

#

but i started actual knowing how to do it in 2020

#

in 2018 and 2019 i didnt understand it so im not really good

#

I could teach you how to write this and so you could start doing web dev for other people in like 3-6 months

#

if you want you can

#

i dont really know php good

#

im better with html stuff

#

ok do you want to dm me?

#

alr

#

ill dm

native tide
#

what's the difference between name of web page

#

and name of web site

proper hinge
#

A site is made up of one or more pages

#

Think of it like book title (site) vs chapter title (page)

native tide
coarse egret
#

what does child and sibling meaning in css when refering to selectors?

inland stirrup
#

The child combinator (>) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the direct children of elements matched by the first.

The general sibling combinator (~) separates two selectors and matches all iterations of the second element, that are following the first element (though not necessarily immediately), and are children of the same parent element.

vestal hound
#

section time (descendant) selects time
section > time (direct descendant) selects nothing
div > time selects time
div + a (immediate sibling) selects nothing
div ~ a (sibling) selects a
img + a selects a

inland stirrup
#

Django

class Category(models.Model):
     bid= models.ManytoManyField(Listing)
     category= models.CharField()
---------------------------------------------------

What should my query be for getting all the objects related to a manytomany field that is bid in the above example

inland stirrup
vestal hound
inland stirrup
#

...if i do that will i get all the objects of Listing table?

vestal hound
#

wait

#

do you want the Listing

#

or the Category

inland stirrup
#

i want listing but from category

#

like if i want to get all the listing that are in a category

vestal hound
#

then it is as I said

#

why

#

is your attribute called bid

inland stirrup
vestal hound
#

but your model called Listing

native tide
#

@native tide i was able to do it

vestal hound
#

for a category object

#

so more accurately category.bid.all()

native tide
#

i jsut made the html file a php one and left my original code and put at the top a php include

#

then included the nav bar

inland stirrup
#

lemme try that just a sec

native tide
#

@native tide congratulations. Though I have no idea about PHP only Jinja2

inland stirrup
#

@vestal hound i love you !! it worked !!

native tide
#

yeah im not really good with php either

vestal hound
elfin bluff
#

hello

#

anyone working with django ?

inland stirrup
#

yeah wassup

rugged charm
hexed perch
#

hi, i have python and django interview tomorrow. which topics should i consider as most important? and which are common question?

serene prawn
rugged charm
#

lead-create/ is the endpoint that executes this fbv @serene prawn

serene prawn
#

yeah but

#

It says you're sending get request

#

not post

valid girder
rugged charm
serene prawn
#

You really can't ๐Ÿ˜…

#

Make a form or use postman or similar tool

rugged charm
serene prawn
#

A bit, yes

rugged charm
serene prawn
#

I think docs explain it well