#web-development

2 messages · Page 70 of 1

glass sandal
#

yes

wooden badge
#

Uncaught TypeError: document.getElementById(...) is null

(line 11) if (document.getElementById('img').src != "/static/uploads/AlpharaFavAoiOgata.png") { newimgpath = document.getElementById('img').src; }

glass sandal
#

Move your script tag to end of the document

wooden badge
#

i did

glass sandal
#

Hmmmm

#

Then change <script with <script defer

wooden badge
glass sandal
#

HMMMMMMMMMMMMM

#

idk why check the id

#

ok I am confused now lol

wooden badge
#

same id lol

#

js is

#

complicated XD

#

i feel like we re doing spaghetti code

glass sandal
#

yes

#

exactly

#

S P A G H E T T I

wooden badge
#

i wanted to send this

glass sandal
#

aaaa

wooden badge
#

brb

#

@ me if anything

glass sandal
#

kk

native tide
#

hello

#

i have a problem

#

when i do flask run it tells me ERROR could not import <projectname>

#

if anyone knows ping me

native tide
#

@native tide Did you set your FLASK_APP variable?

#

what do you mean by that

wooden badge
#

@glass sandal came back

glass sandal
#

aaa

wooden badge
#

wyd?

glass sandal
#

I mean

#

So

#

now what was your prib

#

prob*

wooden badge
#

hehe

#

well ofc i didn t fix that one

#

f in the chat

#

ok so remember when we did (function {} )

#

can i include more code in () ?

glass sandal
#

Yes

native tide
#

can anyone help

pulsar turtle
#

is django easy to learn

dapper tusk
#

there is a lot to learn, but it is not too complex

pulsar turtle
#

i assume you need to know python first

dapper tusk
#

yes

warm ridge
#

hi, anyone here has or knows where to get a django rest framework template with good practices implemented. and maybe many use cases with long bussines logic???

native tide
#

I am not even sure where to put this query:

elif request.method == "POST":
        # We have a post request.
        # If the post request is a form, the request json will return the data within
        # the form.
        
        json_obj = await request.json()

            #   If the command ping request is made then ---->>>
        if json_obj['json']['command_ping']:
            if json_obj == "1":
                print("Enabled ping")
                bot.command_ping = True
                command_ping = "on"

            else:
                print("Disabled ping")
                bot.command_ping = False
                command_ping = "off"

                # If command say is enabled/disabled
        if json_obj['json']['command_say']:
            if json_obj == "1":
                print("Enabled say")
                bot.command_say = True
                command_say = "on"

            else:
                print("Disabled say")
                bot.command_say = False
                command_say = "off"```
```html
<form action="/" method="POST" id="ping">
        <legend for="command_ping">Ping</legend>
                {% if command_ping == "off" %}
                <button value="1" name="command_ping" onclick="submitForm()" class="off">Enable</button>
                {% else %}
                <button value="0" name="command_ping" onclick="submitForm()" class="on">Disable</button>
                {% endif %}
        </label>
    </form>
    <form action="/" method="POST" id="say">
        <legend for="command_say">Say</legend>
                {% if command_say == "off" %}
                <button value="1" name="command_say" onclick="submitForm()" class="off">Enable</button>
                {% else %}
                <button value="0" name="command_say" onclick="submitForm()" class="on">Disable</button>
                {% endif %}
        </label>
    </form>```
#
    if json_obj['json']['command_ping']:
KeyError: 'command_ping'```
#

when I enable say this comes up and vice versa

real surge
#

Can someone tell me a good website to learn html and css ?

native tide
#

How does one make all of these moving dots clickable

ruby fjord
#

@native tide that would only work if you implemented all of the dots using some 2d canvas or something

#

you can't make items in an image clickable

dapper tusk
#

you could do it with svg animations, but I have no idea how well would it work

native tide
#

Is there a way to optimize it?

#

So that it loads such as one

untold oasis
#

I'm looking on how to secure the user credentials that were entered on my login page.
Currently i'm sending it as json to my backend server and saving it in db as plain text...
So my question is - Where do i encrypt my password? in the backend app before writing it to database? or before making the post request in javascript.
and also suggest the libraries.

dapper tusk
#

ideally, you do not use passwords at all and use something like oauth, passwords are PITA. Otherwise, you will need to research what the current best practice for storing passwords. Under no circumstance should you use anything other than a full dedicated password library on both server and client, not sure what the current one is.

untold oasis
#

hmm

dapper tusk
untold oasis
#

thanks

modest scaffold
#

can someone help me and explain why my submenu is going off to the side of the sceen

#

anyone?

brisk jay
#

Hey, so i',m working with flask. Error message is all.. deep flask stuff.

But i'm thinking my error is with the template code.

#
<div id="main-container">
    {% for result in data %}

    {% if result['result']['poster'] != 'N/A' %}
    <div class="container">
      <div class="box">blablabla
      </div>
      <div class="content">
        <p class="title">{{ result['result']['title'] or 'N/A'}}</p>
        <p class="sub-title">{{ result['result']['plot'] or 'N/A' }}</p>
        <div class="img">{{ result['result']['poster'] or 'N/A' }}</div>
      </div>
    </div>
    </div>
  </div>
    {% endif %}
#

Is this incorrect?

proper hinge
#

Can you show your view's code?

brisk jay
#

I fixed it, On the bottom I have missed a space on {% endblock%}

young maple
#
urlpatterns = [
    path("", views.outdex, name="outdex"),
]```
```py
urlpatterns = [
    path("app1/", include('app1.urls')),
    path('admin/', admin.site.urls),
]```
```py
def outdex(request):
    return HttpResposne("Hello world!")```
This is django
there is an error
I'm really not sure what to do
native tide
#

@young maple What seems to be the error?

odd oar
#

Probably the extra commas

#

You only need a comma if there is another element, don't put it for the last element

bleak bobcat
#

Doesn't matter in python

cold schooner
#

Is that mispelling of HttpResponse (HttpResposne) the problem? @young maple

young maple
#

Ohh

#

yeah

#

Thanks sorry for the late reply

#

I was out

#
Traceback (most recent call last):
  File "C:\Users\yapji\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\Users\yapji\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\yapji\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\yapji\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
    self.check(display_num_errors=True)
  File "C:\Users\yapji\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 392, in check
    all_issues = self._run_checks(
  File "C:\Users\yapji\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 382, in _run_checks
    return checks.run_checks(**kwargs)
  File "C:\Users\yapji\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
    new_errors = check(app_configs=app_configs)
  File "C:\Users\yapji\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "C:\Users\yapji\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver```
#

There is more

#

But I think it's easier if someone connected to code help vc

#

and I stream my screen

#

never mind got it to work

