#web-development

2 messages ยท Page 72 of 1

flint breach
#

You set up a rest api, setup the endpoints you need, setup auth

#

depends on what you specifically mean

#

care to elaborate.?

frosty veldt
#

Anyone knows how to use flask-socketio on heroku?

brittle iris
#

hey guys
i want it so people can download a folder from my django project
so it acts as a storage so people can download from it

flint breach
#

what have you tried

swift sky
#

hello, im following this DO tutorial

#

and I'm a bit confused in the server block portion

#

specifically this section ```server {
listen 80;
listen [::]:80;

    root /var/www/example.com/html;
    index index.html index.htm index.nginx-debian.html;

    server_name example.com www.example.com;

    location / {
            try_files $uri $uri/ =404;
    }

}```

#

so for this line server_name example.com www.example.com;

#

the actual website im trying to host on there has its DNS (?) set up as such

#

example.example.com

#

does that make a difference?

#

should I do server_name example.com example.example.com

rigid laurel
#

there's nothing wrong with asking here, but you might have better luck asking in #tools-and-devops or possibly even in off-topic

swift sky
#

oh thank you

#

I will spam away xD

#

I think I asked in dev ops last itme

rigid laurel
#

if I was trying to solve your problem, my first port of call would probably be OT

swift sky
#

thanks

lucid eagle
#

Hello

crystal quartz
#

Hello everyone, I have a flask app which is set up to send emails to users. I would like to format these using html which I know how to do technically but I absolutely hate trying to build the HTML content in python because message_content="<html><h1>" + str(a) + etc etc is a total pain. Is there some sort of way I can use jinja or another technology/extension to make this easier?

flint breach
#

perhaps, jinja2 or some templating engine would do you good

quick cargo
#

Flask has a jinja engine built into it

crystal quartz
#

Yeah, 100% - I use jinja2 to serve the html for my web pages, and I love it - but how do I repurpose this to get the jinja2 output to a string rather than display to the user?

quick cargo
#

jinja outputs a string by default

#

its just flask's render_template that formats the template and returns it with the content types etc...

crystal quartz
#

ok, great - and I'm sorry to be really dumb about this, but...

#

at the moment I use a command like:

#

return render_template('users/list.html', user_list=user_list)

#

which does the jinja magic itself

quick cargo
#
from jinja2 import Environment, FileSystemLoader

template_env = Environment(loader=FileSystemLoader(searchpath="./templates"), auto_reload=True)
def render_template(name, **context):
    template = template_env.get_template(name)
    return template.render(**context)```

is a quick and dirty way
crystal quartz
#

awesome, thank you

#

that's really helpful

sick pulsar
#

for anyone that does flask, what's the 'typical' way to implement text searching

broken basin
#

Hello Developrs

#

I have to verify Heroku account to add custom domain but none of my card is not working with heroku.
Any alternative ?

cold anchor
#

@crystal quartz you can just use flask's render template, no need to reinvent it

#

here's an example I have of sending an account verify email:


class UserController:
    ...

    @staticmethod
    def verify_user(user):
        """Send the verification email the user."""
        if current_app.config.get('SEND_EMAILS'):
            ses_client = boto3.client('ses')
            ses_client.send_email(
                Source=current_app.config['FROM_EMAIL'],
                Destination={
                    'ToAddresses': [user.email],
                },
                Message={
                    'Subject': {
                        'Data': 'Verify your email address'
                    },
                    'Body': {
                        'Html': {
                            'Data': render_template(
                                'emails/verify.html',
                                verification_link='{}'.format(UserController.make_verify_link(user))
                            )
                        }
                    }
                }
            )
        else:
            current_app.logger.info('skipping email send')
modern hearth
#

Guys, I am developing an app in flask and for whatever reason I need an object which I create in the create_app to be accessible everywhere.

#

I could assign it into app.something = ... but that seems wrong to me.

cold anchor
#

what are you using the object for?

modern hearth
#

Well, a json store

#

dont ask me why

#

lol

cold anchor
#

there's nothing wrong with assigning it to the app object as long as it doesn't change over time

modern hearth
#

yeah but intellisense wont discover it

#

which will drive me crazy ๐Ÿ˜„

#

so I would need to inherit from the Flask object in order for it to work with intellisense

#

but that seems like an overkill to me

#

I also tried making the object static (without instantiating)

#

but I actually need to access the app.instance_path

#

so I need to refer to the app

#

but it gave me an error about the context

#

any ideas?

cold anchor
#

I would just add it to the object, though I personally don't care about my editor giving me code completion

modern hearth
#

well okay then

#

thanks

halcyon swan
#

I can't seem to find an a good guide on parsing jsons and getting certain values I mostly use javascript.

#
{
  "connections": [
    {
      "friend_sync": false, 
      "id": "", 
      "name": "Otis_Goodman", 
      "show_activity": true, 
      "type": "reddit", 
      "verified": true, 
      "visibility": 1
    }, 
    {
      "friend_sync": false, 
      "id": "", 
      "name": "Otis_Goodman", 
      "show_activity": true, 
      "type": "steam", 
      "verified": true, 
      "visibility": 1
    }, 
    {
      "friend_sync": false, 
      "id": "", 
      "name": "OtisGoodman", 
      "show_activity": false, 
      "type": "xbox", 
      "verified": true, 
      "visibility": 1
    }
  ], 
  "user": {
    "avatar": "", 
    "discriminator": "", 
    "flags": 256, 
    "id": "", 
    "locale": "en-US", 
    "mfa_enabled": true, 
    "public_flags": 256, 
    "username": "Otis Goodman"
  }
}
#

test the type xboxto see if it exists in a json

#

I would also like to try to get the id type from user but I am not sure how to get it without confusing with the other id types

flint breach
#

basically you parse the json, which is basically a dictionary in python once deserialized then you simply iterate through the connection keys to get individual objects

for obj in dictionary['connections']:
  print(obj)
#

look into the json module

#

specifially json.dump and json.load if it's a file, or json.dumps and json.loads if you're making requests (in memory json)

#

if you're using javascript, the same principle applies, you just don't need any specific "javascript modules"

#

if you've got any questions, feel free to ping me

fickle bobcat
#

Anyone here a flask expert? very good with blueprints/namespaces?

I've used flask before, but nothing really advanced and I now I have to debug a flask issue, but I can't figure out what the problem is.

I was able to read the docs and create my own flask app using blueprints and namespaces but I still can't debug the original.

I just get a 404 with no other errors. Can anyone help?

coral wind
#

what are pros and cons of flask and django?

flint breach
#

it's heavy weight and opinionated, but that's a pro and con

#

it's batteries included, meaning it's got a lot of stuff built in, which you'll probably need anyway

#

lots of third party apps for anything you'll need

#

lots of magic underneath though, things that are implicit that you can gain knowledge of with time

#

overall it's preety sweet, i can recommend some playing around with it

coral wind
#

youare talking about flask?

flint breach
#

flask is preety minimal

#

i was talking about django

#

flask is preety minimal in comparison, not batteries included

halcyon swan
#

how would I get the json from jsonify to load so I can get the key?

flint breach
#

can you show the snippet where you get the json object

halcyon swan
#
{
  "connections": [
    {
      "friend_sync": false, 
      "id": "68vym9ze", 
      "name": "Otis_Goodman", 
      "show_activity": true, 
      "type": "reddit", 
      "verified": true, 
      "visibility": 1
    }, 
    {
      "friend_sync": false, 
      "id": "76561198856903539", 
      "name": "Otis_Goodman", 
      "show_activity": true, 
      "type": "steam", 
      "verified": true, 
      "visibility": 1
    }, 
    {
      "friend_sync": false, 
      "id": "YzY4NzgwOTE4MjQwZmIyZDBmMDJkOGIwY2ZhZWI4ZTc2NzllN2M3MDVlMTM3Yjk5MDE5ODBiYTM4MDQ0MjlkMA", 
      "name": "OtisGoodman", 
      "show_activity": false, 
      "type": "xbox", 
      "verified": true, 
      "visibility": 1
    }
  ], 
  "user": {
    "avatar": "0b617bcf8d51f63329044929df981f5c", 
    "discriminator": "0018", 
    "flags": 256, 
    "id": "348631584863289346", 
    "locale": "en-US", 
    "mfa_enabled": true, 
    "public_flags": 256, 
    "username": "Otis Goodman"
  }
}
#

is this what u mean?

flint breach
#

did you try what i wrote earlier?

#

it's basically a dictionary in python

halcyon swan
#
for obj in dictionary['connections']:
  print(obj)```
