#web-development
2 messages · Page 228 of 1
but when i add it from a form connected to the API (backend)
it doesn't sends
default value
idk whyy
man idk why
Like constraints of a variable would conventionally be set with a method
the way it works is called type hinting - it's just a feature that's supported by Python. In general when you type hint something, it is only a hint and you it could technically be any type
but pydantic does some introspection and checks the types and it will then change it's behaviour based on those
!e
a_variable : int = "not an integer"
print(a_variable)
@rigid laurel :white_check_mark: Your eval job has completed with return code 0.
not an integer
Anyone know how to start a production server for flask?
So colon hinting updates annotations attibute of the object? annotations would not throw an error when the return value is of another type?
I'm honestly not entirely sure, but in my experience I've never had to manually set __annotations__ for anything
Ok thanks
hey i am getting this error from this code
from selenium import webdriver
driver = webdriver.Chrome(r'C:\Users\ahmad\OneDrive\Desktop\Apps\html\chromedriver')
driver.get('https://www.wolframalpha.com/problem-generator/quiz/?category=Calculus&topic=BasicIntegrate')
wd = webdriver.Chrome(executable_path=driver)
players = driver.find_elements_by_xpath('//td[@class="problemImage ng-isolate-scope ng-scope"]')
C:\Users\ahmad\PycharmProjects\pythonProject3\main.py:2: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
driver = webdriver.Chrome(r'C:\Users\ahmad\OneDrive\Desktop\Apps\html\chromedriver')
C:\Users\ahmad\PycharmProjects\pythonProject3\main.py:5: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
wd = webdriver.Chrome(executable_path=driver)
Traceback (most recent call last):
File "C:\Users\ahmad\PycharmProjects\pythonProject3\main.py", line 5, in <module>
wd = webdriver.Chrome(executable_path=driver)
File "C:\Users\ahmad\PycharmProjects\pythonProject3\venv\lib\site-packages\selenium\webdriver\chrome\webdriver.py",
line 71, in start
self.process = subprocess.Popen(cmd, env=self.env,
File "C:\Users\ahmad\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 966, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Users\ahmad\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 1375, in _execute_child
args = list2cmdline(args)
File "C:\Users\ahmad\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 561, in list2cmdline
for arg in map(os.fsdecode, seq):
File "C:\Users\ahmad\AppData\Local\Programs\Python\Python310\lib\os.py", line 822, in fsdecode
filename = fspath(filename) # Does type-checking of `filename`.
TypeError: expected str, bytes or os.PathLike object, not WebDriver
anyone know what this is? if the error doesnt make sense i had to remove a bit of it in order to fit it in
starts here - "DeprecationWarning: executable_path has been deprecated, please pass in a Service object"
yeah i fixed that
but now it is saying this
TypeError: expected str, bytes or os.PathLike object, not WebDriver
idk how to fix that
oh wait
from selenium import webdriver
import pandas as pd
driver = webdriver.Chrome(r'C:\Users\ahmad\OneDrive\Desktop\Apps\html\chromedriver')
driver.get('https://www.wolframalpha.com/problem-generator/quiz/?category=Calculus&topic=BasicIntegrate')
wd = webdriver.Chrome(executable_path=driver)
players = driver.find_elements(by=By.XPATH, value='//td[@class="problemImage ng-isolate-scope ng-scope"]')
new code
idk if i fixed it
1 sec, I have something like it
Also doesn't look like you changed the original error for executable path - you have to use Service() class - https://stackoverflow.com/a/70099102
yeah i saw that do you just add .service() to that line i was trying to delete
this one?
yeah ok i added it
Yeah try -
wd= webdriver.Chrome(service=Service(ChromeDriverManager().install()))
it still gives me that error
do I even need this line?
can i just delete it when i do i dont get any errors
Make sure you have the imports
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
ok
well now I got
ModuleNotFoundError: No module named 'webdriver_manager'
ok
im putting pip install webdriver-manager
ok no more errors
nice
thx
yeah im just trying to webscrape a page for a specific image
i just need to find the image rn
are you using bs4
no selenium the website has javascript so i need to use selenium
and for some reason i cannot find the image
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(r'C:\Users\ahmad\OneDrive\Desktop\Apps\html\chromedriver')
driver.get('https://www.wolframalpha.com/problem-generator/quiz/?category=Calculus&topic=BasicIntegrate')
wd= webdriver.Chrome(service=Service(ChromeDriverManager().install()))
players = driver.find_elements(by=By.XPATH, value='//td[@class="problemImage ng-isolate-scope ng-scope"]')
try running this
im trying to just get the math equation part
im trying to get this
Hey does anyone know how to get a static file imported from JavaScript using a fetch request (with Django)?
I have some images I want to load as textures for this WebGL project I'm working on, and I'm trying to figure out the best way to get those images loaded.
I currently put a script tag/element in one of my HTML templates and then load the textures there so I can use the Django template syntax to dynamically load the static files, but I would like to get away from putting JavaScript directly into the HTML. I'm not sure how I can properly reference static files from another static file (JS file in this case) while having the path dynamically generated by Django on the back end.
If it were JSON data, I was downloading, I would know how to do this, but an image seems like it would be a bit different.
Ok thx I'll take a look at it
guys what is this? should i worry about it?
im just trying to upload my flask app to github
i read somewhere that i should ignore this but im not sure
or maybe i should use: git config core.autocrlf true
im having issues with venv
should i convert it to 'requirements' or what?
so all I have to do is just put the requirements.txt in my github and stop worrying about the venv folder?
Yes. it is useless to commit venv
it is big and will be broken once its absolute path is changed
plus it is silly to commit such bit depepdencies
have you checked its size? it takes hundreds of megabytes!
Alright mate, thank you. I just did the pip freeze and pushed my requirements.txt to my github.
👍
Use static root inside your JS file e.g:
My STATIC_ROOT = 'static/'
so I would use it: src="static/path/to/other-static-file.js"
Hello! I want to create custom manager from QuerySet class in django, but when i do it, it stops working https://pastebin.com/dqMLSVwC Can someone help me?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
# solution
def calculate_total_cost(self):
return self.annotate(
total_cost=Sum(
F('products__quantity') * F('products__price')
)
)
I'm new to using FastAPI and I'm quite impressed so far. I have a basic JWT authentication scheme kind of working. However, I have a Depends for a route where I would like it to fail if the dependency returns None.
@app.post("/highscores", tags=["highscores"])
async def add_high_score(score: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
...
The function get_current_user checks the JWT token for validity, extracts a user id and loads the user from the database. However if the user has been deleted then the token is valid but there is no such user, so the function returns None. Is there a way to force the dependency to fail in that case?
Or should get_current_user raise an exception if no user could be found?
Use a different dependency called require_user which raises a HTTPException
i.e. ```py
def require_user(current_user: User | None = Depends(get_current_user)):
if current_user is None:
raise HTTPException(401)
return current_user
@iron magnet ?
@frank shoal Ah, that’s a great idea!
Probably not quite python question but... I have a big table from sqlite bd on a home page and i want to add sorting and filtering. What is the best way to implement it provided I have no JS experience?
I use fastapi to interact with the db and a little jQuery
I suggest using datatables.
Tell me more please
I used Semantic UI to add tables to the page, but there is no pre-added sorting
If you have a lot of data, you could use ajax and the pip library sqlalchemy-datatables to handle it.
!pip sqlalchemy-datatables
Hm ok, so its not in vanilla sqlalchemy?
It's not a plugin, just a layer on top.
I.e. I have full sqlalchemy installed
You just give it a list of columns, your url search params, and your initial database query, and it handles the rest.
When I have a input field for example and when the field get changed I want to make a popup to save the Changes. How could I detect the change of the input field?
for images <img> use get_attirbute("src")
this will give you the link, for a href use "href"
try jQuery.sheet?
Is there maybe any way to do it with Flask?
You can take Discord Roles as a example. If any Text/Permissions gets changed you get a prompt to save it
Thats what I need
that would probably be a javascript thing and not python
Well it wouldn't be too hard to make a CRUD endpoint in flask.
It would just be detecting when a input is changed and setting a flag.
It's a bit simpler in a framework like vue
I got a small question, I got a db on mongo and using flask.
Do you guys know anyway I can show the database on the website in interactive way? so the users can filter through stuff, search and export the results ?
hmm looks pretty neat but I can't see export feature
Would it just loop a GET request or how would that work
thanks i'll dig in
single requests containing all the data via a PUT request. or some of the data with a PATCH request
put is replace. patch is edit
two options
a) Building frontend on your own (Full customization to any desires, longer development)
b) using some already prebuilt tool (Nearly instant development, limitations in features which are nearly impossible to add)
But is that even possible with a simple <input>?
datatables seems to have everything I need
You would need to use the onchange event and mark a variable named something like dirty
I tried with the onchange event and jinja context proccessor but it called the onchange function already when the page was loaded
Hello ladies and gentlemen! Got a quick question regarding managing classes. I finally worked out a working webshop with a "Item" class. The "Item" class has many functions on it and is referenced in other classes to make the cart and checkout process running. Now i want to specify the products by creating new classes like "Shoe" or "Tshirt" which each has own attributes additional to the "Item" class attributes. What are my options to do that or what is recommended to do? I came around Abstract Base Model but i can not reference to abstract models. I read about PolymorphicModel, but is it really the way to go?
with sqlalchemy or django?
you ever tried to work with it on flask?
The table isn't loading at all, tried with hard coded data and its good
ajax is just a old version of fetch
make an endpoint in flask, and you should be fine.
like it should be a GET that returns the array ?
<table id="table">
<thead>
<tr>
<th>Field 1</th>
<th>Field 2</th>
<th>Field 3</th>
</tr>
</thead>
</table>
<script>
$(document).ready(function() {
$("#table").DataTable({
processing: true,
serverSide: true,
ajax: "{{ url_for('datatable_ajax') }}",
});
});
</script>
Guys have you heared about pyscript ??
from datatables import ColumnDT, DataTables
from flask import Flask, request
from .models import db, Table
app = Flask(__name__)
@app.route("/datatable_ajax.json")
def datatable_ajax():
columns = [
ColumnDT(Table.field_1),
ColumnDT(Table.field_2),
ColumnDT(Table.field_3),
]
query = db.session.query().select_from(Table)
params = request.args.to_dict()
row_table = DataTables(params, query, columns)
return jsonify(row_table.output_result())
libraries: flask, sqlalchemy, sqlalchemy-datatables
the Table and db is sqlite?
it's your sqlalchemy models
i'm using mongodb, i'll change that part
!pip mongo-datatables
thank you sir
the documentation is from 2019, doesnt working rn
have you tried it before ?
nope.
im not getting any error but its not working lol
Im getting this weird long request
127.0.0.1 - - [11/May/2022 22:12:32] "GET /datatable_ajax?draw=1&columns%5B0%5D%5Bdata%5D=symbol&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=0&order%5B0%5D%5Bdir%5D=asc&start=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&_=1652296289001 HTTP/1.1" 200 -
im using this but altered the python method on app.py
how would you suggest I can add real time chat into my flask web app?
what is that?
you meant stock charts ?
I meant chat 😂
oh sorry I read "charts" 😅
lol
How can I turn this into a flask app?
import requests
API="http://api.brainshop.ai/get?bid=166402&key=Plje0nBq6IAuFf0S&uid=[uid]&msg="
question = input("Question> ")
response = requests.get(f'{API}{question}')
print(response.json()['cnt'])```
Hey trying to run a flask app in docker container, I keep getting the error "FLASK_APP has no env variables"
anyone has idea how to setup enviroment variables in windows?
How are you running it? Compose, docker run, or dockerfile?
ok so im trying to make a login/form thing, but I'm confused on how to submit it. I would like for it to be put into a json file if thats possible
heres my form code incase you need it: https://hastebin.skyra.pw/idusicovih.htm
i'm using selenium to add items into a cart and I just wanna know if that is a safe thing to do? I want users to be able to use the window i opened to buy whatever is in their cart
Missing '
Hi guys! Could you help me with modals? I have 2 modals on the same page but contents of both appear on the same popup window one under another
https://semantic-ui.com/modules/modal.html
How can I devide 2 modals?
A modal displays content that temporarily blocks interactions with the main view of a site
can u be a little more clear/.
@hard whale
post ur output
and what u expected it to be
I mean is there any id for modal to open some content in separate pipups?
Not in the same one
someone can help with my problem? https://stackoverflow.com/questions/72211918/the-view-budget-views-budget-didnt-return-an-httpresponse-object-it-returned-n
You probably returned None there
Hmm but where is the none? Everything on b_form is copy/paste from a_form that is working
You don't return anything explicitly at the end
Oh, right, sorry 😅
Didn't see the render call
the render call was on else: statement
and i was getting that error
i removed the else and reverted the indentation on render and i dont get error nor income value is adding
a_form still working
no idea what is wrong :/
I'm not sure what's wrong there too, all i can suggest is debug it and see what you actually return from the function 🤔
Won't the post request get resent to the same view if u use redirect
@short flax
Won't it become infinite post loop
🤔
Well maybe.. but still b_form somehow is not valid
can u send b_form model?
or form validator
`class BudgetData(models.Model):
SPOZYWCZE = "Spożywcze"
CHEMIA = "Chemia"
RACHUNKI = "Rachunki"
ALKOHOL = "Alkohol"
GRY = "Gry"
CATEGORY_CHOICES = [
(SPOZYWCZE, "Spożywcze"),
(CHEMIA, "Chemia"),
(RACHUNKI, "Rachunki"),
(ALKOHOL, "Alkohol"),
(GRY, "Gry"),
]
category = models.TextField(choices=CATEGORY_CHOICES, default=SPOZYWCZE)
cost = models.FloatField(default=0)
date_added = models.DateTimeField(default=timezone.now)
user_expense = models.ForeignKey(User, on_delete=models.CASCADE, default="")
income = models.FloatField(default=0)`
its the model
b_form use just the income at the bottom
class AddIncome(ModelForm): class Meta: model = BudgetData fields = ["income"] help_texts = { "income": ("Add your income."), }
and the form
def require_appkey(view_function):
@wraps(view_function)
# the new, post-decoration function. Note *args and **kwargs here.
def decorated_function(*args, **kwargs):
if request.args.get('key') and request.args.get('key') == APPKEY_HERE:
return view_function(*args, **kwargs)
else:
abort(401)
return decorated_function ```
can anyone tell what this code snippet actual does under the hood?
guys, i cant understand this: if i create templates in django, am i doing some kind of frontend development? so if i create just an api in django, can i then make the frontend in, for example, react and take the information from the django api i made? or am i confusing a lot of concepts?
Yes you can do font-end dev and just connect to your django backend.
Templates are for FE dev for those that don't want a full FE framework like React/Vue
You'll look into Django REST or Graphene / GraphQL for that.
Hey, im planning to build a Chat Room Web App using Django and for the past day or two iv just been researching and watching videos on it because its a whole new realm for me. But one thing i havent been able to understand is how Redis is used? so to my understanding Redis makes queries to the database way faster because everything is stored in "memory". And you cant use "inMemory" for your CHANNEL_LAYERS unless its for testing purposes, which is to my understanding why Redis needs to be used for production and deployment. However i dont actually know how the process works. Like once you write channel_redis.core.RedisChannelLayer in settings.py to like initiate it, is that it? or do you have to start configuring and managing your code to suit it or something? I havent found any material that has helped me understand this part of it. Mostly i just see people use 1 line and thats it or something.
if anyone knows any good material that helps understand Redis i would really appreciate it.
I haven't used it much but my understanding is that Redis is a cache, so I would think that you wouldn't want that for a real-time implementation.
It would be better suited for something where you don't want to have to hit the server a lot, so maybe some queries that won't change often.
oh sorry i meant Asynchronously im an idiot i thought Real Time and Asynchronous are the same but they not
redis is a simple key-value database. imagine it as a dictionary that can stores as keys and values only strings, and all of them are stored in RAM ;b
plus the record has a time to expire property (which can be inifinity), once it is expired, it becomes not valid
so you can tinker with how long is valid the record there
tinker?
you can set something like redis.set("abc", "123", TimeDelta(minutes=5))
your record 123 will be valid for 5 minutes
after that something happens
ohh i see
redis.get("abc") to get the value of 123
so sort of like Snapchatish
for example sending a message and then you can set a time until that message is removed?
oh right
anyway. The point of Redis is that it is just the same dictionary, but its data is shared across instances of your application
accross multiple backend instances (we usually ran several django app instances in parallel to handle traffic of multiple users at once)
or even across several different backend apps
but it is basically still same dictionary with a bit different functionality, which just ensures having dictionary with shared memory across app instances
right but do i need to specifically mention it to store things in it? so for example (exclude django channels) if i wanted to save something to the database i would usually use the .save() command, do i need to do these types of things when using redis?
If u a pervert, you could reinvent the wheel and make the same with multithreading stuff btw 😉 but it will be complex and not needed of course
redis default library just gives redis_conn.set and redis_conn.get, that's it
at maximum it can give you saving and getting objects in bulks in addition
the rest is something invented on top of it
oh so when you declare it using something like this is that all that needs to be done?
CHANNEL_LAYERS = {
"default" : {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": # etc
}
}
sigh. details of the channels implementation is details of the channel implementation. If it uses it that way, ok.
those are already details under the hood of the django channels library
any library can use under the hood any other library/stuff
the difference is only channel library requiring to have raised infrastructure object of redis
same when Django requires instance of postgresql if u wish to work with it (it utilizes Sqlite3 as default alternative though)
Ah right. Thank you this was very helpful and informative, i appreciate it.
Hi guys, I have a website project powered by Flask. This website presents a visualisation of some common sorting algorithms. The sorting algorithms themselves are written in python, but the implementation of getting the data is written in Javascript atm. Is this a valid approach? Because, when I click on a "sort" button, Javascript sends many requests to Flask using requestAnimationFrame
docker-compose
it does not sound like valid approach. Too many requests
as a fix, consider sending frames in bulk, all at once or just more frames per request
or implementing sorting at client side in js (the most performance wise approach to this problem)
ahhh so do the sorting algorithms in javasccript itself right
yeah. Preferably consider using frontend framework like Vue.js
it will make your job way way easier
because Vue.js will bind your data from its Model to be directly shown as in its View, in a MVVM scheme as far as I remember
You will be able just to have the data changed in Vue (sorting it when doing smth), and it will automatically rerender to user screen
everything at clientside, without any requests
this is the easiest approach to Client side javascript
oh really?
so i don't have to use any python?
or can i still use flask
cuz i really like the templating
Vue.js has 10 times more powerful templating
giving you also access to stuff like SCSS
so don't even use flask?
Using vue.js, I miss jinja's pipe syntax
attempt to write js in jinja, and the piping problem will be seen like a minor 😆
ok 1 more thing
i want to make like a debugger sort of screen
so basically the data of the sorting algorithm is passed into a linked list
which can display the variable names of the current "step" or "pass" of the algorithm in a table
or some sort of display type
xD, i did literally stuff like that once. I made debug shown from Ansible running playbooks 🙂
and this will also happen alongside the visualisation
so u saying all this is still a frontend task
it sounds to me like a still just frontend
how hard is it to pickup vue.js
I got a hang and started doing my projects within a matter of 1 and half of a week in vue.js
with learning frontend literally from zero
html, css, js, i knew nothing
are there any good tutorials that get u up to speed
at the website is written that you can learn vue.js from 2 hours to within a week. Vue.js is easiest to learn out of frontend frameworks
I got started from
Then went through
then made a stop at
plus went through one less worthy to mention book
and then started learning vue.js docs
how does vue do this
it is magic under its hood
a matter of using Patterns of Programming and having Clean Architecture in itself
just cool designed code and the data flow of data
which becomes a bit complicated if we remember that it works that well while being in browser and its ecosystem, DOM and browser APIs
amazing framework.
basically it is using as far as I know virtual DOM, which is reviewed to the user
How vue (and most other frontends) works: When state changes, it destroys the node and rerenders it instead of editing it inplace like you would do with jQuery and DOM traversal.
and probably uses all those javascript listening stuff in order to get feedback back
in React people can control rerendering at a lower level apperently
more complicated framework to use
curious
what if in higher component happens the change?
and we froze with v-once child components of this component
hmm ok
If you need to manually rerender a node for whatever reason, (you're probably doing wrong reactivity, computed, watcher, key with v-for) you can use $forceUpdate()
if the element is in the child component, you can use emits to update the parent. There's also inject and provide for similar, global functionality
any good guides to use vue.js quickly
emits is essentially making your own events, like @change="onChange"
I enjoy this channel. https://www.youtube.com/c/ProgramWithErik
My name is Erik Hanchett and I'm a web and Java developer from Reno, Nevada. I've been a programmer for many years now and I've always been wanting to give back to the community. I started this channel, and my website (www.programwitherik.com) as a way to teach people what I know.
I started learning web development seriously in early 2015, bef...
Ben Awad for general javascript and react.js
There's also this to play around. https://sfc.vuejs.org/
okay thanks!
btw are there some youtube tutorials on vue.js?
see the channel I posted.
Here's a whole playlist
https://www.youtube.com/watch?v=YrxBCBibVo0&list=PL4cUxeGkcC9hYYGbV60Vq3IXYNfDk8At1
Hey gang, in this Vue 3 tutorial series for beginners we'll learn Vue.js (using version 3 - the latest major version) from the ground up & use it to make a couple of nice web projects - a reaction timer & the beginning of a small, simple blog. In this video, I'll give you a quick intro to Vue & the new features Vue 3 has to offer.
🐱💻 🐱💻 BUY T...
thank you so much
been working on my first Flask project for a while, i love Flask, so good.
That's a good looking frontend.
thank you, I was learning / doing frontend before switched to python / flask
but I'd say it's 50% completed
Good luck on your way to full-stack
maybe soon, you can switch to fastapi as a rest backend for your react or vue app
sure, I'm just working on Flask and building this project for my upcoming internship (company uses flask)
what about pyscript ? 🙂
wdym?
is it a weird attempt to make frontend python scripting?
not valid for real world production
i hate javascript
There is a choice in javascript, javascript and javascript for frontend
Have I mentioned javascript? xD
i used vanilla JS for like 9 months without a framework, it was a pain
😄 😄
well technically there is typescript in addition. But you know, it is still javascript under the hood.
for this, or for flask / api projects, apps you don't really need js. but you could easily integrate js / react or any frontend framework into it
i might do it later
yes it is. Frontend framework javascript is different and much better
but i feel like that would be an overkill for an internship
also i want to deploy this to heroku with docker lmao
i use django
used*
there is lots different techs this development things going more complex always..
yeah I'd like to learn django down the road long-term
any good frontend tutorial?, I have my flask project and I want to stop using bootstrap and write my own styling.
Does it make sense to automatically create a new table for every use when they sign up? To keep record about that particular users activities
wdym?
table for every user?
Hello there.
I'm working at a small company that already have a fully implemented java backend, but wants to start migrating to python, starting with some more costly endpoints.
Is there a more a more recommended framework ? A guy in another channel recommended me FastAPI, since my objective is exactly to go fast
But is it recommended for big and scalable servers ?
I've found fastapi to be similar to spring in some aspects.
Yes. To store stuff like "people interacted with", notifications,etc
Just user specific stuff
if im planning to interview for an internship, should I just improve, tweak this app or try to build as many as possible?
Wouldn't it make sense since pulling that data from a per user based table would be faster than using one general table?
anyone here familiar with selenium, also django, running locally?
Django here but not selenium
well my app is trying to execute a chromium.exe file, but I get an error that it has the wrong permissions. I'm able to run it in heroku, and locally elsewhere, but not here locally through the procfile
I'm sure its a windows 10 permissions thing, chmod 777 apparently is not a thing here
I tried cacls myfile.txt /g everyone:f
on the exe, but I get the same error
Selenium but not django
well here is the error I'm seeing "selenium.common.exceptions.WebDriverException: Message: 'Home-Finance-App' executable may have wrong permissions. Please see https://chromedriver.chromium.org/home"
someone can help me with my problem in django? https://stackoverflow.com/questions/72211918/the-view-budget-views-budget-didnt-return-an-httpresponse-object-it-returned-n
most likely wrong .exe path to your chromedriver
that makes sense to me. I've added the full path to the .env file to the exe
(I am new to django)
If the .exe is for the chromedriver it just means you have to have it on your local machine - how are you calling it?
chrome_options.binary_location = os.environ.get("GOOGLE_CHROME_BIN")
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--no-sandbox")
driver = webdriver.Chrome(executable_path = os.environ.get("CHROMEDRIVER_PATH"), chrome_options = chrome_options)
my workaround is to comment that code out and to use this code when I run locally and it works fine.
options.add_argument('--headless')
options.add_argument('--disable-gpu') # Last I checked this was necessary.
driver = webdriver.Chrome(chrome_options=options)```
though the latter doesnt work when I push to heroku
Actually I havnt tried, but I'm sure it wouldnt.
and in your .env for the app the driver is stored in "GOOGLE_CHROME_BIN", correct?
yeah right
Scratch that, it's actually referencing where it is on your local machine - what is the "CHROMEDRIVER_PATH"?
GOOGLE_CHROME_BIN = "C:\Users\aa\Home-Finance-App"```
I set both to the same 🤷♂️
I might be spending too much time on it already... the work around isnt horrible for me.
Lol, ok well is that where it is ?
yes, ha I did put the chromium.exe file where the enviornment variable is pointing to, above
and changed its permission using some windows ca function
@inland oak I updated my production server and I can still access the django admin but I'm getting an nginx gateway error when accessing the site. There were no nginx changes. Anything stick out as a possible reason I'm getting the gateway error?
how will you make the models for that/
?
Create a REST API for cars. It should contain accounts, CarBrand, UserCar, and CarModels. Each user has to be extended by default Django abstract class and should contain a few more columns (for your choice). Each car object contains relations to the user and CarBrand. Each CarModel contains relation to CarBrand. It is all your decision how you will distribute models to different apps. Please make the API URLs with filters (custom typed). All models should be with soft delete.
Models fields:
CarBrand [name, created_at, deleted_at]
CarModel [car_brand, name, created_at, update_at]
UserCar [user, car_brand, car_model, first_reg, odometer, created_at, deleted_at]
Auth:
Please extend the default Django user class and add some custom fields. Create login, and register functionality. User default Django permission classes.
It doesn't look like it's referencing the ChromeDriver itself though, try extending the path with the actual chromedriver variable
there can be multiple reasons
Do u use cloudflare? They restrict traffic to 80 443 ports
Same questions goes if you use AWS for example
then we can ask questions in how you deploy your stuff, docker-compose, kubernetes or whatever system
pulling directly from github
manually?
Yea
that's already a reason in itself.
ok I'm not sure what that means, when I have run selenium in the past, I just download the exe, put it in the scripts directory, and it runs fine. There is no other 'chromedriver' directory, as far as I'm aware
it already means that you can't rely on that you did not change nginx / code of deployment
because your deployment is not automated / not a code
But nginx is only on the prod server.
u a supposed to have staging environment to test your deployment
even it is homelab, we still having staging / testing env
that's another problem, that nginx is present only on the prod.
your staging environment to test your stuff should be as close and similar to prod as possible
i see no reason why you have nginx only in prod
You're suggesting to run it also locally?
i am suggesting to raise temporal infrastructure in DO that exactly matches prod one, but just uses cheaper resources
if you do it for work
Yea I'm actually going to set that up now, but I'm going to have the same problem in the staging server.
that's exactly the point
to discover it in staging before making deployment to prod
if you made mistake and something like that appeared in prod, you are supposed to have a way to rollback yourself to previous prod version, and then calmly debugging in staging/dev env
Yea, I'm not disagreeing with that. 😄
Ok this could be a django/windows thing, I've never ran selenium that way - strictly python/mac, most of the current errors since the update have to do with calling the executable path which has since been replaced with the Service() object, but doesn't seem to be the error you're encountering right now - if chromedriver is somehow enabled within the heroku app through the application source path solely that could also point to Heroku implementation taking care of the issue you're seeing locally. Have you ran it on this machine before?
no I have not run into issues (like this) with selenium before. I think youre right its a django/windows thing. I know when I put this on heroku, there were two heroku specific github build packs that had to be added. But like I said, in my experience running locally, I've never had to get more than just the exe.
anyway I have a workaround, its messy and annoying lol, but it works for what I'm doing just fine.
If it works and there's no dire need to have it be ran the exact same way, Heroku has it's own way of doing things sometimes - but also be careful with it, they had a security issue running GitHub pipelines a few weeks ago.
Just curious, when you launch the app locally are you running it in a virtual environment?
thats interesting, I didn't know that. My plan right now is using the heroku app only to make already public data more easily accessible to me (for now), so I'm not too worried about that. But it is good to know, thank you.
I am yeah
I still don't think GitHub is allowing connection to Heroku via pipelines - I had a couple minimal apps deployed that way that have since been disconnected by GitHub while Heroku has been prompting a force change of passwords - https://github.blog/2022-04-15-security-alert-stolen-oauth-user-tokens/
I guess I don't understand the heroku buildpacks, from the desription on heroku, they are scripts that are run when the app is deployed. is that considered a pipeline?
hi @native tide
Is there any documentation to lear about follow notation in django
Heroku buildpack is basically a compiler service - different from the pipeline implementation I'm referring to, the buildpack can be a seen as a step in the pipeline towards deployment. When you upload your app to Heroku directly that transfer can be seen as part of the "pipeline process" independent on whether that step is automated or not. If you host your app in a GitHub repository and make updates to the codebase by pushing changes etc. you could set up a pipeline that connects to Heroku, any changes you make to the codebase and push to GitHub will be automatically processed by Heroku to update your application.
oh, I remember the github linked deployment options. This is great, thanks.
for me these 15 steps were a great intro: https://devcenter.heroku.com/articles/getting-started-with-python
oh you asked about django... well that is django on heroku
Hello guys, I'm using semantic ui to make my page look better but I faced some weird stuff... I have 2 tables and I want them to go one under another when browser window is narrow and they cant fit together. But what i get is they overlap before actually going one under another
<table class="ui black selectable collapsing table">
here is the table class i use
Both tables are in
<div class="column">
That's if they ever work together again, this is a major breach of trust when it comes to security, GitHub has standards to protect their users which was compromised by the Heroku (Salesforce) partnership.
I want tables to keep their size ie no scaling to browser size
This is probably more applicable to #user-interfaces
And when the window is too narrow one should go under another
Its web page tho
Not sone offline gui
only offline guis being classified as uis is an interesting take
🤷♂️
try explicitly stating their height in css
should work
If u r sure that channel fits better i can move np
If I've got a button in Django that is chained to both trigger a submit/post request and a JS script, is there any way I can make the JS execute first?
Right now I've got a view that takes a really long time to render, so I want to trigger a loading screen to pop up with a JS script before the next page starts loading.
I didnt write a single css line of code in this project , i hope there is some way to just use semantic ui classes
I think the point is that this is a Python server, you can check out the Devcord discord for more specialized help with html/css/js and online ui frameworks
I'm fine thanks
Okidoke, I'm not gonna judge you when you realize this is a python server, and this channel is mainly for web hosted python backends rather than UI.
Take it as a friendly server recommendation, not me telling you to go somewhere. They are a lot more general UI than you are going to find in this server.
I got your point, i'll ask elswhere
im trying to deploy to heroku but this is what i get:
ERROR: Could not find a version that satisfies the requirement dataclasses==0.8
ERROR: No matching distribution found for dataclasses==0.8
why?
do you have a link handy on this? this is interesting to me. Is there an obvious and better alternative to heroku?
link to what?
If you're referring to the breach all you have to do is google "github heroku security breach" and it comes up. I'm surprised it's not being talked about more, although it seemed to affect organizational accounts more - (including npm).
The more comparable alternatives in terms of popularity and use-case to Heroku App integration would be AWS services, although I will say there's a higher learning curve dependent on chosen deployment option when it comes to networking and devops. Heroku is a pretty decent service as it's simplified some of the processes you'd have to configure manually via AWS, so it's a good option for production minimal applications. And there's always the perspective of looking at the glass half full, in this case, Heroku tightening up security on their end.. Heroku of which hadn't even recognized the breach until Github informed them. - https://thestack.technology/github-hacked-npm-data-downloaded-in-an-evolving-supply-chain-attack/
There's also GitHub pages which can act as a pipeline service similar to Heroku (i.e. pushing changes to the codebase configures the deployment app automatically) and is relatively easy to set up. - https://pages.github.com
yeah, i officialy hate heroku
By the way, bruh, Digital Ocean is working out VERY well. Really enjoying the alpha deployment with pipeline to git for changes. Their offering is very solid experience.
Interesting. I tried to use Heroku for my Flask deployment. That went...ok.
Then I tried to use Heroku to test out a cron redis server for some Django Async. Went poorly.
Gotta say, Heroku gets left in the dust next to my Digital Ocean experience.
I got an email about that breach. Was that the public repo brute force attack? Or something else?
👍
heyy I need some guide for starting programming... any professional who can help me.. pleasee dm me it's important😭
holy shit
i just deployed my first docker app on heroku
spent like 10 hours straight bugfixing but now it works
cant believe itttttt
I'm serializing models and sending it through the websocket, for the serialization I'm using django-rest-framework
the models also contain images but when the images are being serialized the absolute url of the image isnt being shown (only the relative url of the image)
looks like to get the absolute url of the image i need to pass in the request object into the serializer context but I dont have access to a request object (since im using consumers)
one person suggested that to override to_representation and return the image url there but that doesnt seem like a very good way since the host of the backend can change which will lead to a lot of bugs
Can anyone recommend some easy plot framework to draw plots in real-time from sqlite table
I use FastAPI + SQLite + website with semantic ui elements
I would like to implement a visualisation of 5 variables changing their value overtime
private repo attack via compromised Heroku Oauth tokens.
is there anyone i can ask for Flask help?
maybe i can use the socket library?
im not sure how exactly though
I have a flask app and I want to give different results for different users.
How is this possible?
I use flask-login ofc
im gonna ask a very stupid question here so just bare with me. I wanna build a Chat App with Django Channels + Redis right. And iv been watching alot of tutorials in the past few days and reading the docs however im so confused as to when i should stop watching the videos that makes a chat app and start implementing everything myself. Because right now all iv done is pretty much just copy paste from the Django Channels docs...and i, myself have not implemented anything. So should i just stop watching these videos and start thinking what i want in my app and start researching specific things i want instead of watching someone make the whole project? idek why im asking this lol
wat the heil do u want imo
Ultimately, what is considered enough hand-holding will fall down to you as the learner. You might find that stopping watching now, and working things out yourself is helpful to you learning, or you might find that building the entire project while someone is holding your hand is more helpful
Over time, you'll find that you've developed skills, and picked up a few techniques that help you start working on your own
ye i think i might just start myself and see how it goes because ultimately if i keep on watching the vids, in the end i will just get all the answers when i havent even started yet and then there's no point to doing the project if iv literally seen how you implement it.
I wouldn't necessarily say there is no point
It can help you pick up skills and tools that are used in the video, you've just gotta find what works for you
ye true
what kind of code can i use to read the data in my database and show it in this page (m using flask)
anyone?
You use Jinja syntax in your template. So in your apps.py i think it is, put whatever data from the database you want in a variable and then pass that variable to your template. Then in your template use Jinja syntax to loop over that data and grab the things you need.
So for example, in apps.py if i select all the fields from the database and pass it to a variable called data, and then do something like data=data to pass that variable to ur template. Then in your template, you loop over data by doing something like:
{% for d in data %}
{{ d.fieldname }}
{% endfor %}
damn i love using https://sqlitebrowser.org/ with my databases
ye its so good
i already use this but still it didn't show the data in the home page
show me your code
ur using User instead of user
change all of them to user all lowercase letters because thats the variable looping through the User variable that has all the database data
even the class is named User ?
no no
so in ur template ur using for example {{ User.fullName }}, change that to {{ user.fullName }}
remove that capital letter from all of them that are in the <td> tags
no
just change it inside
td
e.g:
for i in fruitsList:
print(i)
it will print that fruitsList array element which is on that index
anyone used htmx?
should i change something here ?
all u need to do is just change User to user in every <td>
Yes. You should use dictionary
it's django
right?
nah it's flask
its flask
okay ignore dictionary part
yet , nothing changed
show the code
the html ?
ye
can you show the code where you pass the User variable to this template
this is for signup.html
idk what current_user is but the variable u passed is called user not User
and ur looping through User which doesnt exist
idek what current_user is
request.user
but this is flask
oh right
dont you want to pass the data in your database?
the probleme that i wanna show the data
in your home function create a variable call it like data or something and in that variable select all the fields from the database you want
right now what ur doing doesnt make sense. u are looping through current_user which from what it looks like just gets the current user thats logged in
but how does current_user have the data you want form the database
yes
It's not an array like this :
Food = [
// FRUITS LIST
{
"orange":"good",
"Banana":"tasty",
"Pineapple":"nice"
},
// Vegetables List
{
"Carrot":"red",
"Raddish":"super"
}
]
It's only single object like this:
{
"orange":"tasty",
"pineapple":"fresh",
"apple":"red"
}
Hey, I have a model like this
class Task(models.Model):
name = models.CharField(max_length=120)
hours = models.SmallIntegerField()
mins = models.SmallIntegerField()
created_at = models.DateTimeField(db_index=True, default=timezone.now)
I wanna make a filter that returns every object created in the current year and month
I tried something like that, but this is not what I want
Task.objects.filter(created_at__date=timezone.now())
any thoughts?
Task.objects.filter(created_at__range=["2011-01-01", "2011-01-31"])
Task.objects.filter(created_at__year='2011', created_at__year='2011')
Are you sure about this?
pretty sure it should work, try it out
raise FieldError(django.core.exceptions.FieldError: Cannot resolve keyword 'created_atyear' into field. Choices are: created_at, hours, id, mins, name)
created_at__year
it was ur typo
i assumed you'd realise'
created_at__year
change it to this^
discord wouldnt let me add another _
can I ask u a q?
yh
depends what you want to do
ok
what are you creating your framework for?
maybe give this a read
Django has two types of views; function-based views (FBVs), and class-based views (CBVs). Django originally started out with only FBVs…
Thanks
Works fine, appreciate ur help, thank you.
Also interested in your approach, I want to display my database and filter the results with a search box
If you have a time, I need your help with another issue, I wanna return the highest month in which objects were created,
let's say we created three objects,
object_1 in month 2
object_2 in month 5
object_3 in month 5
so we have to return 5 with is the highest month
I did something like this and it works fine
mx, highest_month, dic = 0, 0, defaultdict(lambda: 0)
for object in Task.objects.all():
month = object.created_at.month
dic[month] += 1
if dic[month] > mx:
mx = dic[month]
highest_month = month
but my question is how can I optimize it using something like the aggregate method?
sorted_dates = sorted(chain(query var1, query var2, query var3), key=attrgetter('datetime')) @zealous oar
can you explain your thought?
I wanna return the highest month where objects created, not the biggest
what do you mean
Let's say the user created 2 objects from Task model in May and 5 objects in January
Then January is the highest month
you mean you need it sorted in reverse order?
that will sort it in ascending order
sorted_dates = sorted(chain(query var1, query var2, query var3), key=attrgetter('datetime'))
this will sort from January to December @zealous oar
yeah, thank you
Hello ladies and gentlemen! Got a quick question regarding managing classes. I finally worked out a working webshop with a Item class. The Item class has many functions on it and is referenced in other classes to make the cart and checkout process running. Now i want to specify the products by creating new classes like "Shoe" or "Tshirt" which each has own attributes additional to the "Item" class attributes. What are my options to do that or what is recommended to do? I came around Abstract Base Model but i can not reference to abstract models. I read about PolymorphicModel, but is it really the way to go?
Hey theres something i have been wondering about django channels and its not really something i can specifically search about. So channels uses consumers.py which is their version of views.py. My question is that when i create an authentication system where user can register, login and logout, do i have to do this in consumers.py with new syntax that come with channels module since im using async and await or can i just do it normally in views.py?
Hello, any one using Django with vuejs !
xD i did. I have already made project with this combo
A guide for how to ask good questions in our community.
don't ask to ask, just ask (google it)
@inland oak I did google that found, axios, Django rest react , Django vuejs nothing really straight forward but thx 🙏
I think they were just saying that you don't need to preface your question with an intro. Not that you should google it instead.
Hey, why would someone use django REST or Flask, instead of FastAPI + SQLalchemy?
I haven't used flask or fastapi very much. But the reason I wouldn't want to change from django is because there are some features it has that I really like and don't know how they are in those other frameworks. Like django's orm, migrations, drf
flask uses sqlalchemy and alembic for orm and migrations
I have no idea what drf is
drf: django rest framework?
fastapi does that by default. Return a dict in your view, and it will output as json
there's also pydantic which helps with the schema
no no, i mean literally, google "dont ask to ask, just ask"
and yeah, Django as Django Rest Framework and Vue.js with Axios for requests library, that's how usually stuff happens
Django is really nice of course but it has one major minus which other devs could say...
...it forces u to marry the framework (with all of its out of the box solutions)
to accept its architecture and build on top of it
polluting your business layer of code logic
that could be seen as a literally a nightmare
and once u marry the framework, changing it to some other framework for the project becomes nearly impossible task
So... against of Clean Architecture stuff
we can also say that it also introduces the problem of upgrading the project
imagine upgrading the project to newer version, when Django stuff goes across entire your project in each code section?
once u upgrade django... since the dependency is not really in one place localized behind proper code layer separation, it becomes a bit of a nightmare when everything breaks everywhere
I did not check at the depth FastAPI, I wonder if it is different in this regard, it should be in theory since it said to be microframework like Flask
Flask is certainly not forcing anything.
for its downsides, Django gives in exchange blazingly fast development speed, and quite high familiarity of other Django devs with structure of the project. It is always essentially remains the same everywhere, regadless of the project
I have a Jinja template:
{% extends "boards/board.html" %}
{% import "macros.html" as macros %}
{% block title %}Threads • {{ super() }}{% endblock %}
{% block main %}
{% for thread in board.threads %}
{{ macros.post(thread, "article", url_for(".thread", slug=board.slug, token=thread.token)) }}
{% endfor %}
{% endblock %}
When I try to render it, I get jinja2.exceptions.UndefinedError: 'thread' is undefined. It looks like the thread variable defined in the for loop isn't accessible in the macro call. How can I pass thread to the macro?
Never mind it was a problem with the macro
So im trying to have this collapsible information be auto un-collapsed when a link is pressed
<details>
<summary>Click to show summary one</summary>
## Title One
...
## Title Two
...
</details>
This issue is that if someone was to click a link to my GitHub repo with a link in the following format:
github.com/Username/Repo#title-onegithub.com/Username/Repo#title-two
The link would take them to the page but the section would still be collapsed, and it would not take them to the proper section/header. Is there a way so that when someone clicks the link it's automatically un-collapsed so they can see the information in the header instead of having to manually un-collapse it first?
Please ping when responding if you have the answer, thx
What's the relationship between a post and a comment? I know a post can have many comments, but can a comment have many posts? Should I use a foreign key?
I understand they have an orm and migrations, but django's are quite good
hey guys trying to learn how to host a flask website on cpanel and following this tutorial, https://www.a2hosting.com/kb/developer-corner/python/installing-and-configuring-flask-on-linux-shared-hosting
however when i try to access the webpage it shows 503 service unavailable
the error log shows this
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
ModuleNotFoundError: No module named 'encodings'
Learn how to install and configure a Flask application on a Linux shared hosting account. This Python-based framework enables you to quickly and easily create websites.
any idea on what i need to do to get it working?
$ch = curl_init('https://api.smsbroadcast.com.au/api-adv.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
curl_close ($ch);
return $output;
}
$username = 'USERNAME';
$password = 'PASSWORD';
$destination = '0400000000'; //Multiple numbers can be entered, separated by a comma
$source = 'MyCompany';
$text = 'This is our test message.';
$ref = 'abc123';
$content = 'username='.rawurlencode($username).
'&password='.rawurlencode($password).
'&to='.rawurlencode($destination).
'&from='.rawurlencode($source).
'&message='.rawurlencode($text).
'&ref='.rawurlencode($ref);
$smsbroadcast_response = sendSMS($content);
$response_lines = explode("\n", $smsbroadcast_response);
}
can anyone show me how to convert this to a python request?
Maybe something like this 🤔
data = {
"username": "Username",
"password": "Password",
"destination": "0400000000",
"source": "MyCompany",
"text": "Some Text",
"ref": "abc123",
}
response = requests.post(
"https://api.smsbroadcast.com.au/api-adv.php",
data=data,
)
"APIKeyUsername=": "xxxxxxxxxxxxxxxxx",
"&APIKeyPassword=": "xxxxxxxxxxxxx",
"&to=": "xxxxxxxxxxx",
"&from=": "Physio",
"&message=": request.POST['InstantMessage'],
"&ref=": "xxxxxxxxxxx",
"&maxsplit=": "5",
"&delay=": "1"}
url = "https://api.smsbroadcast.com.au/api-adv.php?"
y = requests.post(url, data=dict)```
shouldnt this work?
@serene prawn
I did this, its not working at all
I don't think you have to use & there
@serene prawn
Example API Request:
https://api.smsbroadcast.com.au/api-adv.php?
APIKeyUsername=myuser&APIKeyPassword=mypass&to=0400111222,0400222333&from=MyCompany&
message=Hello%20World&ref=112233&maxsplit=5&delay=15
page 3
It's a form data object, requests should take care of constructing request body
& is used to separate fields in form data
copied your code
Can you send your current code?
data = {
"username": "xxxxx",
"password": "xxxx",
"destination": x.number,
"source": "Physio",
"text": "Some Text",
"ref": "abc123",
}
response = requests.post(
"https://api.smsbroadcast.com.au/api-adv.php",
data=data,
)
print(response)
@serene prawn
Check response.content
also change source to from
data = {
"username": "xxxxx",
"password": "xxxx",
"to": x.number,
"from": "Physio",
"message": "Some Text",
"ref": "abc123",
}
thank u so much!
Hello, can anyone help with this?
hello, can anyone help with this:
'phone': phone_no,
'message': msg,
'key': 'textbelt'
})```
I'm getting error: Positional argument cannot appear after keyword arguments
@serene prawn added u, got some difficult html questions
@native tide what is proxies?
What is a proxy server and how does a proxy server work? Find out all you need to know about proxy servers at PCMag.com.
i know what a proxy server is
what is your proxies variable
I'm new to python can anyone give me tips??
are all of the flask app routes available to the public?
I am starting up with Python backend development, what should I use? Flask, FastAPI or Django?
I want to iterate through the div and get all a tags and get the href from those a tags
How can I achieve this?
# This statement searches for replies from the current date which match unique_num, primary_key, & datetime
Replies_ = Replies.objects.all().filter(unique_num=unique_num)
InstantMessages_ = InstantMessages.objects.all().filter(unique_num=unique_num)
ScheduledMessages_ = ScheduledMessages.objects.all().filter(unique_num=unique_num)
all_messages = sorted(chain(Replies_, ScheduledMessages_, InstantMessages_), key=attrgetter('datetime'))
for x in all_messages:
print(pendulum.parse(x.datetime).to_day_datetime_string())
return all_messages```
does anyone know how I can change the x.datetime with the .to_day_datetime_string() method and return it as a regular django model?
just through a regular python script
?
I tried but it gives me NoneType with bs4
I try to get the page content with requests
from bs4 import BeautifulSoup
import time
import requests
headers = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36"
}
page = requests.get("https://www.spycolor.com", headers=headers)
soup = BeautifulSoup(page.text, "html.parser")
for grads in soup.find_all("div", class_="box small"):
for grad in grads.find_all("a"):
a = grad.find("a")
print(a["href"], a.get_text())
This doesn't work.
Traceback (most recent call last):
File "D:\Python Projects\Gradient-Of-The-Day\test.py", line 15, in <module>
print(a["href"], a.get_text())
TypeError: 'NoneType' object is not subscriptable
In this tutorial, we will learn about the Python String startswith() method with the help of examples.
print(a.startswith("href="))
see what that does
@native tide
ah shit nope
thats a boolean value
regex
Oh my I hate regex :/
how do I get the path of the file uploaded in django?
is there any way to run selenium async of my flask app? I want to make the behaviour of when i load a certain page I want selenium to open up in the background while the original page that i started to load runs
Hey everyone, how would I go about connecting to an sql database through VS Code?
I downloaded the mssql extension but I'm not sure what to do next, just looking for some guidance
someone judge my website pls
last time for now
try sending me an email in the contact form
the email can be fake
I was wondering if I could get some help on this.
I'm using this method to update my website based on my git master branch: https://gist.github.com/noelboss/3fe13927025b89757f8fb12e9066f2fa
The issue I'm running into is that my whole repo is being push to my website (intended by the method above), but I want to just push a specific directory from my master branch to the web server
How do I modify the script above to do so?
I have files on my master branch that I do not want to be pushed to my web server, for example README.md, .gitignore
I put the files I want on my webserver into /html in my git repo
I just want to push up the contents of /html to the web server
from flask import Flask, render_template, request, redirect, url_for, flash
from flask import g as globally
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import null
@app.route('/')
def index():
return render_template('index.html')
# A decorator used to tell the application
# which URL is associated function
@app.route('/info', methods =["GET", "POST"])
def create():
if request.method == "POST":
global name
global email
global profession
global country
global hobby
global youtube
global para
name.globally
# getting input with name = fname in HTML form
name = request.form.get("name")
# getting input with name = lname in HTML form
email = request.form.get("email")
profession = request.form.get("profession")
country = request.form.get("country")
hobby = request.form.get("hobby")
youtube = request.form.get("youtube")
return render_template("create.html")
@app.route('/info/themes', methods =["GET", "POST"])
def themes():
return render_template("theme_select.html")
@app.route('/info/themes/black', methods =["GET", "POST"])
def theme_selected():
title = f"Hello I am {name}"
para = f"Greetings, I am {name}. I'm a {profession} from {country}. I love {hobby}, Make sure to check out my blogs!"
return title
return para
return render_template("/black_theme/index.html")
print(list)
if __name__ == '__main__':
app.run(debug=True, port=2000)```
yo so like i wanted the variables to be accessable but am having some problems with it rn
flask can't do global because it breaks threading and i don't know what to do
Using Django, I am trying to do a @property on a model to sum a field, its returning a Sum(Value(Decimal('700.00'))) class, how can I just get the value?
hello
```# urls.py urlpatterns = [ ... path("slug:category_slug/", views.category_blocks, name="category_blocks"), # Views all the series in that category path("slug:category_slug/slug:series_slug/", views.series_blocks, name="series_blocks"), # View all tutorials in series path("slug:category_slug/slug:series_slug/int:tutorial_id/", views.episode_blocks, name="episode_blocks"), # View spesific tutorial nr. ] # views.py def category_blocks(request, category_slug): # logic to display all tutorial with category is category_slug def series_blocks(requests, category_slug, series_slug): # logic to display all tutorial with category is category_slug and series is series_slug def tutorial_blocks(requests, category_slug, series_slug, tutorial_id): # logic to display all tutorial with category is category_slug, series is series_slug and tutorial is tutorial_id
# This is the way to access multiple slugs with different names
https://stackoverflow.com/questions/54748625/django-2-multiple-slugs-in-url
I am currently following a django tutorial by sentdex. The tutorial is making a clone of https://pythonprogramming.net/. In the tutorial he uses only one slug in the url, but I think its more conve...
how do i add a loader when there is a long operation being performed in my Django view?
hey, Im tryna use datbase queries with Django Channels however im not getting it right. Iv looked up that i need to use database_sync_to_sync but i cant find much examples online of how to use it properly. The only way i get it to work without error is something like the following code however all it prints out is <coroutine object SynctoAsync...>
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.user = await database_sync_to_async(self.get_users)()
print(self.user)
self.room_group_name = 'chat_%s' % self.room_name
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
@database_sync_to_async
def get_users(self):
return User.objects.all()
You already decorated your function with database_sync_to_async, no need to wrap it second time in your connect function
ye but if i do this i get django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async
self.user = await self.get_users()
That's weird, where is it raised from?
wdym?
The exception
doing this raises it:
self.user = await self.get_users()
try converting it to list?
return list(User.objects.all())
oh that workd
why did it work like that and not what i done before?
because i got it from the docs
.all() still returns queryset and then tries to do some database opreration in async context
Which is raising synchronous operation error
Example in docs is different
return User.objects.all()[0].name
This is example from the documentation
ye but isnt it similar i just didnt hard code it
i mean i did try it before exactly as teh docs and it didnt work
Now you know
ye thank you vm
I want to create a model, which lets you select break times for specific weekday. I don't know what is
the best way to link those two models together. I think manytomany field gets messy and confusing
really fast. I want to be able to keep it clean and organized.
Models.py
WEEKDAYS = (
(1, 'Monday'),
(2, 'Tuesday'),
(3, 'Wednesday'),
(4, 'Thursday'),
(5, 'Friday'),
(6, 'Saturday'),
(7, 'Sunday'),
)
class Breaktime(models.Model):
weekday = models.IntegerField(choices=WEEKDAYS, unique=False)
break_starts = models.TimeField()
break_ends = models.TimeField()
class Breaktimes(models.Model):
weekday = models.IntegerField(choices=WEEKDAYS, unique=True)
breaktimes = ??
I think many to many relationships are the only choice, but is there a way to filter out the weekdays?
Please if anyone could offer some guidance. I need to use Google Maps API to generate a custom map with a set of custom markers based on info stored in models in Django.
i see, and in order to access those variables that was passed into my url in a class based view, would I just then do something like this:
class CategoryListView(ListView, category_slug, series_slug):
...
when i scroll down, if i want all the content on the page to scroll except the bootstrap nav bar which should stay in the same place, how would i do that?
Using CSS. You can set the position to fixed or sticky
https://www.w3schools.com/css/css_positioning.asp there are examples here
Hi, I am trying to show a key inside each dict into an html, can anyone please tell me how to do it ? here is the code:
{% for class in classes %}
<li>
<div class="menu">
<h2 class="menu-title menu-title_2nd">{class} </h2>
<ul class="menu-dropdown">
{% for i in range(1, 5) %}
<a href="{{url_for('upload_marks_page', grade='class_2', subject='maths', test_name='test_1'}}">
<li>Test {{i}}</li>
</a>
{% endfor %}
</ul>
</div>
</li>
{% endfor %}```
how can i update e table with buttonclick
Hey fellas, I am a freelancer developer and customer asked for a simple website to serve my app on. There is like couple functionalities and some simple interfaces. What is a fast way to deploy this?
okay I think
Wagtail is a great start
damn i love flask so much
dorsia
How do e commerce website backend work?
Hi guys! Can anyone recommend some big web dev discord for html/css topics? I have some issues with my Semantic UI implementation:)
like any other backend.
Do you have a specific concern or question?
I use ajax
what programming language is best for website backend except for php?
java or python
personal opinion
i would say javascript
as nodejs
my website
has a expressjs backend
a websockets chat app is a good example of have a backend to a website
its very small
thanks
thanks
PHP backends
Can range from super primitive php
Like old school embed php in Python page
To modern laravel
If you gonna do a php backend
Learn Laravel
Its a lot like express js in Javascript
And flask in Python
But obviously it's php
Can anyone recommend alive discord to ask about html, js, css issues?
I'm struggling with page layout
you can ask me
Thank you! Could you take a look at #user-interfaces
I posted my question there
I'm new to web dev and trying to make my web page scale properly on any screen/browser size
Hello
How to secure a Flask app against CSRF ?
using non GET request for important actions will increase a bit level of security. (making necessary for hacks to use JS injection at least)
Then we could CSP protection in order to protect us from unauthorized JS files, that will be a first level protection.
for 100% solution, any super important action should be verified by something like getting number from SMS sent to user / email sent to user (preferably email, it looks less bothersome)
plus i heard about CSRF tokens, perhaps they can improve situation a bit too
i would agree with @inland oak, make sure you don't accept GET requests for those endpoints, and then i would recommend CSRF tokens as the primary measure after that
hey, anyone know how to partially fade an element using css?
like this?
Partially fade what element and how?
they said border up top
.your_class {
height: 100px;
width: 100px;
margin: 100px;
border: 10px solid rgba(255,255,255,.5);
}
i think that works
getting better
niceee
thanks mate
I kind of understand with the GET and POST end points
This means, on this line <form id="derogationsform" action="{{ url_for("form_area")}}" method="POST">
I should create another function which accepts only POST?
This means what i should have 2 functions ( 1 for GET - rendering the form page, 1 for POST - handling the post request ) ?
u already have it as endpoint it seems
Form works by submitting as post by default
@app.route("/form_area", methods =["GET", "POST"], endpoint="form_area")
Hey, i'm trying to automate a get website orders script but I am running into HTTPSConnectionPool issues when I try to call it as an executable. Can give me a hand with this?
image of error message
The website might not be https
It is, also it works most of the time, this error happens 10% of the time
maybe you go too fast
Possibly, at what point would I try to slow it down do you think? the initial get or iterating through the orders? Somewhere else?
¯_(ツ)_/¯
robots.txt specifies a crawl delay of 600
so just time.sleep(.6) after each request
Should I use help channels for django questions?
It's a web dev channel after all, it's find to ask django questions here
I asked it in a help channel a minute ago. In #help-burrito
Hey, how would you call a file that initialize a connection with a db? Like by convention
dbconnect, connectiondb, dbconn, dbconnection I guess. Everyone would understand these.
ConnectionBuilder is my preference.
Help channel is closed, damn. Let me ask again. Submitting form doesn't do anything. Not even redirecting the url. But if I manually open the html file without server, it redirects.
use /createuser instead of createuser/ for the form action
didn't work, and normally it should be createuser/
Also, I think you're passing xedni to the redirect response
method is not called, nevermind the redirects.
form action path is relative if it doesn't start with /, meaning if the current path ends with /, it will be appended. If it doesn't, the last path item will be replaced
yes, it should. Btw, I can manually call the function with link.
But submit button does nothing
Anything in the console or network inspector?
I used jquery to test the button, it can give an alert(""). And directly writing the link activates the function. I can see print("") codes in console.
How are you submitting normally? pressing the submit button, or pressing enter on the password field?
Also, you should make the input type="password"
pressing button. password can wait 😄
But does anything show up in the network inspector when you press the button?
Ctrl+Shift+I, press network
looks like nothing happens.
Nothing in console either?
nope.
Did you register an onsubmit event and call preventDefault()
if you mean front end stuff, they work. I opened the html file directly and it redirects.
Can you share the entire html file?
sure
Hey @lime jolt!
It looks like you tried to attach file type(s) that we do not allow (.html). 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.
oppsie
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
And /js/modal.js?
whats wrong with it?
idk, you didn't post it.
Post the modal.js too please
You disabled the click event in all children in the modal.
just use bootstrap's builtin features to dismiss the modal.
you're not using bootstrap, though....
not worth using bootstrap, idk
i created modal 3-4 times but forget how to do it 😄
it works, there are other problems but that's the only part i needed help
thank you
So, CSRF is important and @csrf_exempt doesn't disturb it?
should i use @csrf_exempt everywhere?
tell me something what goes on better. Django + python or html css Javascript and python
Hi guys, I was looking for a Flask-React monorepo for my project and surprisingly I couldn't find any, so I made one instead. Check it out here and feel free to use it on your projects :)
https://github.com/Jesse0502/React-Flask-Monorepo
Hi, i have a webpage with 4 div's acting as buttons, and using ajax i want to send which button was clicked, and then update my <p> tag which uses class=text1 to show that direction. (I also want to create a MySQL database and then send that data to that database, so if anyone can help with that it would be much appreciated)
At the moment clicking on the buttons work, and the value is shown because im using the 'get' method, but i dont want to get that data, i want to 'post' the button click to the server, and on success: change my <p> to the value of the button clicked. Havent really understood online resources about each of those things, so any input/changes you guys can give me would be much appreciated ❤️
#main.py
from flask import Flask
from flask import render_template
from flask import request
from time import time
from flask import jsonify
app = Flask(__name__)
@app.route('/')
def index():
direc = request.args.get('direction')
print()
print('Direction:', direc)
print()
return render_template('index.html')
if __name__ == '__main__':
app.run()
#Javascript
$(document).ready(function() {
$( "div[name='button']" ).on('click', function() {
$.ajax({
url: '',
type: 'get',
data: {
direction: $(this).attr("id")
},
success: function(response){
$(".text1").text(direction);
}
})
})
})
i do this without using ajax if you would like to know
var xml = new XMLHttpRequest();
xml.open("POST","{{url_for('new_data')}}", true);
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
dataSend = JSON.stringify([new_data, type]);
xml.send(dataSend);
make a http request on the javascript
then for the python
how?
oh wait heres the video i followed
//JavaScript Part//
var xml = new XMLHttpRequest();
xml.open("POST","{{url_for('func.func')}}",true);
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xml.onload = function(){
var dataReply = JSON.parse(this.responseText);
};//endfunction
dataSend= JSON.stringify({
'page_data':'some_data'
});
xml.send(dataSen...
found it
wym, like he doesnt show it in action?
Ye
well you gotta experiment with it
So not sure if its same functionallity as what i need
I dont see how he gets the button onclick
theres no function bound to it
No check of onclick
you said you wanted to send a value to the db with a click then also put that value in an html element right
Yes
This is how the webpage looks
just put an onclick for a function that has the httprequest in it?
function send_data(new_data, type){
var xml = new XMLHttpRequest();
xml.open("POST","{{url_for('new_data')}}", true);
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
dataSend = JSON.stringify([new_data, type]);
xml.send(dataSend);
if (type[1]){
if (type[0] == "song"){
window.location = "{{url_for('song_page')}}";
}
}
}
i mean this is what i have
What is urs sending?
im sending a song's spotify id
Can you show ur html so i can see how you bind the send_data function to it
sure
This is very much not the modern way to do requests in js. I would highly recommend looking at the fetch API which is much more standards. This method hasn't been popular for probably a decade or more.
oh damn rly
why not modern?
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
This is the standard way to do it
okay so u did add an onclick attribute to the div
yes
Tested SQLModel for FastAPI. It’s a really good extension over “plain” SQLAlchemy and Pydantic.
i made a game with js, css, html, but i want to save the player's score into the django database automatically after each game. How would I be able to do that?
what framework
django
django is horrible i regret even trying it
i finally understood not to touch it unless your creating a huge ass project
wasted 4 days learning that shite
"learning" kek
hello to all, I just wanted to ask a small question I want to make a bot to do research on the txid of the bscchain for example someone has a track to help me start I am a beginner
welp, i think it's too late to turn back, i just spent 3 months trying to learn it and i just started getting the hang of it
how fun
is there anyone who could help me with connecting two tables in one database in Flask and SQLite?
i want to make a webapp that uses the spotify api in python, is it better to download a library like spotipy or just use the web api directly in python?
omg i just did it
goddaymn
I've been wondering: is there any particular single best order of these three in Django? Or something that should not be done?
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
[...]
]
ButtonClick.query.first()) prints <ButtonClick 1> always(first id)
ButtonClick(content=request.form.get('direction')) returns <ButtonClick lastID>
I dont want ID, i want to get the last item(direction) that was just added to db, what i would get if i were to post directly in SQL (SELECT content FROM button_click ORDER BY id DESC LIMIT 1;)
The reason i want this is because the response gets sent to a <p> and i want it to update according to the value(unnecessary i know but i want to anyways), how can i go about doing this using sqlalchemy?
class ButtonClick(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(5))
@app.route('/')
def index():
return render_template('index.html')
@app.route('/clicks', methods=['POST', 'GET'])
def clicks():
if request.method == 'POST':
direc = ButtonClick(content=request.form.get('direction'))
db.session.add(direc)
db.session.commit()
print('To DB', direc)
print('direc.query.first():', ButtonClick.query.first())
return jsonify(direc)
$(document).ready(function() {
$( "div[name='button']" ).on('click', function() {
$.ajax({
url: '/clicks',
type: 'post',
data: {
direction: $(this).attr("id")
},
success: function(response){
$(".text1").text(response);
}
})
})
})
_ _
_ _
Hey! i'm building a search and i'm querying for 'plugins'
I want to match my query with the most relevant plugins but I don't know how I should get started with that.
Here is what I have:
#app.py
@app.route('/dashboard/search/', methods=['GET', 'POST'])
def search():
if 'username' in session:
user = mongo.db.users.find_one({'name': session['username']})
if user:
if user['account_active'] == False:
print("Account is not active.")
return redirect(url_for('index'))
else:
pass
print(request, request.args)
if request.args['search']:
query = request.args['search']
l=os.listdir('plugin_base/plugins')
plugins_D = [x for x in l]
try:
plugin_file = importlib.import_module(f"plugin_base.plugins.{query}", f"exec")
plugin_conf = importlib.import_module(f"plugin_base.plugins.{query}", f"config")
pfc = plugin_conf.config
except:
plugin_file = "None"
plugin_conf = "None"
pfc = "None"
print(pfc)
if query[0] in plugins_D:
pass
return render_template('dashboard/search.html', search=plugins_D)
I want to add the plugins that are most relevant to some sort of list so I can do something like this:
<!-- search html -->
{% for result in search %}
<h2>Plugin Result</h2>
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ search['name'] }}</h5>
<a href="/dashboard/plugin/{{ search['name'] }}" class="btn btn-primary">Use this Plugin</a>
</div>
</div>
{% endfor %}
I think it's pretty easy to understand what I'm trying to do.
Thanks in advanced! :)
Is there any visible problem here? Or should I check somewhere else? I am trying to make a login system, the user exist but it leads to fail. I tested, it can get the username and password for x and y.
am I even using my database? Tutorials on internet shows it like this
Guys help
from django.urls import path
from . import views
urlpatterns = [
path('cards', views.CardList.as_view()),
path('cards/<int:pk>', views.CardDetail.as_view()),
path('decks', views.DeckList.as_view()),
path('decks/<int:pk>', views.DeckDetail.as_view()),
path('folders', views.FolderList.as_view()),
path('folders/<int:pk>', views.FolderDetail.as_view()),
]
# preferables
# deck list
# /api/decks
# deck detail
# /api/decks/<int:pk>
# card list
# /api/decks/<int:pk>/cards
# card detail
# /api/decks/<int:pk>/cards/<int:pk>```
I'm using django rest framework. In the comments, you can see how I want to design my API
Dpaste is a website where you can store text online for a set period of time. Dpaste is written in Python using the Django framework.
this are my models and views.py
I don't get how I can have my routes set up so it's /api/decks/<int:pk>/cards <-- lists all cards within that deck
how does that work with API
you sure youre supposed to use request.post
because youre not posting anything, youre getting the information from 'username' and 'password'
the request method is still post though
probably can just do request.form['name']
do u know what i am saying?
class RecipeSerializer(serializers.ModelSerializer):
rt = serializers.SerializerMethodField(source="ingridents",read_only=True)
def get_rt(self, instance):
try:
return json.loads(instance.ingridents)
except:
print("Error")
class Meta:
model = RecipeModel
fields = '__all__'
Can someone help me i'm trying to convert json into list but it returns null
"rt": null,
though there are data in ingridents
"ingridents": "2 cups cooked chicken chopped\r\n½ cup mayonnaise\r\n1 stalk celery chopped\r\n1 green onion diced (or chives or red onion)\r\n1 teaspoon dijon mustard\r\n½ teaspoon seasoned salt\r\npepper to taste\r\n1 teaspoon fresh dill optional",
I'm trying to convert this ingridents to something like this
"ingridents": [
{
"2 cups cooked chicken chopped"
},
{
" stalk celery chopped"
},
{
" teaspoon fresh dill"
},
{
" green onion diced "
},...
]
that's ingridents in models.py
ingridents = models.TextField(default="")
Noob question here, what would be the most secure way of me storing user OAuth2 tokens?
Do I just... chuck it in a database? There has to be some sort of more secure way, right?
Fixed it thanks everyone
Hey 👋 , is anyone working with Django channels in real-life projects?
I was wondering is it a good choice to accomplish this task, or do I have to think of another stack like Node, Elixir, Laravel, .. ?
Any advice/hints would be great to start my research.
hey i have db model named profiile
i wanna make a feature to let user download his/her profile
(i can't add a file/imagefield for downloading) cuz that data would be generated after thier profile would be created
by this data i need user to give a option to download it
and the main issue is ** if user clicks on download this template/img should open and then i want user to download this jpg** but how can i retrieve dynamic data inside a image file?
plz help
How to use python for website backend?
You can use Fask or Django. They're free Frameworks
flask, Django or fastapi
Thanks
Thanks
you need to use something like Pillow to generate the jpeg. Another option would be Jinja+Markdown+Pandoc to make a pdf, then convert the pdf to a jpg
i m trying to create a chatbot using django as the backend, but i m having trouble showing the responses
when giving the result for a query, how do I also show the previous chat history?
I can generate image by pillow that's not the issue but I want image to give dynamic data and only some data to be changed (see the above ss) I want other things (i.e instructions or qr) to remain untouched
then write some code to do that?
def make_image(dynamic_data):
static_data = load_your_static_data_here()
<pil code that munges the static and dynamic>
return img
So i am using django to make an app and when i try to change the colour of my nav bar it wouldnt change my css wont reflect any changes its almost like my program is frozen even when i delete the css file nothing changes can anybody help
every other thing seems to be working like the html and backend part but not css
it takes minutes to show the change Why????
I've worked with django for some time but we're trying to migrate our codebase to fastapi
Didn't work with react specifically but it's similar to other frameworks
Can I ask you some questions related to Django & DRF?
Yeah
It's better to ask your question right away so people could see if they can help you or not
I'm getting stuck when trying to build a feature for my Saas that allows users to log out of respective sessions or all sessions.How can I implement such a thing? Here's the overview of what I'm trying to build. I took this inspiration from Khalti which is a payment gateway of my country. It's built with Django & React. I will also create a mobile app.
How should I keep track of mobile logins with my app version and mobile device name? This is the API response of sessions. How can I implement this in an exact way?
What auth mechanism should I use here?
sessions?
You can use pretty much anything as underlying implementation - sessions, tokens, jwt's, with any of them you would have to keep track of active tokens so people could invalidate them
It might be simpler if you choose to just invalidate all tokens before a specific date, since it won't require you to keep track of all active sessions
I'm not familiar with django packages really
I got the general idea. Thank you
I think we can discuss the specifics, other people might help you too
Invalidating user sessions should be a solved problem at this point
I would be happy If someone joins the discussion
hi, how can i localize the datetime form fields in my django app?
my server is 4 hours behind my actual timezone, and when i pass a time of 8pm in my local time to the form it appears as 8pm in server time in the database. But ideally it should appear as 4pm in server time.
how can i fix this?
i've set the USE_TZ = True setting in settings.py too
guys how i can get access token use get method? djang rest framework
is it possible to use js frameworks like reactjs along with pyscript? would this make the website really slow?