#
path("", views.outdex, name="somethingdex")```
#

could someone explain what the name= does

#

It doesn't change the title of the site

icy sparrow
#

Guys, is django working different in Linux than windows?

dapper tusk
#

I have had it work about the same

quasi cave
#

No the django works same with both linux and windows

icy sparrow
#

No, I mean is it different to develop, are there any command changes etc

dapper tusk
#

not really

#

you may need to use python3, but if you are in a venv, it should be python

nimble epoch
#

@native tide did you find the solution?

halcyon trail
#

wow

#

ok

#

good 4 u

#

st.sabina rulez

#

uh is that hacking

#

oh

#

OOOOOH i get it

#

no

#

no im not

#

what

#

did i do it wrong?

#

hello

#

Are you trolling? ._.
@native tide Are you trolling? hmh

#

screw what

#

do you not get it like me

#

are you not smart like me?

#

ur trying to troll

nimble epoch
#

Ok ok what’s the problem?

halcyon trail
#

@native tide is trolling

#

over a link

nimble epoch
#

No I mean what’s wrong with the code 🤣

halcyon trail
#

What the hell..?
@native tide hey! say bell

#

no cuss

#

idk whats wrong

#

I DONT KNOW CUZ IMMA LOSER OKAY.

nimble epoch
#

I DONT KNOW CUZ IMMA LOSER OKAY.
Ok.😉

#

@native tide you SQLALCHEMY_DATABASE_URI is wrong. Check it again

keen lily
nimble epoch
#

Yw

#

@keen lily sorry I’m not sure that I can help. I’m not master in django.

halcyon trail
#

try that one

modest scaffold
#

i need some help with CSS

#

how do i make a child element 100% height of the parent element

native tide
terse surge
#

hey peopl

#

ee

#

i have a question

#

are rest apis a good option for a lot of data?

fiery portal
#

sure why not

terse surge
#

you sure?

#

im thinking it would cause a lot of load on the web itself

#

else i would be using it

native tide
#

it think a api make a service even faster, because the data is raw

cold anchor
#

can you clarify "pressure on the web"?

#

do you mean the web server? or the whole of the internet?

quick cargo
#

it depends on the data but yeah a rest api is fine

#

ive ran API's handling 30k+ requests a second without and real 'load' per say due to it being a rest api

twilit zenith
#

hey, how can I create empty field in Django models

#

description = models.CharField(default='')

#

like this?

native tide
#

what datatype should have your filed?

#

*filed

terse surge
#

web is website for short, so web server

zealous siren
#

Rest APIs are very common, in fact, most sites are just Javascript frontends with data retrieved via REST API or WebSocket

brisk jay
#
Traceback (most recent call last):
  File "/home/krage/.local/lib/python3.6/site-packages/flask/app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/krage/.local/lib/python3.6/site-packages/flask/app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "/home/krage/.local/lib/python3.6/site-packages/flask/app.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/krage/.local/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/krage/.local/lib/python3.6/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/krage/.local/lib/python3.6/site-packages/flask/app.py", line 1953, in full_dispatch_request
    return self.finalize_request(rv)
  File "/home/krage/.local/lib/python3.6/site-packages/flask/app.py", line 1968, in finalize_request
    response = self.make_response(rv)
  File "/home/krage/.local/lib/python3.6/site-packages/flask/app.py", line 2098, in make_response
    "The view function did not return a valid response. The"
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
#

is there any way i can see what actually went wrong

#

No matter what type of error I do, this is the only thing i get.

#
                        <div class="embed-responsive embed-responsive-16by9">
                            <iframe class="embed-responsive-item" src="https://www.youtube.com/embed/{{ x.get_youtube_trailer(result['result']['title'], result['result']['released']) }}?rel=0" allowfullscreen></iframe>
                          </div>    
#
    def get_youtube_trailer(self, _title, year):
        year = year.split(' ')
        results = YoutubeSearch(_title + 'Trailer', max_results=10).to_dict()
        points = {}
        for i in results:
            id = i['id']
            points[id] = 0
            title = i['title']
            if _title.lower() in title.lower():
                points[id] += 1
            if 'movie' in title.lower():
                points[id] += 1
            if year[2] in title:
                points[id] += 1
            if 'official' in title.lower():
                points[id] += 2
            if 'hd' in title.lower():
                points[id] += 1
            if 'parody' in title.lower():
                points[id] -= 1
            if 'remix' in title.lower():
                points[id] -= 1
            if 'fanmade' in title.lower():
                points[id] -=1
        data = {k: v for k, v in sorted(points.items(), key=lambda item: item[1])}
        return str(list(data)[-1])
brisk jay
#

Made many attempts

#

¨Made it work, not sure what actually was the error, but it works now

frail estuary
#

okay, I don't really know how web security works as far as making API calls or what is exposed.

I have a React app making calls to a Flask backend, both of which are running on the same Heroku dyno. The react app first makes a get request with a user's username and password to the flask app, and it logs them in. If a user wants to update their profile they make a post request to flask. When I make the post request, should I pass in the user's password again and verify again inside flask?

#

As in, is it insecure to be able to make a post request that only needs a username? Again, everything is running in on heroku

terse viper
#

no, you shouldn't keep sending passwords

#

once you log in the first time, you should generate a token for the client, which identifies that particular login session. that token is presented next time, and has a limited lifespan

#

that's the most basic method. these days however, you would want to mint a JWT which can be a lot more flexible. At this point you should take a look at the various libraries that are available for this work

#

and React has libraries for JWT authentication (often via Redux). take a look at examples

frail estuary
#

okay, thanks!

terse viper
#

if you're developing both React and Flask, look for React JWT tutorial, and look for Flask JWT tutorial, and hopefully they meet in the middle

untold oasis
keen lily
#
11/Jul/2020 20:59:32] "GET /socketcluster/ HTTP/1.1" 404 2610
Not Found: /socketcluster/
#

what kind of error is this? it keeps getting spammed in the terminal every 45 seconds

#

found nothing on google

terse viper
#

something is pinging your /socketcluster/ path, likely automated bot scanning for vulnerabilities

keen lily
#

i don even have a socketcluster path

terse viper
#

if it is one of those, those bots have a list of possible vulnerabilities, you'll see paths like the wordpress admin page, or phpmyadmin login page, stuff like that

keen lily
#

why is there a bot

#

scanning my path

#

is that supposed to come with django

terse viper
#

no, it's someone else on the internet doing it

#

probably a dark web thing. they're likely running large amounts of automatic scans across the internet for sites with vulnerabilities

keen lily
#

yikes wtf

terse viper
#

this is why we use firewalls and we update software

keen lily
#

i just stopped running the code

terse viper
#

if it helps to know, having any web server open on a common port will be scanned. it's pretty much unavoidable

keen lily
#

ok this shouldn be an issue for me right

terse viper
#

probably

keen lily
#

did not know that wow thanks

terse viper
#

if you're just doing some dev for yourself, you can make it a bit less scary by using a non-standard port

#

you'll avoid most of the automated stuff

#

I don't think anyone's targeting you specifically, there's just a lot of automated bots out there hitting IPs at random on the hopes of finding an unpatched wordpress site or something

keen lily
#

it's local tho

#

does that mean anything

terse viper
#

oh

keen lily
#

like it's not even hosted anywhere

terse viper
#

oh my bad, that might be something else then

#

but point still stands - you open a port 80 or 443 on the internet, and you'll get scans

#

on local, I'm not sure. something is looking for that path

keen lily
#

yeah i've never heard of that

terse viper
#

no idea then, something that has access to your server is scanning for it

#

does your server tell you what the source IP is from?

#

at least you could try to figure out which machine it's coming from

#

it should be a LAN or loopback address

#

if it's your own machine, then there's some service or program installed that's doing it

keen lily
#

gonna run the web again see if it pops up

#
[11/Jul/2020 21:16:05] "GET / HTTP/1.1" 200 732
Not Found: /favicon.ico
#

it stopped for the time being

#

must've been some website i visited, i dont know

#

thanks bro

terse viper
#

the favicon.ico thing is something that browsers will try to fetch automatically

#

favicon.ico is the icon you see in your tabs and bookmarks

#

if you go to your server with a web browser, it'll probably try to fetch the icon

wispy quiver
#

anybody have any recommendations on a good website builder that has strong eshop support?

#

i want to build my own personal/eshop website

#

without mucking about in the code

glass blaze
#

use shopify

indigo kettle
#

urls is where routing happens yes

#

I wouldn't call views.py the frontend, it does serve the html to the frontend though

limber laurel
#

What does flask paginate use for getting the amount to display etc. Like is it efficient?

mint compass
#

didnt understood ur question

#

what does it mean

#

???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

rapid scarab
#

big brain

sudden grail
#

hey, i have problems with django and migrations

#

i created a simple model:

#

class Something(models.Model): first_name: models.CharField(max_length=30, null=False)

#

when I try to makemigrations, then in the migration file the first_name is not added

#

just an id field

#

which is auto added

#

fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ],

#

Why is this?

#

How to solve that?

native tide
#

class Something(models.Model): first_name: models.CharField(max_length=30, null=False)
@sudden grail change first_name: to first_name =

sudden grail
#

@native tide JESSSSSUUUUUUUUUUUUSSSSSSSSSSS

#

omg, iam so stupid 😄

native tide
#

dw, it's easy to overlook sometimes 😛

sudden grail
#

i thought its js object or whatever, dont know hwy

#

why*

#

thanks mate! 🙂

native tide
#

np

sudden grail
#

what does dw mean?

dw, it's easy to overlook sometimes 😛
@native tide

native tide
#

Dont worry

sudden grail
#

cool 😄

inner quail
#

🤣🤣🤣🤣`

native tide
#

is apscheduler fine to run periodical background functions on flask app ?

#

Its really trivial thing simple db query and deleting enteries that are found

native tide
#

fghjklp';[']

#