flint breach
#

the dictionary is just a variable

#

cna you show the code where you get the json object

#

not the json itself

fickle bobcat
#

nvm about my problem, I fixed it.

native tide
#

what is the difference between django-admin startproject projectname and django-admin startproject projectname.

lilac root
#

Hey I have a few questions about implementing zoom oauth in django, I've taken a look at allauth and it doesn't support zoom. I've also seen django oauth toolkit, bit I'm not too sure about the implementation. Lastly I saw DRF's django-rest-framework-social-oauth2, looks like this might help, but I'm not sure.

halcyon swan
#

@native tide why is this in python discord ๐Ÿ˜›

shadow hornet
#

@native tide we don't allow recruitment here

halcyon swan
#

also randomly friending me kinda weird man

#

@flint breach how would I query if xbox type exists?

flint breach
#

what is the difference between django-admin startproject projectname and django-admin startproject projectname.
@native tide nothing, if you mean django-admin startproject projectname ., then it basically treates the current directory as the project root

#

otherwise it creates a new directory named projectname and treats that as the project root

#

@flint breach how would I query if xbox type exists?
@halcyon swan xbox type?

#

aha

#

basically iterate through each object

#

and again, the obj is a dictionary

#

obj['type'] == 'xbox' should be enough

native tide
#

ok

flint breach
#

basically it's just a convinience

#

also, like most shell commands

#
django-admin startproject --help
usage: django-admin startproject [-h] [--template TEMPLATE] [--extension EXTENSIONS]
                                 [--name FILES] [--version] [-v {0,1,2,3}]
                                 [--settings SETTINGS] [--pythonpath PYTHONPATH]
                                 [--traceback] [--no-color] [--force-color]
                                 name [directory]
#

using --help as a positonal argument will usually reveal the possible options

#

the things in square brackets are optional

native tide
#

Good evening, I'm trying to deploy my flask app on AWS, app is a Spotify API authorization which needs redirect_uri to the server:port so it could display spoti login page and get auth token.

#

question is, does redirect_uri need to contain the server's public dns4 ?

#

and how do i actually open a port so it could run the auth login? I have all inbound traffic enabled in AWS

coral wind
#

has anyone worked with pythonanywhere for hosting django apps?

#
19:47 ~/website $ python manage.py startapp genericapp
  File "manage.py", line 16
    ) from exc
         ^
SyntaxError: invalid syntax
#

i dont even know how to start an app there

#

are there any alternatives to it?

#

aw

#

by just writing python ive learne theat the shell console uses python 2

#

i can just use python3 instead of pythonbut its mildly infuriating

fickle raft
#

I don't see a channel for scraping, so can I ask the question here instead?

#

or is it under use

glacial loom
#

Im having a issue with heroku and my web app

#

it keeps on giving a request timeout

#

webapp is made with flask

#

im running it with socketio.run(app)

#

and this is the procfile

#

web: gunicorn main:app

cold anchor
#

are you doing anything intensive on startup? it looks like gunicorn's workers aren't starting within the timeout window

glacial loom
#

no

#

there are some background threads but they dont start until you fill out a form so it shouldn't have any intense processes

#

@cold anchor

distant trout
#

can someone please tell me the difference between

"sqlite:///database.db" VS "sqlite:///database.sqlite3"

halcyon swan
#
@app.route('/me')
def me():
    discord = make_session(token=session.get('oauth2_token'))
    connections = discord.get(API_BASE_URL + '/users/@me/connections').json()
    if (connections['type'] == "xbox"):
        print("oh ya!")
    return jsonify(connections=connections)
#

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

#

am I doing something wrong @flint breach I am clueless at python

glacial loom
#

um

#

whats supposed to happen?

#

@halcyon swan

halcyon swan
#

if the persons oauth2 connection has xbox in it I print oh ya

glacial loom
#

ive been trying everything to get this fixed

#

heroku^

#

im trying to run a flask web app

#

web: gunicorn main:app

#

procfile^

flint breach
#

am I doing something wrong @flint breach I am clueless at python
@halcyon swan ill help you out tomorow, right about to go to sleep ๐Ÿ˜„

halcyon swan
#

ok

verbal wyvern
#

Is this a place to ask a question about scraping or no

glacial loom
#

i think its fine unless it breaks the websites tos

native tide
#

always good to check so u dont get ip banned

neon needle
#

Can someone help me about django?

foggy geyser
#

Hey, I want some help in using Django media and static files in Google storage PLEASE!, I am using GKE in the same project as the Storage, but when I send a request for uploading in the Storage I get a 403 Forbidden response.

#

@neon needle I can ๐Ÿ™‚

brittle iris
#

hey guys
my admin panel page is now not serving static files
dunno what to do

coral raven
#

Flask-mail not sending mails

#

anyone knows why?

hasty remnant
#

Hey guys, so i'm going to create an amazon like clone using django and mongodb, and i have to create this Cart Schema, i want to store multiple objects on that schema, which field should i use for it ?

#

it should be like an list/array field where i can store the objects of products

rigid laurel
#

What do you mean?

#

I don't think you're using those two terms quite correctly

glossy olive
#

@coral raven there's probably a security setting you'll have to disable (at least in gmail)

flint breach
#

am I doing something wrong @flint breach I am clueless at python
@halcyon swan you have to loop like i showed before

#

i advise you lookup into the language basics, before trying to do something with it

#

Can someone help me about django?
@neon needle !ask

median meteor
#

what do you need with django?

broken basin
#

Anyone used gatsby static site generator

frosty veldt
#

Anyone knows a css optimizer module like node's csso?

granite loom
#

hey guys anyone can tell me about django and its usge

flint breach
#

basically a framework that let's you build web applications with python

fickle basin
#

Hello so , can any one tell what to check when routes in Django seems broken , like the redirection are wrong what should I check first ?

flint breach
#

check if you specified the correct arguments when reversing

#

check if the url reversal points to an actual view

#

can you show what exactly django outputs?

#

feel free to ping me when you do

wind walrus
#

Is it possible to create a combobox sort of thing with wtforms?

#

Itโ€™s like a SelectField but the user can enter their choice of the choice doesnโ€™t already exist

#

Ping me pls

balmy shard
#

Bois

#

I'm having some trouble clicking an element with selenium

#

It has a unique id and I copied it directly

#

Dm or @ me if anyone knows how to fix it

wind walrus
#

Did you wait for it to become clickable

#

@balmy shard

#

If you try to click an element before the page fully loads itโ€™ll crash

balmy shard
#

I did

wind walrus
#

Are you running in headless or normal

balmy shard
#

Normal

wind walrus
#

Cos for my project it crashed in headless but worked in normal

#

Hmm

bleak bobcat
#

What does it says ?

balmy shard
#

Cos for my project it crashed in headless but worked in normal
@wind walrus I'm pretty sure it dont open the browser in headless

#

Wont*

wind walrus
#

It doesnโ€™t open the browser, it should work hidden

#

But I got selenium timeout in headless

#

Worked fine in normal

balmy shard
#

Ok

ancient basalt
#

What do people use to edit their html/css? Whatever app they are coding their web app in? Do people still use something like Dreamweaver? I'm trying to figure out why my rows don't line up and been using pycharm to code my django site.

bleak bobcat
#

Community or professional edition ?

ancient basalt
#

professional

bleak bobcat
#

Then it's fine to edit html/css/js files, the community edition however does not support those

balmy shard
#

@wind walrus I said elements not element ๐Ÿ˜‘

#

That's the problem

errant remnant
#

hlo, guys can some one help me here, its about websockets

ancient basalt
#

@bleak bobcat I'm editing in it, i'm just having a hard time finding the error in the code. It doesn't even display that there is an error. just lazy/blind and was wondering if there was an easier way to find the issue

bleak bobcat
#

Is the row above it inside a parent .container ?

ancient basalt
#

well I am an idiot/lazy

#

lol thanks figured it out. I guess after staring at it for a day everything just blured together

quick belfry
#

What are some clean and formatted ways (data representation) by which i can display my data after user inputs a query

dense slate
#

How did this server get the reddit links to post to Discord?

faint abyss
#

