#web-development
2 messages · Page 230 of 1
I use React, Next with django and its good.
View the SOURCE CODE:
https://codepen.io/dcode-software/pen/vYpJXmG
In today's video we'll be building an exercise (workout) tracker with HTML, CSS, JavaScript and Local Storage. This project is perfect for beginner/intermediate JavaScript developers.
🏫 My Udemy Courses - https://www.udemy.com/user/domenic-corso/
🎨 Download my VS Code theme - ...
Hello
How is it possible to implement HSTS in Flask, please?
So make it?.........
Take a look at this maybe: https://github.com/GoogleCloudPlatform/flask-talisman
Just this or there is more? 🙂
from flask import Flask
from flask_talisman import Talisman
app = Flask(__name__)
Talisman(app)
Sir but I don't know how to do it
The default configuration:
Forces all connects to https, unless running with debug enabled.
Enables HTTP Strict Transport Security.
It says it does
Maybe list the features you want to make here
This is a good tutorial
thank you, i will try to destroy my app 😄
thank you sir I will have a look
what is that supposed to mean? I don't humour sometimes 😂 😅
No worries, and please don't call me sir 😅
It is easy to create a web app, but the same web app should also work after implementing some security features 😄
Sir in my fitness app there should be steps counter, calories counter, workout plans or a app like healthyfime
You want to make an app or website?
Guys, do you have any recommendation to add to my first Flask project? https://hwizlh.herokuapp.com/
Make a check if the email has an @example.com
dont let the user enter fooba.example.com
make the check in backend
Alright
You can implement this check in HTML as well. With this you can check before the user presses Submit
but everyone will be able to modify the HTML and bypass it.
This is why you should also make the check in back end as well.
Yeah, I know about that, I'm also using password_hash, but since it's just a project for an internship I'm not really concerned about issues like that.
No one will use this but yeah, I'll look into that, thank you mate!
A website
even if it is internal, there will always be at least one person with malicious intents, just for the lulz.
if it is internal, it is better, because you can force users to enter only one type of email address.
This is my check, it only allows foo.bar@google.com
import re
googleemail = re.compile(
r"(\.|^)[\w]{0,64}(\w+[\.]\w+){0,54}@(google)\.com(\W|$)"
)
Thank you mate for the help
On the other hand, what do you think about the project? I know its not extra complex but im coming from frontend and I've learned a ton about flask and python making this.
I am not the right person to go into more details about it. I am new to flask myself.
from my pov, the mail seemed like an important subject . 🙂
Ah sure, I really like flask tho, it's pretty good.
I sometimes wonder if it would be a good practice to put an NGINX reverse proxy in front of the Flask App.
and implement the security features in NGINX rather than in Flask
Well... Why not?
If u find them sufficient
The point of flask Auth only in better flexibility
Sorry, i do not understand this.
flask gives you ability to make ANY auth solution, which will be within same programming language attached for example to database for adding/removing users
or in any other way... you can implement any type of auth
attaching/removing cookies to the sent requests to flask, which will persist auth
or any data you will input to JWT tokens
Flask has 100% flexibility to make any kind of Auth
Nginx will allow only really limited auth, for example i often protect admin services with at least basic auth from Nginx
you can probably try hooking some other auth things, using nginx, but it will be... ugly monstrocity between different kind of systems
in best case, it will be highly likely making only hard coded user system which stores data directly at hard drive where nginx is located
So... really limited options to auth system with Nginx
and consider in addition that you are limited only to FREE version of nginx ;b
if Nginx is enough, sure, do it. But if you need any complexity beyond 1-3 users, better to use flask
I was thinking mostly in securing the web app with an Nginx or as a Reverse proxy
Something along these https://www.acunetix.com/blog/web-security-zone/hardening-nginx/
But i see that there are multiple Python modules for doing these ( Talisman Flask, Flask SSLify, etc - the hard part of this, is that i have to find them 😄 )
Ah, u will need to do it anyway
Because... If u use flask with templating html stuff, u need to serve static files with nginx
And reverse proxing the rest of stuff into your gunicorn server
Although even when using flask as rest, u a still probably required to put nginx in front
at least if u wish stuff like before framework caching
any project ideas?
I found these good for learning purposes:
- Blog Website with auth, comments and crud.
- Real time messaging app
You could do both of this with either just flask,django etc.. or make an api with that framework and connect with a frontedn like react/next.js(this would make it a fullstack project)
that dopamine rush everytime when you solve something
it remains even after a year sheesh
https://github.com/Twxtter/Twxtter-main/blob/92a881279a795016a59a817e1a1a9ed3145896da/twitfix.py#L786 - https://paws.aaw.ooo/57tcy1.png
https://github.com/Twxtter/Twxtter-main/blob/92a881279a795016a59a817e1a1a9ed3145896da/twitfix.py#L825 - https://paws.aaw.ooo/o1deux.png
So the code is recognising appNamePost, but then not applying it to appname.
The config for appname is https://paws.aaw.ooo/ewp028.png, and this is what it's setting ti to as an output https://paws.aaw.ooo/ymeegr.png
Need help understanding why.
trying appname=f"{config['config']['appname']}{appNamePost}", also doesnt work
which leads me to believe that something isnt taking the template when it should be
Any ideas?
twitfix.py line 786
print(" ➤ [ T ] vnf type is Image")```
`twitfix.py` line 825
```py
appname=config['config']['appname']+appNamePost,```
hi i need help with flask development and sql?
i would like it to post products as a product card here, however, they aren't showing up and not sure why
code for the html layout:
{% extends "layout.html" %}
{% block content %}
<h1> Asad's Shop</h1>
<div class="shop-container">
<h2> Products </h2>
<div class = "dropdown-menu">
<a class = "dropdown-item" href = "{{ url_for('home', query= 'price-high')}}">Price - High to Low</a>
<a class = "dropdown-item" href = "{{ url_for('home', query = 'price-low')}}">Price - Low to High</a>
<a class = "dropdown-item" href = "{{ url_for('home', query = 'Eco-high')}}">Eco - High to Low</a>
<a class = "dropdown-item" href = "{{ url_for('home', query = 'Eco-low')}}">Eco - Low to High</a>
</div>
<div class = "card-deck">
{% for products in product %}
<div class = "product card">
<a href = "{{ url_for('products', products_id=products.id) }}">
<img src = "{{ url_for('static',filename='products_pics/' ~ products.id~'.jpg') }}">
</a>
<div class = "card-body" style = "height: 20%">
<a href = "{{ url_for('products', products_id=products.id) }}">
<h3 class = "item_name">{{ products.title }}</h3>
</a>
<h5 class = "item_price" style = "colour: black"> £{{ products.price }}</h5>
<h5 class = "item_eco" style = "colour: black"> {{ products.eco }}</h5>
<p class = "item_description" style = "colour: black">{{ products.desc }} </p>
<a href = "{{ url_for('home', addBasket=products.id) }}"><button type="button">Add to basket</button></a>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
from shop.models import User, Product, Basket
from flask import Flask, render_template, url_for, flash, redirect, request
from shop.forms import sign_up, login_form, checkout_form
from flask_login import login_user, current_user, logout_user, login_required
from shop import app, db
@app.route("/")
@app.route("/home/<string:query>")
def home(query=""):
products = []
Product.query.all()
if query == "price-high":
products = Product.query.order_by(Product.price).all()
elif query == "price-low":
products = Product.query.order_by(Product.price.desc())
elif query == "Eco-high":
products = Product.query.order_by(Product.eco).all()
elif query == "Eco-low":
products = Product.query.order_by(Product.eco.desc())
return render_template("home.html", products = products)
db
help would be greatly appreciated thank you very much
this part:
<img src = "{{ url_for('static',filename='products_pics/' ~ products.id~'.jpg') }}">
take a look at it again
i wasn't quite sure how to use images, i was thinking if i make it a sql row as well, and have it stored there
i'm kinda lost
just for testing, put an image into your static folder
then
<img src="{{url_for('static', filename='something.jpg')}}/>
Don't really think you can make a relationship between SQL and an img src command haha
ah solid i've got a few pictures already, i'll change the filename to that then
oh wait hold, i decided to change the folder name a while back to just pics
i'll try it now
changed it to 'switch.jpg' and nothing came up
Yo. I need to create a YearOnlyField, and be able to filter by from_year & to_year. How would you do this?
can anyone recommend me a good resource for learning about escaping flask & html?
So I have this XML file, and when parsing with lxml I get element names like {urn:oasis:names:tc:opendocument:xmlns:container}rootfile
I'm trying to match with xpaths on just the rootfile part
hi flask users, what does this error mean
{% extends "layout.html" %}
{%block content %}
<h1>"{{product.title}}"   </h1>
<div class = "item-container">
<div id = "image">
<img src="{{ url_for('static', filename= 'pics/' + product.title + '.jpg')}}" width = "400" height = "400">
</div>
<div id = "info">
<p> Price: {{product.price}}</p>
<p> Ecological footprint: {{product.eco}}</p>
<p> Description: {{product.description}}</p>
<p><a href="/add_to_basket/{{ product.id }}" style="background-color:black;">Add to basket</a></p>
</div>
</a>
</div>
{% endblock content %}
@plain kettle hi
show your route response
what are you returning from the route
remove the ()
it's treating product as a function
...or it is a function
ah hi thank you for your help
the route is this:
@app.route("/product/<int:product_id>")
def product(product_id):
product = Product.query.get_or_404(product_id)
return render_template("product_page.html",title = "Product", product = product)
wait i fixed it
it turns out i mistyped the product as products = Product.query
I've come up with a really good solution: I just deleted the registration option from the app, so there is only login option. I have a user for the app so I'm the only who has access to the content. So it's fine because I can present it during the interview and I won't be able to store any user data outside of it. What do you guys think?
thank you for the help @eternal kestrel
np @plain kettle
Hey, is anyone offering web design? And if so what prices?
I know a guy if you are interested, pm me
I did, you didnt respond lmao
hi again stuck on registering
everytime i register on my website, it clears away the password field, seemingly suggesting it does not like the password
@app.route("/Sign_up", methods = ["GET","POST"])
def Sign_up():
form = sign_up()
if form.validate_on_submit():
user = User(username=form.username.data, password = (generate_password_hash(form.password.data,method='sha256')))
db.session.add(user)
db.session.commit()
flash("Sign up successful. Enjoy")
return redirect(url_for('home'))
return render_template('Sign_up.html', title = "Sign up", form = form)
this is the routing
{% extends "layout.html" %}
{% block content %}
<form action = "" method = "POST">
<section id = "username_new">
{{ form.username.label }} {{ form.username }}
{% for error in form.username.errors %}
<span style = "color: red;"> [{{ error }}]</span>
{% endfor %}
</section>
<section id = "password_new">
{{ form.password.label }} {{form.password}}
{% for error in form.password.errors %}
<span style = "color: red;">[{{ error }}]</span>
{% endfor %}
</section>
<section id = "password_confirm">
{{ form.ConfirmPass.label }} {{ form.ConfirmPass }}
{% for error in form.ConfirmPass.errors %}
<span style = "color: red;">[{{ error }}]</span>
{% endfor %}
</section>
<section class = "">
{{ form.submit() }}
</section>
</form>
{% endblock content %}
the sign up
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(15), unique = True, nullable = False)
password = db.Column(db.String(50), nullable = False)
def __repr__ (self):
return f"User('{self.username}')"```
the database
anyone have experience deploying flask app on raspberry pi to web?
so i was watching corey schafer's tutorial part 2 where he talks about bootstrap and the things he pastes into his code from the bootstrap website is different from what i'm seeing in the website, what do i do?
(flask btw)
well do i copy paste corey schafer's version code or do i copy the latest one in bootstrap website
i'm assuming that there wont be any difference in code syntax if i use the newer version?
I’m making a flask app rn and I’m wondering what’s the best practice for making web apps. When using a database like SQLAlchemy or SQLite3, should I make a REST Api to go along with it? Or is it not necessary?
hey, how can i go abouts creating sort of pagination for a Chat App ( Using Django Channels) whereby when visiting a chat room, only e.g. 10 messages are loaded and if the user scrolls through the chat log, every time they reach at the top load another 10 and so on depending on how many messages have been saved in that chat room.
django-channels question
How can I read cookies from a WebSocketConsumer
hey guys is it possible to create just backend projects with django?
Yep , you can create api's with django and drf and deploy it online.
okay thanks.
Hello
I am not using Flask Login.
I am using session
Is there a possibility to show an html element only if certain users have logged in?
These users are stored in a database.
Template tags like user.is_authenticated would get the job done ig.
check DRF pagination. I'd implement scrolling with React and call an api every 10 messages
iv never used DRF and React
Hey. How do I integrate a pdf reader into my website?
Does anyone know any pdf reader plugins? Not any of those comic-like ones
That'll work well with django
is it possible to use pyqts .ui files to build a website instead of directly writing html? at least with flask it shouldnt, but maybe im missing something?
My experience is mostly (now) with PostgreSQL and Django. sqlite3 is solid for getting started. But lately, I've opted to connect to a production ready DB (PostgreSQL) even for initial dev work. This saves time in the long run for me. SQLAlchemy is well regarded but I've not used. PostgreSQL is rock solid and scalable in any production scenario. As for making a REST API, that would be use case specific. I could see value in that if I've built a web app, for example, and want to also release an ios or Android app. I get asked a lot about if I've used a REST API, but my experience is doing the Django-tango and working with the ORM. As my experience grows I'm finding that serving me really well. But then, I've not as yet built a web app where an API was required. Is a REST API necessary? That depends. If you want to facilitate something other than your Flask application connecting to the DB, then yes.
I would say this depends entirely on what you want to do. If you want people to be able to consume your app as a REST API, build one. If you don't, don't. Designing and implementing a REST API is not a trivial task, but it's useful if there is a use case for it.
There are so many possibilities, I don't have a specific recommendation, but did you see https://stackoverflow.com/questions/14081128/how-to-embed-a-pdf-viewer-in-a-page ?
@golden bone @ionic raft Oooh ok got it thank you!!
I was also wondering, how come in this Tech w/ Tim vid,
he doesn’t use an API in this case? It seems like the front end needs to make changes to the backend a lot, but he doesn’t use one. Is there any particular reason why? Or is it because he wasn’t planning to deploy the website and so he didn’t use one. I’m guessing if he was actually planning to deploy it, he would have needed to make an API rather than directly communicating w/ the database right?
Welcome back to another video in this blog tutorial series! In this video, I will be showing how we can create posts and have those posts show up on the home page. I'll also show how you can view all posts posted by a single user.
💻 AlgoExpert is the coding interview prep platform that I used to ace my Microsoft and Shopify interviews. Check it...
I have not watched that particular tutorial. However, I've seen some of Tim's tutorials and he's quite good. As for your question, at a guess this would come back to the requirement being coded for. This appears on the surface to be a tutorial to walk you through creating a blog web application with Flask. Blog's are a common topic for dev tutorials because they cover core elements of web app development that will lay a good foundation (you will learn about DB and CRUD, using the application layer to work with the DB/presentation layers, and the presentation layer for the end-user to interact with the app). At a guess, I'd imagine he's not using an API because the requirement isn't there. You do not need to craft an API to deploy. I have two deployed web applications, being used by real-world clients, neither of which have an API. The second may end up requiring an API, but only if market demands push for smartphone apps.
Oooh ok thanks!! I had always thought that if u don’t use an API, it would mean the front end is directly communicating to the backend. Since in the vid he isn’t doing that in this case, how does the front end talk to the backend w/o an API?
That's a great question. My learning path to development in Python started with a 100 day boot camp where this was laid out nicely. One challenge with tutorials is that they are focused on a specific requirement and don't often get into the underlying realities. I can speak for Django, but I did spend about 1.5 months with Flask before I went to Django. However, at their heart there is a fair bit of overlap. The simple answer is that the application layer is the middleman. You build an object model to tell the ORM how to structure/build the DB. You build the view at the application level to do the talking with the DB. The view takes care of building web pages to send to the browser (the front end), and receiving user input. Your code at the application layer is really the key part in all this. The application layer (the middle) is what speaks to the back end and the front end.
Hey All,
Been fighting with a problem all day and just can't seem to figure out a solution or find one online and was hoping to get some help....
The short and long of it is I'm using flask and wtforms as a front end for a tool I'm building and I'm struggling with dynamic form creation:
I have a python list of devices I pulled from an api and I want to create a form that prints this list and allows a user to select any or all of the items in it and pass the list of selected devices back to be processed against, I have no problem printing the list but can't figure out how to make each item a selectable form field and have it append that item to a new list on submission...
I thought this would be a relatively simple task but either I'm missing something or it's a lot harder to create a dynamic form than i thought
Oooh got it thanks!! So from my understanding from what u said, using an application layer and an API are 2 ways of going from front to back end. What would it look like just going frontend to database? Would it just be like a user clicks a button and it doesn’t send any get/post requests and it just updates the DB?
Indeed, an API and the application layer are two ways of communicating with a DB. I would not advise going directly from the front end to the DB. There are good reasons for the current N-tier approach (presentation-application-data). The main one is focus. The presentation layer shouldn't include logic, it presents. The application layer does the logical grunt work. When you bring logic into the presentation layer things can become challenging.
That makes sense, that rly cleared things up!! You’ve been a huge help. So does that mean by simply using Flask, flask itself provides the application layer? And also ik going from front end to DB is not recommended, but I was wondering what it would look like code wise (so ik what not to do)
I did see this, yes. But none of these give a book-like feel. It's supposed to be used in a library app. And I want to be able to remember last read position
Any jinja gurus here?🤔
Can anyone help my donut? My donut is sad, can't find any solution that works... #help-donut
I'm a little disappointed that I put so much effort into getting my docker-compose project perfect to throw up django, postgres, nginx, cloudflare tunnel, redis... and now I get started with learning DigitalOcean to find that they don't support docker-compose. They can translate apps made with a Dockerfile into something they all their "App Platform" but like... if I would have known this, I would have spent all this time learning their "App Platform" and not how to get docker compose just perfect
And now im thinking, do I even still want to use Digital Ocean if it cant just deploy from docker-compose directly.
Does anyone have any advice for where I should get my cloud service?
I know that places like heroku and whatever will let you serve a free python app, but Im more interested in learning learning a cloud service that is a little more... reputable for real apps.
I know that i dont want to do Azure. There is what else? AWS? Linode?
please don't cross-post. this is answered in #tools-and-devops
sorry, I
realized it was not suited for here when i saw that there was a devops channel
When you send a link in a discord chat, discord usually just displays the picture / gif associated the link. How is that done? does discord send a get/post request or something to the link and displays whatever it finds?
Just curious
I'd think it would be a waste of resources to be sending http requests to every link someone sends though
It's part of a HTML document's metadata
However, yes it does send a request on every link. But it's pretty insignificant overall to do.
That's hella interesting thanks much!
It does GET. If its content-type is an image, it embeds it. If it's html, it reads the <meta> tags for opengraph properties.
https://www.opengraph.xyz/
Thanks!!
I stumbled into the exact same realization. In the end though, I opted with Digital Ocean and a Docker Image. The outcome...it is an OUTSTANDING service. I'm using DO for production deployment of Django apps in docker and I am truly blown away with the ease of management. And to be clear, there's not much time needed to "learn" their app platform. If you have a docker image and deploy, it does a very good job.
You've mentioned the big players except Google Cloud.
I've not used DO but they have VPSs right? You could run Docker Compose inside of one of those. Then if you want to gradually migrate things like the databases out if it makes sense to
I see now someone already told you that, this is why you shouldn't crosspost 😩
yeah, i didnt cross post on purpose... I just started here and I realized there was a better place to talk about it after. And I should have edited my old post if was gonna do that but i didnt.
anyway...
the main thing im discovering is that... like a few people have said, the tools they have may not be what I expected, but if I ignore them and work out of docker compose exclusively, im missing out on the power in their services.
i imagine everyone is like that.
Right now i have a mix of cloudflare and DO. I'm gonna stick with it and try to learn how they do things.
#web-development so flask ques can be asked right?
sure
oh thanks...how can the data in a html file be updated without refreshing the page
they say ajax or xmlhttp reqs and stuff
Yeah, you have to send request to your backend using javascript if you don't want to refresh the page
hm
I can't imagine using Django as not rest API.
Building Frontend without modern tools, SCSS, Vue. JS is too... Bad path in my opinion. I don't want to have dirty code appearing just because of chosen tools
.NET Core API?
hey I am quite new to web dev, I was wondering if anyone knows why I am seeing the horizontal line in the middle of my tables?
could it possibly be I am missing a closing tag or smth
Building REST API's isn't necessary if you're using django templates, otherwise if you have some sort of client app (web, mobile, desktop) you in most cases should use rest
Agreed. In the early stages of these projects the front end is mobile first. If clients demand them, then apps and rest api will follow.
I mean, if you have an app that interacts with your backend you should use rest 🤨
I am getting an error in this Flask app that I am working on. The details are in #help-burrito, please help me if you can
So I am getting another error while running the app, and the #help-burrito channel is still up so please help me :/
Hi, so I have the following question:
Say I have a website for my car dealership
and I want to give the user, the option to "recommend" cars
meaning that say some user wants to sell their car to me, they will enter their email, phone number and the car's model for example
what's the correct way to implement something like this with django-rest framework?
Do I need a separate app for this? If I do then wouldn't that result in code duplication since I will have to rewrite the car model + the user information (email and phone number for example)?
I was thinking of just creating a new class that extends my Car model class and just add user email and phone number in there
and then create a new endpoint /recommend or something which will be connected with that model
is python a good framework for web development. when i say python i mean python not django even tho they are the same thing but i don't think so
It is pretty good, but i guess it depends on your requirements
I hope this isn't needlessly pedantic, but python is a language and django is a web framework for python (one of many).
The question appears to be whether the python language is good for web development. I can only say it appears a lot of people think so. :) I haven't yet embarked on that journey. It will be interesting after many years of suffering with Ruby on Rails.
Makes sense
A couple of the strongest reasons to go with RoR were unhelpful in our case (at work) but it was only years in that we realized it. First, ORM (didn't use it - had to make it work with weird OS / architecture at the backend, so ended up hand-rolling our models in a non-ActiveRecord way). And second, the whole notion of an "opinionated framework", while I could see the appeal, actually worked against a lot of things we wanted to do differently. :p
I now believe the "opinionated framework" idea was largely a reaction against some of the flaws baked into Ruby as a language, and the Ruby coding culture at the time.
If I were to rewrite it today in Ruby, I'd probably go more lightweight (e.g. Sinatra) while continuing to use Vue for the front end (as we still do today). In Python (my hobby coding projects, not work), therefore, I'm looking to not repeat that sort of mistake. Therefore, I'm planning a webapp in Django + Vue (or if I'm up to the challenge, React instead, though I'd have to learn that first).
Hello guys, i am learning django. I'm trying to bind html with css but failed
Who can help me
I learned about Flask during a workshop.
I need help with Python
write your question
is there any discord server completely for web dev ?
anyone knows why i'm getting this error in django?
TemplateDoesNotExist
when the template does exist
Either the filename is wrong or you haven't set Django up to look in the right place
how do i set django to look elsewhere
it finds a non existing source, it does \templates\templates\
instead of \templates\projectname\
it works normally for other apps
but for this app it can't find the templates for some reason
ait ill read up on that thank you
I have a Database and Post related question in #help-ramen. Any assistance at all would be appreciated, thank you so much 😄
can anybody help me in oauth ?
hey i read up on some of this
it didnt help
django was looking for the index.html inside of templates/templates automatically so I just changed the file name from templates/appname to templates/templates
and it works now
Regarding the on-going conversation about using a REST API framework for Django verses using the ORM. If you're using the ORM you've got extra layers of protection from vectors such as SQL injection attacks. If you're using a REST API framework you had better be paying extra attention. I found this post very informative. https://www.stackhawk.com/blog/sql-injection-prevention-django/
Let's dive into SQL injection with a quick overview, some examples, and how to prevent such attacks, using the Django framework.
can some one tell me how i can read the id out of this <button type="button" id="userbtn" class="btn btn-sm btn-danger" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> that i can make my browser.find_element_by_css_selector(" ").click() click it
i got send here from generall chat but idk if thats the right place
read it how
like literally, you have that HTML as a string, and you want to read the ID?
I dont know if the web-development channel is the right one but does anyone has experience with the socketio library ?
yes
like i want the programm to click the button but i am to dumb to finde the id of it
beautifulsoup would be best
i am really new at that so pls dont blame
but if you literally just need to solve this one problem, you could get away with just some string search operations
ehh and how can i do that
so like
say we have
a = """<button type="button" id="userbtn" class="btn btn-sm btn-danger" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">"""
you could do a = a[a.find("id=") + 4:]
and that'll get rid of everything before the part where it says id="
ehhh then how
and then a[:a.find("\"")] would give you the ID
ehhh could u do that fore me
cause idk how to do that and my englisch is bad
so i am not really understanding what u mean
you can literally just copypaste those three lines of code into a file to see it working
a = """<button type="button" id="userbtn" class="btn btn-sm btn-danger" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">"""
a = a[a.find("id=") + 4:]
result = a[:a.find("\"")]
print(result)
if you put that in a file and run it, it'll print the ID
<button type="button" id="userbtn" class="btn btn-sm btn-danger" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
wait lemme try
how can i runn this
same way you'd run any python program
i runned it but it dident do anything cause i runned it wrong i guess
I think you might need to slow down a little and just go through some basic python tutorials/courses before coming back to this problem
it seems like you're lacking some fundamentals
bro pls could u do that fore me i just need that 1 line
i just need to copy paste it in then then i am done
hello
i am learning django and trying to create a voting website i am on the models part and trying to create the databases
this is what i came up with is this correct or proper at least?
what i want to create is a voting website with dynamic positions where the positions can also be altered like for voting for organization for classroom for election something like that
I'm no expert but seems ok
i don't think it applies to web development but i have this doubt on beautiful soup, i posted it on #help-potato but i don't think anyone understood what i wrote :')
Can you have a look at it please ? :)
anyone here have experience with flask?
Flask is a popular framework
can someone help me send data from my views into django class field (trying to set IntegerField's max_value) during run time....
My Django Template:
{% extends 'main/base.html' %}
{%block title%}Delete List{%endblock%}
{%block content%}
<form method="post" action="/delete/">
{%csrf_token%}
{{form}}
<button type="sumbit" name="Delete List">Delete List</button>
</form>
{%endblock%}
my function inside view:
def delete(response):
if response.method=="POST":
form1 = DeleteList(response.POST)
print(f"delete button pressed: {form1.is_valid()}")#just checking
if form1.is_valid():
""
print("valid form: {}".format(form1.cleaned_data))#just checking
return HttpResponseRedirect("/display")
else:
#form1 = DeleteList(10) -- i want to do this...and use a number to set maxVaue of a field
form1 = DeleteList()
return render(response,"main/deleteList.html",{"form":form1})
my django forms class:
class DeleteList(forms.Form):
#i was trying to make this __init__ work but seems to be buggy
"""def __init__(self,maxValue:int, *args, **kwargs):
super(DeleteList, self).__init__(*args, **kwargs)
self.fields['id'] = forms.IntegerField(label="Enter id",min_value=1,max_value=maxValue)
#id = forms.IntegerField()"""
id=forms.IntegerField(label="Enter id",min_value=1,max_value=10) #-- only this seems to work
to elaborate , am trying to do something like form1 = DeleteList(10) in my functions inside view and with the int value i pass in there , iam trying to set the IntegerField's max_value on forms class
every time this form runs , the max_value of integerField will to be different
sorry if this seems to be lengthy , do ping me if this is confusing , i can explain
Thank for anyone trying to help 🙂
anyone here who uses python in block-chain development??
anyone used quart before? im convertin my flask app to quart and i cant use request.environ any more
Any recommended Web Development course with Python?
My flask app is returning an error for some reason. The details are there in #help-cookie so please help me if you can
Hello i have a recruitment task to make DRF API for uploading images, one of the requirements are to have user account tiers like: basic, premium etc and they have more privilages by the tier. I'm wondering how to implement that? Using admin groups is ok? Or there should be some other ways?
Just based on that last screenshot before the channel closed, it looks like maybe you didn't import flask ?
Nope, that wasn't the error, in the templates files, I was using the "flask.url_for()" command to use the url_for() function but I imported it using "from flask import url_for"
That was the thing that returned an error
Anyone familiar with URL internalization in Django?
anyone has an idea why my static css doesnt work in django
i made a folder inside the app folder 'appname/static/appname/styles.css
but django doesnt seem to register it
SOLVED..
i put "{% static 'newyear/styles.css' %}" inside rel, instead of href
How can i route traffic through a FastAPI server to another server(s)?
class AbstractBaseSettings:
relpath_to_envfiles = Path.cwd().parent.parent.parent.iterdir()
deploy_conf_map = {
"dev": [
f for f in relpath_to_envfiles if "env" in f and 'dev' in f
and not 'prod' in f and not 'sample' in f
],
"prod": [
f for f in relpath_to_envfiles if "env" and 'prod' in f
and not 'dev' in f and not 'sample' in f
]
}
assert all([(True if penv not in deploy_conf_map["dev"] else False)
for penv in deploy_conf_map["prod"])
def __int__(self, system_context=None, env_file=None) -> None:
self.system_context: Literal["dev"] or \
Literal["prod"] or \
None = None
self.env_file: str or Path or None = Path(env_file) \
if isinstance(env_file, str) else env_file \
if isinstance(env_file, Path) and env_file is not None \
else None
if not self.env_file.exists():
pass
# Alright, this is how I know I need a break.
lots of errors in there but to fix up but the last comment says it all
I'm just gonna conclude with... I tried the deploy config where you have ten million env files.
It sucks. Horrible way to do it.\
im gonna reduce the number of env files to where i know what is coming from where exactly and cant get confused when its importing incorrectly into the conf file as None or something else. Instead there will be several conf files that figure out what goes in place of what after the env is loaded in. Not before.
I would suggest putting the router rule in nginx instead.
Im very new to server development, can you pls elaborate? So how would the flow look like? FastAPI->Nginx->Other backend servers?
it would be nginx -> fastapi, and nginx -> other backend.
And how would authentication work in this case?
GraphQL server(Strawberry)
Do you manage it?
Yes
are you using jwt?
That will the backbone of the API
That is the plan
May i pm you, to not flood this channel?
using nginx, you would have something like this. ```nginx
upstream backend {
server backend1.example.com;
}
upstream graphql {
server gql.example.com:80;
}
server {
listen 80;
...
location / {
proxy_pass http://backend;
}
location = /graphql {
proxy_pass http://graphql;
}
}
something like that.
as a beginner django user, you guys all seem like geniuses tbh :))
nginx is a server you should definitely look into
You can use it with docker even
Thank you!
My use case is a game server and match state is going to be stored on server and the GraphQL API would do the state update. So the incoming requests have to reach a specific server(where the state is stored).
Every match has an ID so... do you think i could make the routing based on this information with Nginx?
Why not just host it on a different domain?
Sorry, i know what is a domain, but i dont understand why would i do that? So it is a round based strategy game, doesnt require lightning fast responses. Probably there wouldn't be region locked servers, so all requests would go through one "gate"/"entity" (auth and load balancing/routing) and matches would run on servers served through GraphQL API and they would scale if there are too many matches.
new domain, like a subdomain. You should be able to do it in your cloud provider.
So the game server would send the info to the game clients in which subdomain it runs and after that the client would only send requests to that subdomain?
In this case there is no need for Nginx, right?
Yes
thanks a lot for the thoughs @frank shoal
As an example, minecraft uses status.mojang.com, api.mojang.com, sessionserver.mojang.com, api.minecraftservices.com, sisu.xboxlive.com, authserver.mojang.com
Can you recommend an article/page describing this architecture?
I use https://wiki.vg
note that minecraft's backend (and client) is proprietary and closed source. Nobody but mojang has access to it.
Hey
I’m new here
Does anyone know from where can I learn programming as a total beginner? (Any online free courses, YouTubers…??) I’m trying to create my own website so hopefully I can find someone to teach me programming 🙏
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Good day, peeps. Newbie here. Short question. When do you know your flask web app needs an API?
(app not yet developed, so structural planning stage) Only to expose app's data externally, or are there some internal use cases for API?
The horror, the horror. Don't ask about it ;b
just kidding.
Ask here I guess. Good place as any
The only alternative I could think
#tools-and-devops as a more generic channel for any extra tool
solved in help. thanks 🙂
.....
kinda
it's crazy easy to crack
if "env" and 'prod' in f a typo?
Hi there
Can someone explain what the point of "defaults" parameter in this example is?
def printer(positional, defaults, *args): print(positional, defaults, args)
It mean something like this:
def printer(positional, default="defparam", *args) ?
If so, and I want to call the function with default value I make call like that:
printer('positional', 'args1', 'args2', 'args3')
Output should be this:
positional defparam (args1 args2 args3) but it is not.
Instead it is:
positional args1 (args2 args3)
This is topic from args, kwargs lessons.
can any one help me
django
Hi 🙂 anyone can help me please ? i got this javascript
(function lazy() {
function lazyLoadMedia(element) {
let mediaItems = elems(element);
if(mediaItems) {
Array.from(mediaItems).forEach(function(item) {
item.loading = "lazy";
});
}
}
lazyLoadMedia('iframe');
lazyLoadMedia('img');
})();
.
and i just want to not apply the lazy loading attribute to a particular image (which would be identified by it's source/name) is someone has a clue in this 🙂
quick question, should this set the var, and if so why would it error at len() 0 if i can see that the element has a value in the inspector
newDateTime = driver.find_element_by_xpath("/html/body/div[2]/div[6]/form/div[1]/div[2]/table/tbody/tr[2]/td[10]")
How could I get the browser/machine language with flask?
I didnt quite get how I could use requests.accept_languages where does the request come from? 🤔
well, i know about that one, yeah, but I got this error
So I thought something was imported as requests
It should be request, not requestS.
In flask request is a request local variable (it's unique on each request)
Could you tell me more about that?
so i have this repeating code something like if entry not found: raise http exception 404 in each of my API methods.. get.. put.. post ..delete... wondering what would be best practice for eliminating the repetition
thanks!
Hey, its my first time sending an message here, recently i started an project to bring more performance to python in webapps , anyone here that use PyPy3 for web development can help me with some feedback?
Its still in the beginning but o want some feedback, an orientation from the community
https://github.com/cirospaciari/socketify.py
I got some really good preliminary results (faster than Golang Fiber over 1.2 million of req/sec):
https://github.com/cirospaciari/socketify.py/discussions/10
Read the flask docs
How can I build the absolute url of an image from a WebSocketConsumer?
I looked into consumer scope but that doesn't provide everything I need.
What I'm currently doing to get the absolute url is py dict(self.scope["headers"])[b"host"].decode()) + settings.MEDIA_URL + value.name but how can I get wether the server is using http or https
Is there something like request.build_absolute_uri but for WebSocketConsumer
@native tide is this issue still exist?
HI, when i try to serialize my datetime field it doesnt end up outputting the same date thats in the database. Anyone know how i can solve this?
class ChatRoomMessage(models.Model):
room_name = models.CharField(max_length=100)
user = models.ForeignKey(User, related_name="user_messages", on_delete=models.CASCADE)
content = models.CharField(max_length=255)
date_sent = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.content} {self.room_name} {self.date_sent}"
# Must change the time its not displaying right
def serialize(self):
return {
'room_name': self.room_name,
'user': self.user.serialize(),
'content': self.content,
'date_sent': self.date_sent.strftime("%b %d %Y, %I:%M %p")
}
So i already have USE_TZ = TRUE, same with USE_L10N and have already set the timezone for TIME_ZONE,
But ye idk why its happening
Trying to get this link , but its returning empy list
No I fixed it
But if u can help me with one more thing 🙂
use isoformat:
datetime.datetime.now().isoformat()
Date should be the same, maybe your db browser converts dates into your local time or your django app does that
You can also manually convert it into utc time via .astimezone(tz=datetime.timezone.utc)
so im talking about this line:
'date_sent': self.date_sent.strftime("%b %d %Y, %I:%M %p")
The format in the database is the exact same as that line however the time for some reason is displayed differently
in settings.py iv made it so it displays localtime
Which is better for fullstack mern or python
So, time is the same, just format is different?
Use technologies that make sense for your project, don't stick to specific stacks
the opposite. Time is different, format is the same
What's the time?
I was asking for to study fullstack ,im a beginner so im in bit of a dilemma that what to choose to persue fullstack web development
You're essentially asking if js is better than python, it's not, they have different uses
You can use both mongo and react with python
wdym?
What time you have in db and what python sends you?
1st is python, 2nd is db
oops
What's your timezone?
AEST
iv got it in my settings.py
its only 2 hrs if its past 12 for whatever timezone python is using but look here, its AM not PM. these were sent at 6:55 PM
Hm, i see
chat_messages = await self.save_messages(self.room_name, message, get_user_instance)
@database_sync_to_async
def save_messages(request, room_name, content, user_name):
messages = ChatRoomMessage(room_name=room_name, content=content, user=user_name, date_sent=timezone.localtime())
messages.save()
return messages
Is it correct time for you rn though?
in the database yes, but not what is displayed to the user
like in the above image
this line seems to be changing the time for some goddamn reason and i cant figure out why
'date_sent': self.date_sent.strftime("%b %d %Y, %I:%M %p")
You're using django templates?
ye im using templates offc
Hm 🤔
It should convert datetimes to your local time
https://docs.djangoproject.com/en/4.0/topics/i18n/timezones/ Read on timezones in documentation, i didn't work with templates though
what are u referring to when u say Django Templates ? arent u talking about the html files you create
ye in general i am using templates but im not tryna solve this in templates.
I need a little help
I recently got into flask web dev
and I was working with checkboxes
I'm trying to create this in flask
I made it in tkinter
but
is there a checkbox method to detect if a checkbox is checked?
in flask
in kinter we would have to set the on and off value but how do I do that in flask?
flask deals with backend, not html frontend.
You need to use javascript.
if you use jquery, you can do if ($("#check_id:checked").length)
If not jquery, you can do document.getElementById("check_id").checked
elements of type checkbox are rendered by default as boxes that are checked (ticked) when activated, like you might see in an official government paper form. The exact appearance depends upon the operating system configuration under which the browser is running. Generally this is a square but it may have rounded corners. A checkbox allows you t...
thanks
In what context are you trying to detect if a checkbox is checked?
If the checkbox is part of a regular HTML form submission and you're processing the data within Flask, and has a name attribute set, you can do `flask.request.form.get('<name of the checkbox input>'). It'll return a truthy value if checked or None if unchecked.
As well, if you had a group of checkboxes for a related value and they're using the same name attribute (example is a selection of pizza toppings), you can use flask.request.form.getlist(...) to get all the options checked.
However if you're trying to detect outside of a form submission within Flask, and say you were trying to toggle DOM elements depending on a checkbox's status, then as others mentioned, you can use regular JS, JQuery, or even HTMX.
hey every one does any one know how do i catch exceptions onflask_apispec use_kwargs decorator ????
!d flask.Flask.errorhandler
errorhandler(code_or_exception)```
Register a function to handle errors by code or exception class.
A decorator that is used to register a function given an error code. Example:
```py
@app.errorhandler(404)
def page_not_found(error):
return 'This page does not exist', 404
``` You can also register handlers for arbitrary exceptions...
use that.
hello... im looking for a german guy who build us an web app for planing workers
is it normal to one day feel like i know so much but the next day feel like i know nothing?
how i am currently passing a marshmallow schema to the use_kwargs decorator ??
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>422 Unprocessable Entity</title>
<h1>Unprocessable Entity</h1>
<p>The request was well-formed but was unable to be followed due to semantic errors.</p>
this is the return i am getting and i could't figure out where to add the error handler
No, it's much more common to feel both of those things every single day, not one day than the other 😂
im serving personalized content dynamically, is it a better experience for the user for their time to first paint to be lower and the content to not be as personalized straight away or a long time to first paint and a more detailed webpage (which takes longer for the server to process due to db calls etc)
Mate, i've been working on my project for so long. Somedays I feel so good after solving something or implementing something, but somedays i feel like i don't know anything
That's what progress feels like. Embrace the challenge and celebrate the success when it comes
Sure, you are right. Thank you
Hello, a question: how can I change a header in flask? I have tried with
class localFlask(Flask):
def process_response(self, response):
response.headers["Server"] = "Server1"
return(response)
but only another header with the same name is created
What are the best languages for front and end developement?
Also, could you suggest any youtube course (any length) for web developement?
Also I have heard Django isnt really great when it comes to back-end developement what do you think about that?
Hii. Question. I'm making a web app where a user can upload a sudoku puzzle image and the backend solves and returns the solution on the web page. My question is would that change be reflected to all users? How do I make it so that the specific user is returned his specific solution. Can anyone shed light on this?
You have many options but if you want things to change dynamically on the same page, you're most likely going to need some form of JavaScript.
Yes but I mean say you upload an image of some sudoku. Backend solves it and dynamically updates the page. Would I (another user) see your solution? How would i make it so that you see your solution, and I see mine.
If that makes sense lol
I just figured it out. Thank you!!!
i am using websocket library to connect with a server i am not understanding how to communicate with the client and server ! anybody help me plzz
??
Hi...does any one know any frameworks or work arounds to enable live or on demand streaming possible while using storage buckets to hold the video files
Hey im having an issue relating to DateTimeField in django. I use timezone.localtime() when saving objects into the database in order to display the correct time for my location. I have the following enabled in settings.py TIME_ZONE = 'My location', USE_L10N = True, USE_I18N = True, USE_TZ = True. The problem that im having is that in the admin dashboard, the time is displayed correctly and as intended however when i query in python to get certain objects, the time is printed out in UTC even tho im querying from the database. 1st image is essentially the result when querying from the database, 2nd image is viewing the same object/message from the admin dashboard.
There's WebRTC for django if you want to use live streaming, I think it allows VODs too
It might be just what you want.
Thanks I will look it up...might you know any that can work with fastAPI or flask?
I am trying to create a todo list in Django, when I want to delete an item, I have to create another html page for deleteing it. I redirect the user there and then wait for it to confirm the deletion of an item, is there a way to simply click on a button a just delete the item, or just clicking a button and doing some sort of function, without creating a form or another html template
nvm im dumb dumb forgot .name
hey guys
i have an 'edit' function in my web app, which just allows me to edit the input value from the SQLAlchemy table, so basically the rows, for example the 'title' of an object.
It works perfectly fine, except for the first item
So I can use the 'edit' function on all the items except the first one
Have no clue why
edit: solved it
does somebody has an Idea how to make a bidirectional client Python/Web and the Server Python Flask. There are framework like socket.io, signalR, which would you recommend?
I don't maybe WebRTC works for flask i have not idea.
fastapi has websockets built in
Heyho,
i hope im am correct in here with django and an sql issue 😄
I am trying to add an String "Name" and an Int "ItemID" into an model and into the database.
My Model is this:
itemid = models.IntegerField()
name = models.CharField(max_length=50)
def __str__(self):
return f'{self.itemid}'```
Everytime i run
new_item.save()```
it shows Field 'itemid' expected a number but got 'New Item'.
If i run
new_item = items(1, 123456,"New Item")
it works
After opening sqlite db with dbweaver, i see an column called ID. Shouldn't be the column autoincrement?
i have these code
from django.db import models
import uuid
class User(models.Model):
id = models.UUIDField(
primary_key = True,
default = uuid.uuid4,
editable = False)
lastname = models.CharField(max_length=100)
firstname = models.CharField(max_length=100)
mi = models.CharField(max_length=20)
age = models.IntegerField()
gender = models.CharField(max_length=20)
birthdate = models.DateField()
vote_status = models.BooleanField(default=False)
poll_status = models.BooleanField(default=False)
class News(models.Model):
id = models.UUIDField(
primary_key = True,
default = uuid.uuid4,
editable = False)
title = models.CharField(max_length=100)
headline = models.TextField(max_length=300)
content = models.TextField(max_length=2000)
date_posted = models.DateField(auto_now_add=True)
class Comments(models.Model):
id = models.UUIDField(
primary_key = True,
default = uuid.uuid4,
editable = False)
user_id = models.ForeignKey(User, on_delete=models.CASCADE)
news_id = models.ForeignKey(News, on_delete=models.CASCADE)
comment = models.CharField(max_length=500)
date_posted = models.DateField(auto_now_add=True)
and this table relations
for these 3 tables the user,news, and comment did i implement it correctly on my code?
Can anyone recommend a good tutorial for building a basic website with Flask, where they also build the HTML and CSS from the ground up? Lots of the material I see online has pre-made templates, or they are copy/pasting code snippets and I'm not learning much from that. I want to learn how to cook, not just follow a recipe, if that makes sense.
freeCodeCamp.org has lots of video content on youtube. and check the official website. first make sure you want to learn with template or REST. This are two different aproaches
Thank you, I will look there. I'm not familiar with REST, I'll have to do some research...
Should you still use PHP to keep track of logins and sign ins if you're using Flask python backend?
I have a question.
No. Use something like Flask-Login
If you use a corporate ldap server, use flask-ldap-login
flask-msal if you use microsoft accounts
I'm making a flask app
...and wondering if there is some way to dynamically choose dimensions for an image that is generated for a html page so that it fits on the screen?
For my specific example, I am making images from pdf file. (just the first page) ```py
def pdf_preview_image(pdf_path, image_destination):
"""
:param pdf_path:
:param image_destination:
:return:
"""
# Turn the pdf filename into equivalent png filename and create destination path
pdf_filename = split_path(pdf_path)[-1]
preview_filename = ".".join(pdf_filename.split(".")[:-1])
preview_filename += ".png"
output_path = os.path.join(image_destination, preview_filename)
# create png preview and save it
fitz_doc = fitz.open(pdf_path)
first_page_pix_map = fitz_doc.load_page(0).get_pixmap()
first_page_pix_map.save(output_path)
return output_path
fitz is like a pdf library
pdf files range from 8.5x11 to 42x36 so the images can be quite big.
If you already had / willing to make different image files for the different dimensions and you're okay with the different image by width breakpoints, you could use a picture element with a few sources
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture
I guess I'm wondering if there is a way to determine the user screen size so that I could adjust the dimensions likewise. Or is there like a standard image size web developers consider a maximum size?
What I should start learning if I want to work on websites??
html
Html, css
is it possible to tell if a web app to heroku was deployed with docker?
anybody good at beautiful soup, need help parsing specific information from a page that has wonky text
What do you have for code now? What does the info you're trying to parse from look like?
can anybody help plz
https://stackoverflow.com/questions/72470353/cannot-query-ahmed-must-be-user-instance
django
If I have a registration form for users, is it safe if it only has "username" and "password" section in it? I removed the "email" section.
Or storing any user data is always unsafe?
I mean, only "username" and "password" shouldn't be personal data, right?
Or just use Two-factor auth ?
Or provide "dummy users" for testing my app?
Yes.
Hey, how can i force scroll to the bottom of the container as soon as page is loaded? (javascript)
Hey, im writing an application in django. Parts of my app need to be in django, like the login, registration, main page and some other pages. But i want the user dashboard to be in react. How could i have this part of the website written in reactjs?
Hi! Can anyone tell me how can i refresh the screen in kivymd on a click of a button. Actually i'm creating a fact app in which i will get random facts in click of a button. But i unable to do it on a click on button.
My code: https://paste.pythondiscord.com/arekewirul
hello,, iam trying to refer this documentation: https://bootstrap-table.com/docs/api/events/ and try to make a jquery for my bootstrap table , it just wont work at all
The Events API of Bootstrap Table.
after reading the docs i came up with this: but this never seems to work
$('#display_table').bootstrapTable({
onClickRow: function (row, $element, field) {
alert("testing");
}
})
anyone here used jquery with bootstrap ? and know how to get a row clicked listener (sort of)...?
dunno. it's not just you. doesn't work for me either. try chaining .on() from the bootstrapTable() object instead.
$('#display_table').bootstrapTable().on('click-row.bs.table', function (e, row, $element, field) {
alert("testing");
});
note as per the API doc, e (the event itself) is passed as the first argument with this form.
i don't use it. but might have a solution for you above.
Ahhh
once upon a time, i used to use jQuery. don't anymore. it has all been replaced with vue + webpack + babel
I wish the stuff they put in the docs would just work just like that
Alright let me try what u posted
checking their issues ...
I'm using Bootstrap table (http://wenzhixin.net.cn/p/bootstrap-table/docs/index.html)
I'm trying to add click event
$('tr').click(function(){ console.log('test'); });
but it doesn't work. I know...
this is a old answer ^ but this seemed have worked for them
maybe something got changed in recent years , idk
this.
dunno what that's all about though ... i'm just using the "getting started" example code and in the jQuery load handler, attach the bootstrapTable there. ... no vue at all.
I’m trying to click a button on a webpage with selenium, but for some reason I cannot find any element in the page
It either says stale element or element not found
iam trying to make my code similar to a example visible on that link u posted , will update !
you mean the "welcome.html" they linked?
i only see the .on() form in there, too. but nowhere in the doc explains why onClickRow no longer works if you aren't using Vue. :p
oh
i think it's just a doc bug, then. the Events page talks about there being two ways to do it. the first way via "options" and the second with on(), but if you look at the Table Options page it doesn't list any of the on* events as being options anymore. https://bootstrap-table.com/docs/api/table-options/
The table options API of Bootstrap Table.
mhaaaa i got it to sort of work via vue
<script>
new Vue({
el: '#table',
components: {
'BootstrapTable': BootstrapTable
},
data: {
columns: [
{
title: 'Item ID',
field: 'id'
},
{
field: 'name',
title: 'Item Name'
}, {
field: 'price',
title: 'Item Price'
}
],
data: [
{
id: 1,
name: 'Item 1',
price: '$1'
}
],
options: {
search: true,
showColumns: true
},
onClickRow() {
//on click row
alert("testing");
}
}
})
</script>
so now this onClickRow() functions would get called everytime a row is clicked on
but i still dont know how to access the values tho , testing
Vue is certainly nicer. looks like progress! :)
onClickRow(row, $element, field) {
alert("field:"+field+"-"+"row.name:"+row.name+"-"+"row.id"+row.id);
}
@somber plover thanks , this seems to work for now
so apparently onclickrow works on vue
and not on js i have no idea
but seems to work for now
<div id="table">
<bootstrap-table :columns="columns" :data="data" :options="options" @on-click-row="onClickRow"></bootstrap-table>
</div>
this is how i create the table for it to work with vue ^
but there is one big problem here
it is a heck of a lot less mysterious to have the handler explicitly put in the template like that ...
:data="data" ...... iam creating data on vue and i hope there is some way to just use my old html tables oops
than the more mysterious binding on load of the handler when the table is instantiated
personal taste.
(and is one of many reasons why I no longer directly write jQuery ;) )
haha
and this is the js
new Vue({
el: '#table',
components: {
'BootstrapTable': BootstrapTable
},
data: {
columns: [
{
title: 'Item ID',
field: 'id'
},
{
field: 'name',
title: 'Item Name'
}, {
field: 'price',
title: 'Item Price'
}
],
data: [
{
id: 1,
name: 'Item 1',
price: '$1'
},
{
id: 2,
name: 'Item 2',
price: '$2'
}
],
options: {
search: true,
showColumns: true
},
onClickRow(row, $element, field) {
alert("field:"+field+"-"+"row.name:"+row.name+"-"+"row.id"+row.id);
}
}
})
it works , i just need to experiment with it for sometime to learn how it works... all i know rn is it just works like magic , iam new to vue , this is goona be interesting
Hey there!
Am I able to generate object like this
filter_obj = Q(field1=value) | Q(field2=value) | ... # Some other fields
and then filter over this object? As initial data I have fields: Iterable[str], value: str and QS
Can i get vote on using sqlite3 for production.(django)
Someone know how to print pinged ip adress in html?
does someone know of a good tutorial to design apis?
trying using js
No. sqlite3 is not thread-safe, so you'll get bottlenecks.
Plus it's too easy to lock up the database by forgetting to close a connection.
Does that happen with django though , since i'll be using the django ORM.
You're still limited to one session at a time.
The thing is i'm facing a lot problems using postgres inside docker.
What kind of problems?
its a project for my college association , so on a local server
then it might not matter much.
Hey I have a question
Let’s say someone wants to hack their old instagram account? What do they have to learn? And how long will it take them?
(Sorry sent this on the wrong chat)
I got a take home project to create a chat application in Django and I built it using channels following channels documentation tutorial but I'm quite confused on how to make them secure(end to end only)
This is what the requirement said:
Third part of this project is for you to make this web socket secure. You don’t have to add any certificates to make the protocol ‘wss’ instead of ‘ws’. But you have to come up with a way to make sure just using the socket link no third party can see the streams. That mean you have to add a layer of security to view the stream.
I've looked into https://channels.readthedocs.io/en/stable/topics/security.html but I don't think that is it, would appreciate if anyone could push me in the right direction.
ok
did you guys use django to code a website
Yes
Yes
I'm using the builtin webbrowser library
import webbrowser
I uploaded my flask app with a requirements.txt and i don't know how to include webbrowser as a requirement since I'm used to only putting stuff from pip in there
here is an example of what is in my requirements.txt
could someone help me out with this? I have some code not behaving correctly because of this
urllib3==1.26.9
Werkzeug==2.1.0
wsproto==1.1.0
zipp==3.7.0
It's part of the standard library, so you do not need to and should not include it in requirements.txt
requirements.txt is for third-party dependencies
I am trying setting up flask-mail email for outlook. I had it working with gmail
I found this link
https://superuser.com/questions/1521236/how-to-allow-less-secure-app-access-in-microsoft-email
I tried
MAIL_SERVER= 'smtp.office365.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USE_SSL = False
MAIL_USERNAME = os.environ['EMAIL_USERNAME']
MAIL_PASSWORD = os.environ['EMAIL_PASSWORD']
and I tried
MAIL_SERVER= 'outlook.office365.com'
MAIL_PORT = 995
MAIL_USE_TLS = True
MAIL_USE_SSL = False
MAIL_USERNAME = os.environ['EMAIL_USERNAME']
MAIL_PASSWORD = os.environ['EMAIL_PASSWORD']
https://imgur.com/a/luH7JSb
What am I doing wrong?
Thanks for the help
anyone here ever made a purchase shop code in python?
hmmm
guys, in my django project , i have a js function set up that would trigger based on clicks from a bootstrap table, so the part visible on the code is only of importance here , iam looking for ways by witch i can delete id received in this function ,, can someone help me go in a correct direction -iam clueless as of now
..
...
.....
else if($(this).data("delete-id")){
id=$(this).data("delete-id");
alert("delete clicked: "+id); //was just testing to see if it works and it works..
//in here i need to make some way to connect to my django models and delete that perticular id...
}
i have already setup a delete page and this is the view function for it :
def delete(response):
temp = models.ToDoList.objects.all()
max_id=0
for i in temp:
max_id=i.id
if response.method=="POST":
form1 = DeleteList(max_id,response.POST)
if form1.is_valid():
"if valid input , then delete that id"
temp.filter(id=form1.cleaned_data["id"]).delete()
return HttpResponseRedirect("/display")
else:
form1 = DeleteList(max_id)
return render(response,"main/deleteList.html",{"form":form1})
i think the way to go forward is to somehow make my js function do a post method so that i can just handle it in my delete views function .... is this correct ? how do i do this btw
Hey guys, have a django question, I use the login_required decorator to redirect the user to the login page, but after loggin in, it redirects user to the index page, not the view that triggered login_required, how will I fix it?
You must set login redirect url to index page
showing error UnboundLocalError at /
local variable 'cartItems' referenced before assignment
def get_cart_items(self):
orderitems = self.orderitem_set.all()
total = sum([item.quantity for item in orderitems])
return total```
Checkout my new Django Course!
https://dennisivy.teachable.com/p/django-beginners-course
We will begin to add in core user functionality such as “add to cart”, “update cart” and “checkout”.
Source code:
https://codewithsteps.herokuapp.com/project/cd0492f3-ee93-471a-9dbc-b047233336c3/
Follow me on Twitter for updates and more personalized con...
time:33min
were can i put my image of my project so that when i send mail from my app those image can be view by receiver
i want my image in internet
How can I have two OneToOneFields in a single Django Model?
This works:
from django.db import models
from django.conf import settings
class FriendRequest(models.Model):
author = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
This doesn't:
from django.db import models
from django.conf import settings
class FriendRequest(models.Model):
author = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
recipient = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
The second one throws:
interactions.FriendRequest.recipient.
interactions.FriendRequest.recipient: (fields.E304) Reverse accessor for 'interactions.FriendRequest.recipient' clashes with reverse accessor for 'interactions.FriendRequest.author'.
HINT: Add or change a related_name argument to the definition for 'interactions.FriendRequest.recipient' or 'interactions.FriendRequest.author'.
interactions.FriendRequest.recipient: (fields.E305) Reverse query name for 'interactions.FriendRequest.recipient' clashes with reverse query name for 'interactions.FriendRequest.author'.
HINT: Add or change a related_name argument to the definition for 'interactions.FriendRequest.recipient' or 'interactions.FriendRequest.author'.
Solved it by adding related_name='recipient_by_%(class)s_related'
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
from pprint import pprint
"""
options = Options()
options.binary_location = r'C:\Program Files\Mozilla Firefox\firefox.exe'
options.headless = True
driver = webdriver.Firefox(executable_path=r'D:\Documentos\pythonProject\api_test\geckodriver.exe', options=options)
url = "https://banguat.gob.gt/cambio/historico.asp?kmoneda=02&ktipo=5&kdia=16&kmes=05&kanio=2022&kdia1=20&kmes1=05&kanio1=2022&submit1=Consultar"
driver.get(url)
xpath = '/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/div/table'
element = driver.find_element(by=By.XPATH, value=xpath)
rows = element.find_elements(By.TAG_NAME, "tr")
dollar_dict = []
for row in rows[1:-1]:
cols = row.find_elements(by=By.TAG_NAME, value='td')
dollar_dict.append({cols[0].text: float(cols[1].text)})
pprint({'dollar': dollar_dict})
"""
url = 'http://www.banguat.gob.gt/variables/ws/VariablesDisponible'
my_obj = {'xmlns': 'http://www.banguat.gob.gt/variables/ws/'}
x = requests.post(url)
content2 = x.content
soup = BeautifulSoup(content2, 'html.parser')
print(soup.prettify()) ```
Hi guys, I don't know what is my wrong, I need to obtain data from that url('http://www.banguat.gob.gt/variables/ws/VariablesDisponible')
i'm working at a django project for school, i want to use a css file but he don't recognized it as a css file. Someone that knows why?
ah but that will take me to the index file or wherever the original link always is
fixed by giving a hidden input tag value of the redirect site and fetching it during authentication and then redirecting there
How do websites display(render) images of different size but the image looks pretty much the same despite the difference in aspect ratio? Is there a specific formula? or have I misunderstood anything?
hi guys, how do i connect my apache web server to the internet??
First, you open your ports
Local, firewall, router, etc
Maybe do some port forwarding (ports 80, 443 TCP)
(optional) assign a dns name to your public ip
You should probably go through a reverse proxy and cache service like cloudflare if you expect a lot of traffic
Hello guys, how can I run my python script in web asynchronously (Without refreshing the page). Can it run on ajax?
Use JavaScript to poll your endpoint and update the page dynamically using the DOM api
Hey, i have a django webserver where certain code does not run on my production server but it does run on my machine. I have isolated some things that cause the error, but cannot get django to write the error log to a file, somehow. When i allow error logging, it just causes all of my requests to return an error 500...
what do i do?
It also just does not log
this is my logging config
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': '/var/www/debug.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
What are the differences/benefits to using aiohttp's websocket support vs using websockets?
resp = requests.get('https://wax.api.atomicassets.io/atomicmarket/v1/assets?collection_name=nfsocialexgg&schema_name=nfse&page=1&limit=1&order=desc&sort=asset_id')
data = resp.json()
asset_id = data['data']['asset_id']
print(asset_id)
### And the error I get is
TypeError: list indices must be integers or slices, not str
https://github.com/scriptslay3r-code/NonFungable-Search
The Json response is too long to post here. But it's in the readme
#help-avocado Figured someone from here could help me out
data["data"] is a list of dictionaries. Each one has an asset_id.
can we talk about web scraping here?
is it possible to run a flask function without the route ?
What do I need to know to make a website that is accessible on the internet?
If you're not asking how to violate laws or ToS, then yes
If that's literally all you want to do, you need to know how to open a browser, type and click and that's about it. Wix, Weebly, Squarespace, etc. require nothing more than that.
No
Like there is a page with some words
And I need to take these words
There are various tools you can use depending what you need to do exactly... here's a relatively simple approach: https://timber.io/blog/an-intro-to-web-scraping-with-lxml-and-python/
In this post, you will learn how to use lxml and Python to scrape data from Steam. I will teach you the basics of XPath so that you can scrape data from any similar website easily. In the end, you will also learn how to generate a JSON output from your script. So what are you waiting for? Let's begin!