hgvfhcghjkl;[\

#

\kjhjkl;[\

#

'];pkjhjkp[]'

#

]';lpklp[]

#

[lp[]

#

];[]

nocturne jetty
#

!ban 696791483105411072 Spam doesn't contribute to this community in any meaningful way.

lavish prismBOT
#

failmail :ok_hand: applied ban to @tender tiger permanently.

coral raven
#

He was speaking the language of gods

fickle fox
#

Guyys i am trying to create many to many relationship but i found some problems xD

#

can anoyone help me

#

let me send code in here

#
subs = db.Table(
    'subs',
    db.Column('uid', db.Integer, db.ForeignKey('Users.uid')),
    db.Column('id', db.Integer, db.ForeignKey('BlogPost.id')))


class BlogPost(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(72), nullable=False)
    content = db.Column(db.Text, nullable=False)
    author = db.Column(db.String(20), nullable=False, default='N/A')
    date_posted = db.Column(
        db.DateTime, nullable=False, default=datetime.utcnow)
    pinn = db.Column(db.Boolean, default=False)
    htmlrender = db.Column(db.Boolean, default=False)

    def __repr__(self):
        return 'Blog post' + str(self.id)```
#
class Users(db.Model, UserMixin):
    __bind_key__ = 'Users'
    uid = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), nullable=False)
    mail = db.Column(db.String(90), nullable=False)
    pw = db.Column(db.String(256), nullable=False)
    role = db.Column(db.String(30), nullable=False, default='User')
    subscription = db.relationship(
        'BlogPost',
        secondary=Com,
        backref=db.backref('subscribers', lazy='dynamic'))
#

ands this is error

#

pls ping me if you can help me

native tide
#

@fickle fox table name is not the same as model name try users.uid

#

Same for blog post I assune

#

In the intersection table

fickle fox
#
subs = db.Table(
    'subs',
    db.Column('uid', db.Integer, db.ForeignKey('users.uid')),
    db.Column('id', db.Integer, db.ForeignKey('blogpost.id')))```
#

@native tide u mean like this

native tide
#

Yes, not sure about blogpost table naming convention though

fickle fox
#

nah s till doesnt work

#

qwq

#

and i am not sure yet why

native tide
#

@fickle fox try blog_post

fickle fox
#

sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'subs.uid' could not find table 'User' with which to generate a foreign key to target column 'uid'

native tide
#

@fickle fox you sure your changes loaded in the shell?

fickle fox
#

umm i guess so

#

i automatically save them

#

oh lol i re opened it now it works

#

but um how i can check now that db i made

#

subs

#

db

fickle fox
#

umm wait what can make this error

#
sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'mapped class Users->users'. Original exception was: 'Com' object has no attribute 'foreign_keys'
#

ehh god i am getting headache from this....

twilit zenith
#

i saw someone doing request.user.auth_token, how can request have user when im only storing token in the front end?

native tide
#
sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'mapped class Users->users'. Original exception was: 'Com' object has no attribute 'foreign_keys'

@fickle fox Think it has to do with the secondary=Com in your user model, which I believe should refer to the intersection table subs

native tide
#

i saw someone doing request.user.auth_token, how can request have user when im only storing token in the front end?
@twilit zenith They might verify the token and translate it into a user using a middleware. The middleware can modify the request before passing it through to the application

hollow glacier
#

What do you guys call your auth app? (django)

twilit zenith
#

wym?

#

@hollow glacier

hollow glacier
#

Like, the app that you create for your auth stuff. What do you usually name it?

twilit zenith
#

I called it BackendAPI

#

usually API I suppose

#

I call my vue.js Frontend

#

you can call it whatever you want

hollow glacier
#

Since "auth" is taken upp by contrib i would think to name it "authentication", "users", or "accounts"

twilit zenith
#

wait

hollow glacier
#

Like the app that has everything to do with authentication

#

and users

twilit zenith
#

are you using Django rest framework or normal one

hollow glacier
#

regular

twilit zenith
#

oh ok

hollow glacier
#

I know what frontend and backend is tho :P

twilit zenith
#

i created app called account

#

I store everything related to accounts there

#

Auth, register, profile

hollow glacier
#

Thanks!

twilit zenith
#

np, I suppose you're new to Django. I didn't know what to call or where to put what before I got 'my hands dirty' with Django

hollow glacier
#

Yah I'm pretty new haha

twilit zenith
#

you just have to do few projects to learn basics

hollow glacier
#

I've done a few

twilit zenith
#

I followed tutorial by Corey Schafer

hollow glacier
#

I just want to know what you'd usually call it

twilit zenith
#

I would recommend it to anyone

#

ok

#

no

terse viper
#

I use firebase auth

#

but others use AWS cognito

#

it's nice to use this 3rd party service so I never have to store passwords

acoustic oyster
#

I have a django site, I would like to use React for a single page, a photo gallery, I read that it is standard to use an api for something like this. Does it make sense to create an api that serves data for photos on this one webpage? Or are there simpler, acceptable ways to do this?

terse viper
#

API sounds a bout right, though the photos need not be served by the API itself, it can be linked via CDN, though depends what security you need on the photos

acoustic oyster
#

I currently have the db serving the file paths.

Would there be a more protected way than a cdn?

I.e most traffic to this site will be mobile, from Instagram, so the average person should not be able to easily download them.

#

This does not need to be bullet proof by any means, so simplicity is preferred.

terse viper
#

you can have the API serve the images

#

I'm not sure the features of CDNs, maybe some allow access tokens

#

I know things like AWS and Google buckets allow access with a token as well

fickle fox
#

@native tide oh yea, thats it now i fixed it but now i need to fix deleting button because there is issue now in there

acoustic oyster
#

im trying to use all local resources.

Thank you, I'll look into cdn options as well.

fickle fox
#

But i will do it tomorrow, now its late

#

Oh and yea i need to find a way to check data in table

acoustic oyster
#

ok ok, this will be the last time I beg for help here, haha.

In Django I have auth tokens from the django rest framework. Right now the only way to view/get the token is to go the admin page, inspect the page, and copy the raw text of the token in the inspector.

How can I get the token belonging to a user object? I need someway to view/copy/paste the token or otherwise get it so my app can make authenticated requests.

The docs seem lacking on this and I am unable to find answers

#

I see they have built ins for this, but I am trying to learn and do not understand how a token can be accessed

main dirge
#

Has anyone used exchangelib before?

open tinsel
#

I have some html / css

  1. It works in a figure block
  2. Can't get it to work in my block
  3. Can't get it to work as an admonition
cold anchor
#

what do you mean?

open tinsel
cold anchor
#

ok, and what do you need help with?

open tinsel
#
<link rel="stylesheet" href="test.css">

<figure>
<figcaption><span>Note:</span> optional explicit title within double quotes</figcaption>
<p>Any number of other indented markdown elements.</p>
<p>This is the second paragraph.</p>
</figure>
<p>Another following paragraph.</p>

/* section */
<caption><span>Note:</span> optional explicit title within double quotes</caption>
<p>Any number of other indented markdown elements.</p>
<p>This is the second paragraph.</p>
/* section */
<p>Another following paragraph.</p>

<p>Preceding paragraph.</p>
<div class="admonition note">
<p class="admonition-title">optional explicit title within double quotes</p>
<p>Any number of other indented markdown elements.</p>
<p>This is the second paragraph.</p>
</div>
<p>Following paragraph.</p>
#

Test.css


/* p class="admonition-title */
/* https://stackoverflow.com/a/28107458/4539999 */

admonition-title {
  text-align: center;
  color: blue;  
  font-style: italic;
}

.admonition {
  color: grey;
  background-color: lightblue;
  padding: 10px;
}

.admonition.attention::before { 
  content: "Attention: ";
}

.admonition.caution::before { 
  content: "Caution: ";
}

.admonition.danger::before { 
  content: "Danger: ";
}

.admonition.error::before { 
  content: "Error: ";
}

.admonition.hint::before { 
  content: "Hint: ";
}

.admonition.important::before { 
  content: "Important: ";
}

.admonition.note::before { 
  font-weight: bold;
  content: "Note: ";
}

.admonition.tip::before { 
  content: "Tip: ";
}

.admonition.warning::before { 
  content: "Warning: ";
}


figure {
  background: lightcoral;
  padding: 10px;
}

figure img{
  text-align: center;
}

figcaption {
  color: red;
  font-style: italic;
  text-align: left;
}

figcaption span {
  font-style: normal;
  font-weight: bold;
}
/*
section {
  background: moccasin;
  padding: 10px;
}
*/
caption {
  color: green;
  text-align: left;
  font-style: italic;
}

caption span {
  font-style: normal;
  font-weight: bold;
}
#

I want 1st type block to work with 2nd and 3rd block code

#

Seems to work ok in a <figure> block

#

Can I use <myblock> or something?

cold anchor
#

I want 1st type block to work with 2nd and 3rd block code
I don't understand what you mean by this

#

can you explain what you're trying to do a little more clearly?

open tinsel
#

I want the look of the first red block

#

the second block does not render

cold anchor
#

figure {
  background: lightcoral;
  padding: 10px;
}
open tinsel
#

the third block has a break after Note:

cold anchor
#

you're giving it a red background, do you want that on all elements?

#

if so, you can just apply that background for all elements

open tinsel
#

Color is only to distinguish the different attempts

#

Layout is my concern

cold anchor
#

why do you have your css rendering text for you? just put that in the html

open tinsel
#

I can't change the admonition text generated. I need to fix it in css

cold anchor
#

why is that?

open tinsel
#

.admonition.note::before

#

Third party extension

cold anchor
#

why do you need a third party extension to write ~20 lines of css for you that it looks like you're rewriting anyways?

real island
#

hello i am using flask and for some reason, i am unable to see the You are: h1 in my flask run

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

<head>
    <meta charset="UTF-8">
    <title>Test Input</title>
</head>

<body>
    <form method="POST" action="/">
        Flag: <input type="text" name="flag" required><br>
        <input type="submit" value="Submit">
    </form>
    {% if flag %}
    <h1>You are: {{is_correct}}</h1>
    {% endif %}
</body>

</html>
from flask import Flask, request, render_template
from answers import *
import os
# from datetime import datetime

app = Flask(__name__)

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

@app.route('/', methods=['POST'])
def response():
    flag = request.form["flag"]
    processed_text = flag.upper()
    first_flag = os.getenv("FLAG_1")
    if (processed_text == first_flag):
        correct_answer = "Your flag is correct!"
    else:
        correct_answer = "Your flag is incorrect. Please try again."

    return render_template("index.html", is_correct = correct_answer)
 # Launch the FlaskPy dev server
app.run(host="localhost", debug=True)
cold anchor
#

pass flag=flag into the render_template(...) call

open tinsel
#

I just need to format the admonition

#

admonition doesn't display type but I want to add it.
Other processessors do it in the css.

#

.
<div class="admonition note"> is admonition type note
.
I want it styled and displayed on the same line as
<p class="admonition-title">optional explicit title within double quotes</p>

cold anchor
#

Sounds like you want to add the content to the before of the first child and not the admonition itself

open tinsel
#

Probably.

#

I thought I'd get the second example working first.

#

Seems only an issue with reserved words

#

Basically change a <figure> block to <some other> block

#

How would I write that?

p:first-child .admonition.note::before { 
  font-weight: bold;
  content: "Note: ";
cold anchor
#

did you want the look of the first example or the second one?

open tinsel
#

Look of the 1st example (red) using green for second and blue for third examples

#

2nd example is for captions and 3rd is for admonitions

cold anchor
#

you should use consistent tags between them if you want them styled similarly

#

different tags are styled differently by default in the browser

#

and unless you use something like reset.css you won't be able to control it

open tinsel
#

The example are all independent

cold anchor
#

then just use divs

open tinsel
#

they are inside markdown html fragments

#

I'd need a unique block for all captions. How would I do that with divs?

cold anchor
#

I don't think I can help, it feels like we're talking past each other and I'm not understanding half of what you're saying

austere fog
#

how would I make a Flask route that would match any url after a specific endpoint like:

@app.route('/test/<path>')
def route(path):
  return path

# GET /test/foo/bar
# '/foo/bar'
#

the above code would only match /test/foo

#

got it:
@app.route('/test/<path:path>')

open tinsel
#

@cold anchor Seems I can't style <caption> at all but I can use <figcaption>

<div class="caption">
<figcaption><span>Note: </span>this is the title</figcaption>
<p>This is a description.</p>
</div>
<p>A normal sentence.</p>
.caption {
  background: lightgreen;
  padding: 10px;
}

.caption figcaption {
  color: green;
  text-align: left;
  font-style: italic;
}

.caption span {
  font-style: normal;
  font-weight: bold;
}
native tide
#

hello, i am looking out to start django for backend development , can anyone advise me how shall i go about it

austere fog
#

how much python experience do you have?

coral raven
#

Django docs have a basic poll app, start from there

vagrant adder
#

@native tide corey schafer has nice django tutorial series on his youtube channel

cinder juniper
native tide
#

how you made this?

#

i wanted to send this to but it was blocked

cinder juniper
#

It's not whitelisted, Mods have perms but general users don't

sudden grail
#

hey guys

#

Iam doing a many to many relation

#

I've a First and a Second model. Second has firsts = models.manytomanyfield

#

I wanna read all the Second where first_id=1.

#

i do it so:

#

things = Second.objects.filter(firsts__id=1)

#

when i serialize that into a json, then i get something like that:
[{"model": "cool.second", "pk": 1, "fields": {"cool": "something", "firsts": [1, 2]}}]

#

the First models are in the firsts array

#

but,

#

How to change the query to get the First' data as well?

#

so instead of the array 1,2 i wanna see an array of objects with the First model data

#

Can i achieve that without for looping ?

#

So my goal:
[{"model": "cool.second", "pk": 1, "fields": {"cool": "something", "firsts": [{"pk":1,"fields:{},{"pk": 2, "fields":{}]}}]

open tinsel
#

Is there an easy way to do this in CSS? Html is fixed and I have a dozen admonitions:

#
<link rel="stylesheet" href="extra.css">

<p>A normal sentence.</p>

<div class="admonition note">
<p class="admonition-title">this is the title</p>
<p>This is a description.</p>
</div>
<p>A normal sentence.</p>

<div class="admonition tip">
<p class="admonition-title">this is the title</p>
<p>This is a description.</p>
</div>
<p>A normal sentence.</p>

extra.css

.admonition {
  padding: 10px;
}

.admonition-title::before { 
  font-style: normal;
  font-weight: bold;
}

.admonition-title {
  font-style: italic;
}


.admonition.note {
  background-color: lightblue;
}

.admonition.note .admonition-title::before { 
  content: "Note: ";
}

.admonition.note .admonition-title {
  color: blue;  
}


.admonition.tip {
  background-color: lightgreen;
}

.admonition.tip .admonition-title::before { 
  content: "Tip: ";
}

.admonition.tip .admonition-title {
  color: green;  
}

sudden grail
#

help me pls.
I got a very strange error: 'Elso' has no attribute 'get'
i've this: things = Elso.objects.get(pk=1)
class Elso(models.Model): cool = models.CharField(max_length=30)

#

why the hell does it not work?

#

???

#

?

#

??

crimson shore
#

first do makemigrations then migrate

native tide
#

what would be the cleanest way to provide frontend/backend and rest api at once

#

What do you mean by frontend Rest API? Do you want the server to be able to send Rest requests to the client?

#

I'm not aware of that being common practise, usually you only make Rest calls from the client side and the server responds

rapid scarab
#

(sorry to be that guy) what's a good beginner introduction to django? I want to try building a small django app but not exactly sure where to start

native tide
#

@rapid scarab take a look at the django tutorial (poll app)

rapid scarab
#

I did take a look at it, but I don't really like the layout of their guide

#

Also following guides isn't really my thing, bc I tend to just follow everything that's being done - I personally prefer to just have a goal and doing a bunch of messing around until I can figure out what does what

native tide
#

Then you just read the reference as you go and don't do the tutorial project

#

And come up with something small, just try to keep complexity low.

#

The most basic thing would be to make an interface to handle some form of dataset

#

A movie DB or whatever you can come up with.

rapid scarab
#

Thanks for the advice, I'll just try to make something simple and then work my way up by adding small things

native tide
#

I'd recommend looking into the different views that Django provides, you might get an idea you can easily implement from that.

#

Just don't start by making a browser MMO that works with websockets xD

rapid scarab
#

Pffft, I'll make a full AAA game to start, what could go wrong

native tide
#

Nothing at all, you might just end up creating the next RuneScape

#

But Django might be the wrong tool for that

fickle fox
#
db = SQLAlchemy(app)


subs = db.Table(
    'subs',
    db.Column('uid', db.Integer, db.ForeignKey('users.uid')),
    db.Column('id', db.Integer, db.ForeignKey('blog_post.id')))


class BlogPost(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(72), nullable=False)
    content = db.Column(db.Text, nullable=False)
    author = db.Column(db.String(20), nullable=False, default='N/A')
    date_posted = db.Column(
        db.DateTime, nullable=False, default=datetime.utcnow)
    pinn = db.Column(db.Boolean, default=False)
    htmlrender = db.Column(db.Boolean, default=False)

    def __repr__(self):
        return 'Blog post' + str(self.id)


class Users(db.Model, UserMixin):
    __bind_key__ = 'Users'
    uid = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), nullable=False)
    mail = db.Column(db.String(90), nullable=False)
    pw = db.Column(db.String(256), nullable=False)
    role = db.Column(db.String(30), nullable=False, default='User')
    subscription = db.relationship(
        'BlogPost',
        secondary=subs,
        backref=db.backref('subscribers', lazy='dynamic'))

    def get_id(self):
        return (self.uid)```
#

Guys what mioght be wrong here

#

i am trying to create many to many relationship db

#

for my 'like/support' system

gilded monolith
#

primary_key = True at the end of your column in your relationthip table

#

?

#

assuming you're doing this

opal robin
#

hello i and a group of friends are making an webpage whch will allow the user to upload files into cloud. We are using django. We are knew in this field and we are requesting help from someone with more experience with use(We are not complete beignners, i have knowledge on oop gui and other things in python) but we would kindly request the help of somone who is experienced at django. Project will be uploaded on github.

faint abyss
#

Hi!

from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile


@receiver(post_save, sender=User) 
def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)


@receiver(post_save, sender=User) 
def save_profile(sender, instance, **kwargs):
        instance.profile.save()```
Can someone explain how will django call these functions, how does it know when to call save and when to call create?
I mean, it checks if the function has a created parameter or what?
opal robin
#

sorry for interupting

strong glacier
#

Could anyone help me with an error I'm having using Django?

twilit zenith
#

@opal robin by cloud do you mean VPS for hosting a server or S3 for storing images?

#

@faint abyss @receiver is decorator that invokes post_save everytime ('in this case User model') certain model is being created

#

basically everytime 'model' after 'sender=' is created, updated or deleted, function will be called

#

I'm sure you got that code from Corey Schafer's tutorial where he showed how to create Profile page implementation

faint abyss
#

Yeah, I did. But the thing I don't understand is that, why do we have to write 2 functions?

twilit zenith
#

2nd one wasn't necessary but he wrote it for future video when he will show how to update profile

#

2nd function updates profile

#

1st one creates profiles when account is created

faint abyss
#

But, why? It would've been simplier to get the "created" from kwargs, then put it into an if statement

#

and if there's no created, then you update. 😄

twilit zenith
#

I haven't actually thought that

#

you should test both ways

#

let me know the outcome

#

I'll try it myself tomorrow if you're busy rn

faint abyss
#

Okay, I'll let you know If I try out.
But if you do it earlier, I'd be glad if you could tell me outcome 😄

twilit zenith
#

@receiver(post_save, sender=User)
def profile_func(sender, instance, created, **kwargs):
if created:
Profile objects.....
else:
instance.prof.....

#

something like this should work

#

I won't be able to get on pc today as it's midnight rn for me

faint abyss
#

Yeah, but created is unnecessary.
you can do it like that:(hope so)

@receiver(post_save, sender=User)
def profile_func(sender, instance,**kwargs):
    if kwargs.get('created', False) is True:
        Profile objects.....
    else:
        instance.prof.....
twilit zenith
#

hm idk, I don't use **kwargs very often so I don't know how to work with them

#

btw are you participating in Django code jam?

faint abyss
#

Don't know yet 😄

twilit zenith
#

you do have role

faint abyss
#

Yeah, but it only means I applied

twilit zenith
#

oh okay

#

did you submit code for creating blog thingy?

#

I don't remember what it was

faint abyss
#

Article, and yeah I did.

twilit zenith
#

kk gl

faint abyss
#

Thanks! 🙂 And thanks for the help! 🙂

twilit zenith
#

np

#

lmk if you need help with Django, cuz I'm learning it too

faint abyss
#

Yeah I'm learning too, However I've worked in Spring, that's the same but in Java.

fickle fox
#

@gilded monolith ooh okay i did it, but i am not sure in something, shouldnt there be created table or database after db.create_all()??

somber fiber
#

what is the best/fastest module to use for http requests

terse viper
#

requests

quartz schooner
#

object = requests.get(<url>)

#

woops .. didnt see the last message

onyx portal
#

hello! 👋 I am learning how to deploy a server using Python, and am trying to make ... programming concept connections in relation to Swift 5, something Im learning as well. If anyone has some time to talk about terms and such with a student, I'd love to venmo you for a coffee in return for a little learning back and forth 🙂

twilit zenith
#

@onyx portal so you API that'll be used to request data using Swift

onyx portal
#

@twilit zenith sorry, im not sure what you mean

#

grammatically

twilit zenith
#

I assume you'll use swift 5 for developing mobile app

onyx portal
#

@twilit zenith yes! Specifically, trying to integrate the square API

twilit zenith
#

and you're planning on using python to make that happen

onyx portal
#

@twilit zenith yes, using Heroku

twilit zenith
#

Swift > Python (Rest API) > Square API

native tide
#

btw rule 6

No spamming or unapproved advertising, including requests for paid work. Open-source projects can be showcased in #303934982764625920

twilit zenith
#

huh?

native tide
#

I'd love to venmo you for a coffee in

onyx portal
#

@native tide please clarify, this is web development help and donation based

native tide
#

ah oki

onyx portal
#

yes Swift > Python API > Square API. I just learned how to deploy using Heroku, but my new experience makes me a bit rough around the edges. There's this js code that would be easy to use as a jumping off point,but I chose python because the syntax is closer to Swift

twilit zenith
#

you should learn Django and Django rest framework if you're making app that can withstand requests from many users

onyx portal
#

OK, ill start reading that documentation, I've been using it on this getting-started project

twilit zenith
#

djangois great for scalable apps

#

you can also use Flask and Flask's RESTful API

strong glacier
#

Can anyone help me to upload a django project in heroku? I messed up big time and my brain is about to explode 😅

twilit zenith
#

but flask cannot withstand 1+ requests per second

onyx portal
#

awesome! I believe those things are setup well in this getting started project

#

That's okay, this is a small project, mostly portfolio and learning oriented

twilit zenith
#

Flask is also considered as micro framework

#

it's ok if you don't need it for something big

onyx portal
#

am I using the right terms when I say I'm trying to deploy a python backend?

twilit zenith
#

sorry for my grammar btw, I just can't be bothered to think about it because it's 2 am rn

onyx portal
#

This backend is using the libraries django and flask

twilit zenith
#

yeah it's fine

onyx portal
#

oh np, I'm just happy to get help!

#

This backend server is using restful API to communicate with whatever the mobile app is asking for? So conceptually, I'm needing to build this server because it will house what the app gets its data from?

twilit zenith
#

I would suggest tutorial series by Corey Schafer, he has both flask and Django

onyx portal
#

On it

twilit zenith
#

yup

#

he doesn't teach API

#

just framework itself

onyx portal
#

OK. I just needed to cement the reasoning i assumed

twilit zenith
#

Django and flask can be used as a REST API or just Web framework

#

np

onyx portal
twilit zenith
#

rest is what you'll need to learn if you'd like to interact with square and send data back and forth

#

hm yeah

onyx portal
#

The starter server on heroku for square is already pushing the calls through to the Square [sandbox] seller dashboard. But Im not sure how to modify it

twilit zenith
#

but... Django rest framework isn't as easy as it sounds

#

it'll take some time

onyx portal
#

that's okay

twilit zenith
#

kk

onyx portal
#

learning programming has been like playing dark souls

twilit zenith
#

let me know if you run to any problem while using django

onyx portal
#

thank you

twilit zenith
#

👍 np

onyx portal
#

I have a couple other noob questions if that's alright, again, to cement concepts so im not building on a poor foundation. Googling is tricky because im lacking theright keywords

twilit zenith
#

hmu in dms, I'm gonna head to bed, cuz I. dying rn

onyx portal
#

ok

twilit zenith
#

@strong glacier shroph

onyx portal
#

@strong glacier Im inexperienced with Django, clearly, but I did just deploy the server, maybe we can figure it out together

#

what are you trying to do / what do you need help with

west arrow
#

I need help. How do I display data frequently on a template from scraping with selenium without saving it in a model? I tried celery and sadly it can only run functions and cannot display the result without saving it in a model and calling it in a template.

brittle plinth
#

Hi in django I have a model method that calculates the max value from another model:

def highestbid(self):
        return(Bid.objects.filter(listing=self.id).aggregate(Max('bid')))

This seems to be working but when I try to display the highestbid in a form {{ listing.highestbid}} I get this: {'bid__max': Decimal('250')} any help would be appreciated

velvet vale
#

what's difference beetwen AbstractBaseUser and BaseUserManager?

#

in django

brittle iris
#

hey guys

#

i am just wondering currently for my images in which are stored in my django project are in the static/images folder

#

which when i add images from the admin panel it will copy it within those files

#

it is called fileStorage

#

and ive created a directory within my static called storage

#

and i want to whenever i upload a image from my backend for it to go into the storage directory as currently it is going to the images directory

#

how am i able to change the directory for the StorageFileUpload to go into the storage directory within static

#

i want the image upload system to remain the same as that is for when i add the products.

ashen sparrow
#

is there anyway to limit the height of div? maybe have 4 equal height divs side by side?

#

how am i able to change the directory for the StorageFileUpload to go into the storage directory within static
@brittle iris you can add the upload_to parameter to the ImageField

sudden grail
#

hey guys, i need your help. I wanna enter into an SaaS market. What type of product do you recommend to build?

frosty veldt
#

is there anyway to limit the height of div? maybe have 4 equal height divs side by side?
@ashen sparrow You can use the height property in CSS

unique hill
#

@frosty veldt you can include the four divs inside a container div

frosty veldt
#

Yes, but you still need to set the height

unique hill
#

ohh this is not your question

#

???

#

@ashen sparrow you can use the flex-box property

#

check this out

quick cargo
#

So ive benched the tests a bit better using Wrk which seems to be the most common method of bench marking frameworks and the like

#
=========== Sandman ===========
benchmark_wrk | Running 1m test @ http://127.0.0.1:8080/bob
benchmark_wrk |   4 threads and 400 connections
benchmark_wrk |   Thread Stats   Avg      Stdev     Max   +/- Stdev
benchmark_wrk |     Latency    38.02ms   31.07ms   1.15s    98.35%
benchmark_wrk |     Req/Sec     2.74k   398.38     3.97k    87.17%
benchmark_wrk |   651446 requests in 1.00m, 73.93MB read
benchmark_wrk | Requests/sec:  10848.90
benchmark_wrk | Transfer/sec:      1.23MB

=========== Uvicorn ===========
benchmark_wrk | Running 1m test @ http://127.0.0.1:5000
benchmark_wrk |   4 threads and 400 connections
benchmark_wrk |   Thread Stats   Avg      Stdev     Max   +/- Stdev
benchmark_wrk |     Latency    49.43ms   31.70ms 640.40ms   95.27%
benchmark_wrk |     Req/Sec     2.17k   477.85     2.77k    90.92%
benchmark_wrk |   517720 requests in 1.00m, 74.06MB read
benchmark_wrk | Requests/sec:   8618.44
benchmark_wrk | Transfer/sec:      1.23MB```
#

Beating uvloop and uvicorn without even using uvloop itself 😅

sudden grail
#

hey guys, i need your help. I wanna enter into an SaaS market. What type of product do you recommend to build?
@sudden grail ??

unreal atlas
#

hej guys cloud someone help me

modest scaffold
#

could you guys recommend some django tutorials that you thought were good

#

ive been searching around on youtube and none seem suitable for me

dapper tusk
#

I used Corey Shafer and the official one

fallow ruin
#

hello everybody, I am tryin to make a flask app that provides the adminwith capability of submittin forms for other users! These users will then be required to access their accounts with the credentials the provided by the admin.
But I need the forms to update their values after each post request. See, everybody will be provided with a unique number.
And at the time of registration the admin will state the number of members that they want to add. I wanted to use that criterion to auto-fill the new identification numbers that will be provided to the users in a disabled form field after every successful submitted form.
I tried using a while loop, but things backfired in a terrible way! Any assistance will surely be appreciated!
Anyone with any ideas?

gentle hornet
#

maybe run it in separate process?

#

or thread

late stone
#

hi friends, is there a way i can test send emails to the command line using django

#

instead of setting up my gmail and all that yara yara

late stone
#

thanks

midnight phoenix
#

Pretty new to web development: If an API has an endpoint that accepts GET and POST. The docu specifies to write GET, like this
GET https://www.xxy.com/search?_query_param_01
But nothing is specified for POST, then I should assume _query_param_01 should be a key in the json payload, right?

cold anchor
#

if an API has an endpoint but it's not documented, they most likely don't want you using it

midnight phoenix
#

It's documented, but just:
POST https://www.xxy.com/search
For GET all parameters a described in detail, and it's working fine. But I think I'm doing an error formating the json payload.

native tide
#

Whats the correct way to deploy quart apps

terse viper
#

POST may require all values as part of the body, and not as a query param

regal timber
#

Hello
Is there a way to know the TOS of every website ?

thick cove
#

check out their TOS

#

cant know it if u dont know it 🤷‍♀️

regal timber
#

Well what I asked was how to see the TOS

thick cove
#

you can typically find it online pretty easly

#

If you want to see discords tos you can google for example Discord TOS

regal timber
#

and I don't find anything that sound like im not allowed to webscrap

#

is it the case ?

thick cove
#

There is a link to their TOS on their front page

regal timber
#

no

thick cove
#

Yes

#

Terms of Service

regal timber
#
Content
U.GG is not responsible for any third party content or links to any third party content.```
#

is that it ?

thick cove
#

Well you're on the right page

#

Seems like I'm having a slight problem serving my static files...

I have no idea what I've done wrong or how to go about fixing it 🤷‍♀️

native tide
#

do you use django?

thick cove
#

Yes

native tide
#

did you connect correct to your static files at settings.py of your project?

dapper tusk
#

Did you run collectstatic

thick cove
#

I dont need to do that in debug tho?

#

But I did that on my server and it still didnt work

dapper tusk
#

You need to do that when deploying in a way other than runserver afaik

thick cove
#

Only args I have for static right now is ```py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'SylteXYZ', 'static')
]

#

I'm running locally now

#

with runserver

dapper tusk
#

Look at the server log, it should tell you what path static is at

thick cove
#

I'm not running it on a server right now

#

Just locally

#

Enabling Debug makes the website work

#

Disabling it stops it from working

acoustic oyster
#

Idk if this helps, but sometimes I doof and accidentally make two static directories, one in the root directory (does not work until i deploy), but also a working one within the app and in development the static directory in the app is the one being used.

thick cove
#

I only have one static directory 🤷‍♀️

#

Gotten it to the point where it works, but only when putting my own css right in the html in a style tag

#

Reffering to it as a stylesheet doesnt work.

thick cove
#

One day making the website

#

One day trying to fix this

#

Looks like I will spend multiple days on serving static files tho 😳

limber laurel
#

In django for example if I have a users model with a OneToMany relationship with another model, how can I acces the other objects using the user object?

dapper tusk
#

user.collumn_name_set afaik

fast charm
#

Hey guys! im trying to send a post requests to a pishing website, but i cant get my head around it, the website send the data through ajax

        data: parametros,
        url: '../../loginx.php',
        type: 'post',
        success: function(response) {
            resultado = response.replace(/\s/g, ''); // Limpia espacios en blanco
            setTimeout(function() {
                $("#load").hide();
                $("#pc_1").addClass("disabled");
                $("#pc_2").addClass("disabled");
                $("#pc_3").addClass("active");
                $("#aqui_c").html("<b>Tarjeta: </b>"+resultado);
                $("#resumen").show();
            }, 3500)
        }
    })```
i have tried with request and request_html, something like this 
```from requests_html import HTMLSession
url = 'http://bancoestadorut.tonohost.com/inicio/loginx.php'
session = HTMLSession()
r = session.post(data=parametros, url=url)```
my apologies if this is not the right place to ask for this kind of help
terse surge
#

hello

#

im confused atm

#

so me and some other people are building a django + react.js project

#

but

#

i dont know how react will communicate with django backend

#

may someone explain it to me better?

viral sphinx
#

Hey guys why aren’t I able to use smtplib to send emails when in production ?

cold anchor
#

(to preface: I don't know and probably can't help with that)

sending emails in production is a can of worms and it's usually much easier (and cheaper, dollars/work hours) to use a provider like sendgrid, sparkpost, mandrill, or AWS SES

#

speak from the experience of building two marketing email products

woven moat
#

Hi, I made a web scraper using bs4 and requests that gets the text of every link of a website and prints it, now what I want to do is that instead of printing it, it shows it on a website and I want this website to be reachable to every computer on my network, so I should host the website, I'm thinking about using Apache for that although I'm 100% open to suggestions, I don't know what should I do to actually like create and modify the HTML, how should I approach this?

#

also, I'll be hosting the website on a Raspberry Pi, the website doesn't need to be fancy, font will be sans-serif, white background, strictly functional

warm igloo
#

make flask app, print your scraped links and html on your raspberry pi's hostname.local -- for instance default for raspbian os is hostname of raspberrypi so you could go to http://raspberrypi.local:5000 if that's the port your flask app is listening on. No apache needed.

#

@woven moat ^

#

or if you save a static html file and just want to serve that without flask, python's built in http server will suffice for such a small load like your local network

woven moat
#

make flask app, print your scraped links and html on your raspberry pi's hostname.local -- for instance default for raspbian os is hostname of raspberrypi so you could go to http://raspberrypi.local:5000 if that's the port your flask app is listening on. No apache needed.
@warm igloo oh yeah I'll definitely do that

heady brook
#

i'm a begineer, how shall i start?

keen lily
#

How do I put JSON data from an api into a model?

native tide
heady brook
#

ok, thanks man!

native tide
#

@keen lily how are you getting the json data

keen lily
#

from a website that updates

#

spotify data

#

would i use the rest framework?

#

i've been watching this actually which changed my mind on the rest framework

native tide
#

so you're using the requests library to get spotify data from an API?

keen lily
#

because i have no idea what i would use the rest framework for cuz everytime i see/read about it it does something else i want

#

yeah

#

but i just thought i would put it into a model and experiment

native tide
#

it could be helpful but only for using the serializers to ensure you validate the data from the API you're calling before putting it into one of your models

#

but if you're just messing around you can just take the data out of the response.json() and put it in the model

#
data = response.json()
mymodel = MyModel(
  track=data.get('track'),
  length=data.get('length'),
)
mymodel.save()
#

is the problem that you don't know where to run this to get it put into models?

keen lily
#

So what you're doing is

#

youre getting data from the json and putting it into the model

#

is that what u showed right there

native tide
#

yeah

keen lily
#

the 'track' and 'length would be

#

like for example whatever index the data is in

#

so like ['track'][0]

native tide
#

yeah, those are "keys" in the dictionary

keen lily
#

Ok thanks tbh i have no idea what i'm going for at this point because from what i'm seeing is that im overcomplicating things

#

What is the rest framework good for? everytime i've watched/read about it, it seemed really useless

native tide
#

yeah i'd get comfortable with django for a bit and maybe introduce rest framework and serializers once you understand why they're helpful

keen lily
#

what's the point of outputting json data i thought u want to take in json data

#

Oh okay thanks

native tide
#

the point of using a serializer is that you could actually ensure a data format and valid data before it goes into your models

#

but yeah i'd get comfortable with this first

brittle iris
#

Hey guys I need help with uswgi nginx and django

#

I keep getting 502 errors now

#

I’ve spent 15 hours yesterday trying to do what I can, now Idk what else to do

#

Can anyone please help me.

abstract tangle
#

so i have a file upload dialog from bulma, and some js that gets the file from that, how do i access that in django?

proper hinge
#

Is what you're looking for a POST request to some endpoint to upload the file to the server?

abstract tangle
#

hm, i just need it in the view

proper hinge
#

Use JS to update the DOM

#

If you mean you want to display it

abstract tangle
#

something like this:

def myview(request):
  file = get_file()
  altered_file = do_something(file)
  write_to_file(altered_file, path)
  return render(request, "filepage.html", {"image": settings.MEDIA_URL + path})
proper hinge
#

I see

abstract tangle
#

im uploading a image, doing something to id and then i just want to display it

proper hinge
#

So yeah, you need to make a request to upload the file to your server

abstract tangle
#

first time using django or web dev in general

proper hinge
abstract tangle
#

yeah i had that before

#

worked great

#

but i wanted something that looked a bit nicer

proper hinge
#

Nicer in terms of what? Amount of code you need to write?

abstract tangle
proper hinge
#

Or visually?

abstract tangle
#

yeah

#

visually

proper hinge
#

I'm not much of a front end guy

#

You can probably use bulma somehow to style the forms

abstract tangle
#

hmm ok, i guess ill leave it the way it was

proper hinge
#

My experience with front end was to just whack at the stylesheet with bootstrap until it looked sort-of presentable 😄

abstract tangle
#

is bootstrap easier?

proper hinge
#

I don't know. I haven't used bulma so can't compare

abstract tangle
#

it really doesnt mater, its just a debug site, i will only use it as a api anyways

keen lily
#

noob question but

#

how do i specifically get out a piece of data from a model onto a view

#
def musicpage(request):
    user = str(Username.objects.all())

^ my attempt in view

#
class Username(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return f"{self.name}"

my model

#

i have 1 entry in

proper hinge
#

Do you want to display all users or a specific user?

keen lily
#

specific for the time being

#

until i make dynamic url for each user

keen lily
#

yeah about query sets i've been reading and i'm confused...

#

Ok

#

would i add a name to my model

#
name = models.CharField(max_length=50, name='joe'
)
#

like this for example?

proper hinge
#

No

#

A model is meant to be generic

keen lily
#

yeah mb

#

i think use .get?

#

user = Username.objects.get()

proper hinge
#

Yes

keen lily
#

but what do i put in ()

#

or do i not put anyhting

#

thats what im wondering

proper hinge
#

Well what's your models primary key?

#

If you use get you need to ensure your query will only return a single result, so you need to filter by something that is unique

#

Many people can be named joe, so that is not a sufficient way to retrieve a specific user

keen lily
#

so even if the username can only be specific it one person

#

pks are the way to go?

proper hinge
#

Well you could just make the username the primary key'

#

But it's difficult to discuss model design

#

Your model currently doesn't make sense since it only has 1 field

#

I don't really know what you're aiming for

keen lily
#

A person on the website inserts their username into a form

#
def musicpage(request):
    user = Username.objects.get()
proper hinge
#

Anyway, Django will automatically add an ID field as a primary key if you don't specify a custom PK

keen lily
#

this variable goes in between a link

#

and that's it

proper hinge
#

Even if you don't make the username the PK, you need to ensure it's unique somehow, like with a unique constraint

keen lily
#

okay I will go off pks then

#

thanks

proper hinge
#

To answer your original question, you need to pass a context when you render a template

#

You can put the username object into the context

keen lily
#

thanks !

fair light
#

any devs i can contact with for a help?regarding oauth and web backends?

opal robin
#

hi i'm searching for someone experienced with django I and some other developers are making a web chat using django. If anyone is interested please contact me

terse viper
#

have you considered using websockets for that?

faint abyss
#

Hi! I have a question about Django.
So as you can see in the code:

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']```
We inherit from the UserCreationForm.. that's okay, but the UserCreationForm inherits from the ModelForm!
So my question is, why do we have to add the additional email field, if the UserCreationForm defined in it's own Meta class, that we're going to change the User class that **has** an E-Mail field, predefined in the UserModel, therefore it should not be necessary to define the email, just to put it into the fields list.
Like here:
```>>> from django.forms import ModelForm
>>> from myapp.models import Article

# Create the form class.
>>> class ArticleForm(ModelForm):
...     class Meta:
...         model = Article
...         fields = ['pub_date', 'headline', 'content', 'reporter']```
sudden grail
#

Hey, i know its a python community, but anyway. Can you help me out which backend tech to use for rest api with heavy real-time things? (im gonna achieve at through pusherJs).
The two options are: Adonisjs(nodejs mvc framework) or django

native tide
#

i love it because i think the structure isvery logic

dire fractal
#

I just started using the django rest framework and i honestly love it and the structure it has

terse viper
#

pusher uses websockets, so your backend should probably support websockets

#

and also pusher has a bunch of abstraction, so unless there's an actual pusher django implementation, it sounds like you should be using nodejs on the backend

#

if you use pusher on the frontend, you'll need to use pusher on the backend

cold anchor
terse viper
#

yes, I think pusher has a whole comms protocol around it, I don't think you'd want to have to re-implement that yourself

#

but if you drop to raw websockets, or something else similar that's better supported across Django and frontend, like socket.io (which there are python libs for), or JSON-RPC, or others, then yeah, Django websocket backend is an option

cold anchor
#

honestly my (blasphemous) recommendation would be to not use python for websockets

#

I have a websocket API that users connect to and my python rest API handles all application logic and just tells the websocket API "push X data to Y topic"

terse viper
#

that's a nice microservices approach

#

I do use tornado for websockets, it's quite nice. but by the time you are using microservices, it kind of doesn't matter what each microservice is written in any more, as long is it is well defined

somber aurora
#

What's the Qualifiers Task?

cold anchor
#

for the code jam?

woven moat
#

Hi, I made a web scraper in Python using bs4 and requests, it's very simple, it checks the website every 60 seconds and prints in the terminal how many links there are every time it checks, now, what I want to do is to show that on a website that runs locally, so every time it checks, it shows the number on the website, then the next time, it shows the number on the line below and that should repeat again and again until it gets like 10 lines long, at that point it should delete the line at the top, move all the lines up so that line at the top gets occupied again and then make the new line appear
how can I make this happen?

warm igloo
#

My suggestion since following your text above is difficult: diagram this out. 🙂

median meteor
#

@woven moat as I have understood. You would like to have result of scraping process display on a browser page on localhost. If do so you should check Flask or Django framework

warm igloo
#

I talked him through that part yesterday. But now the next step seems he'll need to do some javascript work on the client side as he wants the html output to be constantly changing as the results change on the backend scraping. That correct @woven moat ?

#

Like a scrolling list of links that have been scraped.

If it is a live update kinda thing, the js will need to a bit fancier. If it is just "when I go to the site I see the new list" then you'll also need to store that list somewhere for fetching.

So, a few questions to see what you're really trying to get to.

mortal geyser
#

Imagine you have an API made with Django rest framework which you don't want anybody to call it outside of your web. You have 2 endpoints:
api/images
api/user_images
The first one is going to be used on the main page of the web even without a user logged in and the other one requires to be registered and logged in to reach it. For the second one is easy, you could implement some sort of JWT (JSON web token) to avoid unauthorized requests but what would you use to protect the first endpoint from being used with a simple rest call if you can't ask a user to be logged in to reach it? Does it have sense trying to avoid users to call it from outside your web/frontend?
I don't really know if I should let it open to everybody or if there is a good method to just allow my frontend to call it.
I know that even with a method to protect the first endpoint users can still take the data using techniques like web scrapping but I don't really want to let that endpoint open.

quick cargo
#
Cross-origin resource sharing
Cross-origin resource sharing is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served. A web page may freely embed cross-origin images, stylesheets, scripts, iframes, and videos```
#

might be what you want

mortal geyser
#

it sounds good, thank you!

zealous siren
#

CORS won’t help

#

You will need to add authentication

woven moat
#

I talked him through that part yesterday. But now the next step seems he'll need to do some javascript work on the client side as he wants the html output to be constantly changing as the results change on the backend scraping. That correct @woven moat ?
@warm igloo yeah exactly

#

like you just said, a live update

#

My suggestion since following your text above is difficult: diagram this out. 🙂
@warm igloo yeah sorry, explaining projects in written form is not my strength

warm igloo
#

Don't worry, it is difficult in general. I have to say "draw it out" to a lot of devs on my teams. 🙂

woven moat
#

haha aight cool

elfin mountain
#

@native tide Yes of course. Look up Flask or Django.

#

@native tide Can't answer that question. Look at the documentation and pick one.

woven moat
#

maybe if I put it this way you'll get it better:
this is what the script already does
scraper.py -->
EVERY 60 SECONDS:

  1. scrapes the site
  2. sees every link in the site
  3. counts the links
  4. prints the number in the Terminal
    now, what I also want the script to do is to have a website that gives a live update, so I would see in the website what I'm seeing right now in the Terminal
somber aurora
#

flask is easier but it's for more light websites. Django is harder but it's more for complicated

#

I'm speaking through my own experience people have different

#

@native tide

elfin mountain
#

Analysis paralysis (or paralysis by analysis) describes an individual or group process when overanalyzing or overthinking a situation can cause forward motion or decision-making to become "paralyzed", meaning that no solution or course of action is decided upon. A situation ma...

#

@native tide Pick one of the frameworks, do the tutorial that the documentation provides or pick one of Corey Schafer's YouTube tutorials.

crystal rain
median meteor
#
<script>  

var map = L.map('map').setView([49.175573,20.072700], 11);
    
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

var post_base = {{object_list|safe}}
    
    for (let index = 0; index < post_base.length; index++) {
        marker = new L.marker([post_base[index]["fields"]["lat"],post_base[index]["fields"]["lon"]]).addTo(map)
        .bindPopup("<img style=10%; src=/>");   
    }


marker1 = new L.marker([49.295236, 20.413089],{opacity:0.5}).addTo(map)
    .bindPopup("<img src={% static 'images/lomnica_image.jpeg' %}/>");
marker2 = new L.marker([49.266596, 19.833505]).addTo(map)
    .bindPopup("<img src={% static 'images/dolina_chocholowska_image.jpg' %}/>");


</script>
#

in variable post_base i'm sending a queryset to script and then to create dynamically markers I use for loop in js and that works fine

#

in bindPopup in that for loop i also try to add a path to image but I can't

#

and I know that I can make REST API but I can't any frontend framework so i try find solustion without any frontend framework

#

I'm looking some solustion

tranquil adder
#

Hi, I'm trying to use Facebook graph API since last five days but its documentation is so confusing and I can't find any good resources where I'll get a hint or lead to solve my problem. I've created an app on graph API explorer. My aim is to access all the public IDs of all events of a particular place, so that I can extract information (name, type, time, location, ticket price, etc) related to the events. First thing is that I can't figure out which permissions should my app have for this and how much time will it take to get those? Secondly I don't understand how to retrieve the IDs which I've mentioned above. When I tested with a single ID it did not run properly because I think my permissions are wrong

cannot be loaded due to missing permissions
This is one of the phrases in the error message. I'm sorry if I'm asking for too much spoon feeding. I hope I'm asking this at the right place, please help if someone has experience with this API.

crystal rain
#

and I know that I can make REST API but I can't any frontend framework so i try find solustion without any frontend framework
Afaik, all the frontend has to do is make a get request, which shouldn't require any framework

median meteor
#

so do you think AJAX call would be good solustion?

elfin mountain
#

@median meteor fetch or axios would also work.

median meteor
#

none of them know 🙂

#

I'm googling now

twilit zenith
#

i use axios its very easy to use

#

what js framework are you using on the frontend?

#

@median meteor

median meteor
#

I can none of them so i made pure html and css because my app is static. I’m using leaflet js only to provide map with markers

#

I understand JS but since now I’ve tried avoid to use it

twilit zenith
#

yeah use axios, you'll need cdn

#

google axios cdn and import it to your js file

cold anchor
#

you don't need to use axios if you don't want to

#

fetch is pretty great and does almost everything you'd need

twilit zenith
#

yeah just saying axios cuz its simpler imo

terse viper
#

fetch is actually simpler than axios, but they're both worth knowing

median meteor
#

but what you mean using fetch?

#

I'm not using django REST

dapper tusk
#

fetch is a JS built-in afaik

median meteor
#

you mean metho fetch like post get

terse viper
#
fetch("https://your_backend/blah/blah").then(res => {
  // do thing with data
});
dapper tusk
#

Do note that it does not work with cors

terse viper
#

whether this works with CORS or not depends on your CORS settings

median meteor
#

I have not set any CORS settings

#

I'm not using that eiter

terse viper
#

browser has it on by default, you need to explicitly allow it if it's an issue

dapper tusk
#

Ah NVM, that was probably a slightly different issue then

terse viper
#

"AJAX" is an old term for "asynchronous javascript and XML", with the "XML" part referring specifically to Javascript's XMLHttpRequest function, which used to be the only way to receive data from a server asynchronously without reloading the page. the method became so popular that collectively, using AJAX for websites is what we ended up calling "Web 2.0"

#

however, since then we have had lots of new options than using oldschool raw XMLHttpRequest - some libraries implement it. there's a new API that's widely supported called fetch above that also provides asynchronous requests for data

#

so now, "AJAX" actually just means "asynchronous data fetching" and implies the use of a library like axios, or the built-in fetch

median meteor
#

yes yes

#

that I understand

terse viper
#

so, fetch and axios are probably the two most popular methods to do that

#

fetch is a built-in API that almost all modern browsers provides. and axios is a javascript library

median meteor
#

so to fix that i should fetch an image by js script to variable and than pass to bindPopup("<img style=10%; fetch ( here )");

#

is it correct

terse viper
#

you have two options:

  1. send actual HTML which your javascript just dumps into an .innerHTML
  2. send data, usually json format, which your javascript formats
#

there are pros and cons to both, and I think the correct choice depends on where your HTML is usually rendered from

#

if your HTML is rendered by the server, such that your HTML templates and other designs live there, then it makes sense to send rendered HTML for the frontend to place

#

but if your HTML is not normally handled by the backend, then it would be weird to have the backend send rendered HTML, and would bebetter for the backend to send data for the frontend to format and display

median meteor
#

@terse viper thaaank you for clarifing that concept

#

I used almost 3 days to get such info.

terse viper
#

well... this is a python server, not the usual place you'd go for this information

#

have you tried a Javascript server instead?

median meteor
#

I don't know js 🙂

#

i know more or less. I'm not a frontend but as I can't just make backend so I try do frontend as simple as possible. I know I should start learning some front end framework

#

but I have some wierd feeling more irrational fear that it's complicated

terse viper
#

fetch probably the way to go then

#

then you don't have to deal with the slight complication of loading axios from a CDN

median meteor
#

I have checked... both.... and yes it's irrational fear both are doable

static mulch
#

Hi All,

I'm very new to python but i'm kind of stuck, have been trying to search for my issue for a while now in google as well and i just can't wrap my head around it.
I'm trying import json into python so it can print some values (keys?) that i want.

So far i have

import requests
import json

url = 'https://fake_url'
r = requests.get(url)
cont = r.json()
print r.json()

And this prints all the json just fine, now i want to print specific values this is the top part of the json and also shows what i want to achieve:

{
  "players": [
    {
      "id": 1,
      "first_name": "Racer",
      "last_name": "",
      "team_name": "Racer",
      "position": "Constructor",
      "position_id": 2,
      "position_abbreviation": "CR",
      "price": 26.6,

I want to be able to print the first_name and price I've been trying to do this in countless of ways but i just can't do it.
If someone is willing to point me towards the right direction that'd be great

native tide
#

@static mulch cont['players'][0]['first_name']

#

It provides you a dictionary which has a key 'players' that maps to a list of dictionaries (player object representations)

static mulch
#

that.. was a lot easier than expected, if i want to have ['price'] next to it it tells me string indices must be integers

native tide
#

cont['players'][0]['price']

static mulch
#

but what is the dictionairy here? does it have a name?

native tide
#

you need to get the right index of the player object from the list

static mulch
#

i see, but it's not clear where the 0 comes from at all

native tide
#

the object it returned is a dictionary that has at least a key {'players': [{player_1_dictionary}, ... {player_n_dictionary}]}

#

not sure if this makes any sense

#

the 0 is just the first element in the list

#

since there is a list of player objects/dictionaries

static mulch
#

oh yeah i see! i changed the number and it just prints a different team

#

it's a bit annoying to google this because this seems to be done in multiple ways, and i want to print multiple values now

#

print cont['players'][0]['first_name']['price'] does not work, seems like i have to find a different way

elfin mountain
#

@static mulch You need to understand your data structure

#

Is the data structure returned from cont['players'][0]['first_name'] a dictionary?

static mulch
#

i thought ['players'] was the dictionary in this case

elfin mountain
#

It's in the dictionary that's returned from cont['players'][0]

#

a = cont['players'][0]['first_name']

#

b = cont['players'][0]['price']

static mulch
#

so what a and b return are dictionaries?

elfin mountain
#

They return the data value of the keys "first_name" and "price"

#

You have a dictionary with cont['players'][0] @static mulch

static mulch
#

i see, and in this case i can call ['first_name'] a key, right?

elfin mountain
#

@static mulch Correct. "first_name" is a key

ashen knoll
#

Is there anyone who knows a good framework for web integration in connection with discord.py?

#

i will have a look at it, thank you

static mulch
#

nice, i understand it a lot better now. i can at least keep going with my little project now. thanks!

elfin mountain
#

@static mulch Good luck!

static mulch
#

thanks! what im doing is most likely super inefficient though :p

ferrari_name = cont['players'][0]['first_name']
ferrari_price = cont['players'][0]['price']

print( "Name:",ferrari_name , "Price:",ferrari_price)

williams_name = cont['players'][1]['first_name']
williams_price = cont['players'][1]['price']

print( "Name:",williams_name , "Price:",williams_price)

doing this for 30 ID's will take a while

elfin mountain
#

@static mulch Sounds like a for loop is needed

static mulch
#

Yeah i was thinking something of the like, trying to find examples online that could possibly help

grim spoke
#

Hey anyone good with django could u help me in #help-coconut i have been waiting quite a while with no assistance, been trying to figure this out for ages and can't find anything on websites like stackoverflow about it

#

^ update: ill make a new channel cause it was marked "dormant"

static mulch
#

i'm not sure what direction to go in with a for loop @elfin mountain , any idea what direction i should head or any pointers?

grim spoke
elfin mountain
#
for player in players:
  name = player['first_name']
static mulch
#

hmm for some reason that prints out an entire object and not the first name

elfin mountain
#

are you printing player or name?

static mulch
#

printing player

#

should it be name?

#

just name gives only the name but of only one object

elfin mountain
#

@static mulch what do you want to print?

static mulch
#

i want to print all first_names

#

with price next to it but that's something i can look into later

icy wasp
static mulch
#

errr, somehow i got it to work

static mulch
#

my prints does two different things depending on indentation but i don't want neither of them. one of them prints one correct 'first_name' and correct 'price' but i want to output all the 'first_names' and 'price' when i change the indentation forward it gives me one 'first_name' variable 30 times with different 'price'

players = cont['players']
for player in players:
    name = player ['display_name']

players = cont['players']
for money in players:
    price = money ['price']



print("name =", name, "price =", price)
vernal finch
#

can anyone help with a django problem: I have a model with some optional fields and a foreign key field. I want to take in any number of optional fields and require a field of the foreign model that specifies that model but I don't want to require the user to specify an id, just another field.

native tide
#

@static mulch walk through your code slowly, you go through a loop setting the name. everything in the first loop will finish before it moves to the next loop. so what will be in the name variable when it gets to the print statement?

#

@vernal finch can you show me your model code

thick cove
#

Still wondering why this happens: https://sylte.xyz/
(My static files arent being served) Going to the URL its supposed at gives a 404
Using Django.
Yes, I did manage.py collectstatic
Using cPanel to host because I already paid for it 🤷‍♀️

native tide
#

@thick cove can you post a screenshot, i don't click links in discord

thick cove
#

Like I said

#

no static files are being served

native tide
#

is the twitter icon not a static file?

thick cove
#

uh well then I guess ONE static file was served there

vernal finch
#
  name = models.CharField(max_length=100, default='My Analysis')
  created_at = models.DateTimeField(null=True, auto_now_add=True)
  updated_at = models.DateTimeField(null=True, auto_now=True)
  user = models.ForeignKey(User, on_delete=models.CASCADE)
  instrument = models.ForeignKey(Instrument, on_delete=models.PROTECT)
  eps_ttm = models.FloatField(null=True, verbose_name='Earnings per share')
  time_frame = models.IntegerField(default=DEFAULT_TIME_FRAME, verbose_name='Time frame')```

```class Instrument(models.Model):
  ticker = models.CharField(max_length=10)
  company_name = models.CharField(max_length=200, null=True)
  current_price = models.FloatField(null=True)```

@native tide basically I want to specify a ticker and some other optional fields which have default values to create an Analysis for an instrument. On the response I want to return the full instrument object.
thick cove
#

That's running locally too, not on the serveer.

native tide
#

@vernal finch by not wanting them to specify an ID do you mean you want them to just specify some fields necessary to create the object, but let the database assign the ID?

vernal finch
#

The instrument already exists when you create an analysis, otherwise it will error. I want to specify the ticker of the instrument to create the analysis.

native tide
#

what's a ticker?

#

and how does the instrument exist without a ticker already if it's a required field?

#

it's sounding a little like you need to create a custom form that's going to handle using a subset of fields from both models and then wires them up the way you're thinking in the save method

static mulch
#

@static mulch walk through your code slowly, you go through a loop setting the name. everything in the first loop will finish before it moves to the next loop. so what will be in the name variable when it gets to the print statement?
@native tide I see, only one name will arrive at price and only print one.. Is it possible in the setup i have to somehow link them together? Or do I have to steer away from two loops?

vernal finch
#

@native tide apologies for the late response, just assume an instrument exists and it has a ticker field (it's a string field). When I create an analysis, I want to create an analysis FOR an instrument. So what I do is I supply the ticker of the instrument that I want to create the analysis for. I will then look up if an instrument with that ticker exists. If it does then I will create the analysis. However, also remember that I could also specify a time_frame field when creating the analysis.

Example requests:
{"ticker": "TICKER" }
{"ticker": "TICKER", "time_frame": 5 }

Example responses:
{"id": 2, "time_frame": 5, "instrument": { "id": 2, "ticker": "TICKER", "company_name": "TICKER COMPANY" }}

native tide
#

@static mulch you can do it all in 1 loop

#

@vernal finch ah ok i see what you're saying a little better

#

you might wanna make ticker a unique field or things could get weird if you have 2 instruments with the same ticker

#

are you using django rest framework for this?

vernal finch
#

yes

#

the thing is the ticker is something like part of a composite key

#

ticker is not necessarily globally unique but ticker+something is unique. So I can't really make ticker a unique field (although for the most part it actually will be)

#

@native tide

modest hazel
#

Hi guys, I build bots, I want to create stuff that will appear as human as possible, so I'm building a bot detector to test my builds against. I have the basics down here: https://lafftar.github.io/bot-detector/

I'd like to know what I can detect with Javascript about a user, just linking me to articles will be more than welcome, fingerprinting, tracking, everything is welcome. If you build bots too, you might benefit from this too.

odd oar
#

!rule 5

lavish prismBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious/inappropriate or be for graded coursework/exams.

olive egret
#

I need some help with django please:
Every time I try to create a model using the admin panel,

#

What can I do to get rid of this error?

vestal hound
#

have you run makemigrations and migrate

patent hawk
#

I know this is mostly stupid question, but how do you run python script on web server witch hosts a website? (I have heard you put .cgi at the end of filename and put it in cgi-bin folder. I can't find cgi-bin folder and when I create one it shows my code as if it would be .txt file. I also put :
Options +ExecCGI AddHandler cgi-script .cgi .pl
In .htaccess.

worn aurora
#

to run python script the host needs to support python environment

patent hawk
#

Can I install it in cpanel?

#

If no how to do it?

worn aurora
#

u are on a vps or shared hosting ?

patent hawk
#

?

#

I go to my website.tld/cpanel

#

@worn aurora

worn aurora
#

link ?

vagrant owl
#

Anyone working on flask currently?

#

I'm working on something and I've run into an error I can't seem to find a solution of.

worn aurora
#

error ?

vagrant owl
#

Yeah

#

Hold on, I'll upload a screenshot here.

#

Let me paste the code here

#

C:\Users\USER.virtualenvs\smilecook\venv\lib\site-packages\flask_sqlalchemy__init.py:814: UserWarning: Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:". 'Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. ' C:\Users\USER.virtualenvs\smilecook\venv\lib\site-packages\flask_sqlalchemy__init.py:835: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning. 'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '

#

And my app.py file, excluding the imports, is:

#

`def create_app():
app = Flask(name)
app.config.from_object(Config)
register_extensions(app)
register_resources(app)
return app

def register_extensions(app):
db.init_app(app)
migrate = Migrate(app, db)

def register_resources(app):
api = Api(app)
api.add_resource(RecipeListResource, '/recipes')
api.add_resource(RecipeResource, '/recipes/int:recipe_id')
api.add_resource(RecipePublishResource, '/recipes/int:recipe_id/publish')

if name == 'main':
app = create_app()
app.run()`

#

The config.py file contains the following code:

`class Config:

DEBUG = True
SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://root:root@localhost/smilecook'
SQLALCHEMY_TRACK_MODIFICATIONS = False`
hallow abyss
#

hello guys , i m sui and there are some question about python!

#

is there anyone who use Odoo

vagrant owl
#

Got the solution, thanks!

coral raven
#

hey!

#

any good guide or book to learn flask?

chrome scaffold
#

Tech with tim on YouTube has a good tutorial

tardy trellis
#

@coral raven Corey schefer

#

Too

chrome scaffold
#

^

tardy trellis
#

Pretty cool guide

native tide
coral raven
#

I finished the Corey Schafer one, still have some things unclear

#

he also has a book right?

native tide
#

Yeah

tardy trellis
#

Miguel

#

is also a good one

#

But if you have finished

#

Coreys guide

#

Just start digging your self

coral raven
#

i do not know the html, css part yet, I have to learn that

tardy trellis
#

Aha

#

That

#

W3school

#

Is good

coral raven
#

I copy pasted Corey's html templates and continued

tardy trellis
#

Jonas schmedtman

#

Does some pretty good ones