#web-development

2 messages · Page 27 of 1

vagrant adder
#

Then its a bug in your piece of code

late gale
#

nope it wasn't

#

I was following a tutorial

vagrant adder
#

Gotta go

#

Ask some of the helpers or post in some #help channel

late gale
#

Thanks for trying to help me

hard rock
#

heyyo
I'm planning a projecg which will include an app and website
I've made apps before using Unity and worked with frontend using JQuery, but neither tool is the best solution for an enterprise website

I was looking into using React for website and React Native for crossplatform mobile. Do you guys have any suggestions about where to find tutorials to guide me on this path or other libraries I should consider?

#

thanks

rigid laurel
#

React and angular are the two main front end libraries. Vue is another that is gaining popularity as its ember (I think).

Tonnes of tutorials on YouTube/Google that are OK, but I have yet to find anything for react or angular that is great. Although both have pretty good intros in their own docs

hard rock
#

Thanks Charlie

vagrant adder
#

Vue is also good for a frontend but knida new and idk if it goes along with django(literally everything goes with flask)

native tide
#

I am currently working on a youtube application geared towards helping users gain more viewers. The way it works is by correctly selecting keywords that match well with the user’s channel data such as engagement rate, watched hours and clickrate/ clickthrough. For example, a user with 1000 subs will not benefit from using the keyword fortnite, while a larger channel might. Through the use of AI, I would like to create an app that looks over the user’s channel data and then organize the generated keywords from best to worst.

I have the foundations of the project but I have spent 60+ hours on it and I still have lots more to do. If anyone would like to join my team and work on the idea together, please DM me.

hard rock
#

are you using machine learning?

#

you might wanna check out recommender systems

native tide
#

Are you experience with ML?

keen sphinx
#

so, not about Python but JS... do you guys use some library to perform AJAX stuff, or do you write vanilla JS?

#

I'm quite new at this so everything I've done in JS for a web is to write a function that uses fetch() to POST

spring dragon
#

I don't think I used ajax for a while

#

axios libary works well enough

#

and fetch is fine

keen sphinx
#

thanks, I'll look it up

midnight kernel
#

@keen sphinx i used to use jQuery for AJAX, then I just decided to abandon jquery and use the fetch api

keen sphinx
#

yeah, I've heard jQuery can be avoided for most things nowadays, something like that

autumn bobcat
#

fetch is great

flint breach
#

fetch > ajax?

vagrant adder
#

Yes

hoary spruce
#

Hey so I'm currently trying out this example for login/registration etc: https://github.com/PrettyPrinted/flask_auth_scotch
So I installed Flask-login and Flask-SQLAlchemy.
Then I've installed a virtual enviroment in my folder and did this:

cd (to the directory)
venv\Scripts\activate
set FLASK_APP=main.py

When I do flask run it start and then gives me this error:

Error: Failed to find Flask application or factory in module "project.main". Use "FLASK_APP=project.main:name to specify one.

Anything I did wrong? Because I have every module installed

covert agate
#

@hoary spruce

#

You online?

#

Do pip show flask to see if the interpreter is looking in the same place as where you installed it

#

If not then go to PyCharm > preferences > project interpreter, click the little + to add package and look for Flask.

hoary spruce
#

I’ll try when I’m home from work. But I’m using VSC tho

late gale
#

How can i add messenger chat to my django website

frigid egret
#

Hi all

#

I have a jQuery script on my website and it keeps loading before jQuery library despite it being on the next line. As the result, all files load properly but my script doesn't work because it loads before it has access to jQuery lib.

#

How do I make a script load AFTER jQuery library loads?

#
<body>
    <div class="container">
                {% block content %}{% endblock %}
        </div>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.slim.min.js"...
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"...
    <script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"...
    {% block body_extra %}{% endblock body_extra %}
</body>
#

And then in body_extra I specify a js file that has to be executed on that specific page. Did that to avoid having all my scripts being in one big file.

pale fiber
#
$( document ).ready(function() {
   
});

You script contains in this function?

frigid egret
#

Yes, I'm doing exactly that

