#web-development
2 messages Β· Page 61 of 1
sure, why not?
Ok thx
so there is a urls.py in the Python package folder (within the project) and then there is a urls.py in each individual app folder. how do they relate to one another exactly? when you visit a site, which one gets used first?
i dont think there should be a urls.py in every app-folder by default
so there is a
urls.pyin the Python package folder (within the project) and then there is aurls.pyin each individual app folder. how do they relate to one another exactly? when you visit a site, which one gets used first?
@native tide
the urls.py in your main folder contains all your urls to different views
you can import a view from a different app and then create url for it
yes you're right that there is not a urls.py in every app folder by default
@native tide Yes
lets say you have a app named Login then
so whenever you add a path to a urls.py file that is in an app folder, you have to include it in the project urls.py...... unless you go to like http://127.0.0.1:8000/<app_name>/
right?
from personal.views import home_screen_view # personal is the app
urlpatterns = [
path('admin/', admin.site.urls), # pre-loaded with Django
path('', home_screen_view),
]
you don't have to import the view to the project urls.py if you go to the URL for the app itself, is that right?
from Login.views import someAPI
urlpatterns = [
path('login/',someAPI.as_view())
]
from personal.views import home_screen_view # personal is the app
urlpatterns = [
path('admin/', admin.site.urls), # pre-loaded with Django
path('', home_screen_view),
]
@native tide its better to use the root folder urls.py
oh wow, really? like, all of the time? or at least most of the time?
that makes sense to me
yes
π
Hi there, anyone knows how to import N classes from a directory and append to an array ?
hey everyone! glad to be a part of this community
is this the proper channel to ask django / DRF type questions?
yes
cool! i am pretty new to DRF and was curious: what is the standard method for views...ViewSets or function-based views? does it matter?
im a java dev by day so we have controllers (which i understand are views in Django land) and do what would be similar to function-based views
(i use spring boot so it is annotation driven)
i am a newbie, so maybe a pro will chime in but, here is how i understand it
it goes visit site -> urls.py -> views.py -> (optionally) models.py / DB call -> HTML -> client
views are functions
def members(request):
list_of_all_members = Account.objects.order_by('first_name')
context = {'list_of_all_members': list_of_all_members}
return render(request, "lb/members.html", context)
that is a view
does that help at all?
a little... i understand the chain you mentioned above but trying to see what is the "standard" in regards to this https://medium.com/@ksarthak4ever/django-class-based-views-vs-function-based-view-e74b47b2e41b
well i have gone through literally 6 long Django tutorials and i have only seen function-based views
but again, i'm still a beginner π
haha ok cool that does help tbh! ima watch some more videos and see what is up
im leaning towards function-based views as well
godspeed
thanks @native tide !
yw
thanks for that feedback weep! i went with the ViewSet route for now since i have a better understanding now that it creates most of the endpoints you need auto-magically
@empty anchor always?
they're definitely nice but sometimes you need pages that don't need all of that included functionality
and I'm under the impression that the added overhead comes at some performance cost, vs just a simple FBV where it only contains what you explicitly define
most of the times mark ! but you got a point
Hi, I am doing an NEA project for my studies; before someone calls rules, I am not looking for help. Mainly im looking for common problems faced on the backend when developing an online store. I seek to encounter these problems myself.
any flask gods here?
ngl i would have a look at something like https://tailwindcss.com/
hi all. question regarding django timezones. backend is returning datetimes in ISO 8601 string format (like normal) via DRF endpoint.
front wants back to convert all datetime objects to user local timezone. generally i would think that front should do that conversion based on the timezone details provided from the DateTimeField. thoughts?
Someone can suggest a good tutorial course to develop ecommerce website with django?
because now i found only old tutorial that uses old version of django (1.11) and im searching for tutorial with django 3
depends what you are doing, but generally not a huge difference between 1.11 and 3.0. we were running 1.11 for first while at my office couple years.. since then i've slowly brought us up to 3.0. 99% the same for what we do. tutorial for 1.11 might still be useful
The frontend has a built in way to convert to the local time with JS: (new Date(datestring)).toLocaleString()
Someone can suggest a good tutorial course to develop ecommerce website with django?
@toxic marten Practical Django 2 and Chanels 2 by Fredico Marani
I followed this for my basics as well as this book has a eCommerce tutorial basics for Django.
@toxic marten it's a book but better than any tutorial out there on the internet
Ok thank youπ π @empty anchor
However it's federico not fredico ahah, it's an italian nameπ€£
ahah no problem, im italian
haha, I'm a indian xD
imma dm it to you
oks
hello, I'm trying put data in a <p> tab but don't know how
<p>some stuff</p>
I mean changing info with curly brackets
nevermind I think I figured it out, sorry for the disturbance
you mean templating?
@remote ruin sure I am up for a talk when you want to......... even i'm a noob though xD but with a little bit experience lately
look at your console and find out π€·
i get error post is not defined
even tho it is
@app.route('/posts/pinn/<int:id>')
def pinn(id):
post = BlogPost.query.get_or_404(id)
if request.method == 'POST':
post.pinn = request.form['pinn']
if post.pinn is True:
post.pinn = False
db.session.commit()
else:
post.pinn = True
db.session.commit()
else:
return render_template('posts.html', post=post)
it seems something is wrong with my html file :/
What does Werkzeug say on the console?
Now i know this may not be the right place to ask, i got the UI (CSS) of the speeddial, but next I'm trying to get/put the functionality on clicking of each and every button...
The page from which i extracted the info was a packed app... and had the location chrome-extension://<id>
Which means it's a chrome extension and Vivaldi is chromium based
When i type its location in addressbar it doesnt appear. Is there any other way i can access it ?
Isnt it chrome-extension. Plus your message made be switch, surprised I havent heard of this before, its pretty good.
@restive kindle it's a packed app, and yes it's strange. But i think because it's a chromium based so it allows chrome extensions
And I'm using debug-packed-apps flag to inspect elements
any react + django developers here?
hey any good ideas for flask projects?? TIA
Asking good questions will yield a much higher chance of a quick response:
β’ Don't ask to ask your question, just go ahead and tell us your problem.
β’ Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
β’ Try to solve the problem on your own first, we're not going to write code for you.
β’ Show us the code you've tried and any errors or unexpected results it's giving.
β’ Be patient while we're helping you.
You can find a much more detailed explanation on our website.
@native tide
the speed dial is a kind of extension actually or better call it a packaged app (legacy chrome extensions), it has a remote base which can be modified with DevTools of Vivaldi
devtools://devtools/bundled/devtools_app.html?remoteBase=https://chrome-devtools-frontend.appspot.com/serve_file/@ce637bfd730e6b2e549bf8def38f849ela26bd3/8cpanel=elements&dockSide=undocked
display block on tbody
maybe you could take the approach of
instead of putting everything in the same t-row
{% for vouch in vouches %}
<tr>
<td>{{ vouch['value'] }}</td>
<td>{{ vouch['author'] }}</td>
<td>{{ vouch['member'] }}</td>
<td>{{ vouch['comment'] }}</td>
</tr>
{% endfor %}```
No css needed
And it'll naturally go 'stacked'
@twilit zenith
it worked thanks
π
hey y'all! Is anyone of you familiar with the pushshift API? I was using psaw and basically used their demo example to grab posts from 2017. But somehow it retrieves only the latest posts and not from the time indicated:
from psaw import PushshiftAPI
import datetime as dt
api = PushshiftAPI()
start_epoch=int(dt.datetime(2017, 1, 1).timestamp())
data = list(api.search_submissions(after=start_epoch, subreddit='neo', filter=['url','author', 'title', 'subreddit', 'num_comments', 'comments'], limit=10))
print(data)
This is what the code above returns for me, if I use limit=1 instead of 10:
[submission(author='anonboyGR', created_utc=1590054802, num_comments=0, subreddit='NEO', title='Pi Network Cryptocurrency', url='https://www.reddit.com/r/NEO/comments/gntymq/pi_network_cryptocurrency/', created=1590047602.0, d_={'author': 'anonboyGR', 'created_utc': 1590054802, 'num_comments': 0, 'subreddit': 'NEO', 'title': 'Pi Network Cryptocurrency', 'url': 'https://www.reddit.com/r/NEO/comments/gntymq/pi_network_cryptocurrency/', 'created': 1590047602.0})]
notice how this is in fact not from 2017...
This is the link to the example I used: https://psaw.readthedocs.io/en/latest/#first-10-submissions-to-r-politics-in-2017-filtering-results-to-url-author-title-subreddit-fields
guys how to update boolean type column on click?
@app.route('/posts/pinn/<int:id>', methods=['GET', 'POST'])
def pinn(id):
post = BlogPost.query.get_or_404(id)
if request.method == 'POST':
post.pinn = request.form['pinn']
if post.pinn is True:
post.pinn = False
db.session.commit()
else:
post.pinn = True
db.session.commit()
else:
return render_template('posts.html', post=post)```
this is code and its not updating it :/
you need to db.session.add() first before you commit
do you have a model for your db?
class BlogPost(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(72), nullable=False)
content = db.Column(db.Text, nullable=False)
author = db.Column(db.String(20), nullable=False, default='N/A')
date_posted = db.Column(
db.DateTime, nullable=False, default=datetime.utcnow)
pinn = db.Column(db.Boolean, default=False)
def __repr__(self):
return 'Blog post' + str(self.id)```
@native tide but i am trying to update it
well yeah but you need to pass your BlogPost Model to the db. you just randomly do db.session.commit()
how does the db know what it is supposed to do?
so i should use db.session.add(post)?
@app.route('/posts/pinn/<int:id>', methods=['GET', 'POST'])
def pinn(id):
post = BlogPost.query.get_or_404(id)
if request.method == 'POST':
post.pinn = request.form['pinn']
if post.pinn is True:
post.pinn = False
db.session.add(post)
db.session.commit()
return redirect('/posts')
else:
post.pinn = True
db.session.add(post)
db.session.commit()
return redirect('/posts')
else:
return render_template('posts.html', post=post)```
here is an example how to update:https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/#querying-records
Has anyone here integrated an AWS Chime instance with python or a Django Server ??
yeah i need it
maybe use lambda function
@empty anchor you have to go to your console service and select lambda
for aiohttp, is it better if I re-use the ClientSession or is the performance cost negligible enough to forget it? I'm multiple async functions independently of each other so I'm wondering if maybe I should combine them under the same ClientSession for a perf boost
i.e. maybe put them into one class with self.session = aiohttp.ClientSession...
hey friends , django or laravel(php) ?
Whatever you want
Anyone know how to set the success_url in .as_view() to be a namespace?
app_name = 'accounts_app'
url_patterns = [
...
path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(success_url='reset/done/'), name='u_password_reset_confirm'), # 'password_reset_confirm.html'
path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='u_password_reset_complete'), # 'password_reset_complete.html'
...
]```
I've tried using reverse() but didn't have any luck.
Figured it out. Instead of...
success_url=reverse(pattern_name)
I had to use...
success_url=reverse_lazy(pattern_name)
That'll be very handy to know going forward.
Hey! I'm new here, trying to learn more about Python. Django vs Flask?
I'm going with Django because there's a lot more job opportunities and I don't wanna spend a year learning about the web just to start working.
But if you use Flask you'll learn things much more thoroughly and customize it as well.
I'm trying to print all the cookies from a website.
Instead it outputs this:
name='COOKIE NAME I SPECIFIED', domain=None, path=None
Why is this?
Rest of your code? Howβre you accessing the cookie? Session module? Cookie module?
Are you sure the cookie is set?
I'm currently trying to put 2 <div>s side by side on each line
however, with my current code my 4 <div>s all go on the same line-
how might I make it so that only 2 can be on each line?
.flex-container {
display: flex;
}
.flex-child {
flex: 1;
/*border: 2px solid yellow;*/
display: flex;
justify-content: center;
margin: 5px;
margin-top: 20px;
padding: 100px;
background: #7d7d7d;
border-radius: 30px;
margin-left: 10px;
margin-right: 10px;
font-family: 'Ubuntu', Helvetica, Arial, sans-serif;
font-size: 50px;
color: white;
}
.flex-child:first-child {
display: flex;
justify-content: center;
margin: 5px;
margin-top: 20px;
padding: 100px;
background: #7d7d7d;
border-radius: 30px;
margin-right: 10px;
margin-left: 10px;
font-family: 'Ubuntu', Helvetica, Arial, sans-serif;
font-size: 50px;
color: white;
}
this is what I am currently using (css)
flex-basis
and flex-wrap
use flex-basis to indicate the "base" amount of space you expect the divs to take up
(say, 50% for two columns)
and use flex-wrap: wrap; to enable wrapping of flexbox items (which is off by default )
hey guys, I want to start in webdev with python. I am more of a data science guy but I want to start building web apps for my team. What frameworks or libraries should I start learning? Btw, I also heard of "Flutter" is it good?
.flex-container {
flex-basis: 50%;
flex-wrap: wrap;
display: flex;
}
.flex-child {
flex: 1;
/*border: 2px solid yellow;*/
flex-basis: 50%;
flex-wrap: wrap;
justify-content: center;
margin: 5px;
margin-top: 20px;
padding: 100px;
background: #7d7d7d;
border-radius: 30px;
margin-left: 10px;
margin-right: 10px;
font-family: 'Ubuntu', Helvetica, Arial, sans-serif;
font-size: 50px;
color: white;
}
.flex-child:first-child {
flex-basis: 50%;
flex-wrap: wrap;
justify-content: center;
margin: 5px;
margin-top: 20px;
padding: 100px;
background: #7d7d7d;
border-radius: 30px;
margin-right: 10px;
margin-left: 10px;
font-family: 'Ubuntu', Helvetica, Arial, sans-serif;
font-size: 50px;
color: white;
}
like this?
I'm probably doing something wrong, stil shows 4 on each
does anybody how I can track the number of active users currently viewing a page using django?
nope
I strongly suspect it's not possible even in theory
you'll know when someone loads the page, but how do you know if they're looking at it, or if they got up and got a cup of coffee?
or opened another tab or ... ?
Closest thing I can think of is some kind of JavaScript thing that monitors for in-activity, but then that's no longer just a Django thing.
Hello bois
I'm downloading images from a django web server but it's really slow... I don't really know why
response = requests.get(info["signed_url"], stream=True)
with open(pic_name, 'wb') as handler:
for data in response.iter_content(chunk_size=1024):
handler.write(data)
Do any of you has an idea on how to make it faster ?
I am working with Flask and as far as I understand unchecked checkboxes are not serialized in the form subission POST request.
Question is, how do I check for existence of a given checkbox within the if form.validate_on_submit() call?
At the moment, I am checking for existence in the following way:
if request.form['show_logo']:
# Do stuff
The problem is that when the checkbox is not checked (hence not serialized and sent in the request), the above if statement returns a KeyNotFoundError
Solved, I simply ended up checking for its existence in the form fields:
# check for checkbox existence in returned form
if "show_logo" in request.form:
# do stuff [...]
As default, django creates static folder inside each app. But i want also to create a static folder outside the app, this static folder outside app has some files that aren't app-related, it has files that are used all-around in the site. So how can i create static folder both inside each app and both one outside the apps folder?
i mean that
I red about STATIC_URL STATIC_ROOT inside settings.py, but i didnt understand very well
Anyone know how to do form validation in flask
@native tide have mid-level experience with Flask, where did you get stuck?
@tender crater thanks for the reply!
so i have a form
and on submission it sends the data to routes.py right
# After a test is submitted
@app.route('/submit/', methods=['POST'])
@login_required
def submit():
data = request.form
p
return redirect(url_for('userprofile'))```
when submit is pressed, the contents are POST to routes right
and data = request.form
my question is
how can i do form validation, so the user can only submit the test once all of the questions are answered?
pls
how can i do form validation, so the user can only submit the test once all of the questions are answered?
@native tide do you mean that users can currently send partially complete forms and you specifically want to prevent that from being allowed?
If that's the case you should specify validators (very easy with wtforms) in your form definition, example:
from flask_wtf import FlaskForm
from wtforms.validators import DataRequired
from wtforms import StringField
class CoolForm(FlaskForm):
name = StringField("Your name here", validators=[DataRequired()]
surname = StrinField("Your surname here", validators=[DataRequired()]
This will prevent the form from validating when those two fields are not filled out.
Right, in flask you have to declare your form in a class somewhere as specified in the documentation https://flask.palletsprojects.com/en/1.1.x/patterns/wtforms/, it'll make your life easier
to make it a wt form ? @tender crater
theres a reason we didn't use wt forms
im not sure why i'll ask my team mates but we aren't using them for a reason
@native tide got it, to be honest i always sticked with way back when I started as it was suggested in the official docs and it is very well documented
now I really wonder what's preventing you guys from using it π
do you know how to validate for a html form?
@tender crater reason we dont use wt forms
is because there is a varying number of questions per test
@native tide Uh, that's a cool use case
huh
Anyways, I would personally write a helper method that takes your form as an argument and performs all the checks on your form
But haven't to much experience outside wtforms. Will give it some thought in some spare time
Sorry, wish I were more helpful
can someone tell me why flask form is giving me wrong error
its not showing me "Invalid email address"
but instead the path to the email_validator moduel
module*
{{ form.password.label(class='form-control-label') }}
{% if form.password.errors %}
{{ form.password(class='form-control form-control-lg is-invalid') }}
<div class='invalid-feedback'>
{% for error in form.password.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.password(class='form-control form-control-lg') }}
{% endif %}
</div>```
this is the code that is supposed to show the "invalid email address" message
what does your form class look like?
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, EqualTo, Email
import email_validator
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=3, max=16)])
email = StringField('Email', validators=[DataRequired(), Email(email_validator)])
password = PasswordField('Password', validators=[DataRequired()])
confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
submit = SubmitField('Sign Up')
class LoginForm(FlaskForm):
email = StringField('Email', validators=[DataRequired(), Email(email_validator)])
password = PasswordField('Password', validators=[DataRequired()])
remember = BooleanField('Remember Me')
submit = SubmitField('Login')```
Email(email_validator) is wrong
oh
but i cant use Email() alone
it gives me error if i dont use email_validator
What's the error it gives you?
ah
That means it must be installed, not that it must be put in that spot
oh
Validates an email address. Requires email_validator package to be installed. For ex: pip install wtforms[email].
let me try it without the email_validator argument
oh wow lol it worked
thank you so much, this has been bothering me for 2 days now
The Email() validator treats its first argument as a custom error message
so that's what was happening π
now I know! thanks again π
does anyone have a good link for a django explanation, not only django but also how a website actually is structured
im a beginner and starting to make my first website with python/django
the django doc is a bit hard to understand for me
@remote ruin https://www.feldroy.com/ highly recommended book. It goes from very basic principles to actually building a real-world application
@tender crater thx a lot
oh wow this actually for the alpha version
and it costs 50$ π
This is good resource on django.
hey guys, if i load a static .js file from my directory how can i have it access to jquery ?
Load jquery in the html first
yup that worked! thanks
hey all, beginner with a very simple flask app.
When I run flask in the app directory, everything works fine. Tests also run without an issue.
When I run web.py (the file where I sw app = Flask(name)) with regular python I get errors on imports, saying it can not find the app module.
Project tree and import statements here: https://pastebin.com/pv8JPhBN
Any pointers would be greatly appreciated!
I get the same import issues when I try to run the app in a uwsgi container (tiangolo/uwsgi-nginx-flask:python3.8)
@distant trout How is it "not working"?
im following a tutorial from corey schafer and his seems to be working fine.
its highlighted on my pycharm
It does work - PyCharm doesn't understand it for reasons detailed here (https://stackoverflow.com/a/42440466)
Oh
alright this was bugging me for some time now. thanks for letting me know
i can continue with the tutorial now π
NW, glad I could clarify.
BTW. happy to share the full code for anyone interested to help π
@solid flower Why would you run the file manually anyway?
i.e. Flask apps aren't meant to be run with the python command.
@queen bough I tried it while troubleshooting the error I get when running it through uwsgi, it was the same error so I figured it might be related...
but I'm all ready to be schooled π
How are you running it with uwsgi?
Why are you trying to run web.py individually/manually?
@queen bough using this docker image tiangolo/uwsgi-nginx-flask:python3.8
with uwsgi.ini:
[uwsgi]
module = web
callable = app
Got it working just now by setting sys.path explicitly. But that propbably is not pretty :)
from flask import Flask, render_template, redirect
from flask_wtf import FlaskForm
from wtforms import IntegerField, SubmitField
import sys
sys.path.append('/')
from app.peoplecounter.zone import Zone, set_occupancy_for
from app.peoplecounter.camera import Camera
from app.db import db, migrate
from app.config import Config
Try:
from .peoplecounter.zone import Zone, set_occupancy_for
from .peoplecounter.camera import Camera
from .db import db, migrate
from .config import Config
@solid flower
@queen bough ```
app_1 | Traceback (most recent call last):
app_1 | File "./web.py", line 4, in <module>
app_1 | from .peoplecounter.zone import Zone, set_occupancy_for
app_1 | ImportError: attempted relative import with no known parent package
app_1 | unable to load app 0 (mountpoint='') (callable not found or import error)
Try adding an empty __init__.py in the app folder (touch __init__.py)
Hello anyone is familiar with aws?
Already have one there @queen bough
or celery
@queen bough ```
$ tree -P "*.py"
.
βββ app
βΒ Β βββ config.py
βΒ Β βββ db.py
βΒ Β βββ init.py
βΒ Β βββ models.py
βΒ Β βββ peoplecounter
βΒ Β βΒ Β βββ camera.py
βΒ Β βΒ Β βββ init.py
βΒ Β βΒ Β βββ pycache
βΒ Β βΒ Β βββ zone.py
βΒ Β βββ pycache
βΒ Β βββ static
βΒ Β βββ templates
βΒ Β βββ web.py
βββ tests
βββ conftest.py
βββ init.py
βββ pycache
βββ test_camera.py
βββ test_models.py
βββ test_zone.py
from peoplecounter.zone import Zone, set_occupancy_for
from peoplecounter.camera import Camera
from db import db, migrate
from config import Config
Try that?
Seemed to work for me.
|-- __init__.py
|-- u
| |-- __init__.py
| |-- __pycache__
| `-- t.py
`-- w.py
Ignore the naming...
@solid flower
I'm trying to flash a message to my index.html page from my login route but the message is not rendering. Also in routes.py when I fill out the form it prints False to the console but I expected it to print True and flash the message.
def login():
form = RegistrationForm()
if form.validate_on_submit():
flash('Registration requested from user: {} and remember_me: {}'.format(
form.username.data, form.remember_me.data
))
print("True")
return redirect("/index")
print("False")
return render_template("login.html", form=form)
@app.route("/")
@app.route("/index", methods=["GET", "POST"])
def index():
return render_template("index.html")```
login.html
``` <form action="/index" method="POST">
<p>{{ form.username.label }}<br>
{{ form.username(size=32) }}
</p>
<p>{{ form.password.label }}<br>
{{ form.password(size=32) }}
</p>
<p>{{ form.remember_me() }}
{{ form.remember_me.label }}
</p>
<p>
{{ form.submit() }}
</p>
</form>```
index.html
``` <body>
<h2>Hello Index Page</h2>
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
{{ message }}
{% endfor %}
{% endif %}
{% endwith %}
</body>```
@queen bough it now runs in uwsgi yes, but errors out when I run my tests or run it with flask...
Traceback (most recent call last):
File "/home/jeroen/.virtualenvs/people-counter/lib/python3.8/site-packages/flask/cli.py", line 240, in locate_app
__import__(module_name)
File "/home/jeroen/Projects/Code/a/people-counter/app/web.py", line 4, in <module>
from peoplecounter.zone import Zone, set_occupancy_for
ModuleNotFoundError: No module named 'peoplecounter'
Did the tests work with . imports?
yes
OK, so all thats required is a minor tweak to your uwsgi config.
Can you repaste it?
module = web
callable = app```
@solid flower Sorry, g2g, but this may help:
https://stackoverflow.com/questions/16981921/relative-imports-in-python-3
Also, try module = app, callable = web.
thanks for your time and help @queen bough ! I'll look in to it
https://developer.ibm.com/callforcode/get-started/covid-19/remote-education/#tutorials cross-posted to #python-discussion
Use this starter kit to implement an online educational environment and create useful tools to assist teachers and students.
has anyone been able to use https://developer.ibm.com/cloud/call-for-code-request-for-on-line-learning-portal/ to get a *.skillsnetwork.site as per https://developer.ibm.com/tutorials/cfc-starter-kit-skills-network-implementation/ ? I filled out the form but they never created the site.
@queen bough just letting you know I've "fixed" it by adding the parent directory of the app directory on the docker container to uwsgi's pythonpath
A bit cleaner than setting the sys.path... but still... hey, it works! :)
[uwsgi]
module = web
callable = app
pythonpath = /
@solid flower Glad you fixed it. That looks like the correct solution.
How would I request all of my cookies from a website?
Hello guys,
I develop a website with Django to track some covid data.
Please, feel free to say honestly that you think and how can I improve it !
https://dani75i.pythonanywhere.com
Thx in advance
@grizzled crescent Looks great! One thing - I think the sidebar should be in line with the rest of the tables - not above it.
Thx @queen bough
sure buddy, sorry took a while
Hi all, did somebody worked with flask and multi threading? I have a sensor who sends a lot of stuff over protobuf and i want to display the results as a interactive webpage. So the sensor company recommends to get a dedicated thread for receiving the data.
Hello all, I'm new to python and I'am building a flask app, that keeps track of orders/comissions, keeps photos of them and all the information about them and calculates all the finances. How can I make running the app and database (i'm using XAMPP MySQL db, becouse I had expierience with it using PHP) easiest way for end user, I don't want to host it publicly on the web for security reasons, just locally on the computer or local network, is there any way of making it into exe file or i should use something else than XAMPP? Wish you all health!
don't know how big your database will get, but look into a Raspberry Pi as host or docker image. XAMPP is great for development but all this root access to your database can easily destroy your db
What would you recommend using instead of XAMPP?
like i sad: raspberry pi hosting the mysql server or a bit more complex: install a docker engine on your pc and docker you flask app an mysql server. with docker you can create a save env. for you app so that only flask has access to your docker mysql database.
your pc is running on windows?
Yes
there is also a mysql server installer for windows
it's a bit more complicated than XAMPP but I always recommend to create a dedicated user for an app in mysql
I will read more about those solutions, thank you for advice!
there is also a tutorial for docker hosting the mysql database
give it a try so you can easily move your db to other host if you later need it
To be honest I'm totally new to this docker concept and need to expand my knowledge about it, but it looks like better way of deploying than intalling xampp on end user pc π
exactly π
Can someone explain to me why the same HTML file appears differently under the "Sources" tab and under the "Elements" tab?
Sources section
Elements section
I'm inspecting the speed dial of vivaldi
anyone have any idea ?
Hello, am taking the CS50W course am having a challenge with a project using websocket. i want to create a file upload system using flask-socketio and read the file and send a link of the file to client. havent seen a direct instructional material on this. Help pls
I cant display images with django. Someone can help me? See the code
template
views
models
settings
Ive tried a lot of time, and sometimes inside img tag, the path of src has "unknown"
I think maybe the problem is with path. idk...
@amber moat Things like AJAX and AIO sites use things like react that build the html as it loads rather than being a set html file
which is why if you just do to source its just loading JS
@quick cargo interesting. It's just Vivaldi browser's UI. Is there a way i can verify that ?
All i want to do is port Vivaldi's Speed Dial into an extension
I dont think its gonna be possible unless you load the page before hand
I took out the HTML and CSS by inspection. Now I'm trying to put the functionality..
If i simply reference the JS files into main HTML will all the buttons work ?
Or additionally I have to do anything
I dont think its gonna be possible unless you load the page before hand
@quick cargo there are special flags that need to be enabled before to inspect the UI
Well it depends what ur doing
what u wont be able todo is just send a request to the site and get the content from it
im not sure how you would go about loading it with JS enabled and let it render
@toxic marten firstly you have typo in your template, should be 'src' not 'scr', in your 'src' you are putting two variables that are generated next to each other in the path that django is looking for. Have you inspected in the browser to see what path django is rendering?
I cant display images with django. Someone can help me? See the code
@toxic marten I solved the problem, im stupid. Inside database, the path of products image was "images/", but i named the folder "imgaes/"
π maybe take a look at the related_name parameter and see what benefits that gives you π
Can anyone recommend the best library for someone who has no experience of doing web-based stuff with python? Thanks -B
do you mean framework? and either flask or django, but first you need to know how requests work, that will make your life a lot easier
@prime grotto If you're looking at making an app for a larger scale or more modifiablilty, I'd say it's Django. But again @dark hare is right. First make sure what type of requests you dealing with and how they work.
Cheers for the help!
guys how do you change boolean value with flask sqlalchemy???
i am srill confused with it
@app.route('/posts/pinn/<int:id>', methods=['GET', 'POST'])
def pinn(id):
post = BlogPost.query.get_or_404(id)
if request.method == 'POST':
post.pinn = request.form['pinn']
if post.pinn is True:
post.pinn = False
db.session.commit()
return redirect('/posts')
else:
post.pinn = True
db.session.commit()
return redirect('/posts')
else:
return render_template('posts.html', post=post)
@fickle fox What doesn't work?
@queen bough it doesnt change value
You have to make a POST to it so that we can see a value printed.
There doesn't seem to be any POSTs to that endpoint.
A screenshot is not necessary - just the console output (which contains the value printed).
i set it
<a id='pinn' href='/posts/pinn/{{post.id}}'>Stick</a><hr>
once someone click stick it should be post right?
oh so how can i fix it?
And the other answers on the page show how to make a POST.
oh okay
@fickle fox I don't know if that will be the only thing necessary to fix the issue. Ping me if there are any further problems.
isnt this only for js?
No.
okay
It's the same for flask.
https://stackoverflow.com/questions/11556958/sending-data-from-html-form-to-a-python-script-in-flask
okay i ll try to fix it tho i am not getting it from a form
Crossing posting this from the databases chat, could someone help me out:
Is it possible to prepopulate a Model in Django with data scraped from a website, and then access that data later to post onto a Django application? I tried to write a migration to do this for me, but I think I might have written it incorrectly because it seems to give me multiple instances of the model rather than a single instance with all of the data.
@topaz charm Yes. Migrations are unnecessary and probably incorrect. The easiest way is to run the scraper contained in the Django environment and create and save models to the DB.
If you are using Scrapy you could try this module - https://django-dynamic-scraper.readthedocs.io/en/0.13-dev/introduction.html, though I've not used it.
@topaz charm Yes. Migrations are unnecessary and probably incorrect. The easiest way is to run the scraper contained in the Django environment and create and save models to the DB.
By create I mean:
scraped_value_1 = '...'
scraped_value_2 = 0
db_item = Model.objects.create(string_field=scraped_value_1, integer_field=scraped_value_2)
db_item.save()
@queen bough Would each item I scrape be saved as a unique instance of the model? I.e I'm trying to scrape a list of 500 songs from Rolling Stone magazine, would these be saved as 500 instances of the model I create to hold each songs info, or a single model with 500 entries containing info for each song
No, 500 instances of the model.
for i in range(500):
...
db_item = Model.objects.create(string_field=scraped_value_1, integer_field=scraped_value_2)
db_item.save()
@app.route('/posts/pinn/<int:id>', methods=['GET', 'POST'])
def pinn(id):
post = BlogPost.query.get_or_404(id)
if request.method == 'POST':
post.pinn = request.form['pinn']
if post.pinn is True:
post.pinn = False
db.session.commit()
return 'gotovo'
else:
post.pinn = True
db.session.commit()
return 'gotovo'
else:
return render_template('posts.html', post=post)```
it seems i am missing something
<button type="submit">Stick</button>
</form>```
what could be wrong in here? @queen bough
G2G for a while, I should be back in a few hours. Ping me with any further questions.
i.e. You want to monitor without having to submit it?
That will require AJAX to post every time a new option is chosen.
BTW, this:
if post.pinn is True:
post.pinn = False
db.session.commit()
return 'gotovo'
else:
post.pinn = True
db.session.commit()
return 'gotovo'
Can be simplified to this:
post.pinn = False if post.pinn else True
db.session.commit()
return 'gotovo'
next i am going to learn is how to make log in system
and later system for getting likes
i just need to learn how owo
Can i use python with HTML and CSS combined ? π€
yes and no
Python is not a front end language
like HTML, CSS and JS
what python can be used for is back end (server sided stuff)
why is django not loading my css files
I'm using the django tutorial for the poll app, and I just finished the step "write your own view". When visiting localhost:8080/polls, it has a 404 not found error. ```
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/polls
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
admin/
The current path, polls, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
@raw vessel Seems like you forgot to add your url
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
i was heading to localhost:8080/polls
the code is correct
I need some help regarding serving a flask app. I can SSH into this linux server and I have my own directory in that server. In that directory I have code for my flask app, and also an index.html file. I have a URL that will load index.html. How do I get that URL to load whatever my Flask app is displaying?
Would I have to contact the Server Admin to get that to work?
are you running the flask app?
if so, it should have printed something out like "listening on port 1234"
Yes, that works fine
so in your browser, put http://your-servers-DNS-name:1234
if that works; great; if not, you may indeed need to talk to the admin
exactly how does it fail?
I'm guessing the sys admin needs to "open" port 8080
Is there a way to get it to load without having to specify the port
probably not; if you don't specify the port, your browser will choose 80 or 443, and place.com almost certainly uses those ports itself
another option is to get your own host, where you are the admin. It costs some money, but you get complete control
the thing is it's not my project. I just know how to build python apps, but I've never deployed them like this before
this is a big company server
I'll email the sys admin I guess
and yeah, trying to serve to port 80 or 443 gives me permission denied
well that's because you're not root.
If you try as root, you'll almost certainly get "Address in use"
Is it possible for the index.html webpage to redirect to the localhost url?
I think so -- I think you can put a "meta" tag in there that causes a redirect
hmm, I tried doing <a href="127.0.0.1:8080"> in index.html, but that gives me the error:
The requested URL /dashboard/127.0.0.1:8080/ was not found on this server.
no wait, my bad. I had a typo. Doing a link to that just loads localhost on my machine. It doesn't redirect to the localhost of wherever the app is being run from
<html>
?
<@&267629731250176001> spam
!warn @empty steeple posting market research forms is not appropriate for this channel
:incoming_envelope: :ok_hand: applied warning to @empty steeple.
hey
Hey, does anyone have any experience with Heroku.
I have deployed a Flask project onto it
and it is working correctly for the most part
However, my Flask code was generating logs files through the logging module, and being stored.
This worked fine in local environment
But on Heroku I am not able to see/retrieve those files
def get_logger(
LOG_FORMAT = '%(asctime)s %(name)s %(levelname)s %(message)s',
LOG_NAME = '',
LOG_FILE_INFO = 'file.log',
LOG_FILE_WARNING = 'file.warning',
LOG_FILE_DEBUG = 'file.debug'):
log = logging.getLogger(LOG_NAME)
log_formatter = logging.Formatter(LOG_FORMAT)
file_handler_debug = logging.FileHandler(LOG_FILE_DEBUG, mode='w')
file_handler_debug.setFormatter(log_formatter)
file_handler_debug.setLevel(logging.DEBUG)
log.addHandler(file_handler_debug)
file_handler_info = logging.FileHandler(LOG_FILE_INFO, mode='w')
file_handler_info.setFormatter(log_formatter)
file_handler_info.setLevel(logging.INFO)
log.addHandler(file_handler_info)
file_handler_warning = logging.FileHandler(LOG_FILE_WARNING, mode='w')
file_handler_warning.setFormatter(log_formatter)
file_handler_warning.setLevel(logging.WARNING)
log.addHandler(file_handler_warning)
log.setLevel(logging.DEBUG)
return log
Hey,
I'm using Django, and I've already defined a DetailView for my blog posts. However, I'm looking to create another view that filters for the specific users posts so they can refer to them. Is the best way to do is via another view that utilises DetailView?
What I was thinking was to implement it this was this way:
`class YourOwnPostDetail(DetailView):
""" Shows authenticated users their own posts. """
model = News_Post
template_name = 'user/posts.html'
context_object_name = 'post'
def get_queryset(self):
user = get_author(user=self.request.user)
qs = super().get_queryset()
return News_Post.objects.filter(get_author(user=user)`)
Of course, this is not the finished product for the class. What would you guys think?
Django newb here. I've been regularly getting this error that says "django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings." What's causing the error, and how do I define the settings module?
If it helps, the error most recently occurred when I was try to print the contents of some models I had made to make sure they were made correctly. Here is the exact code:
`from models import Songs
for i in range(500):
song = Songs.object.get(rank = i)
print(song) `
It's occured other times as well, this is just the most recent
add ur app in INSTALLED_MODULES didnt read the message until the end
having no experience with web-dev, would you recommend flask or django for the beginning?
django
watch coreymschafer for a startup
on yt
@topaz charm actually, are you running the command python or py manage.py shell? running python is wrong
@maiden tulip It really depends on your use case. Django is more battery complete, Flask is easier to pick up and can be extended if needed. There is not really a "this is better". Especially if you are working with dynamic media files, Django can be very painful to use.
I personally prefer flask because it is a lot more straight forward than Django
i prefer django because my needs are just
it can be done with flask too i believe, but for me its more efficient using django rather than flask
In many ways Django is alot heavier than flask
flask will nearly always be more lightweight and more efficient than django as a framework
they differ in how everything is configure e.g Django's orm
you mean than django
yes ty
@real hare ListView is something you may want to take a look at
@topaz charm in your projects root directory you should have a manage.py and a settings.py file
in there is your INSTALLED_APPS you need to add your app into this list. When runserver is called your app will try to load and attach each apps module to your application. So in installed apps you can define where to point to your apps.py config class, which defines the setup for your individual apps
Hey is it better to use flask or django for a REST API
it depends
you can use either
Flask is more lightweight and would probably be simpler for you
Django can be a bit overkill for a simple rest api
@terse surge , yeah I was running the command python. Whatβs the difference between this and the shell, and why should I run the shell?
Directly typing python, just starts the interpreter.
Using manage.py within a django project sets the environment so that you can interact with your project objects in the shell. As noted here:
Weβre using this instead of simply typing βpythonβ, because manage.py sets the DJANGO_SETTINGS_MODULE environment variable, which gives Django the Python import path to your mysite/settings.py file.
@topaz charm
by using the django shell, you get access to explicit model methods which allow for easy access(queries, calculation, etc). If you are using the python shell, then you will have to connect to the database first (example is using sqlite3 lib if ur database is sqlite) ,and then run sql commands to fetch the tables and so on, the django shells makes it a lot easier
^ its true too, but for a more accurate answer its my answer above
yep
just telling that both ways are possible.In the end of the day, its just a database which can be connected to
with flask, how can i redirect an user to a different page? return redirect()
it says NameError
NameError: name 'redirect' is not defined
from ..idkwhere import redirect
u need to import it i believe, at least in django
from flask import redirect
return redirect("http://www.example.com", code=302)
np
web dev question in #help-pineapple
@quick cargo alright thank you
anyone know what the best way to build just a web store would be? like ecommerce site without the payments portion? which technologies would work best/easiest
can someone help me figure out
how would i go about deleting an old profile picture saved to my database
so once a user updates their profile picture, i want to be able to delete their previous one
because it takes up space on my drive
im using flask
on_delete=models.CASCADE
should be about the same for flask
add it on
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
oh
above
says
if the user is deleted
delete everything else that is associated with it
ive done some research
its prob on_delete=models.CASCADE
there is no one else saying whats model.CASCADE in flask
a clearer example of models.cascade
A died
b: "I CANT LIVE WITHOUT A" commits suicide
hope ive made it clear for u
@terse surge , Would it possible to run the program I wrote above within the shell, or something similar? I should have 500 instances of my "Songs" model saved in my database, and I'm trying to make sure this is true/ and that they were saved in the correct manner. I was trying to do this by printing out data from the models, but I'm not sure how/if I can do this in the shell
yeah
it would work
I dont know how to make it work on python shell too
but
for now
use py manage.py shell
u would write
instead of Songs.object.get u can delete for I in range(500): and do song = Songs.object.all() and then print it
prints all songs
@dark hare Thanks, that's what I ended up implementing
hello
has someone here used sanic
do you know how i can make a route that's like
/app/*
so everything like /app/folder and /app/thing get redirected to the same route
@native tide I guess @app.route('/app/<path_arg:path>')
another thing
how do you do redirects to another website
like for example redirecting to http://example.com
return response.redirect('http://example.com')
I dont know why it puts %27 there
It suppose to be a '
@native tide I recommend you to look at the docs. Both your questions are answered in it. https://sanic.readthedocs.io/en/latest/sanic/response.html
i love every web dvlpr π
ty :)
I'm sure this gets asked a lot, but I want to transition a TK app into a webapp, using as much Python as possible, and touching the least amount of HTML as possible. Anyone have tips where I could start?
How do I transfer data from a model unto a Django template? I need to pull different fields of my model unto different parts of my template, but I'm not sure how to do this since the values() function returns a querySet.
This (incorrect) code gives you an idea of what I'm going for, using dictionary notation:
<h1 class = "rollingText">#{{entry.rank}}: {{entry.title}}</h1> </div> <div class = "row"> <div class = "col-sm"> <img src = "{{entry.cover }}" alt = "Single Cover"> </div> <div class = "col-sm"> <p> <strong>{{entry.releaseInfo}}</strong> <br> <br> <strong>Artist: </strong> {{entry.artist}} <br> <strong>Writer(s): </strong> {{entry.writer}} <br> <strong>Producer(s): </strong> {{entry.producers}} <br> {{entry.description}} </p> </div>
@topaz charm did you follow the Documentation before asking the question??
This is haa got all your answers !!
always try asking questions after you've checked out the basic documentation π βοΈ
class Usertesting(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(username='testmanhaha', password='test123', email='testmail@tests.com')
# self.client.force_login(self.user)
def test_login(self):
print(self.user)
res = self.client.post('/login/', {'username': 'testmanhaha', 'password': 'test123'})
self.assertEqual(res.status_code, 200)``` is this test wrong?
I get 302!=200. I am doing it wrong or should I actauly assertEqual(status_code, 302)
I'm using flask. How do i post my table as a form to the server?
@opal shale you want to display the table data on your page?
Nope. The table acts as an input(some fields are editable) and then I want to send the edited table to my flask method as a POST Request
I have a local web server. It is in flask. This web server lives in a computer. This computer is connected to the internet. However, I cannot accept incoming connections from the internet to this computer because it is blocked by a firewall. I do not have the privilege to allow incoming connections.
I also have a remote web server. This is also in flask. I have total control over the remote web server.
How can the remote web server send requests to the local web server?
Any workarounds are ok too. But speed is important, it needs to immediately respond to requests.
When the remote server received a foreign http request, it needs to request computation from the local web server
For example, maybe a workaround is for the local web server to log in to the remote web server and keep reading the http logs every second and if there's a change it would push the payload
one solution is to disable firewall
I'm using someone else's wifi
To be fair I'm just assuming it doesn't accept incoming connections I've never actually tried
ur using someone's else wifi to run ur server?
Yes
Hey, how can I check someones permissions in discord, from a django website?
first
Nothing illegal about it
The payloads are tiny
1kb
It's just the computation that's heavy
The wifi even goes offline for days but it's cheaper than cloud computing
your local server runs on your laptop or something?
I'm buying a desktop for it
I'd test on my laptop first for the networking part though
Before buying
did you check how the alternative would cost you
Cloud is $11/day
Desktop is like $1500
also
hetzner
is wayvbetter
2$/month for 2gb vps
theyre won many gold awards
theyve*
ah yeah it adds up quickly
i think you should try to see if your school allows it
I can try
i guess it use ports and if thoses are not open you're toasted
They are really bad at network maybe they don't even have a firewall lol
im no network expert
in my experience they close everything so they have less problems
aka no gaming no peer2peer
My school allows gaming
A lot of gamers
But I don't know the specifics
I don't know much tbh
Kek I'll just try inbound connection as a first resort haha
I think this question goes in here but I working on a project where I like navigate to webpages and like click on buttons on the page and so I would have to use selenium to do that right?
Most probably yes
Bet thanks
Hey anyone familiar with scraping Xpaths?
I have a script that scrap by Xpaths and it's not working for specific website.. I think I don't create the Xpath well
Im trying to get the price value in this page
this is the link: https://www.xbox.com/he-IL/games/mortal-kombat-11
but It's doesn't works, I tried this xpath .//span[@class='priceareas priceareaStandard pricedl']//*[@class='leftCol']//h4
Hey guys, when using django, is it possible to run query that sum records which are same value of field that is different than each other? for example
class Track(models.Model):
title = models.CharField()
disc = models.CharField()
class Report(models.Model):
track = models.ForeignKey(Track, on_delete=models.CASCADE)
So in this case i wanted to get sum of all disc 1 's track report
can you rephrase the question?
@tiny siren ```py
<link rel="icon" href="<ImagePath>" type="image/gif" sizes="16x16">
add to your HTML file
I want to make a navigation bar, the method I use now doesnt feel scalable of detecting om which page I am, currently I use a variable current_page and use if loops, I would be happy to hear suggestions for a scalable design of that
thanks @pliant falcon
yw
Hey guys, i'm looking for real restful django projects for practising my skills. Please if you have, then send me
you can also try #680716760134975491 if you looking to start a project based on it
@last hull
can someone explain what wordpress developers do
doesnt setting up a site with wordpress not require coding
Hmm
It might depend on the company, but I'm mine, 'wordpress developers' are usually the php guys
they modify the style to the client's needings
sometimes, when they have special needs, they write their own plugins in php
doesnt that not require coding though
like isnt wordpress just like wix or something
yeah ik
for example, woocomerce, manages all the payment stuff
yup
sometimes the client needs more specific stuff and needs to be programmed
but thats occasional
fairly common in my company
and when what the client needs somethign that cannot be achieved with wordpress
because it'd be extremely bloated with plugins
they hand those projects to my team
and we do it in django
and is that only for one part of the site
so you custom develop a certain part of it but the rest is still on wordpress?
sure thing
that's actually my current project
we use wordpress for the 'CMS'
for the blogs, news and such
and then for the more complex stuff, django
although I'd rather make everything in django
but not my call
wordpress development seems easier than other programming jobs
it is
but they often do more than 'just wordpress'
again, it might depend on the company
alright, thanks for the info
NP
django is python right
but I heard python is really slow, so why is it used for websites?
Wordpress development is not necessarily easier than any other programming jobs.
It just depends on what features you are trying to build ontop of wordpress
Can be any complexity pretty much
@somber crater Because python is fast enough for most tasks
its alright but I think a light theme would be better
alright ill do that thanks
first i need to find out how to make an optional dark mode button XD
time to google
I prefer dark mode
Can someone help me
sanic is messing with my responses
request failed, libcurl error: 18 (Transferred a partial file)
I'm trying to make a flask web app with logins for two different roles: vendors and customers (each have different attributes). I'm having a hell of a time figuring out what to do... I'm supposed to do it with mongodb atlas (mongoengine is what I'm currently using to interface) and Flask-Login or Flask-User, but I can't figure out how to really use it. I know how to do it with sessions, but I don't want to π bc I think it'll be a bit more insecure. Any advice?
Iβve not used FlaskUser but checkout FlaskLogin + FlaskSecurity (which may be abandoned though I think thereβs a fork).
perhaps a dumb question but i am adding a relationship to one of my entities that is one-to-one to the User auth model. However, I want this relationship to be ignored for admin users, how would that work?
when i tried and create a migration it is asking that my superuser had the relationship. in this case would i create two separate models. something like AppUser and AdminUser?
Bit of a stretch here, but does anyone here know of a way to throttle API key requests in Django?
https://i.imgur.com/8Ud093F.png
@distant trout the pink on the right doesn't fit imo
@distant trout dark template is ok. But the pink bar is orribile,change it ahah. And i suggest change the colour of navbar to blue (primary in bootstrap). Red is not bad, but it let me think about alert, errors.
hello
i have a php script that I would like to run on all of my websites pages
how can i do this?
or can i even do this
so i want the php script to run on each page of the website before any other script on that page
I wonder how you could simulate/use an existing domain on your localhost. Can someone help me out with that?π
i got it
for anyone interested
i added: AddType application/x-httpd-php .htm .html to the .htaccess file
@rancid stump You can edit your host files to make any domain point to your local IP I guess.
Ah it didn't work on chrome apparently thanks! But is there also a way to have access to both the localhost and the original website where the domain is from? @dawn ore
https://i.imgur.com/8Ud093F.png
@distant trout I love the colour theme.
Just make an Option when you can choose the theme? Unless you cant do that with websites.
When I render a template using flask, is the template name passed as a variable, and can I accss its value from within my template?
@limber laurel No but you could quite easily parse it via context
@lilac rain There is a million tutorials on google
Win10 is notorious for ignoring host file
https://stackoverflow.com/questions/15871391/implementing-flask-login-with-multiple-user-classes Can anybody decode the third answer here for me? I'm trying to do something similar, but don't know how to connect SchoolAccount (or should I just connect User) to Flask-Login
@quick cargo what does that mean?
Oh request.endpoint is a thing
Is that what yiu meant by that?
does anyone knows tutorial for making login system?
@fickle fox A quick search turned up these results:
https://flask-login.readthedocs.io/en/latest/
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-v-user-logins
https://www.digitalocean.com/community/tutorials/how-to-add-authentication-to-your-app-with-flask-login
https://www.youtube.com/watch?v=8aTnmsDMldY
I would suggest searching before asking. There are tonnes of resources online.
If someone requests an invalid page from my django-rest-framework ListAPIView, I want to catch the exception and just send them the first page instead. Is there a way to do that?
@fickle fox you using flask or django?
flask
do you have any code?
i managed to do my first login yesterday
and registration system
oh nice thanks π

i think you can do without wtforms
but it's better when you learn how to use them, the form.validate_on_submit(): is very useful
you definetely can do without it, but using it is really simple
oh okay 
i'll get an snippet
<form method="POST" action="{{ url_for('site.login') }}">
{{ form.csrf_token }}
{{ wtf.form_field(form.username) }}
{{ wtf.form_field(form.password) }}
<input type="submit" value="submit" class="btn btn-dark">
</form>
if you have flask-bootstrap, you can use this:
{% import "bootstrap/wtf.html" as wtf %}
it's to enforce security, "Cross-site request forgery"
ooh okay
spent 5 hours yesterday figuring out how to implement login system
it's tricky the first time
the worst part was to understand @login_manager.user_loader
after that, it was okay
Hi, i guess my question fits here, does someone have any experience in developing QGIS server plugins?
Anyone know absolue xpath extraction tools or any videos (not using selenium) in python
using beatifulsoup,lxml (I would like to capture the xpath structure from element data)
I dont know if its related to this channel but how you make ads run on your site?
And how they calculate ads per click on site?
take a look on the developer docs for the ad service you are planning to use
I currently have an array full of json scripts scraped with beautiful soup, how do I find the find the json file that has "birthDate" in it?
guys is it possible to share data with android app and site???
like display everything same show all data from db
yes
like social media's apps, app and website?
yes @fickle fox
how???
and with what type of db?
i want to create site with flask
and app is myb java or c++
oh hmm okay
just make sure the backend is reading/writing the same data
for both the app and site
what type of db is good for things like that?
oh okay
Guys, im using flask as the backend running on a server
how do i include header files into the html
i get linking a css file for instance but using this "<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css')}}">"
not just header, but external html files so there isnt big chunks of repeated code
@native forum i think u make a layout page
with the html thats supposed to stay same throughout ur website
then u can use {% extends 'layout.html' %}
@native forum i recommend u watch Corey Schafer flask tutorial
really helpful.
thank you very much @distant trout
π
https://stackoverflow.com/questions/15871391/implementing-flask-login-with-multiple-user-classes Can anybody decode the third answer here for me? I'm trying to do something similar, but don't know how to connect SchoolAccount (or should I just connect User) to Flask-Login
I wouldn't suggest inheritance between sqlalchemy models, it can get pretty hairy using advanced features like polymorphic_identity
Hi guys, I'm pretty new to web development and I'm currently trying to use the spotify API in python using the requests library. I'm trying to get an access token and the guide uses this curl request: curl -H "Authorization: Basic ZjM...zE=" -d grant_type=authorization_code -d code=MQCbtKe...44KN -d redirect_uri=https%3A%2F%2Fwww.foo.com%2Fauth https://accounts.spotify.com/api/token
How can I make this kind of curl request using Python's requests library?
If someone requests an invalid page from my django-rest-framework ListAPIView, I want to catch the exception and just send them the first page instead. Is there a way to do that?
Hello
Is there a way to not send content-length header on sanic?
It's interfering with curl
can someone delete that message above <@&267629731250176001>
i tried this, but it doesn't work
Hello world,
can I use the Django admin interface to allow customers to manage their personal accounts or is it just for admin use ?
for example if I create a shopping site can customers manage their accounts through the django admin interface ?
I plan it out. I write the python. I host it somewhere. Flask is usually involved.
Broad question. Broad answer. π
lol
working on a flask web server, I have a bunch of stuff for logging in that works, but at one point I reditrect the user to http://127.0.0.1:5000/accessdenied (testing rn), which looks like this:
@app.route('/accessdenied')
def access_denied():
return render_template('access_denied.html', home = url_for('login'))
however when I load that page, I immediately get redirected to the Not Found page
im very confused, anyone got any ideas?
and yes, access_denied.html is in my templates folder
and I know the other things in the templates folder are getting picked up because at one point I render a different page for the user and it works
scratch all the previous stuff, I figured that out. I am now struggling with getting the flask app which is just running locally to be available externally, through port forwarding
the port forwarding is all working, and I got everything set up properly to where when I have the ap runnnig, I am able to use https://canyouseeme.org/ to confirm that the port is listening only when my app is running
however I am unable to connect it, even after turning off debug mode
actually, I managed to get it
pls help
<img src="./myimg.png"> or <img src="/myimg.png"> or <img src="myimg.png"> ?
@rustic dragon it depends on its place so if its in the same directory(with the template file) you gotta use this <img src="myimg.png"> if its in a folder in the directory or not in the directory at all you gotta use this <img src="folder_path/myimg.png">
so in the second one you just put the folder path
How do I get my application object into my html template
@limber laurel what are you using?
Flask @feral minnow
so when you do python return render_template("file.html",obj=your_obj) and when you want to add it to html you gotta but it inside something like this {{obj}}
Guys anyone know how to change the text color for a bootstrap navbar?
Hey, I'm trying to build a server with flask and when I run it using the 'flask run' command in powershell it works. However, debug mode is off. When I use the 'set FLASK_ENV=development' command I get no errors and it seems to work. However when I 'flask run' the debugg mode is still set to off. How do I fix this?
@native tide ```python
if name == "main":
your_flask_object.run(debug=True)``` this should work
It's not working
@native tide Can i see you code?
ohh,when I said "your_flask_object" I meant "app" because its contain the Flask(__name__)
It worked?
yes
@feral minnow Yeah but I want to do that in my base remplate and one of the reasons why I want to do it is so I wouldnt need to return a object like that everytime I render a template
what is the object your trying to add?
application
I want to access app.url_map from my template
For my header so I cpuld loop through them without worrying if their names don't change
@limber laurel can you show me an example because im not sure im understaing?
@native tide try this https://pypi.org/project/Flask-Debug/
So lets say I have my base.html template, which includes the header elements
I want to loop in the html
{% for url in app.url_map.iter_obejct() %}
if url == current_url:
Dont render
Else render the button for the navigation bar
@native tide I think you have to put it if __name__ == "__main__": app.run(debug=True)
@limber laurel hmm,I can't think of anything,because when you want to render the template you're calling the template you want and it just make a copy for "base.html" I think.
@native tide So you have to put if __name__ == "__main__" after you done the work so like under every function
ohh
ok I found that the command is actually $env:FLASK_ENV = "development"
which is different then what the documentation gives me
but it works with that
nice, for me I just added debug=True and it worked but I don't know why it wasn't working like that with you
i don't know
I don't need the if statement at all
when I use this command
it works eithe rway
yeah I think this will work too but I add if __name__ == "__main__" because they say its a good pratice,I still don't understand the reason for that tho
@feral minnow Its because when you deploy it you dont want it triggering the app that way
it stops it getting started when another app call the file
oh so when another app that has this code if __name__ == "__main__ the first file will stop working
@native tide np
!d main
'__main__' is the name of the scope in which top-level code executes. A moduleβs __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.
A module can discover whether or not it is running in the main scope by checking its own __name__, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:
if __name__ == "__main__":
# execute only if run as a script
main()
``` For a package, the same effect can be achieved by including a `__main__.py` module, the contents of which will be executed when the module is run with `-m`.
@quick cargo I will try to understand more,thanks π
@feral minnow Ok, ty for your help, but I guess I will continue my search to try and find a way I could import it into a html file without creating a a variable on render.
@limber laurel Np,good luck.
Guys I want to make an auto fit text,anyone know how to do it with html?
nvm,I just found the answer font-size:10vw
If anyone wonders what 10vw is, it's the view port units, in this case, view width
1 vw is 1% of the viewport width
I still have a problem
the list is not fitting
.manga-text > ul {
display: block;
margin: 0 auto;
text-align: left;
width: 40%;
font-size: 18px;
}
.manga-text > ul > li {
white-space: nowrap;
}```
here's the css code
I can use font-size:wv but when i use its either too big or too small
could I have a picture of the actual thing?
Something is wrong then, it should resize.
Inspect the element and make sure that the font sized is in vw
no no im not using vw here
if you see the code above
here's how it looks like when im using vw
also im using font-size:1vw if I put more than 1 it will too big
make media querys with breakpoints
I actually don't know how,I don't work with css too much... can you tell me how?
basically a media query is a piece of css code that does this
if width/height is x
you set element properties
and breakpoints
are general width sizes where you usually make changes
like, phone width, tablet, computer screens..
You are probably better off reading about it here, https://www.w3schools.com/css/css_rwd_mediaqueries.asp
Yup I will have a look thx
When I read about celery best practices, I often see people saying to use db keys instead of actual objects. but this means the data in the db can be changed behind the scenes so it's fraught with race conditions. You could even have data changing between retries. It's even more puzzling because the same best practice blogs say that the tasks should be idempotent. Having all your arguments up front and constant is nessesary for idempotency since then you know you are indeed doing the same operation. Further, if you put data in the db and then look it up in the task then you have multiple writes. if you chain tasks then each one is hammering the db. it seems like this advise is completely backwards 100%.
I'm not familiar with celery (disclaimer), but the articles I've just looked at mention two things:
- You can't very well share ORM objects tied to a database connection between different processes that each have their own connection
- The data may get stale in the meantime
To me, it sounds like it's mainly talking about another issue that the one you're facing: Let's say you're trying to send an email to a user, the user updates his email, then you want the freshest copy of the data instead of having lingering tasks that fall back to the stale data they copied "some long time ago".
At the same time, if stale data isn't your concern and you want to minimize the number of database reads/writes, maybe passing the actual data isn't as bad
I think part of the issue is that celery might use pickle which isn't particularly fast. and using complicated orm objects might make perf not great. and people who dont care might try to send a db cursor over the wire which will indeed fail. or even a query result which could be a stonking huge list.
Anyone can suggest tutorial for,
Django + Graphql Api
https://gist.github.com/mastermeerkat/200747bc51aaa69ce0ad96b5c7a67d23#file-gistfile1-txt
Hey, this little snippet is super slow. Anyone got a clue what im doing wrong?
I want to teach myself django. But currently I have no inspiration of a project that would use Django. Also, I dont know how much other Tech I would need - for example, if I want to build an own website, what else do I need besides Django? Do I need to know JS, Angular, etc? Where to get started?
If you know JS/ANgular, DJango might be too much
I dont know them
If you want to do web, you will need JS (and by that extension, something like React/Angular)
JS Single Page Applications are new hotness
which book would you guys recommend for learning Django
i want to start learning Django
I picked up William Vincent's Django for beginners but i had a hard time following along.
So i rather choose a different one
I don't know
I'm also learning django.
Can someone suggest me a good book for learning Django or the documentation is sufficient?
This is by far the best series that is not "just do what i do" and explaines pretty good.
@earnest osprey Books are generally much better but I suggest you to check this out. Btw which level are you in like beginner or intermediate.
beginner
@native tide Are u also learning django?
yes
So how long have you been programming python
Bc if you are a 10 day coder even though you have learned all the things experience is important
two years or one year
OK
then ok i guess
π
I am beginner to intermediate
ok
and idk why but the complexity that django has over flask makes it hella lot nicer to learn django if you ask me but the reason i asked is that a lot of beginners complete a tutorial series and without experience go straight into writing complex code. You gotta know the basics really well. That's a mistake that i did when i first started coding.
That's the thing that sets up the line between a professional devoloper and me. Maybe except modules we know the exact same thing but he can use it better. Its kinda like we have the same car but he is an f1 pilot and im the regular driver on the rode
Hmm