Hey!
That's just a basic User-Profile Signal file, but my question is, why do I have to include save_profile as well? If I update user, then I update profile as well at the same time, and I also save it. So that's just doesn't make sense.

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()```
What do you say?
crystal quartz
#

Hello web-dev heroes, I am using Flask and I'm a bit confused about how to pass variables. I have a route which is designed to accept form input, which it does fine, but I would also like the option to manually call this definition in my code in other scenarios (DRY) but I'm unsure how to set it up to accept both form input and input from another python call

#

Code as it stands:

#
def mydefname(user_id):
    comment = request.form.get('comment')```
#

I can happily pass the "user_id" element from another definition

#

but how do I also pass the "comment" variable from python while maintaining the ability to also have it populated by the form

distant trout
#

can someone help me with flask postgres

#
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 5432?
could not connect to server: Connection refused (0x0000274D/10061)
        Is the server running on host "localhost" (127.0.0.1) and accepting
        TCP/IP connections on port 5432?```
#

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:booksami@localhost/FlaskQNA'

#

thats the config

green flume
#

Hey guys! How can I get a random value from this array array = (1,2,3,4) ?

#

I tried rand = randint(array), but doesn`t work

dapper tusk
#

random.choice

green flume
#

thanks

brittle iris
#

Hey guys I need to set up a PayPal ipn with python, any tips and tricks to make it work. My web framework that I am using is django.

wind walrus
#

Is it better to use flask-markdown or pythonโ€™s markdown module to create a markdown based blog with flask?

azure saddle
#

I'm having some trouble clicking an element with selenium
@balmy shard well just try putting the program to sleep for sometime and then click

tidal knoll
#

Excuse me admin and friends all, maybe here anyone interested in learning Web Development, I have a free coupon access to all material on progate.com for 30 days, material that can be accessed like, HTML, CSS, JavaScript, React, Node.JS, SQL , Python and Linux CLI, how to simply register an account at progate.com and redeem the coupon code PROGATEASIX113 Hopefully Helpful

wind walrus
#

Is it normal that I have to clear the browser cache every time I make a change in the css file?

#

Using Flask, style.css file located in static folder

edgy raft
#

Hi I have a Django Rest Framework question:
what's the difference between APIView and ViewSet?
I'm making a big app(online register), that after a call to an endpoint will have to do many things
(example: Add student/Teacher/admin to class and return class connection code)

Currently I've made everything work with APIViews(And it works great!), But every time I look in documentation I can see that I might
have better routing and better browsable web api. And that overall it could be easier especially if I would want to use action decorator to perform different operations on the same View

So my question is can I just change my APIViews to ViewSets, and is it a good idea?

stray sorrel
#

Hello, I am trying to fix the pylint error that happens in django using this stack overflow post: https://stackoverflow.com/questions/45135263/class-has-no-objects-member
The problem is that when I try to paste the code, I get those errors, can anyone please help me out?
Thank you in advance :D

native tide
#

@stray sorrel You need to place a comma after each item, since this is a JSON file and requires JSON notation

stray sorrel
#

@native tide I never did JSON before, could you please tell me exactly where I should put a comma ๐Ÿ˜„ I would really appreciate it.

native tide
#

after cmd.exe",
and after the first object's },

stray sorrel
#

Thank you so much ๐Ÿ˜„ I managed to solve it.

native tide
#

๐Ÿ‘Œ

flint breach
#

Is it normal that I have to clear the browser cache every time I make a change in the css file?
@wind walrus developer tools have a friendly option to disable the cache

torpid flax
#

should I use django for web dev?

flint breach
#

Depends on your needs, it handles alot of mundane tasks when it comes to webdev

torpid flax
#

ok

mellow gyro
#

Hi,
for a project im using bottle with some tpl files but i can't get to apply CSS to my file.
Anyone that can help with this?

Thanks in advance!

flint breach
#

but i think it's a good choice to start

stable egret
#

is there a freelancer here that does web development?

#

idk what to learn to start freelancing

#

and yes i have searched the web and youtube a lot

bleak bobcat
stable egret
#

oh thanks !

#

ill check it out right now

mellow gyro
#

@stable egret I'm not a freelancer but i have many friends who are. They just learn a backend language they are comfortable with and make projects on their own, to learn. (this language is 90% nodejs or in that area( see expressJS, typescript, nextjs,..))
then they start looking at a frontend framework that interests them the most, again by practicing a lot. Most of them pick one of the big three ( Angular, React or Vue )
and the main thing i saw them do was practice, make some for friends/family without any pay, just to learn the languages and learn to work with customers.
And once you feel ready to get your name out there, just go for it, don't be afraid. you learn a lot along the way as well !

stable egret
#

thanks !

mellow gyro
#

no worries! Happy coding my guy!

stable egret
#

i want to learn python tho

#

idk if im being influenced by the internet with that choice

mellow gyro
#

Learn whatever you feel like

stable egret
#

aight !

mellow gyro
#

If you want to learn Python, go for it!
I'd rather go with JS and then NodeJS if you really want to freelance in web development but that is personal
Python is also an option with Django.
it's just that with JS you have more roads to walk on, you can go vanilla js, take on a framework likes express or next or nuxt or redux or ...
and for the front end you have even more haha see Angular/AngularJS, React, Ember, Vue, jQuery, backbone,....

stable egret
#

nice !

mellow gyro
#

so the choice really is yours

#

and there are always fellow devs who are very willing to help

azure saddle
#

hey people can anybody help me with atemplate issue

#

?

#

you are requested to DM if able to help

mellow gyro
#

maybe explain the issue so we know if we can help xd

azure saddle
#

ohk

#

well I'm trying to make an website

#

and I'm using flask in python

#

when I try rendering the template of mine using

render_template("index.html")

and run the program it give the error that template is not found

#

while I have already saved the template

#

and I tried to give the full path too

#

but the same error was raised

native tide
#

@azure saddle You sure you have it in a folder named templates?

azure saddle
#

yeh I have

#

well I made one folder named templates and then added that index.html

#

but does it effect?

#

when I try rendering the template of mine using

render_template("index.html")

and run the program it give the error that template is not found
@azure saddle pls help๐Ÿ™๐Ÿ™๐Ÿ™

digital karma
#

this is probably the wrong server for this. but im building a website using WordPress and i wan t to run some python scripts on it. im new to web development so just bear with me. im trying to use FTP-simple in vscode but i keep getting this message: FTP - close!! im not sure if the username and password matter but the ones im using in my code are the same as my admin log in.

#

and when i crl+click on the link in the code it takes me to my site

flint breach
#

do you have ftp server open'

wind walrus
#

If I want to add some JavaScript to a blog post written in markdown and rendered with flask, do I just simply write the js inside <script> on the post itself?

native tide
#

Did anyone have problem with flask mail on heroku?

#

I get this error and I've been struggling for quite a while

#
smtplib.SMTPServerDisconnected: please run connect() first
cold anchor
rigid laurel
#

that Flask Mail package hasn't been updated in like 10 years, probably very insecure at this point

cold anchor
#

if you want to send emails from python it's a lot easier to use something like Sendgrid or AWS SES

native tide
#

@cold anchor you mean mail.connect()?

cold anchor
#

yes

rigid laurel
#

Those are probably much more secure options as well. SES gives you a bunch of free sends iirc

native tide
#

mkay let me give it a go

#

A

#

I ll look into it

#

thanks

#

Do you need a heroku addon for AWS SES?

cold anchor
#

no, just an AWS account

native tide
#

@cold anchor same error >.>

#

frustrating..

fierce helm
#

hii

small raptor
#

anyone here had experience using selenium for web scraping..?

glass sandal
#

Why don't u use BS4 or Scrapy?

slender whale
#

Does anyone have a good, concise video or tutorial on the basics of HTML/CSS

#

I'm interested in learning basic stuff, and maybe making my own website. I still dont quite understand the difference between Django, JS, Flask, NodeJS, etc.

#

Like is front end completely HTML, CSS, and JS?

#

Then backend stuff (which i dont evne know what that means) is Django?

brave karma
#

how would i use django for a database where there are embedded documents more than 2 levels deep

#

im currently trying out djongo cuz the other nosql, nonrel option projects are not maintained

#

django-nonrel hasnt been maintained for 8 years

#

only option seems to be djongo but i cant embed models more than once

glass sandal
#

Yep

#

Add !important

#

Befor the semi-colon

#

So like :