#
my script
});```
#

It's recommended in latest docs to do it this way

pale fiber
#
$( document ).ready

I don't see this condition in you insert

frigid egret
#

Yes, because $(function ()) is the same thing

#

From official docs

// Shorthand for $( document ).ready()
$(function() {
    console.log( "ready!" );
});
pale fiber
#

Yes, I already saw, then it's strange, try load jQuery in <head>.

frigid egret
#

tried that too

#

Same thing. I think it's happening because it takes my script to load way faster than jQuery lib.

pale fiber
#

This should not be, I also have small jQuery-based scripts and they never worked like this if the order of their loading is correct.

frigid egret
#

Yea, it was working fine till some point

#

And I can't even tell when that started happening because even if I roll back, I still have that situation

pale fiber
#

This may be due to slim jQuery?

frigid egret
#

idk really

pale fiber
#

Maybe a bad question but you tried ctr+F5 reload?

frigid egret
#

always do that

pale fiber
#

Try not slim version jQuery

frigid egret
#

Which one's that?

pale fiber
frigid egret
#

Ok, I tried a different way first

#

Local version instead of CDN

#

And now it worked

#

It's still not ok that it doesn't work like it should =/

hoary spruce
#
Location: c:\users\...\documents\python\project\venv\lib\site-packages
Requires: Werkzeug, click, Jinja2, itsdangerous
Required-by: Flask-SQLAlchemy, Flask-Login

You mean this @covert agate

covert agate
#

Oh yikes

#

I've never used VSC before

hoary spruce
#

But the weird thing is, in my main project

#

If I launch that

#

It works, website runs etc

hoary spruce
#

I'm stupid (: @covert agate Was just running the wrong file

covert agate
#

bahaha

#

well glad it's sorted

distant dust
#

I got a quick question. Im writing an flak api that interfaces with another websevice. Is it better to use Flask-RestFul or just use flask and define my endpoints and methods as long as my endpoints dont have more than one method.

vagrant adder
#

It depends how your external webservice communicates and how your flask api model looks like

#

And what your api actually does

late gale
#

Does someone know how to add the messenger chat plugin into my website

vagrant adder
#

What plugin and what website

late gale
#

I added the code they gave me but it doesn't appear

#

Facebook Messenger

#

and my django website actually

vagrant adder
#

Well you should use some kind of authentication

#

Big websites usually have some kind of authentication (oauth,key...)

#

Take a look at docs

#

If docs dont do it, google it

#

Never worked extensively with django since its pretty cluttered for my taste

late gale
#

cluttered for your taste ??

#

Omg Django is so fun to use

#

It helped me finish my website in 5 days

vagrant adder
#

Yeah

#

Too much things tbh

#

Flask is like legos

#

You can include whatever extension you want

late gale
#

I don't like flask tbh

vagrant adder
#

Best thing ever

late gale
#

but really you have to try django

#

It's stunning

vagrant adder
#

Yeah i tried it

#

Some things it does better than flask but flask fits me more

#

Django is pretty cluttered and not very customizable

late gale
#

I actually don't see flask these days

vagrant adder
#

From my perspective

late gale
#

Most companies use django like Instagram

#

Sure , everyone have a different view

vagrant adder
#

Flask is like do it yourself way, and django more strict about doing some things

late gale
#

The best thing about django is it's rapid development

vagrant adder
#

Hmm

#

Never felt that

late gale
#

It always comes in handy

vagrant adder
#

Couldnt feel as free as i felt using flask

late gale
#

Django don't want you to do anything except say what you want

#

and It handles the rest

#

I never tried flask tbh

vagrant adder
#

Yeah i dont like that
I usually do stuff the way it i like and need

#

Yo you need to try flask

#

Flask is rapid

#

Super mega ultra fast

#

Both in performance and dev speed

late gale
#

I want to try another framework besides Django

#

I see people love Laravel

vagrant adder
#

Php is messy and scrapy nowdays

late gale
#

but why do I see laravel at the best framework in 2019

vagrant adder
#

Sql injection, type juggling exploits etc

#

Express for node is biggest i feel

late gale
#

What about Angular

vagrant adder
#

Thats for serving html

late gale
#

I always love Javascript for web

#

Ik but It'll be weak

#

unless your website wont use database

vagrant adder
#

What do you mean by weak

late gale
#

I always prefer backend frameworks than frontend

#

What i mean is how should a front end framework handle a database

vagrant adder
#

Firstly, mongo is like fastest db rn besides postgres

#

JSON based db

late gale
#

Json is lit

vagrant adder
#

And that goes well with js

#

Second, frontend frameworks and backend have different purpose

#

Comparing apples to pears

late gale
#

Frontend focuses on the client side backend focuses on server side and the databases

vagrant adder
#

Backend is for logic and frontend serves html and css

late gale
#

I like your comparison

vagrant adder
#

Google it

#

Google makes wonders really

late gale
#

What i always see on google is people's point of view

#

Some prefer frontend and others prefer backend so it all depends on you not google

#

I see microsoft is updating it

vagrant adder
#

Its for backend

late gale
#

Ik

#

but Is it good?

vagrant adder
#

Lemme get home

late gale
#

Sure

#

I am sorry for bothering

vagrant adder
#

Ye c# is great

#

My 2nd choice(after py ofc)

late gale
#

Yea I know C# actually

#

It's amazing

radiant granite
vagrant adder
#

nope

#

seems interesting tho

#

@late gale here i am

#

let's get back to frontend vs backend discusion

late gale
#

xD

vagrant adder
#

saying backend is better is straight dumb

#

or frontend is better

late gale
#

why

vagrant adder
#

that's like saying i like blah blah blah keyboard

#

and you go like i like this monitor better

#

how is keyboard connected to mouse

#

both have different purpose and do something completely different

late gale
#

Then how should we build a full website with only one framework

#

Front end cant handle the backend stuffs and vice versa

vagrant adder
#

both backend have requests they can respond to

#

frontend responds with html/css/js, and backend responds with some kind of data(usually json)

#

that data can be other format too

#

let's say html

#

backend can send data in html format

#

in flask it's render template, in django it's render() or render_to_response()

late gale
#

django is render()

vagrant adder
#

yes

#

but in real time and big big web apps this is a waste of resources

#

in the time backend server serves html, it can do couple more queries or respond with couple smaller responses(json,xml,yml)

#

waste of resources

late gale
#

what about frontend

#

It's only about html css and js

#

nothing else

#

and it's more easy than backend stuffs

#

but that doesn't mean that backend is better

vagrant adder
#

yes, frontend is there to help web app speed up
it only responds with html and css

#

is usually prefer doing backend since it's more fun and challenging

late gale
#

I actually learned fullstack web but all i have used is backend framework xD

vagrant adder
#

one can learn html and css within 2 months

#

and frontend job field is pretty crowded

late gale
#

true

#

tbh Backend can handle frontend

#

so I still recommend backends xD

#

I made my first website using Django

#

and it was full website

#

with databases and all the stuffs

#

Just Django i used

#

and Sqllite database

#

Anyone can be a frontend developer but not anyone can be a backend developer

#

html , css and js are beyond easy

#

backend languages are a bit difficult

#

C# is not easy as html that all of its codes can be written in one paper without understanding the codes and it will work as a magic

#

but with C# you have to focus carefully because that language is so sensitive

#

no semi colon == error

#

plus C# difficulty is more than html css and js

#

Even If we combine those 3 languages , C# or any backend language will be much difficult

#

Except one language tbh which is python

#

cause it's easy as javascript to me

#

Are u there? @vagrant adder

vagrant adder
#

Just a sec

#

yeah, frontend is really easy to pick up

#

and i find backend more fun and challenging

late gale
#

I agree with you

simple escarp
#

/me doing react + redux + sagas at work in a non trivial project, and doesn't find it easy at all, takes backend tasks over front ones any day

#

Though it might help to learn modern js synthax more systematicaly, losing a lot of time on stupid questions 😬

merry shell
#

I’m gonna have a go at creating a dynamic web page, what framework would be best for a beginner?

vagrant adder
#

i would say take a look at react and maybe vue

#

idk how vue handles dynamic data

ruby palm
#

Hello

#

How can I host my django-made website?

#

Please help

#

Thanks beforehand

vagrant adder
#

heroku,digital ocean, google cloud, linode ...

#

i would recommend heroku for django and flask

ruby palm
#

Its name sounds weird lol like an anime character xD

#

Thank you, kind sir!

#

What does it mean? "1 web/1 worker"

vagrant adder
#

Dont worry about that

#

It means you only get 1 container @ruby palm

steel tiger
#

I would say to use a vps

#

Not heroku

#

They get you in dyno hours eventually

#

Cya

shrewd sand
#

Heroku is good if you have containerised everything

vagrant adder
#

I used it for small and personsal projects

#

Never had any issues with heroku services itself

timid timber
#

Anyone have experience with creating a cloud based service?

vagrant adder
#

You mean serverless?

distant dust
#

@vagrant adder - User hits flask/api/v1/start > posts a url, that checks to see if the URL is in an approved list, if so, the API forwards the requests to a docker image on http://localhost:5000, gets the results back, and then presents it to the user

vagrant adder
#

I think you are better of defining your own endpoint

distant dust
#

Yeah, I thought so, cause I dont need more than one method on each endpoint.

pale fiber
#

Mentors, can someone help me with a problem Django-filter and JSONfield?
I put link when not spam this chat - https://stackoverflow.com/questions/56956120/how-to-use-modelmultiplechoicefilter-in-django-filters-with-jsonfield

late gale
#

Can't I host my website on heroku

No default language could be detected for this app.
#

I have made a file for the language and pushed it to the repository

#

and still

flint breach
#

is django preety much a laravel equivilent for py

vagrant adder
#

@late gale you need to tell which buildpack you want to use

late gale
#

its a django

#

so python i guess

vagrant adder
#

yes

#

heroku buildpacks:set heroku/python

#

that is for python apps

late gale
#

i dont have the heroku app yet

#

I only connected to github

#

@vagrant adder

#

sorry for my ping

#

but shall i download it

vagrant adder
#

np

#

i would recommend downloading heroku cli

late gale
#

ok

#

Thank you

simple escarp
#

so, i don't know django at all, and i tried to investigate performances with an aquaintance on his project, (which is mostly an api app with a react front end), considering he might get a lot more trafic soonish, so we tried to profile a specific api request, and turns out he builds a query set to pass to a seriaziler, which is apparently passed down to all the fields, and the query set is executed as many times as there are items to return, which seems nonsensical, as you want want to execute it once, then call the serializer on each item, to return the complete result, not once per item. It might be related to the fact that he has MethodFields to get related data from other tables, and to conditionally add data. We didn't find a solution yet, the documentation on how to build an efficient api in that situation is sparse, any good resource to direct him to and avoid a potential meltdown in a few weeks? 😆

#

(considering he uses seriaziler a lot, finding a good pattern to solve this problem would probably be useful accross the board in the application)

pure token
#

Dang. Always enable debug logging in dev to see the queries

#

Common mistake is to include related fields in a serializer and not prefetch or select them in the queryset

#

That stuff is easy to pick up in view tests

#

So write good tests for your views

cyan portal
#

Can anyone help m,e with some very basic django ?

late gale
#

@cyan portal What's your problem

keen thorn
#

does anyone here use npm for frontend and flask for backend?

late gale
#

npm?? that a javascript code for a terminal

#

Which type of javascript do you use in frontend?

#

@keen thorn

keen thorn
#

I was just curious why someone would use both npm and flask..

late gale
#

Cause javascript frameworks are frontend and flask is backend so they just integrate to make a powerful one

tacit roost
#

Flask felt too unstructured to me when I tried it

#

Tbh right now Python's in this weird state where the ecosystem is huge but 70% of it isn't asyncio friendly

ruby palm
#

@vagrant adder what do you mean with a container?

#

btw thank you for replying

ruby palm
#

What does Heroku mean when it says that I got only ONE container in my free hosting plan?

rigid laurel
#

Does anyone have any suggestion on books for python web development? Ive built simple stuff with both Django and Flask in the past, but I'm pretty sure I'm not writing fantastic code

kind steppe
#

I've heard Two Scoops of Django is pretty good

#

We've got a couple of books in there, one for flask & one for django

solar laurel
#

Can anyone here help with flask? I’m getting an error related to app context

kind steppe
#

Sure, post your error

#

We'll take a look

solar laurel
#

I'm adding background tasks with APScheduler on runtime depending on an API call. In other words, there are no background tasks when the app, starts. When user makes call on an API, tasks are added on runtime. But I'm getting an error that says:

AssertionError: Popped wrong app context

The application works just fine if I comment out the lines where background tasks are scheduled.

kind steppe
#

Can you post the full traceback?

solar laurel
#

sure. hang on

#
Debugging middleware caught exception in streamed response at a point where response headers were already sent.
Traceback (most recent call last):
  File "/Users/rootkit/Documents/work/projects/flask_email_scheduler/schedulerenv/lib/python3.7/site-packages/flask/app.py", line 2463, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/rootkit/Documents/work/projects/flask_email_scheduler/schedulerenv/lib/python3.7/site-packages/flask/app.py", line 2457, in wsgi_app
    ctx.auto_pop(error)
  File "/Users/rootkit/Documents/work/projects/flask_email_scheduler/schedulerenv/lib/python3.7/site-packages/flask/ctx.py", line 452, in auto_pop
    self.pop(exc)
  File "/Users/rootkit/Documents/work/projects/flask_email_scheduler/schedulerenv/lib/python3.7/site-packages/flask/ctx.py", line 438, in pop
    app_ctx.pop(exc)
  File "/Users/rootkit/Documents/work/projects/flask_email_scheduler/schedulerenv/lib/python3.7/site-packages/flask/ctx.py", line 241, in pop
    assert rv is self, "Popped wrong app context.  (%r instead of %r)" % (rv, self)
AssertionError: Popped wrong app context.  (<flask.ctx.AppContext object at 0x10940b780> instead of <flask.ctx.AppContext object at 0x1093a29b0>)

kind steppe
#

Wow, that's a very cryptic error

solar laurel
#

😄

kind steppe
#

How are you running the application?

#

Looking online it seems like this could be caused by the method the application is being run

solar laurel
#

just to give you a little context, I'm adding tasks on runtime within an API call. I'm not adding them before hand

kind steppe
#

Right

solar laurel
#

I have a manage.py file in which I'm using Manager to run the app. I run python manage.py run to run the app

#

code is like below:

#
app = create_app('dev')  # os.getenv('PAYROLL_PROD') or 'dev')

app.app_context().push()
manager = Manager(app)
migrate = Migrate(app, db, render_as_batch=True)
manager.add_command('db', MigrateCommand)

# import logging
#
# logging.basicConfig()
# logging.getLogger('apscheduler').setLevel(logging.DEBUG)

with app.app_context():
    scheduler = BackgroundScheduler()
    scheduler.start()


@manager.command
def run():
    app.run()
    atexit.register(lambda: scheduler.shutdown())


if __name__ == '__main__':
    manager.run()
kind steppe
#

hmmm

#

I wonder

#

You use a context manager to start the background scheduler, I wonder if it wants the same app context later during the API calls

solar laurel
#

It gives the same error

#

with or without using the context manager

#

in fact i added the context manager because i was having this context error before

kind steppe
#

Right, maybe we can try it in the application though

#

Flask has some event handlers for this, let me just get the docs

solar laurel
#

sure

kind steppe
#

Okay so

#

If you try ```py
@app.before_first_request()
def start_scheduler():
scheduler = BackgroundScheduler()
scheduler.start()

