#web-development
2 messages · Page 161 of 1
how to setup a favicon :)
Using raw HTML?
React is much more popular in the industry
Although I've heard that many people enjoyed Vue since it keeps JS and HTML separate a little more, which is more like Vanilla HTML/JS with a couple really nice touches
I've never touched Angular personally
I am making a flask website with use of bootstrap. When I click on options provided on nav bar, sometimes some options changes their end point to the file from which they are being rendered and give not found error.pls help
hey i want to know how should i start making websites should i learn html css or start with django and flask??
please please dm me with answers
HTML/CSS is definitely necessary, although if you decide to learn them all at once, I suppose that works
can i ask some general questions in this group , about web development
can anyone suggest a cousre for django, or should I go for flask, as i am a newbie
Hi, Like I am having a contact page which is connected to sqalchemy database using xampp, but my contact is not working I mean when user fills and submits, I am not getting a entry on my database, can anyone help me with this please. It's some kind of urgent
I am such a dope for asking this...
In SCSS, I can import a color file (@import 'whatever.js' which has export const Color ...) with my hexvalues and use $darkGray throughout the file. What's the equivalent for a CSS file when importing the colors?
Can't seem to find a way to use the variables from the color file in a basic css file.
I don't believe that's possible in CSS, it's something that the Sass team added
anyone here with Python experience who can help me out 😭 ? I got this beginner python/flask project (+html+css+js+MongoDB) due in 9 days, been stuck for 48 hours now trying to get this CRUD functionality to work (building a comment section), if I can't get it to work soon I'll never submit this project in time. 😓
Definitely!
Do you have some code to share? You could also grab one of the available help channels #❓|how-to-get-help
Got some code to share - the form and probably the model? Getting any exceptions raised?
check please, i need help
hi, im trying to build a chat with django channels or sockets
any one can help with it?
please contact me in private message
hey everyone, is there a way to clear the users session after a specific time and logout them / in order of inactivity or anything else
like I made a configuration on my app for myApp.config['PERMANENT_SESSION_LIFETIME '] = timedelta(seconds=10) but still not workin
and also made a session config session.permanent = True
flask
where are you setting session.permanent = True?
Someone on SO mentioned setting it after a user logs in
https://stackoverflow.com/a/49891626
thanks man
any body here done any minimal application with flask and postgresl which involves models and some migration stuff??
please send me any resources or github repo
You're not adding the correct object to db.session. You're adding an instance of the form, when you're probably wanting to add an instance of the model, I presume the Test model?
How do you dynamically create divs from a JSON file?
In what context are you trying to create these divs?
@fair shale
You can't have two returns in a function
Oh nvm mb
You should really use code markup for readability
yo
can someone tell me the line of code for inserting an image from a link in html? cuz I cant find it anywhere lol
print("Hello")```
So it looks like that
Nah it's
And the three at the end
You need three
In front and end
And you can add the lang
Etc
😂
It's back ticks
`
Copy it
Lolll
Np
Line 3, 4, 10, 102 maybe? Hard to say without the HTML
3,4,10,102? whats that
hey so im making a portfolio website and im trying to make it mobile responsive but am having issues.
This is what the page looks like when i inspect and put it into a mobile format, none of my changes (menu icon plus hidden slide nav bar) appear it just stays as the desktop version but terribly formatted. How would I implement responsiveness properly?
CSS for the mobile part
@media(max-width: 700px){
.text-box h1{
font-size: 40px;
}
nav img{
width: 100px;
padding-top: 10px;
}
.nav-links ul li{
display: block;
}
.nav-links{
position: absolute;
background: #f44336;
height: 100vh;
width: 200px;
top: 0;
right: -200px;
text-align: left;
z-index: 2;
transition: 0.75s;
}
nav .fas{
display: block;
color: #fff;
margin: 10px;
font-size: 22px;
cursor: pointer;
}
.nav-links ul{
padding: 30px;
}
}
any help would be appreciated, im not very experienced in web dev
what are the apps needed in gunicorn?
not sure if they're the same apps used in django
Its a standard WSGI server with the ability to run ASGI workers
so pretty much any WSGI or ASGI framework
you dont need to
but its a very popular server for that
other forms include uwsgi, meinhead etc...
oh sorry, let me rephrase my question
because there's an app parameter when running gunicorn
what should i put there?
its basically a string
in the form of
file_name:app_varible
e.g.
if you file was called foo.py
and your app variable was called app
it would be
"foo:app"
If i remember correctly
in django you want to target the wsgi file
hmm ok
ohh ok
but i still don't know what that app specifically is
you forgot the end parenthesis on that format
if I want a web server that exports an ASGI app, is there any reason to prefer gunicorn over uvicorn?
What do you mean by live server button?
the button to start the live server
na idk how to do tht sry
oh its fine
Is it not in the right click menu?
Ik what you should do
use one of the help channels
they will be able to help you better
lol should have done that first 🤣
😆
whats this for
Any best book or video of Django Rest framework
this is my repl
https://replit.com/@FrostyBoi1/YouTube-Video-Downloader
YouTube Video Downloader
A Python repl by FrostyBoi1
its a yt vid download
how do i make it better
and
deploy it on my website
I am absolute beginners in drf
and how do i make it work and adjust in all platforms
You made it
Why i can't take the form from HTML?
The Table from Postgres
{% for i in Statements %}
<tr>
<td id="type_">{{i.id}}</td>
<td id="name_">{{i.name_id}}</td>
<td id = "url"><a href = "/testword" class="button" target="_blank">
<button type="submit">Сформировать</button>
The form with input
<div class ='panel'>
<b><label for = 'date'> Дата начала:</label></b>
<form method="Post" action="/api/">
<p><input type="text" id = 'datebegun1' name="datebegun1"></p>
<p><input type="time" id = 'time1' name="time_begun"></p>
Python code
@app.route('/api/', methods=["Post", "Get"])
def testdate():
if request.method == "Post":
datebegun = request.form.get("datebegun1")
print(datebegun)
return datebegun
print(request.form)
def write(datebegun):
doc = DocxTemplate('../sv_site/app/static/storage/vacation.docx') #исходный файл
context = {'current_account': 'Name', 'id_account': (os.getlogin()), 'date_begun': datebegun,
'days': "14"} #тэги в ворде
doc.render(context)
path = '../sv_site/app/static/storage/vacation1111.docx'
doc.save(path)
return path
print('OK')
@app.route('/testword', methods=["Get"])
def test_word():
"""
:return:
"""
datebegun = request.form.get("datebegun1")
path = write(datebegun)
file = open(path, "rb")
return send_file(file, as_attachment=True, attachment_filename='File.docx')
print("ok")
I just tried to grab the value from the datebegun1 in html and put it to the docx file
But the file opening with None
I try to send the form datebegun1 to the button and put the value from the form to .docx file
What is the best way to advertise my website?
how to do migrations in flask
I want to do it from manage.py what code should be really included in that Im confused
You need to have a post method to '/testword'
yo guys im getting a error saying theres no such class for the find element by class name although there is a class by that name in the webpage can someone help,Thanks!!
error
For classes in html, any space between signifies different classes.
Example: class = "one two three" means this item belongs to 3 classes 'one', 'two' and 'three'
To make that a single class, try using underscores or hyphens between words without the spaces. Like class='action-primary-checkout'
Since you're making a request, use of the classes that the button belongs to
I tried the hyphon method but it still says Not found
Ok ill try this as an alternate and get back to you
Are you making a request to a page which isn't yours or did you make the html yourself
Its not mine
Alright. You can use one of the classes. However, note that you might get other elements which have the same class on it.
To avoid that, I would advise using another method instead of findbyclassname to get a unique element
Ok ill look into it and get back to you if im still not able to get it, thanks
You cant pass in multiple class names in that function, you could use xpath though el = browser.find_element_by_xpath("//*[@class='action primary checkout']")
THANK YOU SO SO MUCH..it worked 😁
THANK YOU TOO FOR TRYING TO HELP ME OUT
Very cool
Hey, what would be the best way to share data from a C program to a web page?
I have a C program doing stuff and i want to share a buffer of 1kB of data. And i'd like to draw rectangles on a webpages based on the data from the C program.
I'm currently using P5js to draw on the page.
To share the data I'm writing in a file with the C program and reading from it with loadBytes(). It works fine when i'm doing it once, but i'd like to do it every 100 ms or so. but when i try i'm not getting any data with the loadBytes() function, probably because the C file is already writing in it...
Is there any faster way to share those data ? UDP socket? other things i don't know?
Thanks.
Method Not Allowed
The method is not allowed for the requested URL.
That what i see
that means you don't have a POST handler
Python put ImmutableMultiDict([]) in the file
When i print(request.form), the python put the value of the form and in file its looks like that ImmutableMultiDict(['datebegun1', 123456])
ty ty
The testword endpoint should have a post method handler, the form should also have a post method and the form's endpoint (action) should be '/testword'
Thank you so much
everybody
its just my first project in python
i found my problem.
I have 2 <form>
Now,i had 2 form
/testword and /testdate i made the Post method
Is it working now?
Yes
It wasnt in the <form>
{% for i in Statements %}
<tr>
<td id="type_">{{i.id}}</td>
<td id="name_">{{i.name_id}}</td>
<td id = "url"><a href = "/testword" class="button" target="_blank">
<button type="submit">Сформировать</button>
Hi I am trying to do migrations in flask i.e, trying to add table users but not happening pls some one help
Sure. Anytime
hey, i have this code
async def get_json(url: str = 'https://discordpy.readthedocs.io/en/stable/'):
async with aiohttp.ClientSession() as session:
async with session.get(url) as req:
return await req.json(content_type='text/html')
but i keep getting this error
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
can someone please help
Why do you expect that url to return json?
(if I curl it it just returns html, like I expected)
idk i mean i looked at the docs for @lavish prism and found that !pypi uses json... i thought it would work
so is there anyway to convert it to json?
what would you even expect the output to look like?
havent ever worked with json before ¯_(ツ)_/¯
ah, okay. Json isn't some magic bullet, it's just a way of representing objects. If you have a document (website, api endpoint, config file, whatever) that uses json as its format, great! It's really easy to work with. If you don't, you can't trivially convert it to json.
(if you want an easy to work with endpoint to just mess around with, try https://httpbin.org, specifically https://httpbin.org/get)
wokie
Hey fastapi’s users, I have a few classes that I use in all my app, but I only want one instance of each for all my handlers (no need to create them again as there are things like database connection etc). Could I just use globals?
I’m not sure it’s the right pattern with fastapi as there is the dependency Injection pattern that is well established.
After doing some research people proposed a lot of different solutions but it just seems to be over engineered globals (lru_cache, global factory class…)
So in the end I think I’ll use globals, how do managed this?
How to make Flask scroll to a part of the page?
I did not find my answer thats why I copied the question
Hi guys
I am facing a problem in Django forms
This is what I need :
There is a ChoiceField with two choices.
If a user selects the first choice, one text field is shown
If seond choice is selected, two text fields are shown.
Can somebody help?
Make the fields hidden when you select the corresponding choice field call the textfield with it's label
Hello. Who can help me. I do not understand how to write a code in which each letter moves to the next. For example ABC - BCD. Thanks a lot in advance
ord('b')
98
''.join(list(map(lambda i: chr(ord(i)+1), input())))
На здоровье/bless you
can u provide me with some good resources for starting with django and flask?
which one do u think i shiud be going with, django or flask? Im a beginner in web development
i would be glad to receive suggestions
Helloo I am looking for a Discord server based around browser extensions/add-ons. Does anyone know any?
I use django. I hear flask is good for lighter stuff. If your OOP is decent by all means Django. If it's not and you still go with Django you'd have to learn as you go. I prefer books to courses. I'd suggest django 2 by example. That's what I started with. Adrian Holavary's "The django book" can be used as a supplementary material too. Follow the JustDjango channel on YouTube. Really good content. Remember to visit the docs. If you find a good material for flask you can tell me about it. I'd like to try my hands at that too. Cheers.
The above message is meant for you
Hello everyone. Please suggest projects a backend dev could work on to build his portfolio. I'm comfortable with django,drf, channels etc. I just never paid attention to building a good porfolio till now. Most of the things I've worked on don't belong to me so I can't really use them. Suggest projects that would impress you if you were tohire a junior developer. Thank you
How do i access a instance of a user in my javascript with django
The questoin is hard dm me plz
hello everyone is it possible to define a foreign key before django model ? like this :```py
class Model1(....):
test = models.Foringkey(Model2 .... )
class Model2(....):
...
in Django !!!
@app.route('/check')
def access_param():
key = request.args.get('key')
hwid = request.args.get('hwid')
discord = request.args.get('discord')
return "key:"+str(key)+"\nhwid: "+str(hwid)+"\ndiscord: "+str(discord)
database = cluster["test"]
collection = database["info"]
post = {"_id": 123, "Key": key, "DiscordId": discort}
dbi()
collection.insert_one(post)
im using flask and this wont add the stuff into the database, whats wrong, ive been trying for over 30 mins
hello good day, in creating a Django project, is it really necessary to create an virtual environment to a single Django Project?
or is it okay to have 1 virtual environment for multiple projects?
I would say yes, since you'll probably install quite a few dependencies
Like I will install the virtual environment to a root folder
oh okay
I was so confused cause the tutorials that I looked up to are different
Do I need to commit and push my virtual environment to my github repo?
Are you using a manager like poetry or pipenv?
uhm I'm sorry I could not get terms cause I am a beginner when it comes making Django projects 😅
well now my guide is the django docu
How are you installing your dependencies?
oh wait is this the requirements.txt ?
from werkzeug import generate_passord_hash, check_password_hash
when I use this it is showing me an error how can i fix this?
Hey there, trying to get started with django web hosting, i have a VPS with plesk obsidian and followed this tutorial: https://support.plesk.com/hc/en-us/articles/115002701209-How-to-install-Django-applications-in-Plesk-
now i made an index.py, but i get a 403 forbidden. I look in the logs and i see this: AH01276: Cannot serve directory /var/www/vhosts/tekx.it/tekxitdev/tekxitDev/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml,index.htm,index.shtml) found, and server-generated directory index forbidden by Options directive, referer: https://*******.ultrasrv.de:8443/
so apparently it's not looking for an index.py i assume? anyone has experience with this?
when i turned on ngix reverse proxy and changed the additional directives from apache to ngix ones
AH01276: Cannot serve directory /var/www/vhosts/tekx.it/tekxitdev/tekxitDev/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml,index.htm,index.shtml) found, and server-generated directory index forbidden by Options directive
i had those settings in the top boxes first with ngix reverse proxy disabled, then enabled reverse proxy and moved it down one as i read online
it's not in the default httpdocs since this is a subdomain (a development subdomain, the regular one works normally and is a standard html (and a bit of php/JS) site
def access_param():
key = request.args.get('key')
hwid = request.args.get('hwid')
discord = request.args.get('discord')
#return "Key:" + str(key) + "\nHwid: " + str(hwid) + "\ndiscord: " + str(discord)
database = cluster["RegisterableKeys"]
collection = database["UsedKeys"]
penis = collection.find_one({"DiscordId": discord})
sorted_string = json.dumps(penis, indent=4, sort_keys=True)
return sorted_string
it returns null, idk y
If you need a more precise file structure
*****
httpdocs
-(working apache html/php page)
****
tekxitdev
-python-app-venv
--(venv stuff)
-tekxitDev
--manage.py
--tekxitDev
---__init__.py
---asgi.py
---index.py
---settings.py
---urls.py
---wsgi.py
-tmp
--restart.txt
-passenger-wsgi.py
the passenger_wsgi.py
import sys, os
ApplicationDirectory = 'tekxitDev'
ApplicationName = 'tekxitDev'
VirtualEnvDirectory = 'python-app-venv'
VirtualEnv = os.path.join(os.getcwd(), VirtualEnvDirectory, 'bin', 'python')
if sys.executable != VirtualEnv: os.execl(VirtualEnv, VirtualEnv, *sys.argv)
sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory))
sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory, ApplicationName))
sys.path.insert(0, os.path.join(os.getcwd(), VirtualEnvDirectory, 'bin'))
os.chdir(os.path.join(os.getcwd(), ApplicationDirectory))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', ApplicationName + '.settings')
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
i got a new error now: changed these settings
no longer proxy mode and those boxes are filled in different
24487#0: *235 connect() to unix:/tmp/passenger.jRn0OxH/agents.s/core failed (111: Connection refused) while connecting to upstream
nvm that error log in invalid, this is the only thing that appears
ImportError: cannot import name 'CarsModel' from partially initialized module 'flaskapi' (most likely due to a circular import) (H:\crossplatfrom_flutter\flask_api\f laskapi.py)
how to resolve this error
pls some one help me
it indicates most likely circular import
so you have 2 or more files importing eachother in a circular fashion
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_restful import Api
from index import HelloWorld
app = Flask(__name__)
api = Api(app)
api.add_resource(HelloWorld, '/')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://postgres:1234@localhost/flask"
app.debug = True
db = SQLAlchemy(app)
migrate = Migrate(app, db)
class CarsModel(db.Model):
__tablename__ = 'cars'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String())
model = db.Column(db.String())
doors = db.Column(db.Integer())
def __init__(self, name, model, doors):
self.name = name
self.model = model
self.doors = doors
def __repr__(self):
return f"<Car {self.name}>"
from flaskapi import CarsModel
from flask import request, json
from flaskapi import db
class HelloWorld(Resource):
def get(self):
cars = CarsModel.query.all()
cars = cars.dump(cars).data
return {"status": "success","data":cars}, 200
def post(self):
json_data = request.get_json(force=True)
if not json_data:
return {'message': 'No input data provided'}, 400
data, errors = json.load(json_data)
if errors:
return errors, 422
user = CarsModel.query.filter_by(name=data['name']).first()
if user :
return {'message': 'User already exists'}, 400
cars = CarsModel(name = json_data['name'],
id = json_data['id'],
model = json_data['model'],)
db.session.add(cars)
db.session.commit()
result = CarsModel.dump(cars).data
return {"status": 'success', 'data': result}, 201```
these are the two files
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
!code
but i see it already i think
in the flaskapi.py you import from index import HelloWorld
if you look at index.py you import from flaskapi import CarsModel and from flaskapi import db
so you see these 2 files are importing each other in a circular fashion
and that's the error
you following me?
so what should i remove
not have a circular import
i get u r point
so you will need to rework your code so that 2 parts of your code are depending on one another in a circle
so flaskapi has a class which depends on the class helloworld from index, but that helloworldclass depends on the carsmodel class in flaskapi
can't have it 2 ways like that
and looking at it, in flaskapi the import index is unused, so you can just remove it
and that will probably make it work
okay
from index import HelloWorld app = Flask(__name__) api = Api(app) api.add_resource(HelloWorld, '/')
I am using it
ah whoops missed it
I want to access helloworld as resource how to do that
i'm not familiar with flask in any way so i cannot help beyond this sadly
okay
so i think it worked :p
apparently the passenger_wsgi.py needed a chown to ngix
hi, are there any Jinja2 config experts around?
People wouldn’t know until you actually ask those questions.
With gunicorn it's adviced to use nginx or something similar. Is that only because of the thundring herd / buffering problem or are there more benefits of using nginx as a reverse proxy ?
I need to change the {{ }} to another pair. I have a solution that works for Flask, but I need a general approch that will work in FastAPI.
I am trying to get my page to show "Hello World" when I run the code there is no error but it also doesn't show hello world only the default beginning rocket animation, here is the code
main.urls code:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
]
main.views code:
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(response):
return HttpResponse("<h1>Hello World!</h1>")
And mysite.urls code:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("main.urls")),
]
please ping if you have come up with a solution 🙂
Can you look at a website and guess what types of architecture they used?
No. You can only assume.
not in the general case
Try def index(request) instead of response
ok
yeah that didn't work either
restart the server?
wdym?
alr
nope
that didn't work either
@cyan lotus anymore recommendations?
I followed the video two times, two different folders and line for line
I'm just at a loss
I'd try this next path('index/', include("main.urls")), and the go to http://127.0.0.1:8000/index
damn
his django isn't recognizing his app I suggest setting up a new virtual enviroment and recreating the app
Hello, I am begineer just looking for a lot of fun in web development, i am unsure which framework to do, FLASK / DJANGO
flask for learning, django for working
I'm following a Django tutorial, and I am busy copying three basic models from the tutorial. My Profile class:
class Profile(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.PROTECT
)
website = models.URLField(blank=True)
bio = models.CharField(max_length=240, blank=True)
Then in my Post model, I have this line:
author = models.ForeignKey(Profile, on_delete=models.PROTECT)
How does this foreign key magic work? I would have thought that for an FK, I must specify a name for the foreign property.
what do you mean "foreign property"?
I mean the property in the other class that that is the foreign key field that links to the property marked as type ForeignKey. E.g. what property links my author property to the Profile class.
ah
by default it'll be {model.__name__}_set
oh wait hold up
yeah so a Profile will have a post_set
because it's one (profile) to many (posts)
this is done for you by Django
through metaclasses (I think)
Ah, dark voodoo indeed 😆 . Thanks
SQLAlchemy doesn't do this for you, I believe
but Django was really made more for people who weren't programmers first, IIRC
yw! 👋
lastly
you can change this with the related_name kwarg in your ForeignKey
Aah, more sense now. Cool beans
thank u soo much
I'm using Linux on AWS Lightsail to host my django project with Apache. I connect using SSH. I cannot seem to get the db to work without setting permissions to 777, I see that it's not recommended as any user can write to the file. But, if somebody manages to connect to my server as a user, I am not screwed anyway? Am I correct to think that I am protected by SSH anyway and setting permission 777 doesn't matter as I'm the only user?
whilst i just started with django, i also noticed issues with write permissions for the db.sqlite3. I quickly switched over to postgres since i already had it installed. If it's an in development website/not public permission 777 would work fine, but if you go production definitely avoid this
there's built in protection still but you're removing one layer of protection
Okay thanks!
How dk I make my website mobile responsiveness
Like what is the ideal width, that indicates it's a tablet or phone
I usually set @media queries for around 600px, 900px, and 1200px
And sometimes a larger one
whats the point of media queries when flexbox and grid exist?
Are there any screen bigger than 1200px?
Yes, widescreens can be bigger
There should be a way to move an element 70% of the width
That way it would be consistent
width: 70%; exists, which would make it take 70% of the parent
I'll set the parent to 100%
Say you have 8 columns of your site on desktop, which would look ugly on mobile. You could use media queries to make it only have 2 on mobile or something like that.
but why do you need media for that, flexbox and grid will already do that
I want to place a graph consistent in all platforms
That's for width I meant left positioning
Sorry
@media queries are another way to do that, since you might not always want to flex things, or stick them in grids
o. is there a reason why you wouldn't want to flex or grid? in my very new to frontend experience i was feeling like media queries were the way like 10 years ago and now you just flex and grid
What do you mean by left positioning? Like, on a certain part of the page?
Move the position 70% of the parent, moving the element
With position relative
I'm playing with inspect and if I move my screen width to more rbag 1600 my graph doesn't seem all that left it would feel centered
For example, my site is built on grid columns. But like I said earlier, I want flexible columns, so using media queries, I can choose how many columns, width of columns, etc. based on the size of a person's screen
like fully removing the columns on a smaller screen, or just moving them below the other columns so like 1 2 3 4
Posting element
So like,transform: translateX(70%);, which would make the element start on 70% of the parent element
cause isnt that the point of like this with css grid : https://codepen.io/eclairereese/full/JZPZWo
I'm changing the content of the columns as well
For example, take a look at stripe.com. They have grid columns in the background, and if you change the size of your browser window, you can see the number of columns that you see in the background get smaller as it gets smaller
Ty, should it be relative or absolute?
Uh, relative probably
Here's a gif showing how the columns on that site adjust based on width
Wdym main difference?
right they used a flex box for that
No, they used grid if you look at inspect element
Do you see those column dividers in the background?
Those were generating using css grid
Like what does absolute actually mean
No, the @media queries are choosing the number of columns
Yes, flex is choosing the column width
But media queries are choosing the actual column count
but why? given that grid can just... do that already itself ^
your site changing the content of the column i understand i guess, but not this
Do you see how that can be 6/2 5/3
oh, so media queries can keep it uniform but grid by itself cannot
theres no way to tell grid that if it has to wrap, to fill both rows evenly?
Uhhhhh, no idea
sry u kinda got lost in the talk of dawn and i. absolute is going to take it out of the flow of the page
heres an example https://www.digitalocean.com/community/tutorials/css-practical-guide-position-relative-absolute
see the orange box difference from relative, in the flow with all the others, to absolute, takes it out of the flow and throws it in the top left
Np
my understanding is you generally want to not use it unless you absolutely have to since it makes for hard debugging, but dont trust me im as new as you are haha
Never use selenium unless you are testing your own site. If you really need the js to run use requests-html or something that can render it
But you generally don't need the js to run, more rather you are doing the wrong thing
Cant help with ytdl that's against tos
Not at all
It's like a tank compared to a pistol. Do they both shoot things? Sure. What do you want to use in your backyard for hitting a pop can
And you still don't need that js to run 9/10 times
What's the js doing?
lol... At least have a specific instance in mind before trying to argue you need the js to run
None of that requires js to run on your end
Just make the same final login request that the js put together and called
Rendering a video? Where's it rendering from? Make the same request
You need to hang out more in your network tab
Learn what the site is doing under the hood
Yes
Wow your logged in
Without the sites js running to build a form. Without even loading the login page at all.
Wouldn't be parameters that's the = stuff inside of a url
But yeah you send the login as a post
Tank vs gun example
Selenium for instance comes with support for like 5 different browsers and a shit ton of other crap
Puppeteer (what's under the hood of requestshtml) does not
That's why it's way lighter and better
Takes 1/3 of the time plus faster to code
But again, you generally don't need to render the js your doing something wrong 9/10 times
I mean, I hate bs4 personally. I'd just use requests html. It's a fork of the normal requests by the same core dev with bs4esque commands added in
But if you use requests or urllib bs4 is needed to parse
Most people seem to prefer using the bs4 way but I wonder if that's just memes being spread around like selenium usage
Idk
Maybe you prefer one way over the other
Maybe bs4 is a millisecond faster
Idk
👍
how can i solve it
https://github.com/akhileshkoti/Implementing-Graphical-Passwords-to-prevent-Shoulder-Surfing for more info
hey there! i've never worked on server side dev in python, but i have used nodejs before, i'm debating between django and flask, which one is easier to pick up?
Flask is easier to start off with since it's a microframework
ah i see, coming from an express.js background, which one is easier to get started if i want to use the MVC architechture?
Wait a second.
If I have data stored in memory of application running with Gunicorn...
...and during interaction with one of workers I stored in memory some changed state...
does it mean that it got recorded only into memory of ONE of workers?
All other workers will have their memory clean from this record?
uhuh. So if I'll have situation like that I need to organize a way for a shared memory across workers.
Hi!
Anyone experienced with Flask and fcgi?
I have an issue that when I run the code via the fcgi file in the server then none of the paths are found unless they are defined in the fcgi file directly.
On my local, I don't have fcgi file but a regular run.py that basically just creates the app.
What extra config do I miss to get the blueprint routes to the server instance?
I have a question about python web developement
lets say i have a website, and there is a button there
on the button press, can python code be executed?
yup
I say django for MVS architecture
it's not really that hard
There's a great introductory video by freecodecamp on yt
yep. I have a pretty good idea for how it'd look in django views if you want
it's a framework
What does it do?
ohhh
so you can add the entire site logic
it's a VERY good framework in my opinion
like how the website looks
it has a surprisingly great amount of front-end related functionality to offer
but it's not a frontend framework. It works well withother front-end frameworks like reactjs, angular, etc
!code
If to oversimplify
Framework is a bunch of libraries, tuned to work together very well. They take care of all the most common things developer needs in order to build web app
I think you're looking for print in python 
can someone quickly dumb down how python can be used to do some stuff in another app/website, thanks
backend
what are api's and how do they work?
cant really be used to do frontend work (although it can do server sided rendering of HTML with things like jinja2)
Backend wise they can act as the content server rendering content like the aforementioned point on frontend, it can be used as REST api / other API backends. Just what ever really
APIs are just a general term used for on thing communicating with another thing really
Want to learn how to build your first API in less than 10 mins? Click here to get started:
https://developer.mulesoft.com/tutorials-and-howtos/getting-started/hello-mule
Checkout the MuleSoft Platform here: https://www.mulesoft.com/platform/api
The textbook definition goes something like this:
“An application programming interface (API) is ...
and how restrictive are they / how much can you do/control?
thanks!
litterally anything
Does anybody have experience with multi-part forms in aiohttp? i think i get the server side stuff but i cant understand client side for the life of me
how can i make an image circluar in css? or that not possible
border-radius: 9999px
what if my screen is very large?
depends
in the simplest case (square image), border-radius: 50%
otherwise, specify height/width (along with object-fit
well its squar lol
so i could do that
Besides print
from pprint import pprint
pprint(yourdata) is nice too. It has auto formatting, identations for easier reading
Everytime I make some small changes in CSS and reload the website, the flask server doesn't load the new CSS file
is there any solution to this?
I tried disabling caching by changing headers as suggested in a SO answer, but that doesn't seem to be working
@app.after_request def add_header(r): r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" r.headers["Pragma"] = "no-cache" r.headers["Expires"] = "0" r.headers['Cache-Control'] = 'public, max-age=0' return r
anyone here working with wolframalpha api?
is this the right channel for api though 😅
Hello.
I have been struggling with this issue for a long time now and I can't find answers online.
I'm trying to deploy a Flask app to an Apache server, with fcgi.
The file that runs the app, dispatch.fcgi, is below.
The issue is that when deployed, it can only find the routes that are @spare ridge.route in the same file.
It does not find any of my blueprints or blueprint routes. Nor can I create blueprint routes in this file after creating the app.
The application works on my local. Only difference is that instead of this file I run a run.py which just creates the app without extra config that Apache wants.
How can I get it to find my blueprint routes?
PS: It's a shared host, therefore I don't have root access so the fix I'm looking for should probably be on py side.
#!/usr/bin/env python3.7
import os, sys
sys.path.insert(0, "/www/apache/domains/www.somedomain.com/hinnang/hinnangapp")
from hinnangapp import create_app
os.environ['REQUEST_METHOD'] = "GET"
os.environ['SERVER_NAME'] = "somedomain.com"
os.environ['SERVER_PORT'] = "80"
os.environ['SERVER_PROTOCOL'] = "HTTP/1.1"
DOMAIN = "somedomain.com"
PREFIX = "/www/apache/domains/www.somedomain.com/"
sys.path.insert(0, os.path.join(PREFIX, ".virtualenvs/hinnangapp/lib/python3.7/site-packages/"))
from flup.server.fcgi import WSGIServer
from flask import Flask
app = create_app()
@app.route("/")
def hello(): #<- this works
return "Hello World! <a href=\"test/\">to test</a>"
class ScriptNameStripper(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
environ['SCRIPT_NAME'] = ''
return self.app(environ, start_response)
app = ScriptNameStripper(app)
#@main.route("/home") #<- tried to create a route for a blueprint here, didn't work
#def home():
# return "home"
if __name__ == '__main__':
WSGIServer(app).run()
class InboxDetailView(LoginRequiredMixin, FormMixin, DetailView):
model = Contact
template_name = 'dashboard/inbox_detail.html'
form_class = ContactForm
def get_success_url(self):
return reverse('Inbox_Detail', kwargs={'pk': self.object.id})
def get_context_data(self, **kwargs):
context = super(InboxDetailView, self).get_context_data(**kwargs)
context['form'] = ContactForm
return context
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
form.save()
return super(InboxDetailView, self).form_valid(form)
Hello can someone please help me how to make the form save to the current model form because it saves into different model
did you register the blueprints to your app?
@thorn igloo Yes, in init.py in the create_app function it does this
from hinnangapp.users.routes import users
from hinnangapp.companies.routes import companies
from hinnangapp.main.routes import main
app.register_blueprint(users)
app.register_blueprint(companies)
app.register_blueprint(main)
And also, it does work when running locally in pycharm, so that's what makes it difficult
class InboxDetailView(LoginRequiredMixin, FormMixin, DetailView):
model = Contact
template_name = 'dashboard/inbox_detail.html'
form_class = ContactForm
def form_valid(self, form):
post = Contact.objects.all()
myform = form.save(commit=False)
myform.post = post
form.save()
return super(InboxDetailView, self).form_valid(form)
Can someone help please here im trying to save a form field to a model
Forms.py
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
fields = ['reply']
so i want reply field be saved into model form
class Contact(models.Model):
name = models.CharField(max_length=12)
email = models.EmailField()
subject = models.CharField(max_length=12)
message = models.TextField()
reply = RichTextField(null=True)
created= models.DateTimeField(default=timezone.now)
def __str__(self):
return f'{self.name}'
First, you may want to have a look at https://docs.djangoproject.com/en/3.1/topics/class-based-views/mixins/ where you find a bit about mixing Detail View and FormMixin and why better not to do so.
It's working what im talking about that it saves the form to a new model with no fields what i wanted it to do to save it to the current model
not working
it creates this
but it dont save it to the same model
oh self.object returns the model name so thats cool is there a way to check like Contact.objects.get(name = self.object) then i say Contact.objects.create
cant explain it but let me try
Hi, does anyone know if its possible to call a js function from flask?
reply = Contact.objects.get(name=self.object)
reply.save()
@native tide mind if u help im stuck here ik it doesnt have save function but cant type it in code like i want to add the form to it
oh so self.object refers to the model so how to add the form field to the self object cause self.object.reply returns none
ooh waait let me try
ooh i solved it thank you
Try putting self.object.save() in form_valid instead form.save()
def form_valid(self, form):
self.object.reply = form
self.object.save()
return super(InboxDetailView, self).form_valid(form)
That helped me
but why it's showing me like this
Reply: <tr><th><label for="id_reply">Reply:</label></th><td><div class="django-ckeditor-widget" data-field-id="id_reply" style="display: inline-block;"> <textarea cols="40" id="id_reply" name="reply" rows="10" required data-processed="0" data-config="{"skin": "moono-lisa", "toolbar_Basic": [["Source", "-", "Bold", "Italic"]], "toolbar_Full": [["Styles", "Format", "Bold", "Italic", "Underline", "Strike", "SpellChecker", "Undo", "Redo"], ["Link", "Unlink", "Anchor"], ["Image", "Flash", "Table", "HorizontalRule"], ["TextColor", "BGColor"], ["Smiley", "SpecialChar"], ["Source"]], "toolbar": "Full", "height": 291, "width": 835, "filebrowserWindowWidth": 940, "filebrowserWindowHeight": 725, "language": "en"}" data-external-plugin-resources="[]" data-id="id_reply" data-type="ckeditortype"><p>Reply 2</p> </textarea> </div></td></tr>
(Little and unrelated: super doesn't need those arguments, they are not recommended, super() is enough)
I tried |safe but it didnt fix it
oh ok
Ok, let me have a look at this
Oh, ok
So, does it work?
yeea it did it refered the self.object.reply to the form and it saved it to the model now i have another simpler problem that html tags are like this
Im using Ckeditor and i read documents it says add |safe but it didnt help
let me look again
I'm trying to make a Parallax website demo using Html and CSS but the parallax effect is not working. 😕
Can somebody help?
Actually I want to provide a functionality like a user can able to update details
no
Means He would be able to make changes in profile
In django how can I do that ?? Anyone knoww ?
U can use Update View for your profile
Actually very new at django
oh let me send u a video that explain it very well
And I really need to provide functionality because working on a proj
which is assigned by a college
He is using normal views ??
what type of views u want class views or function views
there are two types of views u can use in django
I personally prefer class views for profile
Function views Because I am new to django and Don't know about class based views I tried once using class based views but it is facing errors
Can I share my proj with you
So that you can better understand
class views are very easy to use you just need a tutorial to learn from but let me send u someone used function views for profile
OK
I believe that might help
But I still recommend class views for this
Brown is absolutely right about class based generic views. No need to invent a wheel again. And those views are very easy. https://docs.djangoproject.com/en/3.2/ref/class-based-views/generic-editing/
@twin hamlet U can watch corey schafer trust me everyone love this man
ok
@late gale Thanks Bro
Please if somebody could help?
anytime
share ur code
I'm making a sort of social media app with Flask, and when people post, I want it so if they put HTML in their post it's displayed raw. The post code is injected as a variable with Jinja, like {{ postcode|safe }}.
Like, they post:
<h1>Hello</h1>
The post would show up as:
<h1>Hello</h1>
However, I also want to support injecting HTML (like in their post, \n would be replaced with <br>. So far, however, it's seemed to be either one or the other. How can I pull this off?
You really shouldn't be allowing users to do that on your site. That's a bigggg security issue. Instead, you should allow markdown or a variant of it.
For instance. I could add a script tag to the site and do some pretty big damage.
can someone please help me I added |safe but it shows me like this here's the code
{% if object.reply %}
<div>
{{ object.reply|safe}}
</div>
...
<p>Hey Thank you for your contact</p> on the web site there
Im using ckeditor this reply is RichTextField
anyone ??
it's just a simple problem idk why it occurs
Hi, does anyone know if its possible to call a js function from flask?
Try this
I wish i can help u myself but im not a flask dev
Tried this but in my case it was too slow and the function had to be called constantly
Thanks for the help tho
Oh I fixed my issue thanks
Can someone please help me here
def form_valid(self, form):
self.object.reply = form.cleaned_data['reply']
self.object.save()
email = Contact.objects.get(email=self.object.email)
print(email)
subject = "Replied"
message = render_to_string('dashboard/reply_email.html', {
'reply' : self.object.reply ,})
sendingEmail = EmailMessage(subject, message ,to=[email])
sendingEmail.content_subtype = 'html'
sendingEmail.send()
return super(InboxDetailView, self).form_valid(form)
https://cdn.discordapp.com/attachments/794983442822725653/850792048243507200/unknown.png does somebody know why do i get 2 entries for each endpoint with drf-yasg?
hey all, if I had to create two tables for sqlalchemy like : user and emojis should I use one to many relationship? like one particular emoji could have X users and every user could have just only own one specific emoji , like a smile emoji you can have only one of it, actually any answer would be great and also if you know some good explanation when to use one-to-one, many-to-many , thank you in advance
fixed my issue thanks
I don’t want people to be able to use HTML. I want them to eventually be able to use markdown
I want them to be able to share html code, but it doesn’t run or anything
How do I make my asyncio server work with both https and http, or redirect http to https?
nvm. I can start a separate server and have that one redirect
hey guys how can i set the port for my heroku application? or this isnt necessary?
im have a local project that works fine but when i deploy i get application error
and a lot of forums said that maybe my process.env.PORT variable is wrong
but i never heard of the term
@leaden carbon did you look into the logs of heroku? they're pretty accurate about the error and then it's mostly obvious what's missing/wrong. And the process.env.PORT variable is just the variable for the port you want to serve it, in debug usually 8000 but I never set it.
Is django the best way to do the back end of a website?
im p new to this stuff
and ill be working on my first website project with a friend
so im wanting to do the back end
looking for something thats a bit more beginner friendly
someone told me they recc flask though
so not really sure what the best route is
djangos good. They are both really great its just comes down to whats the website going to be?
so im making a website for my uni club
and within that site
i wanna incorporate a section that allows students to look up previous syllabi
for math courses offered by my uni
and i have the website that allows you to search up previous syllabi
so im not sure if i would have to like download every syllabi one by one
if there is an easier way to do it
without doing all of the grunt work of downloading and uploading the file one by one
sounds cool both will work for you but i guess django will already have the ORM built in
what is ORM?
so yeah object relation mapping* for your db
design choice
i would say it depends what format they are in and whats the functionality you want form it
i have a feeling im going to have to download each syllabus one by one
that will be a bit harsh but its doable
okay thanks so much ill prob end up using django
you can write a script that scrapes them
hmm asked a friend he told me selenium might be able to do the job for me
yeah i like requests and beautiful soup both are great
i have my own question i have a site where you can upload large files 30MB wondering what my options are with that. Where should I hold them? i cant save it user side and i would be worried keeping it in memory. I was thinking a bucket and then just deleting them after the session ends any other ideas?
Using AWS? Throw them in s3 bucket, set a lifecycle rule to autoexpire them after 1 day. Unless you want them dead sooner than that. At least this way you don't have to code around it, you can just let the lifecycle rule do that work for you.
hey can someone explain why this is not working
<script>
function display(){
var x = document.getElementById("hello");
var y = x.getElementsByTagName("ul").getElementsByTagName("li").getElementsByTagName("a");
y.style.color = "red";
if (x.style.display == "none"){
x.style.display = "block";
} else{
x.style.display = "none";
}
}
</script>
<button onclick="display()">Press</button>
<div class="test" id="hello" style="display: none;">
<ul>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
</ul>
</div>
after I add the 4th and 5th line the onclick function does not work
but before I do it works perfectly
hey anyone's up?
getElementsByTagName returns an HTMLCollection object. HTMLCollection objects do not have the method getElementsByTagName. If you look at the console on your browser, you should see this error as well. You could simplify that whole process with something like this:
document.querySelectorAll('#hello > ul > li > a').forEach(a_elem => a_elem.style.color = red)
To toggle the style, you could use a ternary 😉
x.style.display = x.style.display === "none" ? "block" : "none"
A quick final note, if you think the functionality behind this styling or certain elements of this styling are going to be applied elsewhere, you might as well write some CSS, and then with your JS, modify the class on the element.
For instance with the hiding business, you could have a class hidden where display: none. Then you can do the toggling for #hello like this x.classList.toggle('hidden') and it'll handle the toggling for you.
I want to implement multiple user types of user authentication with different login and signup pages with django allauth can you explain any strategy to do THIS.
One question :
Django or flask which is better?
Django, flask and other python web frameworks have their own usecases
StackOverflow reports that Python is currently at the height of popularity. It’s simple, versatile and a fit for the purpose in areas like web development, data science, DevOps, and more. Python is a choice of many companies, including Netflix, Instagram, and Dropbox among others. Those are highly loaded sites that process millions of user reque...
First of all ask yourself why you wanna use python for building a project and why not Nodejs or Ruby. Once you are satisfied with your answer, ask yourself what you wanna build using that language. Django, pyramid and other frameworks/libraries all have some specific scenarios they excel in.
You can do everything in one framework that can be done in the other. Whatever you choose, focus on learning the concepts.
Django is good.
Yeah it’s fun
I’m finally starting on my app
Spent the whole doy figuring out environments
Using pipenv command and finding out all the stuff I can do with it
Making new directories
Yeah sure, just ask it
Guys, is there a telegram chat for python web dev?
I would like to post random memes to random people, have noone to share with ):
how can I do so that I don't have to go to the flask website every time?
@app.route('/login', methods=['GET'])
def login():
return redirect(Oauth.LOGIN_URI)
@app.route('/dashboard', methods=['GET'])
def dashboard():
code = request.args.get('code')
access_token = DiscordOauth.get_access_token(code)
user_object = DiscordOauth.get_user_raw(access_token)
username, _id = user_object.get('username'), user_object.get('id')
return f'User: {username}, User-id: {_id}'
ofc
U've to choose either flask or django both are powerful backend technologies for python
I personally recommend to try them both and choose your comfort
https://codepen.io/Chadezi/pen/XWMqogw 4 images i want to fit in page 2 but i am having difficulty can anyone help me? (html and css only)
There are big companies use Flask such as Netflix and Samsung Also there are big companies use Django such as Instagram ,Youtube and Spotify
and I still recommend to try both , they are very close to each other
are u web dev beginner ?
do you know html css js
and what python level do you have
no worries what about web technology ( html css and js)
they are necessary for any web dev
They called frontend technology which means anything u see ( Texts , buttons , images , animations )
if u don't learn those , how you will display your site
to the user
Also
Don't panic , they are easy
Except javascript it's more challenging
Backend technology is completely the opposite it's mostly about database , security , tests and its not easy as frontend
you want to learn backend without html and css ? then how will you build ur website
U need both
but i will provide some links for html css and js and also backend
though i said there are two backend frameworks django and flask but since you are beginner i will recommend flask , its easier
those two links are frontend
now i gonna send u flask
that all u need
what's ur issue
elaborate please
should i go for php or python for webdev?
whats the best way to integrate react with flask
oh u mean u dont want images to get stick to each others like u have
this is a python server so ^^ but I recommend to choose your comfort
How to setup a react/flask project.
I have decided to put all my tutorials in my channel
"Code With Joran" https://www.youtube.com/channel/UCom-uJL0CkFhGpmM2yutTGw
please follow that channel if you are interested in my coding tutorials
i see
i saw another method online that just uses flask as an api to query database and such
is this similar to that or different?
hey guys anyone good at react?
@tulip beacon yes what's the Q
I am having an issue with Flask. I am on #help-burrito
That is fairly hard to answer since it depends on what you want to do. Also, React is JS, this is a Python server 🙏
You are asking about React, this is a Dicord server for Python, not JavaScript. React is in JavaScript. Hope that helps.
yes
from my experience, let the frontend convert it, in general it can be advantageous to keep backends fairly agnostic
anyone has experience with Twitch API v5?
does anybody know why a decorator on my APIView is giving me the following error?
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a <class 'NoneType'>
class GetEquityStats(APIView):
@valid_equity_required
def get(self, request, equity):
return Response(data="success", status=status.HTTP_200_OK)```
the decorator works, it does not throw any errors and is used in other places in the code.
wondering how you guys use decorators for class-based API views?
Can you get circular imports if you use blueprints in flask?
show the code of the decorator
in the mean time my question, can I check in django which app names for startapp command are forbidden?
I think I will have possible issue with translator app name
the decorator works:
def valid_equity_required(func):
""" Decorator for ensuring passed equities are valid. """
def wrapper(*args, equity, **kwargs):
if equity_is_valid(equity=equity):
func(*args, equity=equity, **kwargs)
else:
raise InvalidEquity("The equity is invalid.")
return wrapper
also, why would certain app names be forbidden?
it breaks django imports.
https://docs.djangoproject.com/en/3.2/intro/tutorial01/
for example name test is not advised, or django
I had experience with translator app I think broke my imports too
it conflicts with already existing django libraries
they aren't written in a perfect way to avoid collisions
ah true, that makes sense
say you were importing something from your app django, it may be confused with the actual package
return func(*args, **kwargs)
where is return 😉
raise InvalidEquity("The equity is invalid.")
not sure if is good way to handle error. I usually cover it with another Response object which has error inside
do I need to return the function?
yes.
also recommending to get functools.wraps
True. I use this util decorator in lots of places which isn't in the views (which is why it's like that)
import functools
def my_decorator(func):
@functools.wraps(func)
def wrapper_repeat(*args, **kwargs):
# my staff
return func(*args, **kwargs)
return wrapper_repeat
add decorator @functools, it will transfer meta information
from decorated function to its wrapping
it makes more reliable working in django
I learned a while ago that using static methods can be used as decorators
any method that returns a method is a decorator
I see. I'll do that, what really is the use of transferring metadata? Will I really benefit from having the docstrings transferring through my functions?
yeah, I learned it yesterday.
Head First book, to learn Pattern Programming is awesome.
I mean it transfers data like __doc__, your dunder things basically
I needed it in order for my Sphinx generator to get info properly
or in some other cases also
Oh that's a good point
there are sometimes other things you function has
Thanks! I appreciate the help. I was dead set that my decorator was working too, that's what coding at 6AM does!
__call__, __iter__ and etc. there are many things, you never know for sure when it will break without them 😉
u a welcome
tbh, I've never even seen __call__ or __iter__. I'll give em a read
@staticmethod
def do_stuff(dec_func):
def some_action(*args, **kwargs):
return dec_func(*args, **kwargs)
some_action.__name__ = dec_func.__name__
return some_action
@inland oak I haven't read that book.
erm. There are too many of them. Better to have some full course meal about it....
I am at the moment reading through all of it in the awesome book clean code in Python
https://www.amazon.com/Clean-Code-Python-Refactor-legacy/dp/1788835832
quite awesome reading
Amazon.com: Clean Code in Python: Refactor your legacy code base (9781788835831): Anaya, Mariano: Books
thanks! i'll write that down
Hey guys.
Django newbie here . How do I pass data from html file to my python script?
Please help!
there are ways to do it in a raw way
but in your case I would get yourself familiar for starters with https://docs.djangoproject.com/en/3.2/intro/tutorial04/
hey guys
my webapp has a scroll bar at the bottom which is moving the entire webapp, what should I do?
I would check out the JS or React Discord channel if you have a react question
JS: https://discord.gg/BebYk3Pa
React: https://discord.gg/jrJwQ5nW
React server looks great.
but SpeakJS looks a bit weird one. They forbid advertising other discord servers. Not very open of them.
def detail(request, question_id):
try:
n1=Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request,'app1/detail.html',{'n1':n1})``` my try expect is correct ig then too when i go to localhost i doesnt show this error it shows that default error
can someone help me here?
Is sharing own stackoverflow question to seek help allowed here?
Its related to django
may as well just copy and paste it
I'm also working with django, out of interest do you know whats the advantage of running django from the commandline, when you can run it from within pycharm
like what's the deal with running a virtualenv from the commandline? I don't understand sorry I'm new
to this
Can you please have a look at it? or should I open a help-channel?
those two are different questions.
virtualenv should be always used for python projects
probably even your pycharm has it inbuilt by defeault.
it makes sure to store dependency for your projects locally, which you can unload into requirements.txt for easy reinstall on another PC.
storing dependency in global pip is really bad.
running django from the commandlike has advantage of really lazy/easy approach
since it is not requiring to configure your IDE.
if you can configure your IDE, it is usually better and more coomfortable way, because it enables for you additional features, like visual debug and + million of plugins.
'probably even your pycharm has it inbuilt by defeault.' - Yes.. PyCharm creates a virtual environment for new projects by default.
yeah I believe pycharm has the virtualenvironment at the bottom
not sure but I think it's called the console no?
small advantage of using console is...
you will know how your project works when you will install it somewhere else.
using super tools should be a step only after you know how to work without them I think
so are you saying learn with the commandline
but later on I ought to use the pycharm editor
yup
okay fine, thanks for the explanation
The advantages I personally gain from running django server from command line is quite a few for example
My terminal just has everything setup to have full workflow, vim as IDE, server std outputs, database consoles etc.
I don't always want to run on debug mode and test the server using gunicorn or stuffs alike. Being in a terminal you can have mulitple instance running in multiple variants. (you can do this from PyCharm too)
With a complex systems where frontend is on a different stack, there's cache running, you want to toggle between stuffs as fast as possible.
I appreciate it
Apart from those, I like my customized terminal more than PyCharm's one.:P
👍
I also rather enjoy working from terminal tbh
not that I have much a clue what I'm doing but I learn
def detail(request, question_id):
try:
n1=Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request,'app1/detail.html',{'n1':n1})``` when im trying to render this error
it's showiing the default error
i m recruting people for projects send me a message !
async def get_items(request):
prices = prices_collection(request)
async with async_closing(prices.find({}, {"_id": False})) as results:
async for row in results:
items = await results(length=None)
return web.json_response(items)```
how to get everything in my database and return it on web?
make sure your item variable is something serializable
can anyone check out what i asked in help-pretzel? its a very quick question any help would be much appreciated
Can I share my project here
If it's open source, sure
It’s open source
This is my open source web framework https://github.com/InsaneMiner/Lemon
It’s a library
path : register.models.py
class User(AbstractBaseUser):
username = models.CharField(max_length=150)
but after python manage.py createsuperuser
i have :
django.core.exceptions.FieldDoesNotExist: User has no field named 'register.User.username'
does anyone why is that happened?
i also have added at setting.py the AUTH_USER_MODEL = 'register.User'
Hello Everyone,
Recently I have developed one blogging website using Django. And I have made the complete development open-source on my GitHub.
Please have a look and share your feedback.
Website - https://hackbotone.com
GitHub - https://github.com/anshumanpattnaik/hackbotone-website
Thanks
im using flask and trying to get my navbar to show on everpage
im using the extend but then
it wont show the pages content
how do i set a navbar on everypage
It sounds more like a Jinja question. If you are using template inheritance then you probably want your top level template (base) to have the appropriate navbar. Your lower level templates will extend that base template and inherit the nav bar. Load your page in the browser and inspect the source html to verify the inheritance works as you expect. https://jinja.palletsprojects.com/en/3.0.x/templates/#template-inheritance
hello everybody, i m new to Django web dev, and i want to make a workflow is there any good library that anyone can recommend expect viewflow, cause i want to make my own REST API and front-end
Hello @weary pond ,
If you're interested you can follow my recent Django project, I am thinking it can be useful for your requirement.
Client - https://github.com/anshumanpattnaik/hackbotone-website
API - https://github.com/anshumanpattnaik/hackbotone-api
@toxic forge have you ever mess around with Extending the existing User model?
with django i mean
@pine trellis yes in Django
I use AbstractUser to override existing or add new fields to User model
you use AbstractBaseUser if you want to remove all default fields including permissions
I would like to interact with a webpage, lets say writing "hello world" to pastebin and post it. How would I do that?
Sounds like time for selenium.
Thank you, I will look into that 🙂
anybody have experience with heroku deployment?
I'm getting this when I try to deploy my flask app to heroku, can anyone help me with this?
did you read the error and go the the link with more info on your failure?
You're using a buildpack and it says your app isn't compatible. Follow the link and see why.
@forest hawk instead of return str(output) you can use return render_template_string(output). Jinja automatically escapes a provided string for safety reasons.
oehh thanks, let me try @outer apex
Could you share a bit more code where you're doing this loop?
Solved, thank you everyone for any tips/help/interesting on all sub channels 🙂
how can i complete my code?
hello I wanted to complete my code by just comparing to a tutorial it's different
how can i do that?
os.path is missing
why didn't work, we need error log when we are debugging
can you come to code help 1
Check out #voice-verification
hope you imported os
Hey @strange notch!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
!code-blocks
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Can u see my code in your DM?
ideally, to your 'DIRS' key in the settings.py, you should write:
DIRS: [os.path.join(BASE_DIR, 'templates')]
nope
If you want I can just help you out myself
what tutorial vid are you looking at?
Python tutorial - Python for beginners - Go from Zero to Hero with Python (includes machine learning & web development project).
🔥 Want to master Python? Get my Python mastery course: http://bit.ly/35BLHHP
👍 Subscribe for more Python tutorials like this: https://goo.gl/6PYaGF
👉 Watch the new edition: https://youtu.be/kqtD5dpn9C8
📕 Get my FREE ...
this is the last 5 mins
actually the last 2 mins
oh, I don't recommend you follow MOSH for django
I failed to help him out due to some mysterious syntax error
there's a very, VERY, good & easytounderstand course that I can send you specifically for django
I'll send it
😆I recommend Flask for beginners
I suggest you first take a break from doing anything: that 6 hour course is pretty hefty, you might get fatigued
dont worry I have been doing this course about a month
Here's the video link: https://www.youtube.com/watch?v=F5mRW0jo-U4
The first few steps are about setting up a virtual environment, then the basic settings of django (where you're stuck at), and the entire foundations of django
Learn the Python Django framework with this free full course. Django is an extremely popular and fully featured server-side web framework, written in Python. Django allows you to quickly create web apps.
💻Code: https://github.com/codingforentrepreneurs/Try-Django
⭐️Course Contents ⭐️
⌨️ (0:00:00) 1 - Welcome
⌨️ (0:01:14) 2 - Installing to Get ...
it is VERY good
I know but it can still feel tiring
@ivory bolt Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!
Our server rules can be found here: https://pythondiscord.com/pages/rules
@ivory bolt from the looks of it, that wasn't a valid invite anyway.
you can just check this place out: I specifically help guide students for web-dev:
https://linktr.ee/learnencode
Not trying to promote anything here
yep it was an old one
Tnx for recommending the course but do you have any idea about how can i fix this error?
@ivory bolt This does count as promotion and you need to ask permission via @hexed spoke first.
surely!
Sorry, I assumed this is your website. Is that correct?
No, just a link to a few accounts to check out to learn from
it's a linktree, though I fully understand
just put it in case anyone needs anything
can you share your settings.py
this chat doesnt allow me
also run pip freeze to see wether you have all valid packages or not
in your virtualenv
copy paste as code block
Hey @strange notch!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
!code-blocks
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
@strange notch as a codeblock, not as a file
or pastebin?
Hey @strange notch!
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.
Feel free to ask in #community-meta if you think this is a mistake.
Can you help me
take a look at this
or you copy paste your code, select it, and double click
*right click
chose code-bock
Hey @strange notch!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
which link?
this
it says this invite is invalid
hmm
try again now
it should work
@strange notch
Feel free to join in any time tomorrow, I'd be happy to help you and others in your situation out
though I think this channel has a lot of resources to offer
Getting ready to make the shift from learning Python to building the web application I have in mind.
The web app is going to have a few things involved:
- Forms for collecting data through wizards (for new users)
- canvas for building diagrams
- The glue to convert info in the wizard into diagrams
- and other persistent web app goodness such as user, support form, and a few more things to boot.
- Phase 1 is about mapping. Phase 2 is about automation. Phase 3...well, that's a ways off 😉
Assuming that made sense, I welcome any thoughts/questions that immediately surface.
The current landing page is https://www.lanesflow.io/ (built on WordPress, slated to be retired)
I anticipate a combination of custom building and leveraging some already invented wheels 🙂
Hi, i have a litte question
What is the best way to storage products for my shopping cart?
Cookies are an option?
Thanks for the data, ill be watching it
this text is pretty hard to read
Also, I'd like to be able to try the main product out without having to sign up
like a demo or something.
In the web version of Discord, I tried using bs4 to copy the element, but it displayed "None". What should I do? The only messages I can see are those while inspecting the element, so how should I proceed?
How to make a django notes app?
I have experience of making a blog app but In this I gotta avoid posting some content
hey so i am making an website that uses react with django rest. The site has some info that has to update real time, firstly i was thinking of having the frontend send a request every 0.5 s to the rest api. Will doing this be a bad idea because i think of so many requests the website will lag a lot so what other solution is there?
websockets 🙂
but, a request every 0.5s isn't TOO bad
ty, could u send me a link where i can learn about them and their implementation
This looks like a good one: https://ide.sourcelair.com/blog/articles/115/django-channels-chat
k thanks
What
actually i want to make options for questions how should i do that
can u come to vc
Which one
bro actually here there speaking is not allowed
Yes
try using async like sockets (asgi protocol if I'm not wrong) for constant stream of info
Hey guys, I am stuck web scraping something using XPath, anyone who can help me out ??
I am using selenium, python
can you specify where you're stuck
How to get started with django rest
Django, API, REST, Quickstart
I wanna get the values of the highlighted part like DL1 D1 D2 etc. And for this I an using the value of the class to get the XPath. But it's not giving me anything
ie an empty list
Special Trains introduced by Indian Railways on a temporary basis to handle peak Summer/Festival traffic India Rail Info is a Busy Junction for Travellers & Rail Enthusiasts. It also hosts a Centralized Database of Indian Railways Trains & Stations, and provides crowd-sourced IRCTC Train Enquiry Services.
How do I start learning Django/Flask?
The stuff i wanna scrape @ivory bolt
search a youtube channel named CoreyMS
it has a great tutorial
also the Django documentation is a good one
Okay, thanks! I know all the basics of Python, should I learn anything else before starting Django/Flask?
well you will know what to learn after you start
like when you come to urls you will likely go and read about POST and GET
and so on
i started django with only python in my mind just like u now
''' info=train.find_element_by_xpath("./following-sibling::div[1]")'''
something might be wrong with selecting the sibling element
Okay, thanks a lot! Btw, I'm a highschooler and started coding 3-4 months ago :)
that's good things will probably be easier for u
im not an expert BTW i just started couple monthes ago
u may catch me up!
u may wanna start with polls app they made in the documetation
a simple good start
i am creating a function based login view and using AuthenticationForm for it. my question is how can i change the label of the username field for that form? (context django)
try this and tell me if it worked
in your forms.py
from django.contrib.auth.forms import AuthenticationForm
class EditedAuthenticationForm(AuthenticationForm):
class Meta:
labels = {
"username": "your_new_label",
}
hi guys!
How i can change the format of date YYYYMMDD to DDMMYYYY?
i put form type='date' from html to python code
or u may wanna check this https://stackoverflow.com/questions/56021253/how-i-can-change-label-password-in-django-froms
hello everyone,
I'm trying to setup python app on my web hosting by using cpanel but i couldn't install a module named "mysqlclient" it gives error. I have been google it around 2 days but i couldn't find a solution. Could you help me please ?
also the hosting provider is godaddy
if i want to create a website where you would make a new room for a game should i use python if i am a bit better at it and don't really have much experience in js
And what framework would I use with python
Flask for learning, Django for building.
Shrugs. It can be done in both languages.
depends on which on you are more familiar. If you are better with python, go for python.
But JS would be still used anyway, just in less amount.
It is possible to go without JS completely though
But most people like having more dynamic interactivity on their web sites. Just python usage makes web site a little bit limited
as well as just using Javascript can feel as limited too. Like... I don't believe in JS to work well for backend (to hell with Node.js)
you can use something like Dash, PyWebIO, to avoid frontend coding
is django docs down rn?
K ty, and yeah I meant for backend what language should I use
I've found some really specific libraries on js tho
Like colyseus
yep, and also Github, docs.python.org, Stackoverflow etc.
fastly boom.
well, in this server you will hear only that python backend frameworks are awesome)
i like Django pretty much (with its plugin DRF)
as alternative FastAPI I heard is good too
Woah I wonder why 😕
But yeah it seems like js has really specific libraries that cater to my needs
I'll have to read up more
@fiery mason for JS, express is the most popular backend lib. For python, its django.
Never heard of it tbh
For small libraries you really only rely on their docs, theres not as many dev resources as more popular libs
can you send a clearer screenshot
yep
Hello, sorry to disturb you. I trying to send file with html form with my python "web server" (http.server). I use cgi to recover it. The file is an .wav audio but when I upload it I only have a part of the file (for exemple if the file last 1 min, I only recover few secondes of it). Can someone help me please ? Thx ^^'
return send_file(as_attachment = True)
Try this
With my form ?
Currently I have a form with file input and his action is "save_file.py" and in it I use cgi