body {
    background-image: linear-gradient((#fdfcfb),(#e2d1c3)) !important;
}
#

@native tide

#

Remove the (

#

Just do like :

body {
    background-image: linear-gradient(#fdfcfb,#e2d1c3) !important;
}
#

Oh and nothing will happen by doing like :

body {
    background-image: linear-gradient(to right,#fdfcfb,#e2d1c3) !important;
}
#

Or maybe first try like a color by word

#

like red and blue

#

Try that to make sure it's not your browser probkem

#

problem*

#

Good

#

np

#

It overrides the value

#

e.g

#

When you have this :

a {
  color: #444;
  color: black !important;
}

The color would be black , not #444

#

And idk why , but gradients don't seem to work for me either (without !important)

#

So that's my prob too

#

yeah lol

#

?

#

Oh

#

Just do :

body {
  margin: 0px;
}

and set your item width/height to 100%

#

It's work

#

Or if your items are in a div or something , in addition to this , do :

#div_id {
  margin: 0px;
}

too

#

Don't forget to set the width of div to 100% too!

#

:)

#

Well , now you know

#

np

#

Guys what do you do in web dev if you're bored?

#

In web dev not in PyGame and stuff

#

And more specificaly , backend

#

:qa

deep cave
#

@brave karma if you want nosql for your site, honestly, just use a different framework than Django.

#

flask is pretty good. or if you want more speed, try an async one and some sort of async ORM?

brave karma
#

dang just learned django for the code jam and wanted to use it :/

deep cave
#

then don't use nosql

#

what's wrong with postgres?

#

Django isn't designed for blazing speed but it's still fast enough for most things.

quick cargo
#

Django does have support for mongodb tbh

#

but i would go with a SQL option for Django overall

#

or any framework thats async for that matter aswell due to nosql options being rather lacking

slender whale
#

I'm trying to control the placement of a table within a webpage using a jinja2 template

template_str = """<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <div style = "poisition:; left:200px; top:400px;">
        {{table}}
    </div>
</body>
</html>
"""
#

However that is not controlling the placement at all. Is there soemthing I am doing wrong?

#

The table HTML would ideally be coming from pandas.DataFrame.style.render() (this outputs a table html/css string)

brave karma
#

theres nothing wrong with postgres its just that the discord bot was made first and made with mongodb

#

not really sure if i wanna rewrite all of that

#

i dont think its worth it, even tho django is great

#

i think im gonna use sanic since the discord bot is using an async client for mongodb but im gonna miss some of django's built in stuff

#

until the code jam ๐Ÿ™‚

quick cargo
#

i hate mongo motor enough to just have a thread pool and just executor pymongo tbh

slender whale
#

Can you control the overall position of a table element by stuffing it inside of a div?

cold anchor
#

you're giving CSS positions without changing the position attribute to something that makes sense for it like relative, absolute or sticky

#

based on what you have, try doing position: absolute;

slender whale
#

position: absolute and position: relative do nothing at all it seems. I was originally using relative I apologize I must have copied it during a different attempt

#
from IPython.display import IFrame, display, HTML
import pandas as pd
import numpy as np
from jinja2 import Template
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
               axis=1)
def color_negative_red(val):
    """
    Takes a scalar and returns a string with
    the css property `'color: red'` for negative
    strings, black otherwise.
    """
    color = 'red' if val < 0 else 'black'
    return 'color: %s' % color
s = df.style.applymap(color_negative_red)
template_str = """<!DOCTYPE html>
<html>
<head >
    <h1 style="position:relative;left:200px">My template for displaying table at specific location</h1>
</head>
<body>
    <div style = "poisition:absolute;left:1000px;top:800px">
        {{table}}
    </div>
</body>
</html>
"""
t = Template(template_str)
HTML(t.render(table=s.render()))
#

Its very frustrating I can't get that table to move.

#

I would just like to say, this is my first time doing anything like this. So please forgive me I am doing something absolutely stupid.

glass sandal
#

Guys what do you do in web dev if you're bored?
In web dev not in PyGame and stuff
And more specificaly , backend

#

Nothing?

slender whale
#

My typo

glass sandal
#

Guys what do you do in web dev if you're bored?
In web dev not in PyGame and stuff
And more specificaly , backend
Not contributing please

green flume
#

of course

azure saddle
#

when I try rendering the template of mine using

render_template("index.html")

and run the program it give the error that template is not found
@azure saddle ....

#

pls help ppl

glass sandal
#

Are you sure you have an index.html file in your templates folder?

azure saddle
#

yeh I have

#

but I made an template folder in some other dir

glass sandal
#

Then you have to point to that dir

azure saddle
#

is there any specific templates folder that is there where we create the html file?

#

yeh I gave an direct path to it

glass sandal
#

So when you wanted to define your app/blueprint you told the app the template folder path right?

azure saddle
#

like I have a folder A there is a main.py file where I'm trying to render the template
and in that same folder A there is another folder named template where I have kept my index.html file

glass sandal
#

So could you just send a directory tree?

azure saddle
#

So when you wanted to define your app/blueprint you told the app the template folder path right?
@glass sandal yeh I tried many a times tho

#

So could you just send a directory tree?
@glass sandal ok

glass sandal
#

Like :
a
-main.py
-template
--index.html
?

azure saddle
#

yeh

#

same

glass sandal
#

Hmmm

#

So you wanna accesss index.html

azure saddle
#

yes

glass sandal
#

And your app/blueprint must be defined like :

app = Flask(__name__,template_folder="template")
#

Right?

#

Either rename the folder to "templates" or do that

native tide
#

in case it's named template

glass sandal
#

Oh so then he/she has to define the folder in app definition

azure saddle
#

And your app/blueprint must be defined like :

app = Flask(__name__,template_folder="template")

@glass sandal well it is like

def home():
    # if NAME_KEY not in session:
    #   return redirect(url_for("login"))

    # name = session[NAME_KEY]
    return render_template('website\\application\\templates\\index.html')
glass sandal
#

Nonono it's wrong

native tide
#

^ dont do that ๐Ÿ˜›

azure saddle
#

??

native tide
#

just render 'index.html'

azure saddle
#

this one?

glass sandal
#

You must not give direct paths

native tide
#

it will look into template for index.html

glass sandal
#

To the template folder

#

Just do "index.html"

#

return render_template("index.html")

azure saddle
#

yeh I tried that

just render 'index.html'
@native tide

def home():
    # if NAME_KEY not in session:
    #   return redirect(url_for("login"))

    # name = session[NAME_KEY]
    return render_template('index.html')
glass sandal
#

Yes .

#

And then define your template folder in app definition

azure saddle
#

but still it was the same error

native tide
#

is your templates folder named templates or template?

glass sandal
#

Or blueprint defenition

azure saddle
#

wait let me share a ss

native tide
#

please

azure saddle
#

just a min

glass sandal
#

Just ... You know, you use blueprints or you have a single app?

azure saddle
#

templates

glass sandal
#

You use blueprints or a single app variable?

azure saddle
#

Just ... You know, you use blueprints or you have a single app?
@glass sandal well I'm really new in web-dev tho so I don't know this

glass sandal
#

Oh so you use app

#

So define your app like :

app = Flask(__name__,template_folder="website/application/templates")
#

And then you can just say "index.html"

azure saddle
#

well It is not like that the dir tree is like
A
-main.py
-application
--templates
---index.html

#

well wait let me share my code

glass sandal
#

So do "templates" instead of that

#

or "application/templates"

native tide
#

You dont have to use templates, that's the default, if it's on the same level as the app

glass sandal
#

@native tide His/Her main.py file is one dir upper

#

So she/he needs too

#

to*

azure saddle
#
from flask import Flask, render_template, url_for, redirect, request, session

NAME_KEY = 'name'

app = Flask(__name__)
app.secret_key = "hello"

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


@app.route("/logout")
def logout():
    session.pop(NAME_KEY, None)
    return redirect(url_for("login"))


@app.route("/")
@app.route("/home")
def home():
    # if NAME_KEY not in session:
    #   return redirect(url_for("login"))

    # name = session[NAME_KEY]
    return render_template('website\\application\\templates\\index.html')


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

So you see app = Flask(name_)?

native tide
#

Yeah okay, if it is as you pointed @azure saddle , add what RaderH2O suggested, applciation/templates

glass sandal
#

Change it too

azure saddle
#

then I may remove templates file?

#

yes

glass sandal
#
app = Flask(__name__,template_folder="application/templates")
azure saddle
#

ohkk

glass sandal
#

Change it to that ^

#

And

#

Your render template

native tide
#

and ```py
return render_template('website\application\templates\index.html')

glass sandal
#

Needs to be changed to return render_template("index.html")

native tide
#

to py render_template('index.html')

glass sandal
#

Yes

azure saddle
#

ohkkk thanks ppl very mcuh๐Ÿ˜Š

glass sandal
#

nah np

azure saddle
#

much*

#

well I'm gonna try rn

glass sandal
#

kk It must work

azure saddle
#

yeh I hope๐Ÿ˜Š

#

ohhhh yesssssssssssssssss

glass sandal
#

It worked?

azure saddle
#

thank you @glass sandal and @native tide very much it works really fine

glass sandal
#

Nah np

azure saddle
#

yeh๐Ÿ˜Š๐Ÿ™

glass sandal
#

Nice

#

You are learning from the documentation?

azure saddle
#

yeh

#

and youtube

glass sandal
#

Oh

#

When I was beginner , I used youtube . It's much better than the documentation .

#

Use Youtube unless you have like a network problem

#

Or you could get used to documentation

#

Which is a better choice imo

daring egret
#

Does anyone know how to print in django some parts of a string like 0:8 or something like this?

azure saddle
#

well I was making a chat room using sockets and making a server
then I saw using Flask for GUI than CLI is better so I made a server and then I'm making a whole website lol

glass sandal
#

Oh I see lol

azure saddle
#

When I was beginner , I used youtube . It's much better than the documentation .
@glass sandal yeh youtube is good

glass sandal
#

Yeah

#

@daring egret wdym?

#

Oh

#

You mean like string[0:8]?

daring egret
#

yeah

glass sandal
#

Oh so imo it's good to refrence it in views.py

glass sandal
#

And that's a better way

#

^^^^

daring egret
#

ok

glass sandal
#

But you can just

return render("file.html",{"string":string[0:8]})
native tide
#

You could, yes

glass sandal
#

Jinja has a way of doing it too right?

native tide
#

Yup

glass sandal
#

Oh I see

native tide
#

return render("file.html",{"string":string[0:8]})รผ

#

why

#

itss not

#

work

#

for

#

me

glass sandal
#

Cause maybe your string is not right

native tide
#

''''python
return render("file.html",{"string":string[0:8]})
''''

glass sandal
#

And I wrote the line with placholders

native tide
#

idk

#

i just know html and c++

glass sandal
#

So file.html must be your file , and string[0:8] must be your variable

#

Like variable[0:8]

native tide
#

ok whatever i play valorant

#

๐Ÿ˜„

glass sandal
#

XD lol

native tide
#

wanna play with me?

glass sandal
#

I don't have lol

native tide
#

So file.html must be your file , and string[0:8] must be your variable
@glass sandal Actually this works directly with jinja {{ variable[0:8] }}

#

oh

glass sandal
#

I am on Linux

native tide
#

ohh

glass sandal
#

@native tide Didn't know that lol

native tide
#

u play growtopia

#

?

glass sandal
#

Used too*

#

Am on linux

#

I can't

#

Play

#

Windows games

#

Unless with WINE

#

That sucks for games

#

Why am I typing too instead of to lol

daring egret
#

I found how to print that variable like in that example it's goes something like this {{variable|truncatechars: the letter at which you wish for the characters to stop}}

#

like 0 or 9

glass sandal
#

Just do {{variable[0:9]}} as @native tide said

daring egret
#

i tried

native tide
#

that works with jinja2

daring egret
#

i gave me syntax error

glass sandal
#

You are using Django right?

#

If yes , it must work

daring egret
#

yeah

glass sandal
#

So what error did it give?

native tide
#

doesnt truncate chars always follow with ...?

glass sandal
#

I myself am not much familiar in terms of Jinja and template languages . So Idk . Maybe he could answer?

#

or she*

daring egret
#

it add like 3 points

#

at the end to signify that the word ment to be longer

#

the {{variable[0:9]}} gives template syntax error

glass sandal
#

Oh I see

#

Maybe the length of your string is short?

#

Oh I forgot , syntax error

native tide
#

probably doesnt work with django's templating engine

glass sandal
#

Yeah maybe

#

Guys what do you do/what stuff do you make when you are bored?

daring egret
#

youtube

glass sandal
#

What stuff in backend definately

daring egret
#

cook stuff

glass sandal
#

In backend

#

Like wut

#

AI?

daring egret
#

potatoes

glass sandal
#

XD lol

daring egret
#

oh

dapper tusk
#

most people do not do backend dev when bored

glass sandal
#

Oof

native tide
#

refactor if you want to kill time ๐Ÿ˜›

glass sandal
#

ummm...what is a refractor ๐Ÿ˜…

native tide
#

Make your code cleaner

glass sandal
#

Oh

#

So it prettifies code right?

native tide
#

Thatll be your job ๐Ÿ˜›

#

but the end result should indeed be prettier code base

glass sandal
#

Oh I see

native tide
#

less redundancy what not

glass sandal
#

That could be a good idea though , but ... idk .... like maybe I should just game dev

#

(Not with PyGame since it sucks imo)

daring egret
#

go watch a tutorial for epic games unreal engine since is kinda free if i remember and make some good old tetris if killing time is on your head or do some mario idk

glass sandal
#

Nah imma just use Love2d

#

It doesn't have shit ton of GUi which I hate as a vim user

#

And it's in Lua

#

Written in C , so it's fast

daring egret
#

i don't belive the language matters that much

glass sandal
#

It does

daring egret
#

if the code is clean so is the software

glass sandal
#

The performance

#

Is

#

Always based on language

#

C and C++ have the lead rn in term of speeds

#

speed*

#

So it'll be fast

#

And Lua itself is a light and fast aaand flexible language

daring egret
#

yeah but it's really negligible for human eye

glass sandal
#

Well , you can't get good performance from Python

#

Even with using Cython

#

It's still slow

#

Although being an awesome language

#

It's slow

daring egret
#

yeah but it's flexible

dapper tusk
#

honestly, gamedev is the only place where python cannot actually be fast

glass sandal
#

That's why I chose love2d

daring egret
#

the boy python stretches from gamedev to webdev

#

too bad it's not really looked for in the industry

glass sandal
#

I mean , Game Dev when I'm bored

daring egret
#

like java and the c boys

glass sandal
#

Web dev when I'm working

#

C is god , but Java... WHY JAVA?

daring egret
#

cuz everyone works with it

glass sandal
#

Does that mean you have to use it?

daring egret
#

you dont have to like it just do it

#

it brings home the breed

glass sandal
#

I mean , I respect your opinion . And it's fine . But java sucks like so bad . It's the only language I actually "HATE" to use

daring egret
#

i know

glass sandal
#

But still , I don't wanna be biased

daring egret
#

it's shite

glass sandal
#

Just use what you want

dapper tusk
#

why do people hate java so much? I never actually had much trouble with it

daring egret
#

the syntax

glass sandal
#

Cause it's good as a platform , sheet as a programming language

daring egret
#

thats where it all begins

#

at the syntax

#

go to w3 school

#

watch all syntaxes

#

the look at java

glass sandal
#

And almost eveyone that went to university , knows it

native tide
#

The only thing I rly didnt like in Java was that you have to propagate exceptions on each method signature if you throw one

glass sandal
#

Guys , just use Python

#

For your common things

#

AND Ai + Web dev

#

And C/C++ for life

quick cargo
#

๐Ÿค”

glass sandal
#

Is it a problem to use C/C++?

dapper tusk
#

you probably should not be using C for anything over 1 small file

glass sandal
#

C/C++ is the mother of all languages and operating systems

daring egret
#

c is used in some car sistems

glass sandal
#

So still god

#

I mean , not ALL languages

dapper tusk
#

C++ is not, C is also not

glass sandal
#

But ALL official ones

dapper tusk
#

C is pretty fundamental though

#

but you should not use it much, it is far too easy to do something incorrectly and far too hard to things correctly

glass sandal
#

C is very fun to use . You must make the functionallity

#

Until your code gets complicated

#

Then you have to quit

native tide
#

lol ๐Ÿ˜›

glass sandal
#

And just

dapper tusk
#

I do not enjoy writing in a language where just testing if it works correctly is not enough to actually assert that the code works

glass sandal
#

rm -f main.c

daring egret
#

what is a good alternative to webdev ?

dapper tusk
#

there is none

glass sandal
#

Yep

daring egret
#

what is similare but not web dev

#

?

glass sandal
#

App dev?

native tide
#

yeah any other kind of development ๐Ÿ˜›

glass sandal
#

XD

native tide
#

Mobile

daring egret
#

is python aplicable in app dev?

glass sandal
#

Yes

#

Kivy

daring egret
#

i thought only java and c-s could do the trick

dapper tusk
#

yes, but you probably want kotlin instead

glass sandal
#

REALLY? There is Dart + Flutter

#

Even Phonegap or Intel XDK can do the job

#

And Phonegap is basically HTML to APK if you didn't know

daring egret
#

really

#

i will document myself

#

on this

#

and try it

glass sandal
#

With limitations though

#

It's fun for some apps

#

But if you wanna go further , use React Native

daring egret
#

scam minecraft hack apps on playstore

glass sandal
#

lol

daring egret
#

^^

glass sandal
#

Ok we must go to off topic maybe?

#

If there is one

daring egret
#

is there a channel for app dev here

#

?

glass sandal
#

user-interface is near to that

#

Since it is about Kivy

daring egret
#

DISCRIMINATION

#

๐Ÿ˜„

glass sandal
#

XDDD

#

But really , love2d is a very good framework though

#

Like you mostly think of the game logic not code syntax

native tide
glass sandal
#

Maybe it's not defined?

#

Or maybe you have to use await?

native tide
#

it was defined

dapper tusk
#
if(promptInput == "Admin"){
    const AdminPassword = prompt("Password")
}
``` the adminpw only exists in the if
#

not outside of it

glass sandal
#

Yeah

dapper tusk
#

unlike in python, {} blocks get their own scope in JS

glass sandal
#

You must define it outside it

native tide
#

if i put it outside it triggers when i don't want it too

glass sandal
#

Make it equal to undefined

#

const AdminPassword = undefined;

dapper tusk
#

then it cannot be const

glass sandal
#

Ah god js is weird

#

Make it equal to a blank string

#

""

native tide
#

there is then no point of it

glass sandal
#

Just define it outside so it'll be global

#

And should it be const?

#

Just make it a var

dapper tusk
#

what you actually want is

if(promptInput === "Admin") {
    const adminPw = prompt("Password");
    if(adminPw === "TheMaster") {
        alert("welocome as admin");
    }
}
glass sandal
#

I mean , you can define it as a var outside the if

#

Then prompt it in the if

dapper tusk
#

better to not have variables

glass sandal
#

And check for it

#

You can delete them I doubt

#

?

#

Or make them like undefined

native tide
#

ok thanks

dapper tusk
#

yes, but this way you never have adminPw hold a value that is not an admin password

glass sandal
#

wdym?

#

Why shouldn't it hold a value that's not an admin pw?

dapper tusk
#

because the variable is called AdminPassword. How does it make sense for it to not hold the admin password?

glass sandal
#

I mean , he/she wants not to have vars

#

Oh

#

Maybe like there is a global way to do it?

#

Like defining a global const var inside brackets

#

Isn't it a way to do that in js?

#

He could make a trigger

#

Like isDefined

#

If it's true , define a const adminpw variable

#

And hold the prompt as a variable

#

That you free after setting it to admin pw

#

@native tide

#

You can define a trigger variable

#

So you can define the const globally

#

So like

var isSet = false;
#

If it's true , set the const adminPw

native tide
#

ok sure

#

thanks

glass sandal
#

And hold the prompt in a var

#

np

distant trout
#
def comment():
    if request.method == 'POST':
        comment_reply = request.form.get('replyField')
        comment = Comment(comment=comment_reply, question_id=current_user, user_id=current_user)
        db.session.add(comment)
        db.session.commit()
    return render_template('question_page.html', comment=comment)```
#

UnboundLocalError: local variable 'comment' referenced before assignment

#

I'd appreciate some help. Whenever I go to the comment route, it gives me the error above

#

Here is the form btw:

    <textarea id="reply-field" name="replyField" rows="3" cols="40"></textarea>
    <br>
    <a href="{{ url_for('comment') }}" class="btn btn-sm btn-outline-info mt-2">Reply</a>
</form>
dapper tusk
#

return render_template('question_page.html', comment=comment) when the method is GET, the comment is not defined

distant trout
#

oh, so is the GET method causing the error

#

I get


The method is not allowed for the requested URL.```
#

when i remove GET

dapper tusk
#

well, you need to decide what should happen with the comment when the method is GET

distant trout
#

I want to make it so after a user wrote a comment and press submit, it adds it to the database and displays the data on the current page.

#

I think i need a second route for each task

dapper tusk
#

then, when you see method GET, you need to get the comment from the db and display it in the template

distant trout
#

Got it! thank you! I'll do just that

wooden path
#

Would anyone be able to help me understand why .validate_on_submit() wouldn't be working?

#

I have a form for a flask app, but for some reason it's not giving me a response

distant trout
#

if form.validate_on_submit():

#

did u add the semicolon

wooden path
#

@app.route('/forms', methods=['GET', 'POST'])
def forms():
    form = InputDataForm()

    if form.validate_on_submit():
        return 'The form has been submitted'

    return render_template('forms.html', form=form)


#

this is what I have

distant trout
#

weird, i dont see anything wrong. I am still new to flask

#

maybe add <h1> tag around the "the form has been submitted" text?

wooden path
#

I don't think that'll change much, but I'll try

distant trout
#

yeah true, that was a kinda dumb of me

#

hopefully someone can help u with it, since im curious now whats wrong here

wooden path
#

oh it might be a good idea to post the html code as well

#

let me do that real quick

#

{% extends "base.html" %}

{% block content %}

<h2>File Input</h2>

<form action="{{ url_for('forms')}}" method="post" novalidate>
    <p>
        {{form.filepath_transcript.label}} <br>
        {{form.filepath_transcript(size=90)}}<br>
        {% for error in form.filepath_transcript.errors %}
        <span style="color: red;">[{{ error }}]</span>
        {% endfor %}
    </p>
    <p>
        {{form.filepath_summary.label}} <br>
        {{form.filepath_summary(size=90)}}<br>
        {% for error in form.filepath_summary.errors %}
        <span style="color: red;">[{{ error }}]</span>
        {% endfor %}
    </p>

    <input type="submit" value="Submit">

<!--    <p>-->
<!--        {{form.submit}}-->
<!--    </p>-->


</form>

{% endblock %}

distant trout
#

im not sure if this makes a difference but ur html method is lower case "post"

#

maybe try "POST"

wooden path
#

doesn't look like that made a difference

distant trout
#

oh damn ๐Ÿ˜ฅ

wooden path
#

hmm I honestly have no idea where to start

#

since I'm not getting any errors

distant trout
#

thats weird, u should be getting an error

#

if something was wrong

#

do u have debug=True

#

on app.run

wooden path
#

yeah

#

all i'm getting are gets and posts

distant trout
#

maybe try displaying the data

#

oh wait nvm ur using WTForms

#

i kinda drained out ur post, so if anyone reads this, scroll up to help him out

native tide
#

@wooden path add to your form in your template file

{{ form.csrf_token }}
wooden path
#

Oh I'll try that out, I was unsure if it was a necessary step

#

WOW IT WORKED

#

THANKS

#

I had pretty much given up (temporarily) and was about to switch to kivy

native tide
#

Don't give up ๐Ÿ˜›

wooden path
#

Thank you once again

native tide
#

np

distant trout
#

@native tide oh wow. isnt that the same as setting secret_key config?

native tide
#

@distant trout Nope, the secret key is used however to securely sign csrf tokens

distant trout
#

ahh i see

#

i was confused cuz usually my forms work without the "{{ form.csrf_token }}"

native tide
#

you can send them around but flask_wtf's form.validate_on_submit will not return true without it

distant trout
#

oh

#

yeah that makes sense

uncut finch
#

Hi is anyone know, how to transfer my django project to another computer?

acoustic oyster
#

@uncut finch I store my Django projects as private Repos on Github. Make sure you are using a virtual environment and store the requirements in a requirements.txt file along with your project.

on the command line/terminal:

pip freeze => requirements.txt

You could also simply use some sort of cloud service (i.e) google drive, or just email the project folder. You would likely need to zip the folder to avoid any issues, and just to be practical.

Transferring is as simple as:

  1. create a virtual environment, save the required modules using pip freeze into a .txt document in the project folders.

  2. Transfer the project folders to another computer using whatever means you prefer

  3. Create a virtual environment on the new machine, activate the environment, and run pip install -r requirements.txt

uncut finch
#

Thank u, I'll try ๐Ÿ™‚

acoustic oyster
#

No problem, let me know if you need more help or if I was not clear enough about something.

#

And now my question:

Hello all, I am using React and Django rest framework. I need to get all
class Character(models.Model)
that belongs to the currently authenticated User (django authentication) into my react app so that I can list all the Characters, then also allow the user to edit the characters in React. What would be the best way to accomplish this?

acoustic oyster
#

probably, what is the issue exactly?

#

@native tide

#

I mean, can you provide more detail?

sly vessel
#

I'm trying to use list comprehension to generate labels in Dash Plotly, but I keep getting this error:

The children property of a component is a list of lists, instead of just a list. Check the component that has the following contents, and remove one of the levels of nesting: 

Code:

@app.callback(Output('weather_page_layout', 'children'),
             [Input('daily_update_interval', 'n_intervals')])
def updateWeatherPage(input_data):
  with open('weather/fc.json', 'r') as f:
    fc_data = json.load(f)  
    weather_page = html.Div(
      children=[
        html.H1('Weather Forcast'),
          dbc.Col(
            children=[
              [dbc.Label(f"{k} - {v}") for k,v in i.items()] for i in fc_data
      )    
    ]
  )
#

Anyone know what I'm doing wrong here?

#

I've tried encasing that entire comprehension in brackets as well, but same issue

acoustic oyster
#

That error is telling you that it cannot accept a 2D List, you are creating a List (children) of lists.

perhaps it is supposed to be

children = [dbc.Label(f"{k} - {v}") for k,v in fc_data.items()]
#

it may be easier to try this outside of comprehension first, since this is a semi-complicated loop

sly vessel
#

I've tried that way as well. Also, I've ran through the loop with a traditional nested for loop and it runs fine

acoustic oyster
#

the issue right now is that children == [[f"{k} - {v}", f"{k} - {v}", f"{k} - {v}"], [f"{k} - {v}", f"{k} - {v}", f"{k} - {v}"], [f"{k} - {v}", f"{k} - {v}", f"{k} - {v}"]]

sly vessel
#

The problem is fc_data is a list of dictionaries too

acoustic oyster
#

something like this^
when it is expecting a 1 dimensional list, yeah, I see that. I see what you are trying to do, but the way you are doing is creating arrays inside of arrays, when you need to append to a single array

#

It might make more sense to do it traditionally for readability. Since it makes sense to append here. If you give me a sec, I can create a list comp maybe

sly vessel
#

I tried doing it traditionally as well, but because the syntax and formatting of the dash components, i keep getting a syntax error

acoustic oyster
#

what does fc_data look like?

sly vessel
#

Abbreviated version:

[{'Temp': '20', 'Humidity': '30'}, {'Temp': '20', 'Humidity': '30'}]
acoustic oyster
#

kk, lemme see

#
def clean_data(data):
    out = []
    for item in data:
        for each in item:
            out.append(f"{each} - {item[each]}")
    return out
sly vessel
#

So someone else in a different channel said to use this:

[dbc.Label(f"{k} - {v}") for i in fc_data for k,v in i.items()]

and it seems to have worked

acoustic oyster
#

I mean, this is the non comprehension way

#

oh nice haha

#

yeah, very nice

sly vessel
#

Which is basically just reversing what I had already

acoustic oyster
#

dang it, they beat me to it

sly vessel
#

I'm still not sure why that works and my original way didn't

#

For example, I thought this:

[[print(f"{k} - {v}") for k,v in i.items()] for i in fc_data]

was equivalent to this:

for i in fc_data:
  for k,v in i.items():
    print(f"{k} - {v}")
acoustic oyster
#

yours creates two lists, since you have two sets of [[]].

yours creates a new list for ever single "i"

theirs creates ONE list with two "layers" of comprehension
rather than creating a list [f"{k} -{v}"] for every "i" theirs creates just f"{k} -{v}" for every "i" by creating "i" then looping through the items.

While yours does this, if you print the output, you should see that every f"{k} - {v}" will be wrapping in extra []

#

Yours is actually equivalent to

for i in fc_data:
  for k,v in i.items():
    print([f"{k} - {v}"])
sly vessel
#

Ah, I see. So for comprehensions the inner loop needs to follow the outer loop as you type it?

acoustic oyster
#

this is the same as the different of
string = "I am a string"
vs
string = ["I am a string"]

#

it depends on what you are trying to do

sly vessel
#

Yeah, that makes sense. The part I'm curious about is why it's

[dbc.Label(f"{k} - {v}") for i in fc_data for k,v in i.items()]

instead of

[dbc.Label(f"{k} - {v}") for k,v in i.items() for i in fc_data]
#

Intuitively you would think as you read it the inner loop would come first, but I guess not

#

Well anyway, thanks the help.

quick belfry
#

Guys,
I have a SQLite database with me. Now i have to create a search function using django.

Can anyone help me how to do it , how load the database via python at the back end & search function using django

nova escarp
#

I'm trying to use aggregate sum with Django. It shows the sum fine but if I add a new instance of the class it doesn't get updated until I close and reopen the dev server. Anyone know why or how to solve this? I can post the code if its needed.

acoustic oyster
#

@quick belfry if you just mean to get specific objects by a filter, the built in method to Django would be

MyModel.objects.filter()

and specify the filters to use.

#

i.e

class MyModel(models.Model):
  modle_name = models.CharField()
quick belfry
#

So @acoustic oyster i need not define feilds of my database anywhere?

acoustic oyster
#

In general, Django can handle most basic DB tasks without writing any actual SQL queries.

The db fields are defined within the models

To filter things you could do:

MyModel.objects.filter(model_name=this_name)
#

^this would return all MyModels objects that have the model_name == (whatever "this_name" is)

#

and generally you would use a queryset so that you can use specific parameters to a url to search the db

#

and then render that in a view

regal cave
#

How do you update context when pulling data from a json in django?

wind walrus
#

I'm creating a blog with Flask (similar to Corey schafer's tutorial)

#

I create new posts on the webpage itself and store them in a SQLAlchemy database

#

I can write posts in Markdown and I have it convert to HTML so Jinja2 can render it

#

How can I embed images to my posts? I know I can upload files with wtforms FileField but that wont let me choose where to embed the picture in the article.

I could also do <img src="absolute path from local drive"> but is that the way to go?

#

Do I have to manually add the image to my static/images folder first then do img src="url_for(static, filename=img)"?

#

But that means other users cant post images

oblique delta
#

this is sorta web dev related: does anyone know, with BeautifulSoup, how to easily get the last child of an element?

fallen eagle
#

I'm working on a django app as part of my online course project. It's like a social media, where users can follow, post etc... In the past I worked with SQL directly, now trying to use ORM.
What would be the best model to use following/followers? is there a video or some resource I can use to understand it better?
I'm not sure if it should be foreignkey or 1tomany relationship, and what should on_delete be? I mean you don't want to delete followers when you delete a user. but not sure how it is handled

fallen eagle
proper current
#

hello, is this the right channel to ask about deployment on web hosters like Heroku? im having troubles with one part of my app there

tranquil sorrel
#

any body know how to scrape <script> tags with product info on e-commerce websites

fallen eagle
#

@proper current what sort of trouble?

proper current
#

it seems to be related to discord voice (pynacl) - or maybe not? it threw me a permission denied error for a .exe file that my code was dependant on

#
2020-07-24T06:28:30.329937+00:00 app[worker.1]: PermissionError: [Errno 13] Permission denied: 'res/ffmpeg.exe'```
fallen eagle
#

is it working in your local lab? I assume it does

proper current
#

yea

#

i jsut read i need to add an additional buildpack, was just confused about the error type talking about permissions

fallen eagle
#

@proper current sorry, I'm not that well versed in this, but I found this: https://stackoverflow.com/questions/45161333/python-heroku-allow-pushed-exe-to-run-oserror-errno-13-permission-denied
see if it helps if you haven't already, otherwise hope someone else who knows better than me maybe able to help

proper current
#

hmm, it seems to be because free VPS like heroku block outbound UDP traffic when youre a free user, didnt find more about that though...

fallen eagle
#

have you tried pythonanywhere.com I found them to be much more user friendly and simple to setup compared to other providers, but they have some outbound limitation too

fallen eagle
#

I'm working on a django app as part of my online course project. It's like a social media, where users can follow, post etc... In the past I worked with SQL directly, now trying to use ORM.
What would be the best model to use following/followers? is there a video or some resource I can use to understand it better?
I'm not sure if it should be foreignkey or 1tomany relationship, and what should on_delete be? I mean you don't want to delete followers when you delete a user. but not sure how it is handled
@fallen eagle
think I found something: https://stackoverflow.com/questions/58794639/how-to-make-follower-following-system-with-django-model

green snow
#

sir i have some doubts ,i had watched your python web automation video,i tried to automate google meet,everything is working well except when i join the meet with the join id,i switch to the child node correctly and interacted with evry element,algood,except the alert box on the chld window can not be closed,it says no such alert,the alert requests for cam mic permission whcih in want to dismiss,Stuck for two days? used wait methods too still no luck?any suggestion?

native tide
#

Is it good practice to have the same sender/recipient in a contact form system created with AWS SES?

hidden jetty
#

hey guys i am doing a project on IRC chatroom should i use django or anything suggest that please

junior kayak
#

django definately

hidden jetty
#

ok

regal cave
#

Hey does anyone know how to get django to return the new data thats changed in the same file thats being used in the view? collectstatic --clear only works because I then have to git add . git commit etc and push it back

summer monolith
#

There is a type of sheet which has columns such as username, data, activity, comment, hours & approval status. It is sorted in descending order on date. I want to get the 1st date available in the records

#

I am unable to perform the inspect element

quick cargo
#

what

young forum
#

Anyone got a good place to learn about APIs and API keys?

native tide
#

does anyone know why i cant seem to be able to reference my css file?

#

the directories look like this

native tide
#

ohh

#

style sheets r like images

#

tx!

grim wharf
#

hello, I've been struggling with a problem for a while now, I've started using django for school a few months back and loved it so much I continued to use it for myself, and now I'm trying to do something that I can't figure out

I was asked to make a blog to show it to the class, so I did, and I'm still working on it now, adding cool stuff over time, and now I'm trying to make a /post/last url that would always lead to the last post (so basically the highest ID in the database), so that way instead of having to remember the last ID number when sending to people I just need to send /post/last and it automatically redirects to the last post (I know it's fancy and useless but it's also because I want to put an URL to said last post at some places on the website), I've tried for 2 days and basically did everything I found on internet, but every time I end up having an issue.. I can find the last id in the db, but it's value is {'id__max': 17}, and I just need the 17, how can I do that ?

glass sandal
#

Oh

#

Just do model.objects.all()[::-1][0]

#

[::-1] reverses it

grim wharf
#

oh lemme try

glass sandal
#

And [0] gets the first item

native tide
#

i think [-1] works too

glass sandal
#

Does it? then better

flint breach
#

model.objects.last()

glass sandal
#

Oh god wow there are 3 ways to do a single thing lol

grim wharf
#

well now I get another issue I also got multiple times, but I think I can fix that one

flint breach
#

[::-1] == [-1] afaik

grim wharf
#

the one Rader gave is the only one I never tried tho xD

glass sandal
#

@flint breach Maybe not? cause [::-1][0] == [-1]

late fjord
#

Hi

flint breach
#

oh im an idiot, my bad

native tide
#

wait

late fjord
#

Do you guys have any experience on freelancing with django

flint breach
#

you reversed it, then picked the first one

glass sandal
#

XD nah np @flint breach

native tide
#

isnt [::-1] reversing

flint breach
#

that's least efficient

#

yea, don't do that

glass sandal
#

@native tide Yes it is

native tide
#

and [-1] just taking the last element

glass sandal
#

Mhm didn't know that

#

But they're all the same anyways

#

[-1] being the efficent

#

@late fjord You need a freelancer?

grim wharf
#

wait so

native tide
#

Does anyone know of an open sourced blog site using Django that is the most full featured Django project you know about on GitHub for anyone to study? I know that there are a million guides on how to buiild a basic Django blog. I dont really need that. I'm wanting to see the most advanced project thjere is

grim wharf
#

model.objects.all()[::-1][0] this or what ?

late fjord
#

no

glass sandal
#

model.objects.last() or model.objects.all()[-1]

#

are the better choices

grim wharf
#

ah ok

late fjord
#

I just want to know how you can find freelancers

glass sandal
#

Oh

#

Fiverr?

#

Upwork?

grim wharf
#

ah well I never had this error before.... "Negative indexing is not supported" lol

glass sandal
#

Oh XD

#

Well

#

I guess it means you can't use [::-1]

#

model.objects.last() must work th

#

tho*

grim wharf
#

yes it does, now this problem is fixed but not what's after

#

for some reason last() wasn't working when I tried using it yesterday, but I must have used it wrong

glass sandal
#

Hmmmm

flint breach
#

you're just looking for the object with the highest field-value?

grim wharf
#

yeah

flint breach
#

you don't need to use last, or first, just a lookup query

glass sandal
#

Oh I see

flint breach
#

Model.models.all().order_by('-field').first()

#

or more succintly, Model.objects.latest('<your-field>')

glass sandal
#

Oh yes

grim wharf
#

also works

glass sandal
#

I thought he/she needed the last object

flint breach
#

i mean technically, it is a first/last object, if you have a sorting on your models

grim wharf
#

well I need the highest id (or primary key)

#

so yeah

#

the last

glass sandal
#

@flint breach But it is not supposed to be the primary key

flint breach
#

so you want litteraly, the last object that was created

glass sandal
#

Oh so last anyways

#

Just do model.objects.all().order_by('-id').first()

#

As @flint breach said

flint breach
#

Model.object.latest() should be alright

glass sandal
#

Yeah

grim wharf
#

yeah that works

glass sandal
#

Nice

flint breach
#

these are actually preety common problems, google should have returned some decent answers

glass sandal
#

Yeah

#

Or even the docs

flint breach
#

get latest created object in django or whatever

glass sandal
#

Yeah

flint breach
#

Learn GoogleFu, it will help you in the longrun

grim wharf
#

what I seached

#

and tried a lot of solutions

glass sandal
#

What did you exactly search?

flint breach
#

django get latest object, first result was alright ;P

glass sandal
#

Like how to get the last object?

flint breach
#

it's fine, wasn't a problem

#

but these problems that seem like it has a common use case, im sure google returns an answer fast

#

just be specific (not too specific :P), and you'll get something outa of it

grim wharf
#

what solution do you get ? because the one I find doesn't work... is it maybe because I'm not located in the same country ?

flint breach
glass sandal
#

Yeah ... most of my problems and other programmers problems are solved by google , nothing else

grim wharf
#

mines too usually

#

this one was a first

flint breach
#

it's fine, im glad you solved your problem

grim wharf
#

yeah thanks anyway ๐Ÿ™‚

glass sandal
#

Yeah and gl on your journey

grim wharf
#

also I don't get this article first by searching this... but I know why

#

or well I guess I know why xD

glass sandal
#

lol

#

Well , maybe your previous searches

grim wharf
#

I think it's the search language

#

now that I switched to english I find it

glass sandal
#

I guess none of the web devs changed during Quarantine

#

(Unless improvement)

flint breach
#

huh?

glass sandal
#

huh?

flint breach
#

I guess none of the web devs changed during Quarantine

glass sandal
#

Ummm... did they?

flint breach
#

nevermind - unsure what you mean

glass sandal
#

nvm anyways

safe glen
#

hello guys , im using flask as backend for my web app and i want to implement a notification feature where a user gets notified real time when an action is taking place like that of facebook . but id like to hear some ideas from you guys on how to make this feature..

rancid fable
#

Sometimes I wonder if I'm made for this stuff

glass sandal
#

Ah god you have to deal with Frontend for the notifications?

flint breach
#

Sounds like a job for either polling or websockets

safe glen
#

@glass sandal yeah i also need ideas on how to implement it at the backend too

glass sandal
#

Well then , ngl , idk how to do it lol

safe glen
#

@flint breach yeah im currently researching on them rn

flint breach
#

Polling js probably simpler to implement, but gonna be less efficient

#

Depends on what scale you planing to build

nova escarp
#

Hi guys, Im trying to implement something in my Django site and not really sure where to start.
I want to take all of the instances of my model and group them based off of date and list that on a page (i.e. wed july 22 lunch, thursday july 23 dinner, etc). And have those dates be hyperlinks that take you to a view (possible detail view?) that has all of the instances of the models from that specific day. I really donโ€™t know where to even start, Im guessing the date links will be a list view but iโ€™m not sure where to get these dates from (I want them to appear only after an instance is created for that date). If anyone can point me in the right direction I would really appreciate it

native tide
#

maybe make a class called event and give it a field of date and maybe event detail like lunch dinner

#

so u would only have one table