#

and then make a request

#

your atexit may have to be rejigged a bit but just give that a try

solar laurel
#

alright, lemme try

#

does it require some argument names f?

#

it raises an error saying so

kind steppe
#

It shouldn't

#

The function will be called without any arguments and its return value is ignored.

#

oh maybe remove the () from the end of the first line

solar laurel
#

TypeError: before_first_request() missing 1 required positional argument: 'f'

kind steppe
#

ah okay, yeah remove the ()

#

my bad

solar laurel
#

yeah, worked without the parentheses

#

but now, how do it import scheduler in my api file?

kind steppe
#

hm right

#

okay so maybe try ```py
scheduler = BackgroundScheduler()

@app.before_first_request
def start_scheduler():
scheduler.start()

#

that should work right?

solar laurel
#

let's run it and find out. i'm not sure though. hang on

#

didn't work. gives the same error

kind steppe
#

drat

#

this may not be a great fix but maybe you could add app.app_context().push() before you try to add anything to your background scheduler

#

there seems to be no documentation on this issue at all

#

I'm reading some chinese forum about it

#

also are you using apscheduler or flask-apscheduler?

solar laurel
#

yeah, i have searched a lot as well. didn't find anything. And I'm using apscheduler

kind steppe
#

Maybe it is worth trying flask-apscheduler

#

hm but then there seems no way to scheudle your own tasks with that library

#

this is such a weird issue

#

oh wait

#

I might have a solution

#

without using that library

#

give me a second

solar laurel
#

yeah, sure. any way that lets me schedule tasks on runtime would work

kind steppe
#

how are you adding tasks?

#

could you give code

#

and then you are adding to scheduler via add_job?

solar laurel
#
day, hour, mins = self.clean_scheduling_time(args.get('schedule_time'))
trigger = CronTrigger(day_of_week=day, hour=int(hour), minute=int(mins))
scheduler.add_job(send_email, trigger=trigger)
#

yes, this is the code

kind steppe
#

right

#

Okay so it looks like the flask module may fix it

solar laurel
#

what do you mean? how?

kind steppe
#

the flask module is made to work with flask app contexts

#

it has support for all the Cron stuff since it just wraps apscheduler

#

but if you use flask-apscheduler and then ```py

from flask import Flask
from flask_apscheduler import APScheduler

if name == 'main':
app = Flask(name)

scheduler = APScheduler()
scheduler.init_app(app)
scheduler.start()

app.run()
#

something like that

#

and then when you want to add job

#
with scheduler.app.app_context():
    scheduler.add_job(...)
solar laurel
#

hmmm alright. lemme give it a try

#

didn't work. raises same error

kind steppe
#

what the heck

solar laurel
#

it's really weird. i've been stuck on it for so long

#

any alternative solution ?

#

alternative to apschduler

#

there's celery but....

kind steppe
#

what are you trying to do, just have a email sent in the background every day of the week at a certain time?

solar laurel
#

yes

#

user signsup and gives a schedule time. a task it scheduled for once every week at the time provided by the user

kind steppe
#

hm right

#

I think celery is the recommended

#

but you could maybe look at threading and https://github.com/dbader/schedule and a database if you are opposed to that

#

oh wait actually

#

i might have just found the issue with apscheuler

#

instead of importing scheduler and using that

#

can you try remove the with and just use app.apscheduler.add_job instead

solar laurel
#

alright, lemme try

#

AttributeError: 'Flask' object has no attribute 'scheduler'

#

gives this error

kind steppe
#

should be apscheduler not scheduler

#

app.apscheduler

solar laurel
#

oh, sorry. wait

kind steppe
#

no worries

solar laurel
#

same weird error

#

:/

kind steppe
#

so so weird

solar laurel
#

lemme give 'schedule' library a try

kind steppe
#

Yeah

solar laurel
#

yeah, I'll take a look. thanks

kind steppe
#

Okay I just put this together pretty quickly

#
from flask import Flask
import schedule
import threading
import time

cease_continuous_run = threading.Event()

app = Flask(__name__)

class ScheduleThread(threading.Thread):
    @classmethod
    def run(cls):
        while not cease_continuous_run.is_set():
            schedule.run_pending()
            time.sleep(1)

continuous_thread = ScheduleThread()
continuous_thread.start()

@app.route("/every/<int:interval>/say/<string:text>")
def schedule_time(interval, text):
    schedule.every(interval).seconds.do(lambda: print(text))
    return "OK"

if __name__ == "__main__":
    try:
        app.run()
    except KeyboardInterrupt:
        cease_continuous_run.set()


vagrant adder
#

@solar laurel if you are doing with statement, app.app_context() .push() isn't needed

#
app = create_app('dev')  # os.getenv('PAYROLL_PROD') or 'dev')

manager = Manager(app)
migrate = Migrate(app, db, render_as_batch=True)
manager.add_command('db', MigrateCommand)

# import logging
#
# logging.basicConfig()
# logging.getLogger('apscheduler').setLevel(logging.DEBUG)

with app.app_context():
    manager = Manager(app)
    migrate = Migrate(app, db, render_as_batch=True)
    manager.add_command('db', MigrateCommand)
    scheduler = BackgroundScheduler()
    scheduler.start()


@manager.command
def run():
    app.run()
    atexit.register(lambda: scheduler.shutdown())


if __name__ == '__main__':
    manager.run()
solar laurel
#

@vagrant adder @kind steppe let me try both of these and see if these work

#

bravo @vagrant adder that worked (Y)

#

thanks a lot

vagrant adder
#

np @solar laurel

#

with app.app_context():
    do_something()

is the same as

app.app_context().push()
do_something()
app.app_context().pop()
#

both are context managers

solar laurel
#

right, i get it now.

#

there is another error though. When running the scheduled task, it now says 'No application found. Either work inside a view function or push'

vagrant adder
#