What do people use for deploying django projects for free?
Ive been trying to get Heroku to work for hours upon hours and it just isnt working, does anyone have any good alternatives or can anyone help me troubleshoot my problem?
I use pythonanywhere for small scale projects, good for testing before moving to a higher solution
No matter what I do I always get the same error:
Heroku will not recognise django_heroku
Ive gone through two tutorials multiple times, looked at probably 20+ forum posts, nothing has worked, the error message never changes
Ive made a new git account and repository multiple times
remote: -----> $ python manage.py collectstatic --noinput
remote: Traceback (most recent call last):
remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 259, in fetch_command
remote: app_name = commands[subcommand]
remote: KeyError: 'collectstatic'
remote: During handling of the above exception, another exception occurred:
remote: Traceback (most recent call last):
remote: File "/tmp/build_d1951427/manage.py", line 22, in <module>
remote: main()
remote: File "/tmp/build_d1951427/manage.py", line 18, in main
remote: execute_from_command_line(sys.argv)
remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
remote: utility.execute()
remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute
remote: self.fetch_command(subcommand).run_from_argv(self.argv)
remote: settings.INSTALLED_APPS
remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 87, in __getattr__
remote: self._setup(name)
remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 74, in _setup
remote: self._wrapped = Settings(settings_module)
remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 183, in __init__
remote: mod = importlib.import_module(self.SETTINGS_MODULE)
remote: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module
remote: return _bootstrap._gcd_import(name[level:], package, level)
remote: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
remote: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
remote: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
remote: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
remote: File "<frozen importlib._bootstrap_external>", line 850, in exec_module
remote: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
remote: File "/tmp/build_d1951427/ostexp2/settings.py", line 15, in <module>
remote: import django_heroku
remote: ModuleNotFoundError: No module named 'django_heroku'```
Its in the requirements.txt file
Ive tried django-on-heroku
Every single person who gets this error message online seems to have a different problem and different solution so it may possibly be the most unhelpful error message ever made
Are you talking about this?
import django_heroku
django_heroku.settings(locals())```
Because yes I have this
I also included it in the requirements.txt file
I also installed psycopg2 and psycopg2-binary which apparently you need
i know you have it in the requirements.txt file but do you need to run a console command in heroku?
like pip install -r requirements.txt?
Ill try it
it's what I need to do on pythonanywhere, heroku might work differently
(ostexp2) osboxes@osboxes:~/ostexp2$ pip install -r requirements.txt
ERROR: Could not find a version that satisfies the requirement apturl==0.5.2 (from versions: none)
ERROR: No matching distribution found for apturl==0.5.2```
Weird
Is this normal?
remote: Installing initially failed dependencies...```
hey guys
I'm not sure if I understand correctly the documentation - I wanted to ask, if I wanted to make a django project that is connected to mysql database, do I need to make a User model as well, so that it will be migrated to mysql database? I'm reading, that Django by default contains "User" model in it, but will it also be available when using outer (not sqlite3) database?
I don't think you need a Django user to run the migration, did you try it?
no no, I'm not building the project yet - I'm just finding out and reading about it. I wanted to make a project that will allow registration of new users, logging in/out etc
and just wanted to know how does that work, that Django offers built-in user models
I know that I will build some other models and wanted to know how it will cooperate
Your User model will be stored in whatever database you use, shouldn't matter
ah, okay, so now I know
thanks!
I want to have an img with a caption, so I tried <figure><figcaption>. But <figure> implies the end of a <p>, where <img> does not. Is there a way to add a caption to <img>, or to keep the inline nature with <figure>? I know I can style it display:inline-block, but HTML validators complain, and it's parsed as if it ends the paragraph.
Maybe wrap the img in a div and put your caption in a <span> and then style their classes how you like
Where do you guys put your process-codes(I don't know if that's what it's called)?
For instance: a function that sends an email.
Do you just drop them in views.py or do you put them in utilities.py?
Hello
is there a way to access get the remaining countdown time of celery apply_async
Under certain circumstances, lets say worker countdown was 15 secs, if a specific event occurs i need to revoke previous task (lets say it now has 10 sec left), and I need to get remaining time of previous worker, sum it with 15 (in this case 20) sec and create new worker with new countdown, and this process should be cycled
what does ur requirements.txt file contain?
ive got a question, is flask better than django or not
The required dependencies for your app to function as intended
They say flask is for small projects. Django is godzilla. I've never tried flask but I know just how 'zilla django is
they are both good but for different purposes. I would say that flask is better suited to "lightweight" applications and the more complicated it becomes then the more you want django
I know the use of requirements.txt file.
I was asking for trying to help him, maybe he left some dependency
I read this wrong😅
Np
Anyway @agile pier thoughts?
I feel things could be more organized keeping it organized
can anyone help me code
I followed along with a youtube video but my code isn't returning a value
i know that feeling can't help you sorry
i'm also a beginner so
yeah im just a shit sandwich rn
Recently i helped smone.. In discord... I can your too.. I can try at least.. Haha lol...
import bs4
import requests
import openpyxl
wb = openpyxl.load_workbook(r'C:\Users\Demar\Document\Vinny.xlsx'')
sheet = wb['Vinny']
r = request.get('https://finance.yahoo.com/quote/AAPL?p=AAPL&.tsrc=fin-srch')
soup = bs4.BeautifulSoup(r.text, features='html.parser')
priceAAPL = soup.find_all('div', {'class', 'D(ib) Mend(20px)'})[0].find('span').text('.','.')
print(priceAAPL)
@viscid bough its not returning a value
M not cruntly at my machine... But it look like.. Something is wrong there
I will dm you.. Once i will be have back on my desk....
not sure I am in the right place here, if I am creating a class , how can I stop a user using the terminal to create custom attributes or overwrite existing ones?
looks like syntax error. Extra single quote on line 5
this doesn't really make any sense, but if you're looking to only provide an interface then you should look at ABC, https://docs.python.org/3/library/abc.html
I am having trouble with a flask app that I am working on. The details are in #help-popcorn so please help me if you can
Hey, I am having an issue with django , details are in #help-peanut , please help if you can.
I built a deep learning model that classify texts into two categories positive and negative, the negative is any text that contains racial slurs or any kind of threatening or doxing, I want to integrate it with another project it is similar to twitter, I want to categorize posts with the model to make it easier for the admin to review them but I don't have any idea how to merge these two projects together, any ideas or references on how to do that
@covert ibex u can add (blank=True, null=True)
Does anyone know how to update my django code on pythonanywhere?
you go to the files section
and you can edit whatever file it is from there
it has its own console as well
Is there a way I can just do a 'git clone ...' sort of thing again?
I tried but it wont let me
i don’t know, i haven’t tried
Anyone understand this?
(ostexp-venv) 14:14 ~ $ git pull
fatal: not a git repository (or any parent up to mount point /home)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).```
Got it working, did:
git init
git remote add origin (url)
git pull
Is SQLite able to be used for Python Anywhere?
I want that field in the database to be required. Just don't want the text that says "This field is required." in the form.
Guys any recommendations on how to set up automatic payments with crypto on a flask server?
Sure.
My suggestion would be to use mysql.
I've a Django issue/ question in help-chocolate. Regarding adding data to existing models via form. Help would be appreciated but no worries if not.
Hey @left kelp!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Search for all registered domains around the world, including gTLDs, New gTLDs, ccTLDs, punycode(IDN) supported.
i have this site
i need to take the extension
like .com , .it , .eu , ecc
but there is cloudfire
it block my API to scrap the page
from selenium import webdriver
PATH = r"C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get(r"https://dotdb.com/search?keyword=crypto&position=any&page=1")```

wrong chat
So I have this code: (app is just a normal aiohttp.Application)
async def main():
async with aiohttp.ClientSession() as client:
app.client = client
try:
runner = web.AppRunner(app)
print(runner)
await runner.setup()
site = web.TCPSite(runner,port=3308,host="127.0.0.1")
print(site)
await site.start()
except KeyboardInterrupt:
await runner.cleanup()
asyncio.run(main())
``` and it prints the `AppRunner` and `TCPSite` object, but then exits and doesn't actually run my site, how can I fix this?
hi im trying to pass some variable for a dynamic site however when i do so i get TypeError: redirect() got an unexpected keyword argument 'username'
flask return statement > py return redirect(url_for('D1'),username=username)
<a href="default.asp">
<img src="{{ url_for('static', filename='images/{{username}}.png') }}" alt="Profile Pic" style="width:200px;height:200px;">
</a>
<p style="padding-left:15%;padding-right:15%;font-weight: bold;text-align: center;">{{username}}</p>```
template html
I need help with BeautifulSoup4 in #help-popcorn
Eventually found out there was an issue with the page but the channel went dormant and you dont allow dm
does anyone know how to monetize a website with banner ads besides using google adsense
website monetization isnt listed as an eligible product for my account
Hi everyone, does anyone have good knowledge of deploying Django on heroku using waitress as the web server on windows. It's almost seem impossible
How can I use this
chart.labels().format('{%Name}');
in Flask? I’m following this tutorial https://www.anychart.com/blog/2020/11/11/venn-diagram-javascript/ but using '{%Name}' gives me an error.
Hey @hollow shell!
It looks like you tried to attach file type(s) that we do not allow (.pdf). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
The tutorial is for javascript
I have JavaScript in my html and I’m running it with Python flask
in python format is used like this chart.labels('{}').format(what_wanna_put)'
Also I actually don’t understand the variable {%name} in the tutorial. Where does it come from? Is it from what’s inside data?
try using a lowercase n in name
chart.labels().format('{%name}');
the name comes from the data you define above presumably
but this is specific to whatever random graph library this is - not anything more generalisable
flask doesn't seem to like chart.labels().format('{%name}'); so now I'm trying the suggestion of abstract
oh it's obvious why
the {% is being mistaken for the opening of a Jinja tag
{% raw %}
chart.labels().format('{%Name}');
{% endraw %}
:incoming_envelope: :ok_hand: applied mute to @native tide until <t:1654506849:f> (9 minutes and 59 seconds) (reason: mentions rule: sent 6 mentions in 10s).
trying this:
chart.labels('{}').format(name);
didn't give any results, no errors and nothing on the webpage
I'll try this now
it works but I'm still not getting a tooltip when hovering over the diagram with my mouse... I'll try copy pasting the whole thing with the {% raw %} {% endraw }
I finally got it working! thanks a lot!
I figured out why i didn't see a tooltip. apparently I can't have a transparent background AND a tooltip
turns out i can have a transparent background with tooltip. just had to use chart.background().fill('white',0); instead of chart.background().enabled(false);
Im using Django
My website is used for seeing all songs in game soundtracks
I have it so if the url is ' ' then it directs to index.html
And if the url has anything else it attempts to find all songs from whatever it got ( 'url/game_name/' gets all songs from game_name)
I want it so if the game does not have any songs then it redirects to index.html
Heres what I have:
from django.shortcuts import render
from django.http import HttpResponse
from .models import Game, Song
def AllGames(request):
return render(request, 'index.html', { 'games' : Game.objects.all() })
def GameHTML(request, game_name):
allsongs = Song.objects.all()
game_songs = []
for song in allsongs:
if song.game.name == game_name:
game_songs.append(song)
game_songs.sort()
#Problem Area:
if (game_songs.count == 0):
return render(request, 'index.html', { 'games' : Game.objects.all() })
return render(request, 'songs.html', { 'game_name' : game_name, 'all_songs' : game_songs})```
If you can see the problem thats great but if not does anyone know a way to write stuff to a console or something so I can check game_songs.count whenever I try putting in a url?
Forgot to mention my problem is that if (game_songs.count == 0) never gets called when it should
I added this but I dont know where it shows up, its not in the web dev tools
logging.basicConfig(level=logging.INFO)
logging.debug(game_songs.count)```
who teach you to name function using camel case?
your logic is wrong. I'll do it in my way, recieve specific game by id and after that retrieve the song using get_or_404 and then if there's no song redirect to html page. I suppose that the relationship of DB is one-to-many? So why you don't use it?
Whats DB?
Database?
I think its many-to-one not one-to-many as well
All songs store what game they belong to
A game can have multiple songs
game can have many songs, so one-to-many
Alright so Im not sure what you want me to do
So your saying I can find the ID of the game_name
Then using get_or_404 I can filter through all songs which have that ID in them
Maybe something like this?
def GameHTML(request, game_name):
game_ = Game.objects.get(name=game_name)
game_songs = get_object_or_404(Song, game=game_)
game_songs.sort()
if (game_songs.count == 0):
return render(request, 'index.html', { 'games' : Game.objects.all() })
return render(request, 'songs.html', { 'game_name' : game_name, 'all_songs' : game_songs})```
get_object_or_404 seems to throw an exception if it returns multiple songs which is what I want
pls
i need help
yeap, but pass to get_object_or_404(Song, pk=game_.id) and Game.objects.get(pk=pk) why you passed the name of the game?
and what the purpose of sorting the songs?
What is pk?
Im sorting them so when they are in order on the website
primary key of your table
Should I be changing this?
urlpatterns = [
path('', views.AllGames),
path('<str:game_name>/', views.GameHTML)
]```
or if you're use this url mapping so there's no need to change
game_songs = get_object_or_404(Song, pk=game_.id)```
This only returns one song and throws an error when I try to sort it
Cant I do something more like this
game_songs = Song.objects.filter(game=game_)```
yes
Cool, just need to figure out how to sort a QuerySet now
Does anyone see anything wrong with this search bar?
When pressing the button it just reloads the page with url 'server.com/?'
<input class="form-control me-2" type="search" id="gameSearch" placeholder="Search for a Game" aria-label="Search">
<button class="btn btn-outline-success" type="submit" onclick="Find()">Find</button>
<script>
function Find(){
var input = document.getElementById("gameSearch").value;
window.location.assign(`${window.location.hostname}/${input}/`)
}
</script>```
Maybe you don't need type="submit" if you're not submitting anything?
Unfortunately that didnt change anything, whenever I press the Find button I get this error:
Usually a search is done like this via a normal form. ```html
<form action="/gameSearch">
<label for="gameSearch">Game Search</label>
<input type="search" name="q" id="gameSearch">
<input type="submit" value="Search">
</form>
Submit will send the user to https://<hostname>/gameSearch?q=<searchstring>
What is name=q referring to
its naming the input. it's determines what query string to use.
in this case, ?q=value
where q is the key
Ill try it
So when I search I get:
/?q=value
How do I get rid of the ?q= part so its just
/value
What are you using on the backend?
Im not 100% how to answer that but I think VSCode, Django, SQLite and PythonAnywhere
One of those is probably the answer
django, then use request.GET.get("q")
Where do I put that?
in your endpoint for /gameSearch
In <form action=... ?
No Im not sure
I mean maybe I do and I just dont know what its called
Very new to web dev
Is this what you meant?
urlpatterns = [
path('', views.AllGames),
path('<str:game_name>/', views.GameHTML),
path('?q=<str:game_name>/', views.GameHTML)
]```
Doesnt seem to work so I guess not
for last expression you shall enable regex r'?q=<>/'
Still doesnt seem to work
urlpatterns = [
path('', views.AllGames),
path(r'?q=<str:game_name>/', views.GameHTML),
path('<str:game_name>/', views.GameHTML)
]```
For the regex one, is the string meant to be all red except for the ? which is orange?
Am I supposed to use re_path?
Something like this? I really need help
re_path(r'(?q=<str:game_name>)/', views.GameHTML),```
|
|
|
Let me start again
Im trying to make a search bar
This is my HTML:
<form action="/gameSearch">
<label for="gameSearch">Game Search</label>
<input type="search" name="q" id="gameSearch">
<input type="submit" value="Search">
</form>```
When I use it the url ends up as:
```hostname/?q=value```
I want it so it either ends up as:
```hostname/value```
Or a way to modify this so the first url works:
```py
urlpatterns = [
path('', views.AllGames),
path('<str:game_name>/', views.GameHTML)
]```
I am getting an error in this flask app I am working on. The details are in #help-bagel, please help me if you can
it took me about 2 months for html. i am planning to do Javascript and css in 3 months is it possible and is that much knowledge any worthy. (hour for each every day)
are you kidding? 2 months for html
not everyday
time to time i was bit stuffed up
still am but ready to put in the effort
yeah, it depends on time how many you can spend
1:30 hour for css, same for js
how bout that
i spend one hour a day, maybe a bit more deepends on the content (documentation, video or just practise coding)
how long it took?
don't remember
can u guess months?
Still looking for an answer to this but in the meanwhile for this code why does the {{ game.img }} work but {{ game.color }} doesnt?
Says it wants a property value:
{% for game in games %}
<div class="col">
<div class="card" style="width: 13rem; background-color:{{ game.color }};">
<div class="card-body">
<img src="{{ game.img }}" class="card-img-top" alt="">
(Removed, unimportant)
{% endfor %}```
@native tide do you have color attribute in Game model?
Yep
class Game(models.Model):
img = models.CharField(max_length=2083)
name = models.CharField(max_length=255)
song_count = models.IntegerField()
description = models.CharField(max_length=2083)
color = models.CharField(max_length=10)
def __str__(self) -> str:
return self.name```
Anyone know of any servers where I might be able to get more answers? I mean I would think these are like noob beginner questions
Hello guys, for updating a ressource on django (non REST framework), would you suggest a post or a put request?
Is it best practice to make CRUD operations even on an app that is not an API?
@native tide You are not using "count" method the intended way. list.count() counts the number of occurrences of an item in a list. https://www.w3schools.com/python/ref_list_count.asp.
I would suggest you use len() method, instead of count()
@native tide Such as: if len(game_songs) == 0:
i need someone to point me in the right direction, I want to create a webapp that essentially takes an upload from the user(which is stored temporarily and deleted after processing) (pdf, doc, txt file) and well reads some text and spits some output out, I need to know what technologies are involved in the taking upload part
Sonds crazy.. When its full stack
if it's cloud based, I would start with creating a S3 bucket to store uploads.
basically have a web server that accepts uploads and stores them in S3, then have a worker (like celery) connected to a store like redis or rabbitmq
ok so I'll need s3, django and a domain?
i dont know much about webdev, a c++ coder here
That is quite broad. If you're using django, you could store the files in a media folder. It would be achievable with django I/0 operations. Depending on the magnitude of users you could use aws or heroku. I think you should be good with heroku as a start. Since heroku serves static files, and takes care of the domain
a process to accept uploads, a place to store them, and a process to process uploads individually
Django - Docker - Heroku
yeah thats what I need
is heroku better than the s3 free tier?
heroku doesn't come with storage.
it just comes with a database (postgres)
I personally use both
note: s3 charges for bandwidth, not storage space
I believe internal access (i.e. from aws servers) is free.
django-heroku installation error how can i solve it???
Have a log or error message?
Using cached psycopg2-binary-2.9.3.tar.gz (380 kB)
Preparing metadata (setup.py) ... error
error: subprocess-exited-with-error
× python setup.py egg_info did not run successfully.
│ exit code: 1
╰─> [23 lines of output]
running egg_info
creating /private/var/folders/60/4zbgw8rd0m9_h_h7ldx47vhm0000gn/T/pip-pip-egg-info-zwowilp6/psycopg2_binary.egg-info
writing /private/var/folders/60/4zbgw8rd0m9_h_h7ldx47vhm0000gn/T/pip-pip-egg-info-zwowilp6/psycopg2_binary.egg-info/PKG-INFO
writing dependency_links to /private/var/folders/60/4zbgw8rd0m9_h_h7ldx47vhm0000gn/T/pip-pip-egg-info-zwowilp6/psycopg2_binary.egg-info/dependency_links.txt
writing top-level names to /private/var/folders/60/4zbgw8rd0m9_h_h7ldx47vhm0000gn/T/pip-pip-egg-info-zwowilp6/psycopg2_binary.egg-info/top_level.txt
writing manifest file '/private/var/folders/60/4zbgw8rd0m9_h_h7ldx47vhm0000gn/T/pip-pip-egg-info-zwowilp6/psycopg2_binary.egg-info/SOURCES.txt'
Error: pg_config executable not found.
pg_config is required to build psycopg2 from source. Please add the directory
containing pg_config to the $PATH or specify the full executable path with the
option:
python setup.py build_ext --pg-config /path/to/pg_config build ...
or with the pg_config option in 'setup.cfg'.
If you prefer to avoid building psycopg2 from source, please install the PyPI
'psycopg2-binary' package instead.
For further information please check the 'doc/src/install.rst' file (also at
<https://www.psycopg.org/docs/install.html>).
[end of output]
Possibly related? https://github.com/heroku/django-heroku/issues/48
ok solved
brew install postgresql
pip3 install psycopg2
pip3 install django-heroku
these three steps
thanks kind sir
Has anyone encountered this error before , "<static_files> was blocked due to MIME type {"text/html"} mismatch {X-content-options : nosniff)
Tech stack : django app running on docker with nginx as reverse proxy and gunicorn as my web server.
Hi everyone! I would like to try using Python instead of JS for web development. I've seen Django, Flask, and FastAPI mentioned, but does anyone have a recommendation for which one I should start with?
I started with Flask and i'm now using Django.
How do you like both of them?
Django has a lot of built in features. I'd prefer you use it.
Thanks for the suggestion! I'll definitely look into it
Good to know! Thanks for the info
Does anyone know how to save a todo list to local storage
how do you get "Connection is secure" for your website?
like this
ping when replying, thank you
you need an SSL cert, which these days you get from Lets Encrypt, which many hosts can do for you.
TLS* SSL is a deprecated technology where sadly the name keeps getting reused everywhere
ah okay, thank you
basically Google pays someone like Symantec to give them a certificate (where Symantec is the certificate authority [CA]) and Google uses that to encrypt the the traffic they serve to you using HTTPS (HTTP over TLS).
This is seen as secure because 1. you trust the CA, 2. they've established their identity with the CA so you know they served the traffic
there's a lot more complexity when it comes to CAs and certificates, but that's the gist of it
what "trust" breaks down to usually is which vendors the operating system vendor has established trust with and includes their root certificates in your OS certificate store
or something like Firefox which includes its own certificate store
or Java which provides its own store as well (usually inherited from the OS, though)
so they can just approve themselves as certified?
not usually what happens, there's usually a chain of trust
but anyways, the easiest way to serve HTTPS traffic (and thus get the "trusted" lock for your domain) is to subscribe to Let's Encrypt service which can auto-renew your certificates and hands them out for free @past cape
@pine yew what is the right word to use instead of SSL?
Looking for a saas boilerplate with social logins, background tasks, great components, stripe etc. Can pay $$$ but like, saas forge demo doesn't even work lmao
I would appreciate a good BP
if have to, doesn't have to be python but would be great... Just not PHP.
This project got me a full time software job. Follow Along as I walk you through tricks I Used. This project got me a full time software job. youtu.be/UGsRT53hgqM
Follow Along as I walk you through tricks I Used. https://youtu.be/UGsRT53hgqM
#Frontend #UiUx #SoftwareDevelpment #HTML #CSS #CrashCourse #responsive #websites
In this crash course, I will show as much about HTML as I can. This is meant for absolute beginners. If you are interested in learning HTML but know nothing, then you are in the right place. We will be creating a cheat sheet with all of the common HTML5 tags, attr...
Maybe just do localstorage.setItem('example', your data )
hey i'm building a react django app and i wanna create an admin interface (a customized one)and idk how to proceed, how would you guys do it ?
I am not getting the desired output in this flask app I am working on. The details are in #help-coconut, please help me if you can.
Hi, is there an option to use django admin panel while having ONLY an in-memory database?
Does anyone know how to set var(--color) as game.color here?
{% for game in games %}
<div class="col">
<div class="card" style="background-color: var(--color);">
// Code
</div>
</div>
{% endfor %}```
Usually Id use {{ game.color }} but it seems theres special rules when inside CSS
Redis is an in memory database. I don’t know if there is a Django extension for it though
my question is outdated for now, I think I found the way:
https://stackoverflow.com/questions/33920368/django-in-memory-sqlite-in-production
thank you for trying to help!
Is it normal for image links to be over 12000 characters long? In a tutorial I was told to make the max length ~2000 but it seems like every time I copy an image link they just keep growing in size
Can someone please suggest me some Flask projects. I'm a beginner in Flask. Thanks in advance 🙂🌟
Let's encrypt is a hard way
Just use Cloudflare, it has it as inbuilt feature to have verified certs
U need to have self signed certs active at your address though
How is it that websites have custom links for every profile? For example, if I visit someone's profile on IG or FB, they have custom links to their profile that is unique to them, how can I implement the same system into my own flask website?
Any idea that you have. The only restriction you should give yourself is that it shouldn't include stuff other than webdev, for example, algorithms. If it is an idea you came up with, even better.
maybe make a basic CRUD
Are you talking about : www.fb.com/person-xyz-(random alphanumeric characters)/ such links ?
Yes
Basic CRUD like student registration something?
not sure how new you are, you might start with a very, very basic CRUD, just to communicate with a database
and build more advanced ones later
to-do app could be the very very basic CRUD
just a simple list with buttons to add a task, edit a task, delete a task
no fancy stuff
no user login
then you can make one with user accounts, each user would have his own to-do list, @gritty vapor
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
@zealous elk you mean a link generator ?
@zealous elk & @wet hinge thanks for the help and suggestions 🙇🙂🌟
hello guys i got issue in ''''''
'''py
class CreateItem(CreateView):
model = Item;
fields = ['item_name', 'item_desc', 'item_prce', 'item_image']
template_name = 'food/item-form.html'
def form_valid(self, form):
form.instance.user_name = self.request.user --> i didn't understand this line of code
return super().form_valid(form)
'''
Heyy
hi
just ask, ill see if i can
perhaps? to your preferences
Ok then dm
I might actually cry...
Why is web app development so incredibly complex and hard...
Everything is hard the first time. Baby taking steps is hard the first times.
Most people know how to solve something as they’ve seen the same/similar problem in past. Just takes time to build that xp.
Hey folks, I'm looking for an old Python 2 project that I can run in a test environment to practice migration to Python 3. I'm working on a migration of a legacy app at work, and I want to try out some techniques I've learned recently. Anybody have any antiques they are willing to share?
what r some things i should remember before shutting down my website considering that i will later host it again in some time
digital ocean btw, i want to stop hosting and continue exactly where i left in a year or two
Because everything is chrome in the future.
Make sure tests exist to make your life easier.
Indeed, that is something that is a part of any good migration. 100% agree.
I dont know if this belongs here but I am creating a website using Flask and I am trying to make a login feature but It doesnt work can anyone help, ps if asked for I will send the full code, please @ me
Are you using flask-login?
Quick question, is the built in hashing system for passwords in django a good up to date one? Or is it smart for me to implement a different algorithm?
TLS because SSL is a dead tech.
ok, thanks
I'm not sure if this is the right channel for this, but I was wondering if anyone knew of how to send emails through a gmail account since Google changed their policy on 5/30?
can i learn in one day how to deploy a flask app to heroku with docker?
yes, there are loads of cut-and-paste tutorials like this: https://realpython.com/flask-by-example-part-1-project-setup/
ah thank you, my app is finally done, all i need to do is to dockerize it
I assume you mean programatically, with Python via SMTP... Does this no longer work? https://geekflare.com/send-gmail-in-python/
Yea sorry that's exactly what I mean, on 5/30 Google decided they would no longer allow "less than secure apps" which smtplib falls under I guess
damn tho, deploying can be so freaking complex
this might be the best one so far https://youtu.be/ZVtv_JkF72M
Hey guys so in this video I just wanted to show you how to deploy your app to Heroku with Docker and then redeploy it once you have made changes.
LINKS
how to run dockerized apps by Travis Reeder: https://medium.com/travis-on-docker/how-to-run-dockerized-apps-on-heroku-and-its-pretty-great-76e07e610e22
Docker mastery by Bret Fisher: https://w...
My company started using something called DuoCircle recently to handle our alert emails, I guess that must be why
:(, was hoping to play around with that while learning some stuff but I guess that'll have to wait until i can figure something else out
Using stuff like sendgrid instead of Gmail account
It is better because not rate limited to humans
Hi. I have this section in my website where the user fills up some inputs. After the user fills all the data, there is a save button, how can I assign a python script to a button? I would like this python script to use a POST method to send the data the user filled in as a json. Anything you know like a video or doc that could help me? Or by any chance someone want's to help me 😄 Thanks in advance to you all 🙂
help how do i make something move if i hover over another thing in css
:hover{}
Use this..
Using Python Django and Github together for a personal website, is there a better way to update my github repo website without having to copy and repaste the code from my IDE to GitHub and see the changes in almost real time?
Hi, does anyone have experience sending data to a browser using flask?
is it normal for docker build (container image) to take more than 10 minutes+?
that really depends on your build stage and app
oi mates i just made my first docker container sheesh
What
CICD
git push or do the equivalent with your IDE
Many people here will have done so... Don't ask to ask, just ask
how to fix this error , in the tutorial of cs50 the instructor didn't do anything on the file settings.py > templates and it worked for him but for me this error occured
how's your TEMPLATE set in your settings.py?
actually i am a beginner
i didn't set anything on templates
no worries on that, everyone were a beginner at same time 🙂
i just made a folder named templates in the project and made a folder named home and in that i have written the html file
yes 😇
what I think you're missing is to setup the DIRS key in your TEMPLATE. Could you show us how's your BASE_DIR being generated? It's in the same file and usually at the beginning of the settings.py
im tryna run my docker container and this is what I get:
[2022-06-08 11:40:15 +0000] [9] [INFO] Worker exiting (pid: 9)
[2022-06-08 11:40:16 +0000] [7] [INFO] Shutting down: Master
[2022-06-08 11:40:16 +0000] [7] [INFO] Reason: Worker failed to boot.
i guess i have to change something in my procfile or gunicorn settings
is this locally or in heroku?
For things like that we would need to take a look at those files
in this in the project1 > home > templates > home > index.html
i want to deploy it to heroku but i was trying to run it locally
maybe i should try to do it for heroku?
@austere isle can you actually send what's in the beginning of this file? The BASE_DIR usually will be there
it probably would fail there as well
ok
for running locally your docker setup shouldn't depend on the procfile, which is a specific file for heroku
OK so now try the following: in the TEMPLATES you will see a key called DIRS where its value for now is an empty list. Try putting there the following:
"DIRS": [BASE_DIR.join("templates")],
it will do so that Django will look for templates inside your apps
would you mind helping me if I share my screen? it'd be easier, i'd be really glad
its a flask app btw
I'm not experienced with Flask but I can try
don't mind at all
I still have some time until start working 🙂
thank you!
now i got this error
how is it your TEMPLATES now?
\
I'm sorry, let's try this here instead: 'DIRS':[os.path.join(BASE_DIR,'templates')]
ok not a problem
now it worked thanks a lot 😇
Nice!
Gonna try this : https://medium.com/featurepreneur/how-to-deploy-docker-container-on-heroku-part-2-eaaaf1027f0b
In the previous article, we’ve seen about How to Deploy a Flask app on Heroku. If you haven’t seen it yet, click the below link to see it.
Hope it works 💀
the only part you should be careful about is to not use sudo to run the docker/docker-compose commands
Because of the WSL?
but it seems to be a nice blogpost