#web-development
2 messages · Page 27 of 1
Thanks for trying to help me
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
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
Thanks Charlie
Vue is also good for a frontend but knida new and idk if it goes along with django(literally everything goes with flask)
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.
Are you experience with ML?
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
I don't think I used ajax for a while
axios libary works well enough
and fetch is fine
thanks, I'll look it up
@keen sphinx i used to use jQuery for AJAX, then I just decided to abandon jquery and use the fetch api
yeah, I've heard jQuery can be avoided for most things nowadays, something like that
fetch is great
fetch > ajax?
Yes
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
@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.
I’ll try when I’m home from work. But I’m using VSC tho
How can i add messenger chat to my django website
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.
$( document ).ready(function() {
});
You script contains in this function?
Yes, I'm doing exactly that
my script
});```
It's recommended in latest docs to do it this way
$( document ).ready
I don't see this condition in you insert
Yes, because $(function ()) is the same thing
From official docs
// Shorthand for $( document ).ready()
$(function() {
console.log( "ready!" );
});
Yes, I already saw, then it's strange, try load jQuery in <head>.
tried that too
Same thing. I think it's happening because it takes my script to load way faster than jQuery lib.
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.
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
This may be due to slim jQuery?
idk really
Maybe a bad question but you tried ctr+F5 reload?
always do that
Try not slim version jQuery
Which one's that?
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 =/
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
But the weird thing is, in my main project
If I launch that
It works, website runs etc
I'm stupid (: @covert agate Was just running the wrong file

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.
It depends how your external webservice communicates and how your flask api model looks like
And what your api actually does
Does someone know how to add the messenger chat plugin into my website
What plugin and what website
I added the code they gave me but it doesn't appear
Facebook Messenger
and my django website actually
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
cluttered for your taste ??
Omg Django is so fun to use
It helped me finish my website in 5 days
Yeah
Too much things tbh
Flask is like legos
You can include whatever extension you want
I don't like flask tbh
Best thing ever
Yeah i tried it
Some things it does better than flask but flask fits me more
Django is pretty cluttered and not very customizable
I actually don't see flask these days
From my perspective
Flask is like do it yourself way, and django more strict about doing some things
The best thing about django is it's rapid development
It always comes in handy
Couldnt feel as free as i felt using flask
Django don't want you to do anything except say what you want
and It handles the rest
I never tried flask tbh
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
Php is messy and scrapy nowdays
but why do I see laravel at the best framework in 2019
What about Angular
Thats for serving html
I always love Javascript for web
Ik but It'll be weak
unless your website wont use database
What do you mean by weak
I always prefer backend frameworks than frontend
What i mean is how should a front end framework handle a database
Json is lit
And that goes well with js
Second, frontend frameworks and backend have different purpose
Comparing apples to pears
Frontend focuses on the client side backend focuses on server side and the databases
Backend is for logic and frontend serves html and css
I like your comparison
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
Anyways, How about Asp.net Core ?
I see microsoft is updating it
Its for backend
Lemme get home
anyone here familiar with fullcalendar.io ??
nope
seems interesting tho
@late gale here i am
let's get back to frontend vs backend discusion
xD
why
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
Then how should we build a full website with only one framework
Front end cant handle the backend stuffs and vice versa
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()
django is render()
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
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
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
I actually learned fullstack web but all i have used is backend framework xD
one can learn html and css within 2 months
and frontend job field is pretty crowded
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
Just a sec
yeah, frontend is really easy to pick up
and i find backend more fun and challenging
I agree with you
/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 😬
I’m gonna have a go at creating a dynamic web page, what framework would be best for a beginner?
heroku,digital ocean, google cloud, linode ...
i would recommend heroku for django and flask
Its name sounds weird lol like an anime character xD
Thank you, kind sir!
What does it mean? "1 web/1 worker"
Heroku is good if you have containerised everything
I used it for small and personsal projects
Never had any issues with heroku services itself
Anyone have experience with creating a cloud based service?
You mean serverless?
@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
I think you are better of defining your own endpoint
Yeah, I thought so, cause I dont need more than one method on each endpoint.
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
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
is django preety much a laravel equivilent for py
@late gale you need to tell which buildpack you want to use
i dont have the heroku app yet
I only connected to github
@vagrant adder
sorry for my ping
but shall i download it
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)
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
Can anyone help m,e with some very basic django ?
@cyan portal What's your problem
does anyone here use npm for frontend and flask for backend?
npm?? that a javascript code for a terminal
Which type of javascript do you use in frontend?
@keen thorn
I was just curious why someone would use both npm and flask..
Cause javascript frameworks are frontend and flask is backend so they just integrate to make a powerful one
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
What does Heroku mean when it says that I got only ONE container in my free hosting plan?
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
I've heard Two Scoops of Django is pretty good
check out the resources page @rigid laurel https://pythondiscord.com/info/resources#books
We've got a couple of books in there, one for flask & one for django
Can anyone here help with flask? I’m getting an error related to app context
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.
Can you post the full traceback?
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>)
Wow, that's a very cryptic error
😄
How are you running the application?
Looking online it seems like this could be caused by the method the application is being run
just to give you a little context, I'm adding tasks on runtime within an API call. I'm not adding them before hand
Right
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()
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
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
Right, maybe we can try it in the application though
Flask has some event handlers for this, let me just get the docs
sure
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
alright, lemme try
does it require some argument names f?
it raises an error saying so
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
TypeError: before_first_request() missing 1 required positional argument: 'f'
yeah, worked without the parentheses
but now, how do it import scheduler in my api file?
hm right
okay so maybe try ```py
scheduler = BackgroundScheduler()
@app.before_first_request
def start_scheduler():
scheduler.start()
that should work right?
let's run it and find out. i'm not sure though. hang on
didn't work. gives the same error
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?
yeah, i have searched a lot as well. didn't find anything. And I'm using apscheduler
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
yeah, sure. any way that lets me schedule tasks on runtime would work
how are you adding tasks?
could you give code
and then you are adding to scheduler via add_job?
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
what do you mean? how?
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(...)
what the heck
it's really weird. i've been stuck on it for so long
any alternative solution ?
alternative to apschduler
there's celery but....
what are you trying to do, just have a email sent in the background every day of the week at a certain time?
yes
user signsup and gives a schedule time. a task it scheduled for once every week at the time provided by the user
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
alright, lemme try
AttributeError: 'Flask' object has no attribute 'scheduler'
gives this error
oh, sorry. wait
no worries
so so weird
lemme give 'schedule' library a try
Yeah
You will need to look at this for having things run in the background https://schedule.readthedocs.io/en/stable/faq.html#how-to-continuously-run-the-scheduler-without-blocking-the-main-thread
yeah, I'll take a look. thanks
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()
@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()
@vagrant adder @kind steppe let me try both of these and see if these work
bravo @vagrant adder that worked (Y)
thanks a lot
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
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'
inside my api, where i add tasks to apscheduler
can you show where you add tasks
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'
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
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?
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
right. so if i go with db.init_app(app), how would i tell the app about my routes?
and vice versa
i would suggest following my init file
yeah, but I'm using flask_restful in my app. and routes are set differently in flask_restful
i see. I'll change it
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 !
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
Hey, anyone here good with React?
@native tide You need a extra bracket
missing a ) on the previous line
After the ]
@native tide For the future, a syntax error means your code is typed incorrectly
Check it again, make sure you have all your brackets, colons etc etc
from flask_wtf import FlaskForm i re read the docs
i need an underscore
thanks anyway bro!
👍
@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
@keen sphinx thanks! I'll look into it when I get back home
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
@keen sphinx can you do return redirect('link.goes.here.com')
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
Anyone here able to help with a CSS related question?
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
Anyone here able to help with a CSS related question?
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
also, is discord super laggy to load / send messages for anyone else?
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
@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.
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
No clue
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
any idea?
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
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
i thought it was just me, but now that you mention it, i think something's wrong
@marble hinge yeah, sure
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
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
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
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
Hello, someone could help me with css ?
is anyone familiar with flask_httpauth?
@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
If so, how? What do I need?
what's special about that form?
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
@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
@ruby palm take a look at shopify
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
hey everyone
for html, can i access the id of the oredered list row?
<!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
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
then im not sure, sorry
its okay
your link in <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> should also probaly start with a trailing slash
?
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
np :)
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 ?
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>
Take a look at corey schafer's django forms
link please?
In this Python Django Tutorial, we will be learning how to use forms and validate user input by creating a user registration page. We will also learn how to ...
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. 😬
is it ok to ping them over such question?..
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
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
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
Yeah it would be alright
Hey I have a question. What does the post attribute do in an HTML form tag?
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
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?
its the link that will recieve the request
Is that where the data from the form is going to be processed?
Not necessarily. It's where you send the data, that server might d send it somewhere else
Question about Flask, this example has an init.py file. On 1 of my pc's I could start it using set FLASK_APP=__init__.pybut on my mac & VPS I cannot seem to get it started. (heres the example code: https://github.com/PrettyPrinted/flask_auth_scotch/blob/master/project/__init__.py)
What is the error
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
Using latest version
but I think it had to do something with the init.py file
that it doesn't have the if "name" = ...
nowp, was thinking about it, but that to be imported to use in an other ....py file
right?
You can use that in if name == main
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
Would that work on that example?
Yes you'd only need one more file outside your folder
After i come home i'll take a look at code @hoary spruce
thanks bud
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?
I suddenly got it to work @vagrant adder
export FLASK_APP=__init__.py
the export is only for mac & linux then?
Do you have git bash @hoary spruce
nah not on this pc
using mac
On mac its export
lemme try to run it on my vps
@hoary spruce put export line in .bashrc
Then source it
So if your vps restarts it will keep that env var intact
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.
upgrade click
pip install -r requirements.txt --upgrade
@hoary spruce nice alias nickname
i saw your code
you can condense some functions into one
you can condense this with simple if request.method =="POST"
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.
Well i'll highly suggest you to learn html for sure
otherwiese there is no point of making backend
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?
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
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
Erase everything from requirements.txt
And put stuff you only pip installed on your pc
zxcvbn_password is installed on pc
gonna delete it from requirements then
what about the static error
Thats because some packages install some prequisites
Like flask installs click,jinja and markup
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'
I'm trying to deploy a Django app to Heroku, it starts to build, download and installs everything, but that's what I get when it comes to collecting static files
$ python manage.py collectstatic --
Try that
Does it work?
I am trying right now
Omg
I should have a credit card to host my website
after all of this
Heroku is bad
Oh
it says credit card
Yes you need bought vps to assign a dns record
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
You cant put custom domain on free hosting solutions
then how should i host my website -,-
Oh wait
I got it
How to host it on heroku
It says application error
I dont understand anything from the logs
so
Creepy
I have installed django-heroku package and still
Corey schafer has good video about deploying to heroku
3 Hours trying to host my website on heroku
Omg
4*
I was following this cause of that error in my logs and I pissed off http://vibhurishi.blogspot.com/2013/02/heroku-error-h14-with-django.html
H14 Error on Heorku Today morning I did a new push to www.bikenomads.co.in with images from the fantastic 2013 calendar. And the w...
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 ***
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?
Nope
It contains text
That's why
But doesnt end with .txt
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
The problem was I was putting wrong directory instead of current directory xDDD
I am so stupid
Nice
How to fix this issue
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
Anyone -_-
did you run migrations
It says no changed detected
and the error didnt solve
I dont like to ping an admin so i gonna be patient -,-
how did you run the migration? it sounds like you tried to create a new migration, not apply the existing ones
I just made heroku do it heroku run python manage.py makemigrations <myapp>
and it says no changes detected in my app
hello?
Hello everybody, I just started to learn Flask with Corey Schafer on Youtube. I created a Flask_Blog folder, containing flaskblog.py. In the flaskblog.py file, there is the code to create a basic Flask server.http://dpaste.com/0V6G5HS
. I go in my cmd and I type the following: http://dpaste.com/0D9GPPA
. And I get this error:http://dpaste.com/1NEY02C
I am on Windows 10.
I am using git CMD
Thanks
So i'm using this tutorial to get a flask app running on my debian vps https://www.phusionpassenger.com/library/walkthroughs/deploy/python/digital_ocean/nginx/enterprise/stretch/deploy_app.html
im not using a vps though
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
bruh
Okey so I got rid of error when doing sudo service nginx restart
But my app doesn't get shown
Can anyone help me how to fix this https://discordapp.com/channels/267624335836053506/366673702533988363/599961312826490910
I have tried migrations and still
It says no changes detected
it says blog_post I cant even find blog post in any file
Anyone?
how cheap/how performant?
A lot of people go with cheap
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
@wraith shoal if you don't mind NATed ipv4 vps, how does 3.5 euro/year sound? https://clients.inceptionhosting.com/cart.php?gid=13
do you have a .edu address you can redeem freebies with?
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)
the app is called microblog and the hierarchy is
microblog.py
app
templates
index.html
init.py
routes.py
I do set FLASK_APP=microblog.py
then run with flask run
and when I go to localhost it just shows a blank page
anyone know what the problem is?
How to add facebook messengar chat plugin into my django website
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?
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
https://pgloader.io/ for example
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
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
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
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
Sure thing
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?
What are you trying to achieve ?
How to upload my files on Dropbox
Django
I dont know anything about file uploads on a service
Dropbox has an API and a Python SDK/API wrapper: https://github.com/dropbox/dropbox-sdk-python
Gonna read it
thanks
I have my drop box token and my app but How can i connect my django into dropbox
Alright who here is good at selenium 😦 I'm about to explode
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?
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
I searched but i didnt understand. It wasn't understandable enough
I didnt find youtube videos for what i want
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
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?
Cascading grid layout library
How can i host my django project on a windows rdp ?
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")
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
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
I highly recommend following this tutorial https://www.youtube.com/watch?v=MwZwr5Tvyxo&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH
In this Python Flask Tutorial, we will be learning how to get started using the Flask framework. We will install the necessary packages and get a basic Hello...
How can i host my django project on a windows rdp ?
@cobalt scarab a windows remote desktop protocol?
If I want to add a field to my db in Django, is this the right workflow?:
- Make changes to the app's models.py file
- 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")```
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
Mate you got 7 help channels for that
They did 7 channels for help then why they did this channel
?
should i ask my questions everywhere in the server
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
Thank you
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"),
]```
^ my settings.py
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!
@late gale Just want to clarify 2 things:
-
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".
-
Please do not add members of this server that you don't know without their permission, good luck fam.
@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
@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.
@covert radish You are an Arabian
That's a race not a nationality.
and I guess that you are Egyptian
You guessed wrong.
so we both share the same race then
That's not the point.
👍
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?
is it indented properly
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
I thought those always needed some sort of element selector before them
like an tag name, class, id, or even just *
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
This is the result.
I am not sure what is wrong with the {% if item["submenu"] is sameas true %} statement
Hello. Can anyone help me with my flask config?
{% if item["submenu"] == true %}
try that @wanton jacinth
@pliant hound what do you need help with
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
have you tried force refreshing in chrome?
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
hm
"""
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
```py
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
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 😃
Np @pliant hound 👍🏻
how do you call the {% something something %} methods in bootstrap? I'm trying to find out more about that
you mean for jinja template ?
You can't call functions within jinja
You can pass variables, lists,dictinaries and tuples
But not functions
@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
Try printing item
What does Python's WSGI compare to in other languages? Trying to learn more about various webservers. [X-posted from #python-discussion]
@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
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!
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.
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
Well, debugging is not an issue here. There are no errors.
Ah. Generally speaking it's not recommended to use the admin panel for this sort of thing, but it can be done.
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
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?
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