hm

#

where

solar laurel
#

inside my api, where i add tasks to apscheduler

vagrant adder
#

can you show where you add tasks

solar laurel
#

sure. one sec

#
class SignUp(Resource):
    """This class handles the signup API endpoint for users"""

    def clean_scheduling_time(self, schedule_time):
        """
        This method cleans up the schedule time into day, hour and minute
        :param schedule_time: time on which the task is to be scheduled
        :return: day, hour, minute
        """
        day = schedule_time.split(' ')[0].lower()[:3]
        hour, mins = schedule_time.split(' ')[1].split(':')
        return day, hour, mins

    def post(self):
        """it handles the post request for user signup"""
        args = user_parser.parse_args()
        username, password = args.get('username'), args.get('password')
        schedule_time, email_to = args.get('schedule_time'), args.get('email_to')

        if username is None or password is None:
            abort(400)  # missing arguments
        from email_scheduler.models.api_models import User
        if User.query.filter_by(username=username).first() is not None:
            abort(400)  # existing user

        user = User(username=username, schedule_time=schedule_time.split(' ')[1], email_id=email_to, email_to=email_to)
        user.hash_password(password)
        user.save_to_db()

        from manage import scheduler, app
        from email_scheduler.utils.utils import send_email
        with app.app_context():
            day, hour, mins = self.clean_scheduling_time(args.get('schedule_time'))
            trigger = CronTrigger(second=10)
            scheduler.add_job(send_email, trigger=trigger)


        return make_response(jsonify({'username': username}), 200)
#

i even tried adding tasks without with app.app_context() at the second last line

#

previous error is gone. it schedules the task just fine. but when this scheduled task runs once the interval reaches, it says 'No application found. Either work inside a view function or push'

vagrant adder
#

hm

#

is your code up on github?

solar laurel
#

it isn't. i haven't pushed yet.

#

but i just read the full traceback

#

this exception seems to occur during handling of another exception

#

the scheduled task makes calls to sqlalchemy with app's model which of course isn't available once the request has finished

vagrant adder
#

can i see your create_app() function

#

and file itself

solar laurel
#
from flask import Flask
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy

from email_scheduler.routes.routes import set_routes
from .config import config_by_name

db = SQLAlchemy()


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config_by_name[config_name])
    api = Api(app)
    set_routes(api)
    from email_scheduler.models.api_models import TaskModel, User
    db.init_app(app)
    with app.app_context():
        db.create_all()

    return app

#

error though is definitely with sqlalchemy call. i commented out that part of code in the task function and just added a print statement, there's no error now

#

i think i'm gonna have to make seperate sqlalchemy connecction and execute raw queries inside the task function

#

or is there a better way to do it?

vagrant adder
#

so

#

you are mixing 2 methods

#

factory and normal

#

this a file where i initialize my app

#

API(app) and db.init(app) are contradictory

#

you gotta decide which method you gonna use

#

and also put some stuff outside the funciton

solar laurel
#

right. so if i go with db.init_app(app), how would i tell the app about my routes?

#

and vice versa

vagrant adder
#

i would suggest following my init file

solar laurel
#

yeah, but I'm using flask_restful in my app. and routes are set differently in flask_restful

vagrant adder
#

i know

#

routes are okay

#

but app initializer is messed up

solar laurel
#

i see. I'll change it

lilac coral
#

Anybody knows if there's a way to redirect a route to another port in Flask? I*m having my website in Flask and a project in Vue which runs separately on another port (I've looked at integrating the two but it seeems to be to much of a hassle for someone new to this like me). So when I go to /vueproject I want to end up at port 8080 !

keen sphinx
#

I don't know the answer since I don't know the HTTP specifications, but looking at the make_response method might help

#

you could try adding the pertinent header for redirecting but with a url and port

#

and returning the correct response code for redirects

gleaming tartan
#

Hey, anyone here good with React?

native tide
#

what is wrong? 😅

shrewd sand
#

@native tide You need a extra bracket

eager hornet
#

missing a ) on the previous line

shrewd sand
#

After the ]

native tide
#

i still get the error

#

oh nevermind

#

it worked

#

but ive got another error

shrewd sand
#

@native tide For the future, a syntax error means your code is typed incorrectly

native tide
#

i know

shrewd sand
#

Check it again, make sure you have all your brackets, colons etc etc

native tide
#

it is an import

#

i know the module is typed like that

shrewd sand
#

Your not allowed a dash their I don't think?

#

Maybe I'm wrong.

native tide
#

from flask_wtf import FlaskForm i re read the docs

#

i need an underscore

#

thanks anyway bro!

shrewd sand
#

Yeah makes sense

#

Np

#

Since it's a syntax error, you know you typed it wrong

native tide
#

👍

keen sphinx
#

@lilac coral this kinda what I had in mind

from flask import make_response

@app.route('/redirectFrom')
def red():
    response = make_response('Hello',302)
    response.headers['Location'] = 'http://myweb.com:8080/redirectTo'
    return response

if you want to make it more elegant and reusable check the request object to get the requested path, so you can take the first part somehow and add the port and page to it

lilac coral
#

@keen sphinx thanks! I'll look into it when I get back home

keen sphinx
#

you're welcome

#

check the 3xx status codes too, I have no idea what they're for and I didn't bother too much to read their descriptions, I just picked one by name

vagrant adder
#

@keen sphinx can you do return redirect('link.goes.here.com')

keen sphinx
#

oh, that looks like a better idea

#

it's @lilac coral's issue though, I'm not working on anything related to that

#

it's @lilac coral's issue though, I'm not working on anything related to that

#

it's @lilac coral's issue though, I'm not working on anything related to that

marble hinge
#

Anyone here able to help with a CSS related question?

solar laurel
#

I'm using http-basicauth where you authenticate with username and password. I have an html form. I do I send username and password along with form when i hit a secure endpoint

marble hinge
#

Anyone here able to help with a CSS related question?

solar laurel
#

I'm using http-basicauth where you authenticate with username and password. I have an html form. How do I send username and password along with form when i hit a secure endpoint? with postman, its easy. I can simply go to the authorization tab and type in username and password

marble hinge
#

also, is discord super laggy to load / send messages for anyone else?

solar laurel
#

I'm using http-basicauth where you authenticate with username and password. I have an html form. How do I send username and password along with form when i hit a secure endpoint? with postman, its easy. I can simply go to the authorization tab and type in username and password

marble hinge
#

@solar laurel if you're using basic auth, you should be able to POST with the following headers:headers={'Authorization': 'Basic {b64encoded-value} where b64encoded-value = base64.b64encode(f'{username}:{password}')

#

you'll have to use a session though.

solar laurel
#

yeah, how do I use session with basic-httpauth?

#

any idea?

keen sphinx
#

also, is discord super laggy to load / send messages for anyone else?
the last message I sent needed like half a minute to be received, and the mobile app showed it 3 times in a row but the desktop one only once

marble hinge
#

No clue

keen sphinx
#

also, is discord super laggy to load / send messages for anyone else?
the last message I sent needed like half a minute to be received, and the mobile app showed it 3 times in a row but the desktop one only once

solar laurel
#

any idea?

marble hinge
#

can you use requests?

#

No clue

keen sphinx
#

also, is discord super laggy to load / send messages for anyone else?
the last message I sent needed like half a minute to be received, and the mobile app showed it 3 times in a row but the desktop one only once

solar laurel
#

yesh, i can

#

yesh, i can

keen sphinx
#

also, is discord super laggy to load / send messages for anyone else?
the last message I sent needed like half a minute to be received, and the mobile app showed it 3 times in a row but the desktop one only once

marble hinge
#

x

#

@solar laurel I can give you an example using requests

solar laurel
#

i thought it was just me, but now that you mention it, i think something's wrong

#

@marble hinge yeah, sure

marble hinge
#

import requests
import base64

username = "admin"
password = "admin1234"
auth = base64.b64encode(f'{username}:{password}'.encode('utf-8')).decode()

url = "https://www.example.com"
headers = {"Authorization": f"Bearer {auth}"}

with requests.Session() as session:
    r = session.post(url, headers=headers)
    # check response object to ensure it was successful
    if r.ok:
        session.get(...)
        session.post(...)
    else:
        print(r.ok, r.status_code, r.reason)
        print(r.content)
#

the POST there does essentially the same thing any real human does when they enter credentials in a login form and click 'submit' or 'login'

#

So that authenticates the session, then you use that authenticated session to facilitate further HTTP requests, including the headers with each request

solar laurel
#

