#web-development
2 messages · Page 195 of 1
You could also use list[str] to say a list of strings
Yes. It's purely a devtime check. It's ignored at runtime
BTW it's not really related to web. Are you using fastapi?
no no was just trying to learn more about OOP
befor learning Django
i still don't understand why some times i see @login_required as decorator befor some functions
things for me to understand 😄
Do you know what a decorator is?
It's a function that takes a function and returns another function
def x(): pass
x = foo(x)
# shorthanded to
@foo
def x(): pass
And the @ syntax merges it with the declaration
Example creation of decorator
def foo(func):
@functools.wraps(func)
def decorator(*args, **kwargs):
# do stuff before
r = func(*args, **kwargs)
# do stuff after
return r
return decorator

You can stack decorators too
okay i will try to understand it further maybe i will need it while coding
Thank you @frank shoal this is a link explaining decorators for any whom are interested to learn it too. https://www.geeksforgeeks.org/decorators-in-python/
How can i fix images going outside my body's height?
the height property for my page is set as follows
min-height: 100vh;
height: auto;
increasing min-height to 200vh works but idk if its bad to do that or not
How do I use Django to run a python function when a button is pressed?
not sure if this is the right section for my question but has anyone worked on a fintech/blockchain project? Or with cryptocurrenies API's?
what button
like on the frontend?
Hi I have a certain confusion while deploying my django project on heroku. When its deployed, the default domain would be no SSL (http://invid19.herokuapp.com). Ive tried to change my settings from ALLOWED_HOSTS = [f'{HEROKU_APP_NAME}.herokuapp.com'] to ALLOWED_HOSTS = [f'https://{HEROKU_APP_NAME}.herokuapp.com'] but it only make the deployed project had a bad request 400 on production then I revert to the old code.
Then, weirdly idk why if I type my domain manually using https (http://invid19.herokuapp.com), it will be no error, but the default domain still using http if we dont type it manually
does anybody now why my django project cant use SSL as a default domain
if i recall correctly heroku does not provide ssl certification on a free dyno. you will need to manually configure heroku through the CLI for https support assuming you have a paid dyno
Yeah, on the frontend, a button which the user presses which triggers some python code
Yeah Ive read this on several blog like stackov etc. What cofuses me a lot is, I've deployed several projects before and suprisingly it make https as it default, and idk why because long time ago I was copasting from a blog "how to deploy on heroku"
here is one example of my deployed project that automatically using https as you type in browser
anti-maba-deadline.herokuapp.com
its weird now when I try to deploy a project once again and its appear http on its default
even though I use the same method to deploy my django project on heroku
is there like a certain Hashing library i can use in both Django and Tkinter?
Can someone please help me with api call and postman,I'm really lost
Could someone help me? I have a button at the end of a form and am having trouble figuring out how exactly to make it submit the form answers to a function
I'm using an event listener but I'm not quite sure how to do it
This is what I have right now document.getElementById("addbtn").addEventListener("click", addEmployer.bind(null, ));
The js function I want to use is addEmployer and it has multiple parameters (which are the form fields)
This is like a super quick question for anyone with any actual knowledge, I just don't know what im doing 😦
hey what is MultiValueDictKeyError ??
def addProd(request):
form = addForm()
if request.method == 'POST':
if form.is_valid:
product_name = request.POST['Product_Name']
product_img = request.FILES['Image']
product_desc = request.POST['Description']
product_price = request.POST['price']
product_seller = request.user
print(product_seller)
return render(request, 'addProd.html', context={"form":form})
Browser
MultiValueDictKeyError at /shop/add
'Image'
Request Method: POST
Request URL: http://localhost:8000/shop/add
Django Version: 3.2.4
Exception Type: MultiValueDictKeyError
Exception Value:
'Image'
Exception Location: C:\Users\Rajiv\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\datastructures.py, line 78, in __getitem__
Python Executable: C:\Users\Rajiv\AppData\Local\Programs\Python\Python38\python.exe
Python Version: 3.8.10
Python Path:
['C:\\Users\\Rajiv\\Desktop\\Ishant Files\\main\\proj\\Back-end\\iCart',
'C:\\Users\\Rajiv\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
'C:\\Users\\Rajiv\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
'C:\\Users\\Rajiv\\AppData\\Local\\Programs\\Python\\Python38\\lib',
'C:\\Users\\Rajiv\\AppData\\Local\\Programs\\Python\\Python38',
'C:\\Users\\Rajiv\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages']
Server time: Fri, 15 Oct 2021 09:26:23 +0000
Hey friends, what is learn Django or php Crouse for beginner? which better for web development?
Django
can anyone recommend a good django course
Yes Django 😂😂
Both if u know python learn Django. If u know Php learn Laravel
If u don't know both learn py and then django it will help in other fields too
Django official doc's quick start section u will find 1
Corey Schafer
CodingEnterpreneur
Trasevery Media
Many bro
@civic crater I can help.
Ping when u're back online (free)
Thanks bro i will check them out
There are thousand
Learn 1 then try ur own
Try not to complete couses instead of it when u complete 1 concept
Try to get better at it and learn in depth
And apply in own use case
And different different parameters n different different uses cases
does anyone know about a dashboard builder drag and drop free?
hello anyone how to remove when I remove or delimit this character?
I am using many to many field
how to remove what
<QuerySet [<ServerGroup and [ServerGroup
I want to display only CHANNEL SERVER, DATA WAREHOUSE SERVER
I'm having an issue with SVG backgrounds on my site: https://dev.mcaq.me/strathloop/code
https://files.mcaq.me/9uhf.png I get these lines inbetween backgrounds. but there are no actual gaps in the image. any ideas?
:incoming_envelope: :ok_hand: applied mute to @native tide until <t:1634324837:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
Hey guys, does somebody know why I'm not able to "stack" two serializers, please see: https://stackoverflow.com/questions/69588647/django-rest-framework-how-to-handle-a-serializer-instance
It seems that Django simply does not accept instance data from another validated serializer within one view
I have a API view in place where I first want to create a new user (already working) and second I want to return the new created user object using my UserSerializer (Not working).
views.py
@api_vie...
if i'm processing a number of events in some class methods, and want to batch every 100 events for insertion to a db, what's the best way to do this? was thinking a class attribute for a list that would contain event data, then when len >= 100 batch it up, send it off, clear the list, rinse and repeat--are there cleaner ways
Maybe a sql transaction?
cleaner?
are you events coming very quickly ?
sounds fine
wrap adding to the list in a classmethod
singlethreaded, right
@dusk portal i m online now
can i see ur html code
for that page
yes
{% extends 'base.html' %}
{% block body %}
<div class="container">
<form action="/shop/add" method="post">
{% csrf_token %}
{% for formcontrol in form %}
<label class="form-label" for="{{ formcontrol.id_for_label }}">{{formcontrol.label}}:</label>
<div class="input-group mb-3">
{{formcontrol}}
</div>
{% endfor %}
<button class="btn btn-success" type="submit">Add</button>
</form>
</div>
{% endblock body %}
👆
Thanx
yup but..
yes done
?
nothin
it was showing that error again but fixed unexpectedly
nice
Anyone here who has an experience of django-autocomplete-light?
tlaking about django html, whats the different between {%extends %} and {%include%}?
if I have 2 base html like navbar.html and footer.html
why I cant extends both of them
?
when i generate requirements.txt using pip freeze > requirements.txt in Django I am getting like this?. why i am getting @ and paths ?
did you use venv
or used global env
What would be the best way to share a variable across my entire Flask project?
I am creating a project tracker and I want all my data in my dashboard, kanban boards etc. to change depending on the Project object stored in current_project. How would I go about initializing and sharing this variable? Currently I am setting it as None at the start of my file, then changing it when a user selects a project. But this naturally means that when I navigate to another site the variable will be reset to None again since all the code reruns...
If you have a solution, feel free to @ me so I don't miss it. Thanks.
Why not use an environment variable?
Oh i see why that won't work
I think writing it to a file would work
I've never had to deal with those yet, this is my first time creating a complex project that's more than displaying a few database files.
Is the value of this variable changing in your app?
Yes, I have a Projects page where a user can select the project he wants to view, and the other pages such as the dashboard should show the data of the currently selected project.
Write it to a file
To a database if you want a more permanent solution
But if it is a website then localstorage works too
I am using Flask-sqlalchemy as my database, so I would have to create a model to store that variable in, correct?
Yes but see if writing to file solves your needs
Database approach will come with The overload of maintaining an additional model
I'll look into it, thank you for your help!
Ah, that's true. I completely forgot about that.
Does that mean I have to store it in the browser cache or something like that?
if you want a user's selection to persist across browsers
use a database
otherwise localStorage is fine
no
localStorage is something that exists on the browser
and can only be accessed/written to with clientside code
i.e. JS
are you familiar
with how the frontend and backend interact
and what they are
Yes, but I'm not sure how I would handle this in any case
if you're using Flask
and don't know how to write JS
just use a database
it's simpler
and honestly
I, as a user
would expect my preference to persist across browsers
So just have a column in my User model for what project is currently selected?
What would be the best column type to use for this? Just store the ID of the project?
a FK would be wise, I think
presumably the project has its own model
Currently I just have this in my user model
currect_project = db.Column(db.Integer, nullable=True)```
should I change it to
```py
currect_project = db.Column(db.Integer, db.ForeignKey('project.id'), nullable=False)```
I don't know the appropriate syntax
as long as you make it a foreign key you'll be fine
nullability
well
Okay, thanks!
I'll keep it on True then I guess
Thank you for your help, I'll test some stuff but I'm confident I'll get it to work 👍
is there any way for me to fix this error? I need the blue colour to be on top of the purple colour
this is the code
If you want blue to be on top of purple, you need to use the z-index in CSS.
but what do i add it to?
Oh, I'm not sure since you're setting it with box shadow, sorry
Maybe it's just the order you put the items in?
What would my other alternative be?
it's not
Just positioning all of the boxes inside a div and overlaying them on each other
I'll just use blue instead of cyan, thanks
<html>
<head>
<meta charset="UTF-8">
<title>Website</title>
</head>
<body>
<input type='text' />
<input type='password' />
</body>
</html>```
how do i make the password input bar go down ?
its side to side with the text
You need to use CSS
This should work, but you really should use a div or some other parent
body {
display: flex;
flex-wrap: wrap;
flex-direction: row;
}
oh, is css super important?
ah, im currently learning flask and html right now, do you think i should css next?
i heard theres this bootstrap thingy in flask that does things like this? im not really sure
anyone know differences between django allauth and django rest-auth?
Yes, you need CSS if you want your website to look any good
Bootstrap is a framework to help with CSS, but you should still learn CSS basics
ah alright, so i heard what bootstrap does is that injects code into html right?
i dont think i enough attention to that course
ah alright, should i learn js after all these?
If you want any reactivity (which is good), yes
how do javascript and flask interact?
if i have js in the frontend and flask in the backend
Yes
im looking at the list right now, for web dev it says theres like php, sass, less i guess i do not need to know these yet right
No
PHP is a server side language, but Python works just fine
Sass and Less are CSS preprocessors, but they aren't necessary
ah alright, how long does it take to like know flask, css, html enough to make a website?
not long.
just paste some tailwind or bootstrap components into templates.
Responsive search built with Tailwind. Search is a special input that allows users to define a text field for entering a search string.
replace some variables in the templates for tags
{{ somvar }}
pass them to the templates
return render_template('index.html', somevar=mydata)
you're done
a day?
i mean you can learn x to the nth degree. but its pretty much it
hey, my dudes.
is there a api service to get images like this for weather?
i can't implement right now
I hosted a django website at GoDaddy...
Can anyone help me in using smtp at GoDaddy so after submission of form mail will generate for individual...
can some one help me with selenium pls assert command
Material icons might have some
CSS question:
I'm learning about CSS transitions through W3Schools, and they show a transition example with an :hover element.
My question is: how can i direct a transition to different element states? like :focus for example.
Any idea how can I create a side panel which shows all sub headings of a blog??
Anything related django, jinja, html or js will work
Thanks
from selenium.webdriver import Chrome
from selenium.webdriver.common import by
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions, wait
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
PATH= 'C:\Program Files (x86)/chromedriver'
driver = Chrome(PATH)
driver.get("https://google.com/")
search=driver.find_element_by_name("q")
search.send_keys("facebook")
search.send_keys(Keys.RETURN)
login = driver.find_element_by_partial_link_text("Фејсбук – пријавите се или се региструјте")
login.click()
wait = WebDriverWait(driver,5)
input_email=driver.find_element_by_name("email")
input_password = driver.find_element_by_id('pass')
input_email.send_keys('pera_peric656@gmail.com')
input_password.send_keys('pera_peric343')
signinbutton=driver.find_element_by_class_name('_6ltg')
signinbutton.click()
wait.until(expected_conditions.element_to_be_clickable((By.TAG_NAME,'_6ltg')))
errormessage= driver.find_element_by_class_name("_9ay7")
assert errormessage.text =="The email you entered isn’t connected to an account. "
driver.quit()
can some one help
why eror
Hello, does anyone know if its good practice to save images as direct files on my website's file system? I was wondering whether it was better to hash, then store inside of a DB rather than the aforementioned method
if you hashed the file, how would you get it back
Sha1 or MD5
idk I saw something on github about hasing the files for security, but ppl seemed to be okay with it
uh
hold up
so you store only the hash?
but
I don't get it
why do you want to store the hash at all?
like
can you help me understand what you think the purpose of hashing is
security and ease of change ig
ease of change?
how does hashing add to security?
isnt it better to store hashed instead of raw?
why do you say that?
also isnt there something about seeing if someone has messed with it, like a hacker; like you can tell
I feel like that stems from a fundamental misunderstanding of what hashing does for you
if you don't mind me saying so
i dont mind at all. im still learning about how cryptography stuff works
okay, so
maybe I can explain
in general, you don't store passwords in plaintext (unhashed)
instead, you store their hashes (with some modifications that I can go into later if you want)
then
when the user sends their password over
your app hashes it and compares it with what's in the database
this ensures that even if your database was compromised
the attacker wouldn't have access to the other accounts
ah
since you can't get back the plaintext from a hash (assuming the hash is good)
so, not MD5, which is broken
so it would be impractical for files to be hashed?
no, not at all
I'm coming to that
you may see when you download software
that the providers also state the expected hash
of whatever you're downloading
this is so that post-download
you can hash the program's files
and compare with the expected hash
and if they match
you know with very high probability that nobody intercepted and tampered with your download, or it just didn't get corrupted over the wire
oh gotcha
so what do you think that I should do instead of hashing?
im finding mixed results on onlines searches
what is the purpose
of storing those images?
just to display to users?
yup
you can just store them
pretty mich
on whatever file storage system you have available to you
what are you using?
like what web framework
flask
hm
I don't know how Flask handles these things
there's probably an addon for this
but in general
you want to have a layer of indirection between your request handling code and your dynamic media management code
do you know what that means
okay
basically
imagine a situation
where you're storing files locally
i.e. on the computer that also runs your Flask server
right?
now say whatever you're developing blows up
and you want to scale
so now you're running your app on 10 different servers
each of which is storing user data on its local filesystem
imagine if a user happens to connect to server 1
stores some files there
and later on on a different computer
they connect to server 4
and now their files are, from their perspective, gone
ideally
you build some sort of abstraction around fetching files and store them externally on, like, Amazon S3
yw 👋 atb!
Hello folks, I would like some suggestions
I want to build a webapp in which I want to compare various cryptocurrencies prices from different exchange services and than recommend the user to buy the cryptocurrency from exchange service A instead of B.
The issue am having is should I use the API's from these exchange services or should I web scrape it?
If there's an API, always use the API
If there's not, check the robots.txt and terms of service to see if you can web scrape
Great explanation, thanks 🙏
Hi, how can i get the first value of a button?
if i have the following values for a button
<button type="submit" name="home" class="button" value="{{ matches[1][0]['name'] }} {{ matches[1][1]['name'] }} {{ matches[0]['start_date'] }} {{ matches[1][0]['price'] }}">{{ matches[1][0]['name'] }}<br> <b>{{ matches[1][0]['price'] }}</b></button>
how can i only get {{ matches[1][0]['name'] }}
the current output is like this Everton West Ham United 2021-10-17
i wanna be able to only get for example "everton"
Hey Everyone!! I want to add Custom Cursor to my Django Website! How can I do so...?
Here's a good article for it
you can read it
https://www.digitalocean.com/community/tutorials/css-cursor-property
?
thanks
wlcm
Hello~
why i am getting this error in django
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'django-insecure-2e(@-ilm2ph7sx34c-0^!o4bcjt2#fx^j=l(m$ey@aqe823q62'
DEBUG = False
ALLOWED_HOSTS = ['labwebsitetest.herokuapp.com','127.0.0.1:8000']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
'lab.apps.LabConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'website.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
``` settings.py file
WSGI_APPLICATION = 'website.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
hey i wondered that flask servers are not for production deployment. But all my code is now written with Flask, so is there a way to turn this into a webserver which you can use for production deployment and which is very simple? and so that i have not to completly overwrite my code?^^
Evry thing is fine ig
try changing the debug to true and figure out the issue
ok
when i do debug=false and run locally the site is working perfectly fine but when i deploy in heroku with debug=false I am getting this error @civic crater
(context django) does doing queryset[:n]
query all rows that queryset requires or the only first n?
flask -> wsgi -> nginx
That kinda depends
There are some special operators in css like > to do that.
So I can have an animation when I click on a button rather then hover?
you can do whatever you wnt on the back end
yes
How?
there is an example
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<style>
.btn:hover ~ .change{
background: red;
}
</style>
</head>
<body>
<button class="btn">Hover</button>
<button class="change">I m going to Change</button>
</body>
</html>
note the tilda(~) used in css
This is also possible
.btn:hover + .change
did you get it?
The + doesn't mean elements that come after?
ok i m not too sure but
+ they r next to each other
~ they r anywhere in the document
> they r inside the element
Yeah so what do they have to do with transitions?
just check this now they will have transition
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<style>
.btn:hover + .change{
transition: .5s;
background: red;
}
</style>
</head>
<body>
<button class="btn">Hover</button>
<button class="change">I m going to Change</button>
</body>
</html>
so sorry i just didn't got what you were trying to say
you can use :active for this
i thought you r asking that how to effect a element by on hovering a different element.
Yes. How can I effect an element with a transition by clicking on it instead of just hovering on it? Can I specify a transition for each state of an element?
yes you can
for clicking you can use :active
Yes but how can I tell transition to effect the element with :active instead of :hover?
Is this what you want
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<style>
.btn{
height: 100px;
width: 100px;
background: yellow;
transition: .5s;
}
.btn:active{
background: red;
}
</style>
</head>
<body>
<div class="btn">Hello There</div>
</body>
</html>
Yes. But if have a :hover and an :active? How can I be specific?
sorry But i cant get what you are trying to say
Like keyframes where you can bind it to different elements at different states.
sorry but i can't get it, any example??
I'm not home now... Give me an hour.
i am no available you can dm me tomorrow
K
in flask, how can i send an empty parameter?
definition:
@option.route("/<Option>", methods=['GET','POST']
def SetOption(Option):
print(Option)
call:
return redirect(url_for("option.SetOption",Option="")
if Option = "" flask will not find a match and triggers error 400
second call, this will works
return redirect(url_for("option.SetOption",Option="x")
how can i send a empty Option?
i solve it, thanks
is the django-ajax-select docs outdated? i am finding it hard to follow
any better package?
so the code can stay the same (even if it is with flask)? I just have to change the method the server is going up?
with Django, how do I get my website to appear? I have it at the point where my website says "IT WORKS!" but the actual website isn't loading. What do I need to do?
In Django+Graphene, my ArrayField looks like ["{'key': 'value'}"] but when I print the arrayfield in a loop, each element is {'key':'value}.
When I return this via graphql to my React front-end, each dict is instead a string so something like "{'key':'value'}". Is there some way to return these as actual dicts? I can't simply parse it because they are returned with double-quotes.
you can make anything insecure
but yea, your flask code is okay so long as its not inviting trouble
think about things like old school SQL injection
Hello guys
So I'm working on a django web application. I wanted to know how can I make a random route on button click. Example I click a html button and it redirects me to a url which is not defined in urls.py but still is a valid page.
See now example I click a button, and the randomly generated url is /kljnsdfkjlnoasdjf
I need django to register that url on the go
rather than me going and routing the url manually
@proven barn Have you tried using a variable for the whole randomly generated url? something like path('/<slug:key>', ...) this would go to a single view from which you can decide what to do with it?
Hey, so I've uploaded my django site to a server, and set everything up with apache, but for some reason my server just can't see static files.
I've tried everything, it just doesn't seem to work, at all
And before you say anything, yes I have setup the config files and etc., they all point towards my static folder which is situated like this:
/var/www/html/mysite/mysite/static
Someone, help me, please
Hello guys!I want to start a project on visual studio code using html ,css,JavaScript,nodejs,Git . Can someone explain to me what path should follow on this IDE to get there?
which port i can host my app
is there free hosting servers?
So I have created a sidebar with django, the only issue is that it overlaps the text on the pages so you can't really see the words. Here is the CSS I wrote and is there any way to fix this problem?
.sidenav {
height: 100%;
width: 160px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #111;
overflow-x: hidden;
padding-top: 20px;
}
.sidenav a {
padding: 6px 8px 6px 16px;
text-decoration: none;
font-size: 25px;
color: #818181;
display: block;
}
.sidenav a:hover{
color: #f1f1f1;
}
.main{
margin-left: 160px;
padding: 0px 16px;
}
Hello, I am trying to host my flask web application but I can't get it to work.
Can someone experience with hosting try to host it for me and see if it works for you?
I am thinking it's maybe problem with my code but it runs totally fine on my local machine.
Hey everyone i just needed a suggestion regarding my website http://virathshuklla.com/
That is it good enough as a portfolio website or not??
Hello everyone, I have a question. What requirements do I need to deploy an app with flask and jinja? 🤔
where r u hosting it
Hey, I am thinking about learning python to build a website for a business idea and im wondering what the max i can do (web development wise) by using only python. Is it possible to get a full website up and running using only python? thanks.
You can never do it with "only" python. You'll need HTML and CSS, and probably some JS too. But the whole backend? Absolutely.
ok thanks, and what exactly would you mean by front end? is that just visuals and such? could i do the whole website with like python and somthing like wix? or would would I have to learn all those languages?
I doubt you can use Python with Wix
And frontend is just the user facing side, the buttons, the links, the stuff that looks pretty
ok yea i got you. theoretically if some site builder like wix did work would python do you think i could build the whole site with only those 2?
I doubt it. No site builder will ever get you the level of customization you need.
How do people usually write good CSS code? Is there like a specific tool that people use? e.g side by side preview type thing
alright, i understand. im just afraid of the fact that it will take me years to learn all i need for 1 project. is there any single language i could use for front end?
You need HTML and CSS, although you could learn the basics in even a week, and JS isn't mandatory, at least to start, but no, there's no "single language" you could use.
alright thanks alot. and to finish it off do you have any suggestions to leaning those languages fast and efficiently?
The MDN docs for HTML and CSS are pretty good
kk. tysm
Oh I haven't tried
Is it possible if you can help me with an example so I can understand it better?
check out htmx for basic interactivity
PyQt with wasm if you're a insane person
wsgi flask apache2 ubuntu
Internal Server Error
ModuleNotFoundError: No module named 'init',...```
Is it correct to put init.py and app.wsgi in same folder?
app.wsgi```py
from init import app as application
import sys
sys.path.insert(0, '/var/www/html/')```
init.py```py
from flask import Flask, render_template
from logging import FileHandler,WARNING
app = Flask(__name__, template_folder = 'template')
@app.route('/')
def hs():
return render_template('index.html')
file_handler = FileHandler('errorlog.txt')
file_handler.setLevel(WARNING)```
apache2 conf
```<VirtualHost *:80>
ServerName www.example.com
ServerAdmin webmaster@localhost
WSGIScriptAlias / /var/www/html/app.wsgi
<Directory /var/www/html>
Order allow,deny
Allow from all
</Directory>```
Hi, I have an error message of the ImportError I've pulled a django project from github but after I activated the env ,installed packages using python -m pip install -r requirements.txt and do python manage.py makemigrations it says that ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? is there anyone encounter this?
Im trying to dynamically change the background using flask based on what is selected from a dict. Can anyone help? Ive tried this background-image: url("{{url_for('static', filename='/img/{{holiday}}.jpg')}}");
You're trying to import from a top level module named init there. Try .init instead.
I am getting the result here <b><span id="smiles_container2"></span></b> and i want to get the out put in
<input type="text" placeholder="Enter the Solute Molecule here" name="solute" id="smiles_container"><br> <br>
``` how can i do this
Are you using a virtual env?
Yes I'm using env
tried to pip install Django but already satisfied
checked the pip freeze as well can see the lib listed on it
Are you sure env activate when you installed package? Try env activate and then install package again
Do we need to learn js
Or python can do everything
I want to use python and it's libraries and MySQL only
Can i use a variable for css? I want my background to change colors based on what webpage the user is on
hi there I was trying to extend user model so user can register with email instead of password but am getting error when i try to create superuser
here I asked a question of stackoverflow please look at this.
https://stackoverflow.com/questions/69611971/valueerror-field-id-expected-a-number-but-got-demogmail-com
it can be done using javascript
This part of the django tutorial covers this fairly well. They are using IDs but you can alter the URL to accept strings into the view: https://docs.djangoproject.com/en/3.2/intro/tutorial03/#writing-more-views
I am working on a Flask project but I am struggling with setting up the relationships between my models. I am getting an error saying I can't use multiple foreign key paths to link my tables. Do I need to use a join table for this and if so, how would I go about setting that up?
Below is a diagram of what relationship I am trying to accomplish. Any help is greatly appreciated, feel free to @ me when you answer.
are you using sql alchemy with flask? flask unlike django doesn't have its own ORM though sql alchemy is common with flask.
I should have specified. I'm using SQLalchemy, yes.
My models are set up, it's just the relationships I am struggling with since it's not just a single link, but multiple e.g. between User and Project.
Before I was using a workaround with a helped function that would store the ID of the current project as an integer in my User model, but that means I have to do a lookup my ID of all my Projects to get the right one if I actually want to get the data stored inside.
whats the definition of a current project. Can a user only be issued with 1 project at a time
The current project is the project the frontend currently displays. The user selects a project in their projects page and the dashboard, kanban board etc. will show only the data from that project.
Do you want to share your models?
Custom properties (sometimes referred to as CSS variables or cascading variables) are entities defined by CSS authors that contain specific values to be reused throughout a document. They are set using custom property notation (e.g., --main-color: black;) and are accessed using the var() function (e.g., color: var(--main-color);).
Do you mean post them here? Sure
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(50), nullable=False)
current_project_id = db.Column(db.Integer, nullable=False, default=0)
projects = db.relationship('Project', backref='owner', lazy=True)
def __repr__(self):
return f"User('{self.username}', '{self.email}')"
class Project(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
description = db.Column(db.String(300), nullable=False)
owner_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
issues = db.relationship('Issue', backref='parent_project', lazy=True)
kanban_cards = db.relationship('KanbanCard', backref='parent_project', lazy=True)
def __repr__(self):
return f"Project('{self.title}')"
class Issue(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
status = db.Column(db.String(50), nullable=False, default='New')
parent_project_id = db.Column(db.Integer, db.ForeignKey('project.id'), nullable=False)
def __repr__(self):
return f"Issue('{self.title}', Parent project ID: '{self.parent_project_id}')"```
As you can see I currently have my workaround in place with current_project being a regular int instead of a reference to the actual current project
I am very new to using databases, I've only had to deal with the regular o2m relationship before
user_project
ok. its cool
often you need another table. with the id of each record in a 3rd table to keep many to many relationships
user_project
user_id, project_id
Is that the join table? I heard about it but I'm unsure how to properly implement it
then you can use sqlalchemy to backref them
so if you storing one relationship. you just need 1 id. so you can store it on the same table as a foriegn id.
but if you need a list of tihngs. then you often want another table
that is just the id of the 2 things you want to relate
it takes years to get your head around it if you're not natural at it. and due to different ORMs etc you can get confused. also if you don't do it for a year you forget a lot
but it's just a look up table
So do I have to do something like this?
user_projects = db.Table(
db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False),
db.Column(db.Integer, db.ForeignKey('project.id'), nullable=False)
)```
yes
then somethign like this
roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users'), lazy='dynamic', cascade="all")
in the model
I don't really understand that last part to be honest
so my model. need to have teh relationship plumbed in
class User(db.Model, UserMixin):
What does the Role stand for?
projects = db.relationship('Projects', secondary=user_projects, backref=db.backref('users'), lazy='dynamic', cascade="all")
sorry i was pasting from my own model as example. that would be more like it
Ah, okay. And cascade deletes the projects when the user is deleted?
only if you tell it to
cascade="all,delete"
so dependso n the relationship
and if you want it to
i.e. you might have load sof user notificatoni setc and shit
I understand. So, with this table does every project only have one owner, or does it have multiple now?
so if that user leaves. delete their crap
the projects_owner table can do many 2 many
and you have bound the relationship with the ORM to your model
so it will now fetch the records auto
wihout you having to do code to update etc. or do joins
How would I go about making sure a project only has one owner or that a user only has one current_project? (they can have multiple projects, but only one selected at a time)
As far as I understand this only handles Users having Projects
create a owner column on teh project table? with a foreign key to the owner
Ah okay, so this is where the FK comes in.. Got it.
ye think about the relation first
then do either a mapping table or whatever they are called with an id for each.
or just do a column with a key you can join on
And when I want to limit the m2m table to o2m, I use the uselist=False parameter?
to be honest. understanding that. is the only thing that separates a front end dev from a back end one.
Well, I'm really thankful you helped me this much
I feel like I have a basic understanding now and can maybe do some research on my own now that I know the general idea
ye. it will set you apart frmo 75% of other devs. and its relatively simple concept
I just wanted to combine creative frontend stuff with my previous Python knowledge, so I thought I should give it a try
Hello guys
So I am unable to access the static files. The thing is that when I have direct routes, example- https://website.com/first/ I am able to fetch the static files. But when I add another route before first example- https://website.com/second/first/ then the static files are not leaded. Why is that so? And how can I fix it?
anyone that can help with flask just to send an email attachment with the help of gmail api
Any idea guys?
It's a django framework btw
can anyone please help me related to an api project i created in python how can i manage project dependencies.. like in node apps we have a package.json file how we deal in python ????
you've got a few options. The vanilla way is using requirements.txt and running pip install -r requirements.txt
I prefer to use poetry since it has a nice cli
Weird question: what was used in before JavaScript became a thing?
So Java was used in web development before JavaScript became a thing?
it all started in the mossaic browser, then netscape came up with javascript.
yeah it was known as live script back then
fun fact: Flash uses a subset of javascript called ActionScript. (It's actually ECMA3)
So people only used HTML, CSS or CSS wasn't a thing either?
lets see.
CSS date release: December 17, 1996
HTML date release: 1993
Before CSS, nearly all presentational attributes of HTML documents were contained within the HTML markup. All font colors, background styles, element alignments, borders and sizes had to be explicitly described, often repeatedly, within the HTML
heh, between 1993 to 1996 people were forced to write all styling parameters only directly to html ;b
So, inline styles were talking about?
Django Roadmap
I've been having trouble finding a good roadmap for python Django developers, any good suggestions?
Build a discord-like application with Python Django. Visit the finished application at https://studybuddev.herokuapp.com/
Get The Full Django Beginners Course:
https://dennisivy.teachable.com/p/django-beginners-course/?product_id=3222835&coupon_code=BRAD
Use promo code BRAD for 50% off
Dennis Ivy YouTube Channel:
https://www.youtube.com/c/den...
it's been the second time I ask for a roadmap and provided a course XD. I need a roadmap to know all of what's needed for a django developer to be known as an expert
I bet every new self taught django dev knows dennis ivy, he's a GOAT on this
https://github.com/kamranahmedse/developer-roadmap so there are those types of roadmaps
very informative and for experts
is there a similar one for django devs?
ImportError: attempted relative import with no known parent package,...```
Renamed `init.py` to `.init.py`, changed
```py
from init import app as application
to
from .init import app as application
Sorry i am confused, what am I missing?
when a from import starts with a ., it means import from the current package
Sorry i fixed it
app.wsgi
import sys
sys.path.insert(0, '/var/www/html')
from init import app as application```
the .init is unnessary
But the line order is important
Thank you so much
I facing issues while uploading static file in django app on heroku
Anyone please help
I used <form autocomplete="off"> on my form. Why are my inputs still auto-filling the username and password? (firefox)
it works in chrome. Sigh
How to make website
static or otherwise?
Hello guys
So I am unable to access the static files. The thing is that when I have direct routes, example- https://website.com/first/ I am able to fetch the static files. But when I add another route before first example- https://website.com/second/first/ then the static files are not leaded. Why is that so? And how can I fix it?
I have two forms one for User and one for user Profile
after successful form validation for both form user is created and profile object also created (i am using signal post_save) .
user = register_form.save()
profile_form.instance = user.profile
user.profile = profile_form.save()
user.save()
profile form data is not inserted into profile of user but its get created. when
register_form.save() called.
Hello everyone, I have a question. What requirements do I need to deploy an app with flask and jinja? 🤔
I'd use gunicorn
this is too generic. There are lots of things involved in the deployment. You need to narrow the scope of the question
Ok for example, in the frontend a production file is created, but in Python one is created too? 🤔
What is gunicorn?
what is production file?
In vue or react with a command create a build file.
I do not know if with a page made with flask you can do that.
Sorry my english is not very good 😆
no need for flask. there are tons of tutorials on youtube about this
Ok, thanks you
Hello guys
So I am unable to access the static files. The thing is that when I have direct routes, example- https://website.com/first/ I am able to fetch the static files. But when I add another route before first example- https://website.com/second/first/ then the static files are not leaded. Why is that so? And how can I fix it?
guys any idea with django framework?
Hi
i need some help
const game = {
elements: {
progressLabel: document.querySelector("#progresslabel"),
progress: document.querySelector("progress#file"),
levelBtn: document.querySelector("#btnLevel")
},
level: parseInt(localStorage.getItem("level") ?? 1),
clicks: parseInt(localStorage.getItem("clicks") ?? 0),
multiplier: parseInt(localStorage.getItem("multiplier") ?? 1),
prestige: 0,
rebirth: 0,
requiredClicks() {
return game.level * 250 + game.multiplier * 50;
},
nextLevel() {
return parseInt(game.level + 1);
},
updateProgress() {
game.elements.progress.value = game.clicks;
game.elements.progress.max = game.requiredClicks();
},
levelingEnabled() {
game.elements.levelBtn.disabled = game.clicks < game.requiredClicks();
},
updateStorage() {
["level", "clicks", "multiplier"].forEach((key) => localStorage.setItem(key, game[key]));
},
buttonFunctions: {
click() {
game.clicks += game.multiplier;
console.log("h")
game.updateProgress();
game.levelingEnabled();
},
levelUp() {
console.log("level up");
++game.level;
game.clicks = 0;
game.updateStorage();
game.levelingEnabled();
},
menu() {
console.log("menu");
}
}
};
game.elements.progressLabel.textContent = `Progress to Level ${game.nextLevel()}`;
game.updateProgress();
document.querySelector(".btn-wrap").addEventListener(
"click",
(e) => {
if (!e.target.matches("button, button img")) return;
const btn =
e.target.tagName === "BUTTON" ? e.target : e.target.parentElement;
game.buttonFunctions[btn.dataset.func]();
},
{ passive: true }
);
okay so
progress.max is not a number (NaN)
game.elements.progressLabel.textContent = Progress to Level ${game.nextLevel()};
its being set there
and it says nan
?
can someone help
flask question
What is profile 'profilepicture' = to in the routes.py example? And in the register function do I need to commit profile picture from the database or is it automatically a commit ?
routes.py in register function
picture = request.files['profilepicture']
models.py`
profilepicture = db.Column(db.LargeBinary, nullable=False, default='default.jpg')
https://pypi.org/project/wtforms-validators/#Alpha Why can't I use this validator method in my Flask app anymore? It just says:
ImportError: cannot import name 'Alpha' from 'wtforms.validators' (C:\Users\magnus\AppData\Local\Programs\Python\Python39\lib\site-packages\wtforms\validators.py)
I have installed it via pip install wtforms-validators... Might it be outdated?
Hi anyone know how to make a eccomerce website what language I should use all packages/imports/frameworks I should use or would you send me full video tutorial because I have no clue I’m pretty fluent in most of the big languages JavaScript,python,java are my main ones so any and all tutorials will do if I need to learn a new language I’m happy to do so so please help me out
look closely, according to https://pypi.org/project/wtforms-validators/#Alpha ,
it should be: from wtforms_validators import Alpha
and not: from wtforms.validators import Alpha
Yeah buddy I did see that 🙂 It didnt work however 🙂
are you sure?
Im gonna try restart my VSCode now and try again
the error says:
ImportError: cannot** import name 'Alpha' from 'wtforms.validators'** (C:\Users\magnus\AppData\Local\Programs\Python\Python39\lib\site-packages\wtforms\validators.py)
no hold on
send the code you have rn
can someone help
restarting vsc wouldn't help
Why does my <img show red and why does it not work? what mistake am i doing that is not showing? pls any help would be appreciated
look closely
do you see anything wrong?
I solved it with using some python code after the sumbit.onvalidation() but looks like reloading VSCode made wtforms_validators work for some reason. Im gonna test it if it works now If i remove my .isalpha() code
no 😅
a normal img thing is
.
umm, you need to send the tag
ending tag
no, that's not he issue
ahhhh
it should be```html
<a href="link"> <!-- you are missing the > -->
<img src="link">
</a>
@cerulean remnant It did work now 🙂 Do you know how I can set the value in the StringField to be '' ?
bro thank you so much 😣 i spent 20 minutes over that silly mistake
Sorry for posting twice but in flask python question I am trying to upload a image from the database
What is profile 'profilepicture' equal to in the routes.py example below? And in the register function do I need to commit profile picture from the database or is it automatically a db.commit ?
routes.py in register function
picture = request.files['profilepicture']
models.py
profilepicture = db.Column(db.LargeBinary, nullable=False, default='default.jpg')
nope, i have never used wtforms-validators before
i didn't even know it existed
<h1>mother fucker<h1> not working helpppp
this code is sooooooooooo hardddddddddddd
Alright 🙂
?
i think he is a troll
code didnt workkkkkkkk
whffffffff
!ot go ask in an off-topic channel
Off-topic channels
There are three off-topic channels:
• #ot0-fear-of-python
• #ot1-this-regex-is-impossible
• #ot2-the-original-pubsta
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
<h1> mf </h1> what did not work?
leave him
i am a pro html ik h1 h2 h3 ``h4 h5 h6 h7 i am biggest proooooo
idk
think soooooooo
i need to
youtube
or google
I told you, leave him
what
i am a new in html
Can someone answer my question?
plsssssss
ye?
yessssssssss
ok
i will try it
flask python question I am trying to upload a image
What is profile 'profilepicture' equal to in the routes.py example below? And in the register function do I need to commit profile picture from the database or is it automatically a db.commit ?
routes.py in register function
picture = request.files['profilepicture']
models.py
profilepicture = db.Column(db.LargeBinary, nullable=False, default='default.jpg')
routes.py ?????? python
Its where you keep your routes
well if you don't know don't anser
loll
you dont know me i am a biggest proooooooo
you need to commit it ig, otherwise i wouldn't be stored, and
profilepicture is just an image (ig)
followup question brb just need to post a error I am getting
alr alr
ping me btw
nevermind that is it
from playsound import playsound
playsound('helllo.mp3')
a=(input('type code:'))
if a == 'help':
print('1 = google')
print('2 = text into word')
print('3 = play song')
else:
print('type ?Help')
a2 = input('type command:')
if a2 == '1':
a3 = input('type website name:')
import webbrowser
webbrowser.open(a3)
else:
print('wrong statement')
if a2 == '2':
text=input('type here:')
from gtts import gTTS
tts=gTTS(text)
tts.save('byee.mp3')
from playsound import playsound
playsound('byee.mp3')
else:
print('wrong command')
if a2 == '3':
from playsound import playsound
playsound('song.mp3')
print('playing song.')
print('playing song..')
print('playing song...')
print('playing song....')```
ohk
<h1>mf<h1/>
where did you copy it from?
its my code lol
if you try it ,it will not work
sad
i am a py proooooooo
whyyyyyyyyyyyyyyyy
heekki
@kind steppe hiiiiiiiiiiiiii
whoppy
whoopty
f
fuck
!pypi gtts
print('hello i am bot if you want to use my commands type help')
from playsound import playsound
playsound('helllo.mp3')
a=(input('type code:'))
if a == 'help':
print('1 = google')
print('2 = text into word')
print('3 = play song')
else:
print('type ?Help')
a2 = input('type command:')
if a2 == '1':
a3 = input('type website name:')
import webbrowser
webbrowser.open(a3)
elif a2 == '2':
text=input('type here:')
from gtts import gTTS
tts=gTTS(text)
tts.save('byee.mp3')
from playsound import playsound
playsound('byee.mp3')
elif a2 == '3':
from playsound import playsound
playsound('song.mp3')
print('playing song.')
// set time out for audio when end
then print('end')
else :
print ('wrong command')
kyaaaa
@thorny shadow cool
thanks
but think so it didnt work in your pc
it's error ?
Hi, I have a question.
Suppose we want to use face recognition in a mobile application using Python language, what library do we use or how do we link these both together?
what wsgi production free servers can i use?
heroku?
that's a host with a free tier.
if you're looking for a production server you can install yourself, gunicorn is my go-to
Hey i have a question about flask.
Im making a betting simulator web-app where i get upcoming soccer games and results from 2 API's. And after im done my project i will most likely use Heroku to host it. My question is when i do flask run and server is open does the code update? for example when the server is open and lets say a game has finished and the results have come out...does the server automatically update? or do i need to rexecute the code by restarting the server?
isnt it gathering from the api?
if so all you have to do as the user is refresh the page? as long as the backend code is correct
ah ok, thanks
np!
is there a way to create a bootstrap navvar with menus accesible by user-rol?
where can i get a simple example?
a menu access by rol,
common user see 1 menu
expert user see 3 menus includin common user rol
admin user see 4 menus
but common user cannot see expert or admin menus
you need to control that with web templating langs dont you?
could be, but ... is it possible by using only 1 template? i really do not like to create 200 templates
got it?
what are you doing in web-development???
?
python web dev = flask, bootstrap and dyango (and html)
and?
"no like web templating ""languages"" "
flask is not python
what do you mean wiht that?
google web templating languages
this is python channel for flask or django
So in your back end you can pull the account type, whether it is a common user, expert, etc
then with Jinja (part of flask), you can do
{% if account.type is 'expert' %}
Or something similar to this if you want
like if statements in the HTML code, done by jinja
Do I use Flask or Django. 
Or Pyramid. lol. Ultimately I think they're all as capable as each other in good hands, but I'm working with a lot of non crud data sources!
Django has the nicest experience so far, but I've run up against some stuff with our special snowflake requirements.
depends
I want to do this visualization as shown in the figure. as i change the molecules on the left side and on the top it should change the middle showing number iteractively using javascript. I know this can be done using d3.js but can anyone share similar examples
you can make using JavaScript, HTML and CSS
how to make website on Google
use google site. Its free
On mobile
What do you want actually? Be clear
I think he wants to ask how to display site ongoogle
You can make site either with HTML CSS JS
Or use a framework like React
And then buy a server and domain for webpage
And then pay a monthly fee to host it
Hey how can I send the request made to a particular endpoint in flask to a list (or) a queue so that I can process and send response one by one.
Goal : Is to build a unique file allocation endpoint will be running windows(don't ask to change to linux its requirement). Where user will hit the endpoint and gets
files. But the file have to be unique one consider all the files are maintained in a single folder. I need some mechanism or tools that can help me in this.
hey all. I've finished a django course and have been exploring it more by creating a project of my own. However, it takes me forever to finish things. I keep thinking that what takes me days and weeks could be done by a senior in two hours, and get really discouraged.
I just want to know, is this normal? was that how it was for you when you were new to django? and also, any tips for making me faster?
if you see your self finishing things longer than a Senior then i would suggest you to strengthen your self to the fundementals of Python for instance at beginning when we did the calculator project it toke us at least 20 lines of code and if statements to do while if we knew about eval() function we could have done it in less than 10 lines of code
summary of it strong foundation of python language will help you save lots of time and code try vising list of comprehension, lambda, decorators, eval(), compile() etc...
Check out background jobs on Miguel grinberg's blog for queueing tasks and running them in the background
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xxii-background-jobs
Hello guys!I want to start a project on visual studio code using html ,css,JavaScript,nodejs,Git . Can someone explain to me what path should I follow on this IDE to get there?
Thanks for the help! I'll make sure to spend some time brushing up my python knowledge!
One more question: how do you make designing easier? I mean deciding what view should do what and what things should be in the same page and what should be separate? I feel like this is one of the things that I spend too long on, so it would be great if there were resources I could read or things I could practice.
as far as i know this is UI/UX field of expertise, as most of interface design befor implementing it to a real project is made in adobe products like adobe XD i think
hmmm, but it does affect the back-end too, right?
nop
try to copy cat certain platforms with same features you want to create and later on implement your own design to the frontend
i'm not familiar with any of this, but it appears that it might have something to do with game.nextLevel
what's the value of requiredClicks() when you're trying to set the progress element?
hi im trying to develop some code that sends a request to https://md5hashing.net/hash/sha256/ along with a SHA256 hash. i want it to search through the parsed html and retrieve the "unhashed" value--if it exists.
here is my code: ```py
import requests # !pip install requests
from bs4 import BeautifulSoup as bs4 # !pip install beautifulsoup4
from hashlib import sha256
def checkHash(sha):
url=f"https://md5hashing.net/hash/sha256/{sha}"
hashPage=requests.get(url)
hashSoup=bs4(hashPage.content, "html.parser")
result=hashSoup.find("span", id="decodedValue").text
return result
if name=="main":
sha="cf80cd8aed482d5d1527d7dc72fceff84e6326592848447d2dc0b0e87dfc9a90" # hash of "testing"
print(checkHash(sha))
however, hashSoup's body only contains a script doing some kind of JSON query
<body>
<script type="text/javascript">
__meteor_runtime_config__ = JSON.parse(decodeURIComponent("%7B%22meteorRelease%22%3A%22METEOR%401.5.4.2%22%2C%22meteorEnv%22%3A%7B%22NODE_ENV%22%3A%22production%22%2C%22TEST_METADATA%22%3A%22%7B%7D%22%7D%2C%22PUBLIC_SETTINGS%22%3A%7B%22stage%22%3A%22production%22%2C%22secure%22%3Atrue%2C%22ga%22%3A%7B%22id%22%3A%22UA-46347216-1%22%7D%7D%2C%22ROOT_URL%22%3A%22https%3A%2F%2Fmd5hashing.net%22%2C%22ROOT_URL_PATH_PREFIX%22%3A%22%22%2C%22DDP_DEFAULT_CONNECTION_URL%22%3A%22https%3A%2F%2Fmd5hashing.net%22%2C%22appId%22%3A%221yyb8dxdjzh9kehs7f7%22%2C%22autoupdateVersion%22%3A%2201a99ac41f6328d0b161779bb728ca366cf4223d%22%2C%22autoupdateVersionRefreshable%22%3A%227807a4994675d2b6b87126e81a90597e65f93071%22%2C%22autoupdateVersionCordova%22%3A%22none%22%7D"))
</script>
<script src="/86a575c16d520b06dd112d530721e721a820067c.js?meteor_js_resource=true" type="text/javascript">
</script>
</body>
please ping me if you know how to either wait for the JSON query to update the page or execute it from Python...
When you say design, do you mean visual design or designing your python code to be maintainable & readable?
Is there anyone who know to make a dashboard with all features and connected to my bot. Please ping me if someone replies
we do not allow recruitment on this server. Stop.
Recruitment is not allowed on this server, as you've already been told.
You're not going to get another warning.
How can I handle two different domains on one website in the best way? My problem is quite simple and I thought it was easy to solve with a URL redirect until i found out that DNS cannot resolve specific pages of a website. So here is the deal:
- I have a website running at www.company.com
- The website has a special product route at www.company.com/product
- The company just bought www.product.com and wants it redirect to www.company.com/product
Now I thought I could identify the root domain with:
print(flask.request.url_root)
print(flask.request.headers['Host'])
And then redirect it to the corresponding route. But now what if a user trys to go to www.product.com/abc? I cannot check for all hundreds of www.company.com routes if the root domain is product.com
There must be an easier way to solve this but i am unable to think of a better way to do this. Any suggestion is appreciated
Someone please answer me also
Hey guys! When I add app_name = 'main' to urls.py I get this error: "Reverse for 'contact' not found. 'contact' is not a valid view function or pattern name."
I need reverses to use my other views which use ListView and DetailView
How do I fix this?
Nvm stupid doubt. Lesson to learn: don't blindly follow tutorials because they have different settings applied.
could somebody help me with my code?
source bin/activate
export FLASK_APP=test.py
export FLASK_ENV=development
export FLASK_DEBUG=1
flask run --host=0.0.0.0
import os
from app import create_app
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
if name=='name':
app.run(port=2021)
it always runs on port 5000, it ignore command "port=2021"
thanks, i just have started the project as usual
did you try flask run --host=0.0.0.0 --port=2021?
Hi, flask dev here ? 🙂
Like, is a flask dev here, or the Flask dev here?
It doesn't matter as long as someone can help me x)
So, I start a Flask project :
from flask import Flask
app = Flask(__name__)
if __name__ == "__main__":
app.run(
debug=True,
port=3000
)
I don't know how to link the app.run () and routes in /controllers/XXX
my __init__.py
from . import controllers
from controllers import *
or from controllers.dbscan import thing
It doesn't work
My home.py
from flask import render_template
from main import app
@app.route("/")
def home():
return render_template('/home.html')
Error : 127.0.0.1 - - [19/Oct/2021 23:10:10] "GET / HTTP/1.1" 404 -
does anyone know why this wont autoplay html <audio src="./song.mp3" autoplay="autoplay" loop="loop"></audio>
Note: Chromium browsers do not allow autoplay in most cases. However, muted autoplay is always allowed.
guys how do you do server side redis sessions with fastapi?
Hey guys, I was wondering about the web service "webflow". I just found out that you can export the website you build to only code and im wondering if I could just build a website through a website builder, export the code and use that code as my front end website code to keep me from having to learn JS,HTML,CSS,etc
kind of?
If you're using something like django, you want to display data from a database and to do that you need to understand how the templating engine works and you need to go in and edit the html and add those things in
You'll probably need to use forms and so you'll want to send forms to the frontend as well
im really stuck lol I have a really good idea for a WebApp business but as far as coding I only know a bit of python. And I dont have thousands to pay somone to do it for me
trying to build a website without knowing the basics of html,js,css sounds very hard
I wouldn't bet on it
Cause like, Ive build plenty of websites with wix and such and its not a problem... I just wounder how it will work with somthing like this and what all the downsides are
I think the time spent learning web languages would be a much better time investment than trying to figure out how to frankenstein a wix site code output into a python backend
html/css are very simple
Fair enough. im just worried it will take 10 years for me to master them to build anything decent. also would it be easier to just learn like reactJS instead or?
Until you want to get super fancy and build apple's landing page or something
That is an understandable worry
It will not take you that long
reactjs is harder
but if you want to build something dynamic and you need that single page app feeling then it may be worthwhile doing that as well
Would it really make a difference like that? And thanks alot for the help. what would you recommend learning first? cause even python at best i know like 35% of the language.
I've built sites without a frontend framework and it can get messy pretty fast. Using something like react or vue makes things much more manageable
I think you should just start building something with django and you'll be forced to learn on the way
alright so finish learning python and build some sort of backend with django and go from there?
I think that sounds just fine. Follow some django tutorials and then build something that you want to build
Awesome thank you so much!
you're welcome!
What can I use for reading dynamic websites that will do it fast?. With selenium I have to wait for 2 seconds to load me 50 elements
facing difficulty in establishing connection with redis queue server running in wsl with local python script
any idea about that ?
its running in windows
What's the error message? Are you running the redis in wsl?
code
class OrderItemModelSerializer(serializers.ModelSerializer):
total = serializers.SerializerMethodField('get_total')
class Meta:
model = OrderItem
fields = ('id','order_quantity','medicine_id','order_id','rate','total')
def get_total(self,obj):
return self.order_quantity*self.rate
error
can anyone help
it has order_quantity in it but it says there is no other quanotity
quantity*
@chilly falcon what does the OrderItem model look like?
yes I'm running redis in wsl but
import rq
queue = rq.Queue('file-allocation-process', connection=Redis.from_url('redis://'))
job = queue.enqueue('common.queue_task.perform_task')
print(job.get_id())```
when i run this program I'm getting
`redis.exceptions.ConnectionError: Error 10061 connecting to None:6379. No connection could be made because the target machine actively refused it.`
can't we connect to program running in wsl ?
I have found solution mistake in serializer that instead of obj.orderquantity i was using self.quantity
First, both your flask app and the redis should be running in wsl(multiple terminals/shells). Also, you should see a bunch of messages when you start your redis service
Anyone knows if Flask-Login is still legit to use? Or are there better alternatives for handling user auth in Flask nowadays? 🙂
I meant it being maintainable and readable, but also deciding where to do what. for example lets say I have a page where people can log some symptoms to track them, but all symptoms are in categories. would it be better to have one form per category in a separate page, or just have them all in one place? These sort of questions are what I mean...I think part of it also comes from the fact that I dont know frontend so I dont know the possibilities there are....but Im not sure if that is all
Is there anyone in this servers who can make a dashboard for bot
Please ping me if anyone replies
i have some query on selenium can anyone help?
Got it we can run the redis in wsl and able to connect from local windows the issues is with wsl firewall which actively refuse the connection to this port. Anyway thanks for your guidance.
Hi I am having problems with importing stuff on my Flask project, this is the error shown:
Traceback (most recent call last):
File "C:\Users\Backup\Desktop\furkanvas\py-env\backend\server.py", line 1, in <module>
from app import app, db
File "C:\Users\Backup\Desktop\furkanvas\py-env\backend\app\__init__.py", line 5, in <module>
from app.api.routes import User
File "C:\Users\Backup\Desktop\furkanvas\py-env\backend\app\api\routes.py", line 4, in <module>
from app.models import Users, Profile
File "C:\Users\Backup\Desktop\furkanvas\py-env\backend\app\models.py", line 1, in <module>
from app import db
ImportError: cannot import name 'db' from partially initialized module 'app' (most likely due to a circular import) (C:\Users\Backup\Desktop\furkanvas\py-env\backend\app\__init__.py)
can anyone help me with this? i can provide some code if requested
You have a circular import, in that you are trying to import the db thing from app before app has finished initialising it's imports. The typical way to solve this is to move one of the relevant imports inside a function, with Flask from what I remember this is typically in your server.py but I may be wrong
that worked thanks
Hello
when i do this
why is their a gap?
can anyone help me fix?
Broadly sounds like you want to be looking into general software design patterns and architectures and how they implemented in Python/Django. In terms of Django I prefer defaulting to class based views and tend towards and API based approach which allows for good separation of concerns. If your part of a team then get your code reviewed regularly, otherwise try to think about coming back to any particular code after a period of time (3-6 months) or if you had to hand the code off to someone else.
can anyone help me with this?
margin-top: 0 px;
is a <div> just to contain stuff inside? like a <header>
that did not work
we dont see the whole code
ok wait
:incoming_envelope: :ok_hand: applied mute to @native tide until <t:1634745451:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 110 newlines in 10s).
!unmute 899531995191853106
:incoming_envelope: :ok_hand: pardoned infraction mute for @native tide.
Sorry, use https://paste.pythondiscord.com
rip
thanks!
@native tide any ideas now?
can you give me the nav part aswell
of html
ok
hii
why do we create class inside a class?
why do you think
Is there any way to handle errors in Django forms? If there is a problem while user is sign up(custom Sign Up Form) to just display an error box rather than displaying the original form
what do you mean
im not sure if this is the right channel or not, but I've got a question.
I want to able to control the contrast in a web picture:
lets say there is this site that has a picture map https://www.legacysurvey.org/viewer#IC 2989
I can make a picture with specific coordinates (dec, ra) like so https://www.legacysurvey.org/viewer/jpeg-cutout?ra=0.8642482&dec=27.6547253&layer=ls-dr9
what I want to know is: is it possible to add a something to the url that controls the contrast of the pic? something like &contrast=1
oh nice! my follow up question would be is it possible to produce a url with this filter and contrast already set it? is it possible to save this setting is my question, instead of adding it each time?
not really
what you can do is get a web (chrome/firefox whatever) extension which allows you to define your own stylesheets
then you can target that img tag and add the filter yourself
so you'd have to create a stylesheet which targets legacysurvey.org/viewer/jpeg-cutout* and ```
img {
filter: constrast(1.5);
}
but this only sets that contrast for you, if this custom stylesheet is set up
a url which has this preset is only possible if the website frontend/backend is expecting a contrast param and actually does something with it
you could add a slider for the amount of contrast
actually are sliders even a thing in html? You can create a range of numbers then selecting the input amount
there already is a slider
hmm, maybe if I elaborate it would help:
I have this google docs excel table which draws pics from different sites (legacy is one of them for example) using a url command.
is there any way somehow to make it draw a picture with a specific requested contrast?
If I understand what you are saying, its something that needs to be done for every picture every time I want to open it?
I have around 4000 pictures in the table, and I want to get the images to the table with a certain contrast if possible
ty so much btw, my knowledge is very poor in this area
yea I didnt think they would have such a specific setting 😄 thank you for your help!
You can try to find a site that is able to take an image url / contrast as query params and return a new image
or write a script which retrieves the images and downloads them -> applies contrast
yea, this seems to be the alternative solution, was hoping I could avoid that, seems complicated 😬
I want to build an CRUD API with DRF which has some sort of auth that only allows users to operate on resources they own. What's a good solution for this?
I have been looking into oauth2, but I find the flow to be confusing. I need to register my app and I get a client ID & secret. For users to get their tokens, they'll need to provide they user and pass in addition to this client ID and secret, which seems awkward. I saw a solution which wraps the token endpoints and auto-injects the client ID and secret, but this seems redundant.
I have a feeling oauth2 may not be the right tool for the job
I'm guessing there is a django-jwt-drf library of some kind that would handle tokens that way.
There is one for graphql
JWT seems simpler. If I understand correctly, a user can request a token by only providing their user/password. Then they can pass that token to protected API endpoints. No need for a client id/secret.
Is there a reason why I can request.user and get my user info but on others I can't?
I'm on the same session
Ah, nvm
I'm dumb
@proper hinge does session authentication not work for you?
Not sure. I thought that was mainly used for websites. I am building an API. No frontend at all.
I got JWT set up and I'm gonna be trying it out, but I think it is more in line with what I was looking for.
it sounds like sessions may not work for you. Great! good luck
Thanks
Hey everyone, I have small question regarding routing for Flask. I have a dynamic route @app.route('/v1/<parameter>') but I want know what is the best way to constrain parameter to a set of values.
You can use one of the built-in converters e.g. <int:parameter> or define a custom one if you really need some bespoke validation
It's covered here https://flask.palletsprojects.com/en/2.0.x/api/#url-route-registrations
I see, I just have a set of valid routes i.e [param1, param2, ...] and I just want to basically check if that parameter is in that set
Does it not make sense for you to just define a separate route for each option?
The way you phrased it makes it sound like they represent different routes rather than just being a parameter
To be more specific
It accepts a parameter in which it grabs data and runs an algorithm on it. i.e if I have country called canada it will run the data on canada
However the list of routes is different and volatile which switches around quite a lot
If it's volatile then you should probably just perform the validation within the function
If it was more static, you could do @app.route('/v1/<any(option1, option2, option3):parameter>')
Hmm maybe volatile isnt the right word, it doesnt just disappear randomly but more so it can change by deployment
The list will be static for each ran deployment, it will auto-generate the required list on each deployment
It is just a string, so I suppose you could format it with whatever values you generated
Hmmm
Is this possible to do in the converter you mentioned
I would also like to give a specific message for invalid routes too
i.e app.route('/v1/<param>/<resource>/' There is no <resource> that exists for <param>. Rather than a generic route error
Yeah you could use the any converter or define your own. I think it's like this, though I am not sure if the values need to be quoted or not.
# this list is generated during deployment
# you could e.g. read a file instead and then parse it into a list
choices = ",".join(["choice1", "choice2"])
@app.route(f"/v1/<any({choices}):parameter>")
def foo(parameter):
...
For custom error handling, look into the @app.errorhandler decorator
I see, thanks for your input Mark. I greatly appreciate it.
I am in need of some help serializing data with DRF and ModelSerializer. When serializing my foreign keys it is returning the ids and I cannot get it to return the value
How have you defined your serializer?
There are several ways to represent the value of an FK.
`class CadetModelSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = '__all__'`
Which field is an FK?
In the models say it looks like
class Student(models.Model): class = models.ForeignKey( Class, on_delete=models.CASCADE, default=None )
It returns the ID (PK) of the class instead of the class name
I have tried multiple SO solutions and cannot figure it out
You need to define a class attribute on your cadet serializer class = serializers.SlugRelatedField(slug_field="name"). I'm assuming "name" is the the name of the field containing the class's name.
You probably also want read_only=True in the slug parameters
This is the error I keep consistently getting __init__() takes 1 positional argument but 3 were given
Can you show what your serializer looks like now?
`class StudentModelSerializer(serializers.ModelSerializer):
_class = serializers.SlugRelatedField(slug_field="name", read_only=True)
class Meta:
model = Student
fields = "__all__"`
Oh yeah, class is a keyword in Python...
That's awkward. I'm sure there is an alternate way to specify this but I don't remember.
I used _class my bad
And I am assuming the Student model also has it with an underscore?
Yes
C:\Repos\ATS\venv\lib\site-packages\django\db\models\query.py in get
num = len(clone) …
▼ Local vars
Variable Value
args
(<Q: (AND: ('id', 1))>,)
clone
Error in formatting: TypeError: init() takes 1 positional argument but 3 were given
kwargs
{}
limit
21
self
Error in formatting: TypeError: init() takes 1 positional argument but 3 were given
This is the traceback I believe
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.
The error is coming from this line
File "C:\Repos\ATS\ATS\cadet_manager\views.py", line 43, in get
cadet_attributes = CadetModelSerializer(cadet_obj).data```
Well, maybe not directly
All I'm doing there is passing in the object of the student model
Yeah I guess that's fine
But it leads to some internal error later
Looks like it's trying to create the model but it's failing
I would suggest you place a breakpoint at ```py
File "C:\Repos\ATS\venv\lib\site-packages\django\db\models\base.py", line 512, in from_db
new = cls(*values)
and see what model it's trying to create and what the values are
Hello, I was wondering if there was a way I could adjust the server response based on the OS/device mentioned in the HTTP request? (preferably with flask) Thanks
@proper hinge What's the difference between the slug field and the Primary Key related field
Anybody use mysql with django ? Or do you use the django native method for databases ?
I have experience with sql and it seems easier to make quick changes
The former allows you to select which field to use for the representation. The latter always uses the primary key for the representation.
I suppose it is possible to use Django without its ORM, but I feel like that kinda defeats one of Django's big selling points. If you don't need an ORM, then why not use a more lightweight framework that doesn't come with an ORM? Also, I believe Django's default authentication feature is tied to its ORM stuff, but not sure.
That’s a very valid point . I was using Flask before , I’m partly trying to expand my knowledge base across stuff and also was keen to see what results I could get with Django since people have said it’s more feature packed and less manual.
My main concern is even when using flask and sql alchemy I had to resort to raw sql to achieve some moderately complex queries , maybe due to lack of skill.
The authentication feature is a big deal for me so maybe I’ll just stick to django orm for now and see .
I suppose migrating later wouldn’t be too much hassle if I code myself into a corner
Do u think python is a good language for web-development?
there is no better place to ask this question than in python web development server!
Surely... with the heaviest concentration of all people, who almost often used only python to do that, you will receive answers only: Yes, YES and YEAH!
Haha right
Which one do y’all recommend I use between django and flask?
I’m trying to get into web development but not sure which one I should get in to
flask can be easier to get started, but django should be better for serious thing
start with flask ;b try django as a next framework after that, think what you like more, then choose between them
I also do have a book who guides a whole web developing using django
But I am guessing it’s not that advanced guide maybe a basic one
hey, how can i pass the value of {{ home_data.split("|")[3] }} into JS?
<scripts>
let your_thing = {{ home_data.split("|")[3] }}
</scripts>
its not always gonna be {{ home_data.split("|")[3] }}
transform it better being the same in your Python code before submittng it to template
keep it as a simple {{home_data}} variable
or transform it later in javascript, your choice
i cant, that is the only way iv managed to fix a previous problem
find the better way then for the logic of this variable
what if i put it in a div and give it an ID? does that work?
those are all means to reach goals. I have no idea what you are trying to reach, what is your goal.
and no idea what you have right now
ye probs shoulda said that before lol soz
so what i want to do is calculate what the user inputs in the field. I want to multiply the number after @ with the number inputted and display it in "potential winnings"
in real time
so whilst they are entering a numberpotential winningsis showing the amount inputted x the number on top
so im trying to get the number after the @ but since its in jinja idk how to pass it to JS
iv bearly worked with JS
{{ home_data.split("|")[3] }} {{ draw_data.split("|")[4] }} {{ away_data.split("|")[3] }} are all inside elif statements in html (jinja)
i want to pass their value to JS
to perform the calculations
JS! Add an on change event handler to dynamically update the text of the potential winnings tag.
Why is it that as soon as i enter the else if statement, i get an internal server error
var cost = document.getElementById("amount")
var potential_payout = document.getElementById("payout")
var odds;
var total = odds * cost
if ('{{ home_data.split("|")[3] }}' != null) {
odds = '{{ home_data.split("|")[3] }}'
alert(odds)
}
else if ('{{ draw_data.split("|")[4] }}' != null) {
odds = '{{ draw_data.split("|")[4] }}'
alert(odds)
}
else if ('{{ away_data.split("|")[3] }}' != null) {
odds = '{{ away_data.split("|")[3] }}'
alert(odds)
}
shouldnt it check through the if statements until one returns true
if i enter one if statement, it works, if i enter multiple it doesnt
Those will all return true?