so the browser handles the request headers when we post form data from the browser?

#

how can i achieve something like https://username:password@www.example.com/? Here, you send username and password in the URL

marble hinge
#

Just do a POST to that exact url

#

but yeah you should be able to just do what I did in the example above,passing the authentication creds in the headers

solar laurel
#

Maybe I'm missing something here. this is what i have done:

class Login(Resource):
    """This class handles the login"""

    def post(self):

        args = login_parser.parse_args()
        from email_scheduler.models.api_models import User
        user = User(username=args.get('username'))
        user.hash_password(args.get('password'))
        headers = {'Content-Type': 'text/html'}
        if user.verify_password(args.get('password')):
            session['logged_in'] = True
            return make_response(render_template('task.html'), 200, headers)

        return make_response(render_template('login.html'), 200, headers)

    def get(self):
        headers = {'Content-Type': 'text/html'}
        return make_response(render_template('login.html'), 200, headers)
#

but after it sends a response, the next request still doesn't authenticate

#

@marble hinge

rain dune
#

Hello, someone could help me with css ?

solar laurel
#

is anyone familiar with flask_httpauth?

marble hinge
#

@solar laurel sorry, I actually don't really follow what all is going on in that code snippet you sent

#

user.hash_password() -- when I gave my example, I mentioned that the username and password needed to be a concatenated string joined by a semi-colon

#

then b64-encoded

#

so if user.hash_password() is happening to the password that is b64-encoded and used in the Authorization header of requests, that won't work

#

because the remote endpoint is not expecting a hashed value of the password; it's just expecting {username}:{password} as a base64-encoded value

ruby palm
#

Can I do those sort of things with django?

ruby palm
#

If so, how? What do I need?

keen sphinx
#

what's special about that form?

ruby palm
#

The transaction of money

#

I'm curious about how do transactions of money work in web development with Python

#

For example which things you need to know in order to make a transaction of money work, how do you do it, if is possible or not to do it with django, etc

solar laurel
#

@marble hinge I'm not really sure how should I use your code snippet in my API. like, in login, how do I maintain a session if username and oassword are correct?

#

also, I read a bit around on the internet, and the developer of flask_httpauth wrote that every request needs to be authenticated separately with username and password

#

app works just fine with postman where i can send auth headers with any request

#

i'm just not sure how to send headers with frontend

vagrant adder
#

@ruby palm take a look at shopify

slim beacon
#

hey can someone help me out with a problem i have with loading a background image in css on a python flask server

#

currently my directory structure is

root
|__static
|__templates
|__images
|__stylesheets

#

my css is stored under stylesheets and there is an image i want to load as a background image into a file being served on flask

#

in index.html under templates i am loading the css like so : <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='stylesheets/style.css') }}" >

#

and im setting the background image like so :

body {
font-family: 'Roboto', sans-serif;
background: url("{{ url_for('static', filename='images/background.png') }}") no-repeat center center fixed;
background-size: cover;
}

#

when i use the <img> html tag to load the background image it works fine

#

but when i try to load it as a background image it fails to load

#

the browser for some reason is requesting for the file as /static/stylesheets/static/images/background.png

twin yarrow
#

hey everyone
for html, can i access the id of the oredered list row?

native tide
#
<!DOCTYPE html>
<html lang="en">

<head>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">

  <title>Bare - Start Bootstrap Template</title>

  <!-- Bootstrap core CSS -->
  <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

</head>

<body>

  <!-- Navigation -->
  <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top">
    <div class="container">
      <a class="navbar-brand" href="#">Start Bootstrap</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarResponsive">
        <ul class="navbar-nav ml-auto">
          <li class="nav-item active">
            <a class="nav-link" href="#">Home
              <span class="sr-only">(current)</span>
            </a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">About</a>
...
``` i have this code of bootstrap 4 starter template, i am using flask and trying to put this in an html index file put the js and css do not show up, debug mode on
twin yarrow
#

show the flask code

#

@native tide

native tide
#

okay @twin yarrow ```py
from flask import Flask, render_template, url_for
app = Flask(name)

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

if name == 'main':
app.run(debug=True)

#

home.html is the file i showed up in a templates folder in the same folder of the py file

twin yarrow
#

for flask i believe

#

css should be in the static folder

native tide
#

i do not have a css file

#

it is from bootstrap

#

online

twin yarrow
#

then im not sure, sorry

native tide
#

its okay

twin yarrow
#

your link in <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> should also probaly start with a trailing slash

native tide
#

?

#

what do you mean

#

i found something related to what u mentioned

#

let me try it

#

it worked!

#

i needed to fix the links

#

thank u bro

twin yarrow
#

np :)

rain dune
#

Hello, question. When I'm using with html "margin-left: auto" it is supposed to push my element to the extreme right of the page right ?

frigid egret
#

Hi all. I'm having trouble understanding how to use forms with ModelForm in Django.

#

So far it's extremely basic but I must be missing something because "submit" button doesn't do anything. Also I don't see how it's attached to the form itself.

#

My forms.py

class OrderForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = ['name', 'phone']
#

My views.py

def order(request):
    form = OrderForm(request.POST)
    context = {"form": form}
    return render(request, 'shop/order.html', context)
#

My models.py

class Order(models.Model):
    name = models.CharField(max_length=100)
    phone = models.CharField(max_length=100)

    def __str__(self):
        return self.name, self.phone
#

and my HTML

<div class="container">
        <form action="/your-name/" method="post" id="order-form">
            {% csrf_token %}
            {{ form.as_p }}
            <input type="submit" value="Submit">
        </form>
    </div>
vagrant adder
#

Why do you have class inside a class

#

Forms arent meant to be created lioe that

frigid egret
#

because it's meta.

#

ok...

#

I saw it in a tutorial

#

maybe I misunderstood it?

vagrant adder
#

Take a look at corey schafer's django forms

frigid egret
#

link please?

vagrant adder
frigid egret
#

Ok, does he explain how to use ModelForms? Cause most tutorial I've found use standard Forms

#

Videos are hard to use sometimes because you can't scroll through it to get to the specific part that you need to understand

#

...and this one is 45 minutes. 😬

vagrant adder
#

Hmm

#

Ask some of the staff since they are transfering to django

frigid egret
#

is it ok to ping them over such question?..

vagrant adder
#

Not sure

#

Ask in dm or ping

frigid egret
#

I made some changes and now it seems to work but it still won't save any objects to DB

#

And I'm not sure how to save it in my case

vagrant adder
#

User.session.add()

#

I think

frigid egret
#

it should be order.save()

#

in my case but I just don't know where to put it and I can't find an example

#

Cause examples I find use regular Forms and views.py in that case looks different

native tide
#

if i wanna use a flask back end for managing web content on a small mostly static site other than a photo gallery and maybe a contact form

#

just using jinja templates would be alright for the front end yeah

#

dont need like react or anything for something so small

vagrant adder
#

Yeah it would be alright

sudden oyster
#

Hey I have a question. What does the post attribute do in an HTML form tag?

proper hinge
#

That isn't a standard attribute as far as I know.

#

There is method="post", is that what you meant?

#

That means that when the form is submitted, it will send a HTTP POST request to the URL in the action attribute.

#

@sudden oyster

sudden oyster
#

Oh yeah I meant the method attribute with the post method. Thanks for the info @proper hinge .

#

Silly me I should specify my own questions first before I actually ask.

#

The URL in the action attribute is where the data from the form is being processed is it not?

twin yarrow
#

its the link that will recieve the request

sudden oyster
#

Is that where the data from the form is going to be processed?

autumn bobcat
#

Not necessarily. It's where you send the data, that server might d send it somewhere else

hoary spruce
vagrant adder
#

What is the error

hoary spruce
#

Error: Failed to find Flask application or factory in module "Bizantium.app". Use "FLASK_APP=Bizantium.app:name to specify one.

#

Bizantium is the name of the folder the code is in

vagrant adder
#

Hm

#

Try upgrading flask

hoary spruce
#

Using latest version

#

but I think it had to do something with the init.py file

#

that it doesn't have the if "name" = ...

vagrant adder
#

Try that then

#

U using create_app() ?

hoary spruce
#

nowp, was thinking about it, but that to be imported to use in an other ....py file

#

right?

vagrant adder
#

You can use that in if name == main

hoary spruce
vagrant adder
#

No

#

init.py

hoary spruce
#

i don't get it

#

How should I actually run it tho

#

So start virtual env, the set FLASK_APP=the folder name or the __init__.py

vagrant adder
hoary spruce
#

Would that work on that example?

vagrant adder
#

Yes you'd only need one more file outside your folder

#

After i come home i'll take a look at code @hoary spruce

hoary spruce
#

thanks bud

tardy nova
#

got a django related question

#

whenever I move my project folder the whole thing breaks and can't run anymore

#

what's up with that?

hoary spruce
#

I suddenly got it to work @vagrant adder

vagrant adder
#

How

#

@hoary spruce

hoary spruce
#

export FLASK_APP=__init__.py

vagrant adder
#

Aaaaaa

#

I forgot about that

#

You can export files also

hoary spruce
#

the export is only for mac & linux then?

vagrant adder
#

Do you have git bash @hoary spruce

hoary spruce
#

nah not on this pc

vagrant adder
#

Then use powershell

#

set

#

Instead of export

#

But have to restart to work

hoary spruce
#

using mac

vagrant adder
#

On mac its export

hoary spruce
#

lemme try to run it on my vps

vagrant adder
#

@hoary spruce put export line in .bashrc

#

Then source it

#

So if your vps restarts it will keep that env var intact

hoary spruce
#

wtf

#
RuntimeError: Click will abort further execution because Python 3 was configured to use ASCII as encoding for the environment. Consult https://click.palletsprojects.com/en/7.x/python3/ for mitigation steps.
vagrant adder
#

upgrade click

#

pip install -r requirements.txt --upgrade

#

@hoary spruce nice alias nickname

#

i saw your code

#

you can condense some functions into one

wooden dragon
#

dose anyone have a good source for html 5 and css styling I'm building a site but i have no frontend skills what so ever.

hoary spruce
#

Well i'll highly suggest you to learn html for sure

#

otherwiese there is no point of making backend

marble nexus
#

just starting to tool around with django, I've worked with RoR before, but just curious how popular web dev with python is right now?

late gale
#

No matching distribution found for anaconda-client==1.6.14
Heroku error

#

How to solve this

#

Whenever I push my files to heroku it says this

#

shall i delete from requirements.txt ?

#

How to disable Anaconda from my project

#

I didn't use it on the project yet

#

Or is there a way to solve this

#

Anyone?

#

Fine I gonna delete Anaconda cause I wont use it for now

late gale
#

I am tired of heroku

#

everytime i push it fails

#

How should i solve this

 ModuleNotFoundError: No module named 'zxcvbn_password'
remote:
remote:  !     Error while running '$ python manage.py collectstatic --noinput'
#

Please help

#

I am tired of pushing too many times

vagrant adder
#

You need to erase everything from that

#

And only type packages you pip installed

late gale
#

Erase what?

#

I made a requirements.txt that have all the packages installed

vagrant adder
#

Erase everything from requirements.txt

#

And put stuff you only pip installed on your pc

late gale
#

zxcvbn_password is installed on pc

#

gonna delete it from requirements then

#

what about the static error

vagrant adder
#

Try putting zxcvbn instead of zxcvbn_password

#

In requirements.txt

late gale
#

the weird thing is

#

it's not included in requirements.txt

vagrant adder
#

Thats because some packages install some prequisites

#

Like flask installs click,jinja and markup

late gale
#

gonna delete that package then i am not using it

#

and what about the static error

#

remote: ! Error while running '$ python manage.py collectstatic --noinput'

vagrant adder
#

Try that

late gale
#

Oh

#

thank you

#

What a hero xD

vagrant adder
#

Does it work?

late gale
#

I am trying right now

late gale
#

Omg

#

I should have a credit card to host my website

#

after all of this

#

Heroku is bad

vagrant adder
#

Nope

#

You can use free plan

late gale
#

I bought a domain for free

#

from freenom

#

and when i add it on heroku domains

vagrant adder
#

Oh

late gale
#

it says credit card

vagrant adder
#

Yes you need bought vps to assign a dns record

late gale
#

what?

#

First time hosting a website so i dont know what are u talking about xd

#

and now I see application error in their domain

#

nice

vagrant adder
#

You cant put custom domain on free hosting solutions

late gale
#

then how should i host my website -,-

#

Oh wait

#

I got it

#

How to host it on heroku

#

It says application error

late gale
#

I dont understand anything from the logs

#

so

#

Creepy

#

I have installed django-heroku package and still

vagrant adder
#

Corey schafer has good video about deploying to heroku

late gale
#

3 Hours trying to host my website on heroku

#

Omg

#

4*

#

I know Corey but he didn't face these errors

#

Cuz he used it many times unlike me

#

Its my first time heroku

#

and heroku is bad

#

When i solve an error , another error appears

#

Unsolvable

#

Heroku doesn't understand Profiles OMG!

#

I am done

#

Last time gonna use that ***

vagrant adder
#

You gotta make procfile

#

Making your linux server from scratch is even sketchier

late gale
#

I made a Procfile

#

and still

#

I hate too many errors but that doesn't mean i gonna give up

#

wait

#

is Procfile not a txt?

vagrant adder
#

Nope

late gale
#

Omg

#

i am so stupid

vagrant adder
#

It contains text

late gale
#

That's why

vagrant adder
#

But doesnt end with .txt

late gale
#

Ty

#

YAAAAAAAAAAAAY its working

#

Programming always proves me that i am stupid

#

OMG!

#

Application Error

#

😢

#

Gonna try a restart

#

OMG!

#

😢

#

Gonna try something

#

Hope it works

#

WORKED!

#

YAAY

#

solve it by myself

vagrant adder
#

Lol

#

Nice bud

late gale
#

The problem was I was putting wrong directory instead of current directory xDDD

#

I am so stupid

vagrant adder
#

Nice

late gale
#

here is the blog template

{% extends "blog/base.html" %}
{% block content %}
    {% for post in posts %}
        <article class="media content-section">
          <div class="media-body">
            <div class="article-metadata">
              <a class="mr-2" href="#">{{ post.author }}</a>
              <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
            </div>
            <h2><a class="article-title" href="#">{{ post.title }}</a></h2>
            <p class="article-content">{{ post.content }}</p>
          </div>
        </article>
    {% endfor %}
{% endblock content %}
#

Here is the views.py

def blog(request):
    context = {
        'posts': Post.objects.all()
    }
    return render(request, 'blog/blog.html',context) #I must add title for the Blog! Remember that!
#

and here is the models.py

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted= models.DateTimeField(default=timezone.now)
    authoer = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title
late gale
#

Anyone -_-

meager anchor
#

did you run migrations

late gale
#

nope

#

I will try

late gale
#

It says no changed detected

#

and the error didnt solve

#

I dont like to ping an admin so i gonna be patient -,-

simple escarp
#

how did you run the migration? it sounds like you tried to create a new migration, not apply the existing ones

late gale
#

I just made heroku do it heroku run python manage.py makemigrations <myapp>

#

and it says no changes detected in my app

tardy nova
#

You need to make migrations then run them

#

Iirc

#

It's a two step process

elder raven
hoary spruce
elder raven
#

im not using a vps though

hoary spruce
#

So I did exactly every step but my nginx gives an error code when i restrart the service:

#
nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Sun 2019-07-14 23:01:54 CEST; 2min 10s ago
     Docs: man:nginx(8)
  Process: 29791 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid (code=exited, status=0
/SUCCESS)
  Process: 29441 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
  Process: 29874 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=1/FAILURE)
 Main PID: 29443 (code=exited, status=0/SUCCESS)

Jul 14 23:01:54 vps688006 systemd[1]: Starting A high performance web server and a reverse proxy server...
Jul 14 23:01:54 vps688006 nginx[29874]: nginx: [emerg] unknown directive "passenger_enabled" in /etc/nginx/sites-enabled/bizan.
conf:9
Jul 14 23:01:54 vps688006 nginx[29874]: nginx: configuration file /etc/nginx/nginx.conf test failed
Jul 14 23:01:54 vps688006 systemd[1]: nginx.service: Control process exited, code=exited status=1
Jul 14 23:01:54 vps688006 systemd[1]: Failed to start A high performance web server and a reverse proxy server.
Jul 14 23:01:54 vps688006 systemd[1]: nginx.service: Unit entered failed state.
Jul 14 23:01:54 vps688006 systemd[1]: nginx.service: Failed with result 'exit-code'.
#

It has to do something with the passenger_enabled but I can't seem to figure out what exactly is wrong

elder raven
#

bruh

hoary spruce
#

Okey so I got rid of error when doing sudo service nginx restart

#

But my app doesn't get shown

late gale
#

I have tried migrations and still

#

It says no changes detected

late gale
#

it says blog_post I cant even find blog post in any file

late gale
#

Anyone?

wraith shoal
#

Cheap python hosting options

#

Preferably Paas

#

Which one do u use

deft garden
#

how cheap/how performant?

wraith shoal
#

Extremely cheap

#

Performance is not a priority

late gale
#

A lot of people go with cheap

wraith shoal
#

Just learning as a hobby

#

I like py

late gale
#

I made migrations

#

and it doesnt solve my problem

meager anchor
#

makemigrations only creates migrations

#

did you run them?

#

manage.py migrate

late gale
#

oh I forgot to migrate

#

srry

#

wait

#

i will see now

#

Actually it did solve my problem but why doesn't my blog posts appear

#

Ty for solving my problem but Why does my blog posts not appearing

#

Patience on admins -,-

#

My blog posts are saved in the database and my images is saved in my windows folder "media".. gonna try to make my media in a file transfer protocol software

#

Ah-ha

#

Heroku doesn't accept sqlite database

#

gonna change my database then into Postgres

deft garden
#

do you have a .edu address you can redeem freebies with?

native tide
#

I'm having trouble getting a basic flask app to show HTML on localhost:5000

#

this is my index.html

<html>
    <head>
        <title>{{ title }} - Microblog</title>
    </head>
    <body>
        <h1>Hello, {{ user.username }}!</h1>
    </body>
</html>

this is routes.py

from flask import render_template
from app import app

@app.route('/')
@app.route('/index')
def index():
    user = {'username': 'Nicholas'}
    return render_template('index.html', title='Home', user=user)
#

I do set FLASK_APP=microblog.py
then run with flask run

#

and when I go to localhost it just shows a blank page

native tide
#

anyone know what the problem is?

native tide
#

okay nevermind

#

I forgot to save the html file after I changed it

late gale
#

How to add facebook messengar chat plugin into my django website

pastel dove
#

If I wrote django app that used sqlite3 and am going to deploy it to Heroku (which uses Postgres) I would have to recreate all my entries in the new Postgres instance right?

simple escarp
#

yes, but you can probably tell sqlite to dump your tables, and import them in postgres, there are even tools to import to pg from about any db

pure token
#

I guess if your sqlite database never changes and just stores some static stuff you can update with a new deploy.. you can keep using sqlite, but that is rarely the case

pastel dove
#

Thanks guys

#

I plan to write to the DB regularly (it's where I store my project descriptions and GitHub links) so I'll see about setting up a postgres db

ashen anchor
#

Is there any way to have a query like so
Model.objects.values("Charfield", "Charfield", "Many2ManyField")

Whereby the many to many field is a nested list of values. Currently it will create a new object in the returned list for every many to many link
To give more context, I'm trying to create a graphql api and this is how I've been able to resolve the values for a standard model, but this one containing many to many relationships is confusing me

native tide
#

Hey guys would anyone be willing to take a look at a webpage I'm in the process of making and give feedback on the way it looks (layout wise and how cosmetically appealing it is)? If so pm me and ill post you a pic

hoary spruce
#

Sure thing

sudden oyster
#

Hey guyz, I have a problem. It's not necessarily big or anything, I just made a form tag and tried using the style attribute for it but it's not working. Why's that?

willow fern
#

What are you trying to achieve ?

late gale
#

How to upload my files on Dropbox

#

Django

#

I dont know anything about file uploads on a service

patent cobalt
late gale
#

Gonna read it

#

thanks

#

I have my drop box token and my app but How can i connect my django into dropbox

plucky thunder
#

Alright who here is good at selenium 😦 I'm about to explode

late gale
#

so whenever I upload an image from admin page

#

It uploads on dropbox storage

#

Can someone tell me If I want to upload my images on dropbox What should i write in

    Image = models.ImageField(upload_to =??)
#

Please

#

Anyone?

#

How can i upload my media files into dropbox folder

#

Guys?

simple escarp
#

please be patient

#

if someone knows, they'll answer. and you can still use a search engine to look for an answer in the mean time

late gale
#

I searched but i didnt understand. It wasn't understandable enough

#

I didnt find youtube videos for what i want

simple escarp
#

yes, because that's a complex task that requires to understand multiple things and piece them in a way not many people did, so you want to learn about how the ImageField works, and how to use python to put files on dropbox and get them back (because you'll need them in your application), and then make the first thing use the second one

#

programming is quite often that, learning how to make things that don't know about each others, work together

late gale
#

True

#

Thank you

native tide
#

I have this problem
I use https://masonry.desandro.com/ to create a masonry layout on my website
and I use a lazy-loader to load content from Python via JavaScript
now, when I load content directly from python, without using the lazy-loader, the masonry grid builds just fine
but with the lazy-loader, the parameters what the masonry js would add to the grid-items don't get added, and my content is displayed in a single column
can anyone help me to figure out how to resolve this?

cobalt scarab
#

How can i host my django project on a windows rdp ?

pastel dove
#

If I want to add a field to my db in Django, is this the right workflow?:

  1. Make changes to the app's models.py file
  2. run python manage.py makemigrations + python manage.py migrate
    ?
#

Im getting an error:

  File "<console>", line 6, in <module>
  File "/mnt/c/Users/ASUS Zenbook/Desktop/Website/site_venv/lib/python3.6/site-packages/django/db/models/base.py", line 501, in __init__
    raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg))
TypeError: Project() got an unexpected keyword argument 'github'```


My goal is to have a field I can store a GH url in
#

Model.py is:

from django.db import models

class Project(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    technology = models.CharField(max_length=20)
    github = models.TextField()
    image = models.FilePathField(path="/img") 
robust needle
#

Is it a bad idea to host a small flask website on pythonanywhere? I'm pretty inexperienced and this is my first flask project. I tried starting with Heroku and beat my head against the wall for like 3 hours before I gave up. Had something up and running on pythonanywhere in like 30 mins. Just don't know how "good" it is? I wouldn't even necessarily mind paying the $5 a month for their basic paid plan if its worth it. Already asked in another channel but realized this is probably the place to ask

late gale
#

Its not bad to host your project and heroku is good . I suffered alot with it when it was my first time that didn't mean i have to give up

#

All you have to do is GTNG

#

Google , Think/Rethink , Never Giveup

#

@robust needle

#

Hosting on Heroku is free

cobalt scarab
#

How can i host my django project on a windows rdp ?

pastel dove
#

@cobalt scarab a windows remote desktop protocol?

#

If I want to add a field to my db in Django, is this the right workflow?:

  1. Make changes to the app's models.py file
  2. run python manage.py makemigrations + python manage.py migrate
    ?
    Im getting an error:
  File "<console>", line 6, in <module>
  File "/mnt/c/Users/ASUS Zenbook/Desktop/Website/site_venv/lib/python3.6/site-packages/django/db/models/base.py", line 501, in __init__
    raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg))
TypeError: Project() got an unexpected keyword argument 'github'```


My goal is to have a field I can store a GH url in
Model.py is: 

```python
from django.db import models

class Project(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    technology = models.CharField(max_length=20)
    github = models.TextField()
    image = models.FilePathField(path="/img")```
late gale
#

Why is there no helping in this channel

#

This channel really have a bad service

#

3 People asking questions 2 days ago and 0 service

#

the only one who was helping in this channel was @vagrant adder

flint breach
#

Mate you got 7 help channels for that

late gale
#

They did 7 channels for help then why they did this channel

#

?

#

should i ask my questions everywhere in the server

flint breach
#

For general discussion

#

Or advice

#

Not bug fixing or homework help

#

Ask in a free help channel and im sure someone will help you out

late gale
#

Thank you

native tide
#

I'm having an issue with serving static files for django locally, i thought i was doing this properly, and i've done this in both production and development before, but still not updating? wondering if i should just implement my own cache busting lol

#
STATIC_URL = '/app/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "app"),
]```
#

for static

#

it was working before, just like randomly stopped working?

#

not sure why it would just randomly stop updating my static files in development mode

#

fixed nvm!

covert radish
#

@late gale Just want to clarify 2 things:

  1. These channels are not "service" like you mentioned earlier or "customer service" in fact; nobody is obligated to provide any kind "service", its mostly up to you to read #welcome > getting help > asking questions the right way. In order to increase your chances of you getting an answer; if someone knows the answer you will most likely be "helped".

  2. Please do not add members of this server that you don't know without their permission, good luck fam.

late gale
#

@covert radish 1- Actually they didn't mention that we suppose to ask in help channels and I READ the rules If so , why did they create these channels then??
2- It's up to you to either refuse or accept I am just trying to tell you that we both have the same nationality so it was gonna be great to know you but its ok Idc

covert radish
#

@late gale 1- You didn't understand my point, re-read it carefully again, you should not feel entitled to get help.

2- You don't know me or my nationality.

I am trying to help you get answers not argue with you.

late gale
#

@covert radish You are an Arabian

covert radish
#

That's a race not a nationality.

late gale
#

and I guess that you are Egyptian

covert radish
#

You guessed wrong.

late gale
#

so we both share the same race then

covert radish
#

That's not the point.

late gale
#

I don't care anyways

#

ty for your response

covert radish
#

👍

calm solar
#

alright guys. im stumped hard. this worked 100% when sending regular request

            if obj.completed:
                obj.completed = False
                obj.time_completed = None
                obj.save()
                data = {'tits': "McGee", }
                return JsonResponse(data)
            else:
                obj.completed = True
                obj.time_completed = timezone.now()
                obj.save()
                data = {'tits': "McGee", }
                return JsonResponse(data)

        elif any((obj.team_assigned_id == request.user.user_id_number, obj.customer_id.account_parent == request.user.client_id)):```
i setup an ajax button to handle the interaction and now only the 'if' is working. as if the 'elif' at the bottom isn't testing true.
#

am i missing something?

flint breach
#

is it indented properly

strong talon
#

does anyone know about [attribute="value"] tags in scss?

#

i originally used them to create functional light and dark modes in regular css

#

but when i switched to scss, its not working?

#

relevant scss

$error-hue: 3;
$error-color: hsl($error-hue, 100%, 50%);
$error-background: hsl($error-hue, 100%, 80%);
$accent-hue: 170;
$accent-color: hsl($accent-hue, 70%, 40%);
$accent-heavy: hsl($accent-hue, 75%, 35%);
$accent-strong: hsl($accent-hue, 80%, 30%);
$text-color: #3b4951;
$background-color: #ffffff;
$shadow-color: #c4c4c4;
$weak-color: #d4d4d4;

[theme='dark'] {
  $text-color: #e2e2e2;
  $background-color: #3b4951;
  $shadow-color: #c4c4c4;
  $weak-color: #ffffff50;
}

[theme='light'] {
  $text-color: #3b4951;
  $background-color: #ffffff;
  $shadow-color: #c4c4c4;
  $weak-color: #d4d4d4;
}
#

it just doesn't translate to the css

proper hinge
#

I thought those always needed some sort of element selector before them

#

like an tag name, class, id, or even just *

wanton jacinth
#

Hello guys!
So, I am stuck with something that I didn't expect to get stuck with. I am using Flask and Jinja as well as a JSON for the data. The issue is that I am unable to evaluate a boolean contained in the JSON file.

The flask code I am using is:

@app.route('/resume') def resume(): SITE_ROOT = os.path.realpath(os.path.dirname(__file__)) json_url = os.path.join(SITE_ROOT, "static/data", "resume.json") data = json.load(open(json_url)) return render_template('resume.html', data = data)

html:

{% for item in data %} <li class="nav-item"> {% if item["submenu"] is sameas true %} <a class="nav-link js-scroll-trigger" href="#{{item}}">true</a> {% else %} <a class="nav-link js-scroll-trigger" href="#{{item}}">false</a> {% endif %} </li> {% endfor %}

JSON :
}, "education": { "submenu": true, "content":{ } },

All other element's "submenu" are false

#

I am not sure what is wrong with the {% if item["submenu"] is sameas true %} statement

pliant hound
#

Hello. Can anyone help me with my flask config?

vagrant adder
#

{% if item["submenu"] == true %}

#

try that @wanton jacinth

#

@pliant hound what do you need help with

pliant hound
#

I'm using libsass with flask_assets

#

And as I'm building up my custom sass on top of bulma, the css output isn't updating

vagrant adder
#

have you tried force refreshing in chrome?

pliant hound
#

I've found I can get it to update if I delete the outputted css file, but it's awful

#

Yeah, I've done hard refreshes and cache clear refreshes

vagrant adder
#

hm

pliant hound
#

"""
Scss(app, static_dir='static', asset_dir='assets')
assets = Environment(app)
assets.manifest = False
assets.cache = False
assets.auto_build = True

sass_bundle = Bundle(
'bulma.sass',
'custom.sass',
filters= 'libsass, cssmin',
depends=('static/sass/**/*.sass'),
output= 'css/bundle.css',
extra= {'rel' : 'stylesheet/sass'}
)

assets.register('sass_all', sass_bundle)
sass_bundle.build()
"""

#

oops

vagrant adder
#

```py

pliant hound
#

ahhh

#
Scss(app, static_dir='static', asset_dir='assets')
assets = Environment(app)
assets.manifest = False
assets.cache = False
assets.auto_build = True


sass_bundle = Bundle(
    'bulma.sass',
    'custom.sass',
    filters= 'libsass, cssmin',
    depends=('static/sass/**/*.sass'),
    output= 'css/bundle.css', 
    extra= {'rel' : 'stylesheet/sass'}
    )

assets.register('sass_all', sass_bundle)
sass_bundle.build()
#

That's the code block

#

the environment config stuff is cobbled together from random suggestions from stack overflow and reddit and stuff, still no dice

vagrant adder
#

static/sass/**/*.sass

#

what is ** supposed to do

pliant hound
#

check for all subfolders in my sass folder, no?

#

Hold on. I just changed the directory to sass/**/*.sass and I may have a winner here?

#

Yeah! That did it!

#

Thanks @vagrant adder 😃

vagrant adder
#

Np @pliant hound 👍🏻

native tide
#

how do you call the {% something something %} methods in bootstrap? I'm trying to find out more about that

stray nexus
#

you mean for jinja template ?

vagrant adder
#

You can't call functions within jinja

#

You can pass variables, lists,dictinaries and tuples

#

But not functions

wanton jacinth
#

@vagrant adder thanks for the suggestion! I tried that but didn't work either. From all the testing I did, it would seem that the issue is somehow in the item["submenú"] part of the statement

vagrant adder
#

Try printing item

prime ridge
#

What does Python's WSGI compare to in other languages? Trying to learn more about various webservers. [X-posted from #python-discussion]

normal karma
#

@prime ridge As you know, WSGI was created to allow writing web applications in Python. It works like this: when your web server, like Apache or Nginx, gets request, it forwards it to the app server via CGI (common gateway interface) which is part of html protocol. Using CGI with Python proved to be problematic, so after time of development, WSGI was created. It allowed the web server to communicate with the Python application server (Flask or Django), without any security flaws and etc. The only WSGI I've personally used is Gunicorn

prime ridge
#

Interesting, I knew about all of that except CGI -- I assumed apache/nginx were just magic, randomly better at serving static files for no good reason. I guess a lot of other languages might opt for building on the CGI spec directly? I'll read more into it!

frigid egret
#

Hi all

#

I'm studying Django by making a generic pizzeria website.

#

Lately I've started encountering some weird situations and I think I might have made some design mistakes that are really difficult to traceback.

#

Can someone please hep me with that?

#

The latest question that I'm trying to solve is this:

#

For each pizza in an order, Django creates an object that contains a reference to the pizza model and user form data.

#

Now I'm trying to make a view in the admin panel that groups those objects into a single order based on user form data.

#

But I can't find any relevant information on google. Maybe I just don't know the method that I should be using... But I also started doubting my design choice.

prime ridge
#

https://stackoverflow.com/questions/1118183/how-to-debug-in-django-the-good-way
pdb is great for debugging, just put import pdb; pdb.set_trace() at the line in your code where stuff starts going funky and your program will stop and let you snoop around

frigid egret
#

Well, debugging is not an issue here. There are no errors.

prime ridge
#

Ah. Generally speaking it's not recommended to use the admin panel for this sort of thing, but it can be done.

frigid egret
#

I just can't get how to make information appear on the admin site the way I want it.

#

Here's an example of my orders (they contain only 2 fields now: name and phone)

#

But as you can see, it renders each pizza separately while I want Django to group those pizzas together based on user_form field

prime ridge
#

Question about your pizza model. Is there a pizza object created for each order, or is there a pizza object for each pizza on the menu?

frigid egret
#

There is a list of pizzas that are displayed on the front page, there's a model for them. When a user adds any pizza to the order, JS adds its ID to localstorage. And on checkout page, when the order is complete, it creates an 'OrderItem' object that has foreignkeys to both user form and pizza model.

#

...let me correct myself