#web-development
2 messages · Page 227 of 1
djiango has a worse learning curve, I take that opinion in mind
though, python is already way easier
also, in case you want to go framework less, you can have a frontend and backend in vercel for free for non commercial sites
I will go with djiango and if i am stuck I will pay a visit to fastapi :D
OK
but im still curious about this popular thing, djiango
cool. Enjoy
Thanks!
there's a huge ecosystem around Django and surely job opportunities
I actually can see that
surprisingly, djiango is becoming a requirement for some jobs
Yep, there's a lot of jobs for django devs but i can see a lot of jobs with fastapi too
Fastapi is just still young, If it is good, in the future you will see more fastapi jobs too
yeah. If you learn Django then learning Flask, FastAPI etc is really simple, not need to invest too much time
FastAPI has similar interface but more features out of the box
Flask ecosystem is also huge. And microservices platforms usually use smaller frameworks
I see
thats interesting
I used flask to do some simple stuff
just experimenting
FastAPI is modern. Flask is popular. I'd use FastAPI today
I see
# Flask
@app.route("/items/")
def items():
if request.method == "GET":
...
if request.method == "POST":
...
# FastAPI
@app.get("/items/")
def get_items():
...
@app.post("/items")
def create_item():
...
FastAPI also has more built-in features compared to flask: dependency injection, validation, automatic documentation generation
You can just check out it's features tbh: https://fastapi.tiangolo.com/features/
So fast api is lighter than djiango and heavier than flask
Yep, but it's also faster than flask
I mean, if you can cut your bill in half...
ahh
i keep getting flask_bootstrap not found error
I installed it on virtualenv on my pc as well
It's quite faster (according to techempower benchmark, it wouldn't reflect real-world speed, but still ...)
does someone how how to auto generate a id/key in flask_sqlachemy NOT PRIMERY KEY?
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
follower_Id = db.Column(db.Integer, unique=True) #HERE
email = db.Column(db.String(150), unique=True)
username = db.Column(db.String(150), unique=True)
password = db.Column(db.String(150))
did you keep a backup
NOT PRIMERY KEY?
yep
have you tried the golden trick, restart
yeah couple of times
Can you share full error?
deactivate and active env for example
yea non primary key
I see
yeah couple of times as well
pip update?
You want to add autoincrement for non-primary key column, right?
autoincrement=True
I tried that
will try now
have you tried pip install flask_boostrap
And?
and when I created a user it shows the value as NULL
@covert yew Did you create a migration?
I just delete the database and it recreate it self when I open the server again
if I have no database when its opening
Hm, ok, try with autoincrement then
if my solution is not working, try to ask people here. if it still persists, open an issue on github page
hey anyone help:
i'm trying to get my div box to be pressed against the top-left corner of the page, but i keep getting this extra grey space
how do i get rid of that?
(my background is grey, and my div box is black)
margin: 0 0; on the CSS
Traceback (most recent call last):
File "/Users/user/Desktop/leetApp-mongo/run.py", line 1, in <module>
from files import app
File "/Users/user/Desktop/leetApp-mongo/files/__init__.py", line 2, in <module>
from flask_bootstrap import Bootstrap
ModuleNotFoundError: No module named 'flask_bootstrap'
doesn't work
is it only top and left?
wait...did you mean in the div or the body?
div
tried pip3 install flask_bootstrap flask-bootstap Flask-Bootstrap
try to import flask before flask_boostrap
from flask import Flask
from flask_bootstrap import Bootstrap
Which db do you use?
then run the code with python3
i once had two pythons installed and I faced some problems with that
sqlalchemy
cyaa
It's a library/orm, i meant the actual database
Like postgres, mysql
sqlite?
Hm, weird, can you make it not nullable? i.e. autoincrement=True, nullable=False
Can you also share your model?
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
follower_Id = db.Column(db.Integer, unique=True, autoincrement=True, nullable=False) # THIS IS THE ONE YOU ARE LOOKING FOR
email = db.Column(db.String(150), unique=True)
username = db.Column(db.String(150), unique=True)
password = db.Column(db.String(150))
first_name = db.Column(db.String(150))
last_name = db.Column(db.String(150), nullable=True)
description = db.Column(db.String(200), nullable=False, default="")
picture = db.Column(db.String(), default="default_profile_pic.jpg")
date_joined = db.Column(db.DateTime(timezone=True), default=func.now())
permissions = db.Column(db.Integer(), default=0)
verified = db.Column(db.Boolean(), default=False)
posts = db.relationship('Post', backref='user', passive_deletes=True)
comments = db.relationship('Comment', backref='user', passive_deletes=True)
likes = db.relationship('Like', backref='user', passive_deletes=True)
saves = db.relationship('Saved', backref='user', passive_deletes=True)
forums = db.relationship('Forum', backref='user', passive_deletes=True)
forums_joined = db.relationship('ForumMember', backref='user', passive_deletes=True)
reports = db.relationship('Report', backref='user', passive_deletes=True)
Well, that's weird, are you sure your database if fully dropped?
Also i'd try on other db like postgres 🤔
is it hard to change database now?, what would I need to change for that
I built a lot of stuff using this one
Just install postgres and connect to it instead
Yep
Doctor in the office
thats it
https://www.postgresql.org/download/
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
whats that
I somehow solved it but really dont know how
@serene prawn Do you have any tool to view/edit databases?
What did Nike use to create design tab in their website
Hello how do i do the css to achieve this kind of spacing on a flex div?
Hello again, Darkwind.
I have pointed that IP in the DNS Server settings.
As excepted, It doesn't work when trying to access the webpage.
Is it because you have to confiugure the flask server too? If, how?
How does one markup HTML in a iframe? I currently have an iframe with type "hidden" and I want to edit it to become visible
page.eval_on_selector("input[id='token']", "el => el.contents().find('input').html('testingvalue')"
I am using playwright for python and attempting page evaluation on the iframe but it just doesn't edit anything at all
I read that sometimes its because the iframe does not load alonside the same domain that the main page does
from flask import Flask, render_template
import datetime
app = Flask(__name__)
@app.route("/", methods=["GET"])
def get_main_page():
return render_template('entery.html', utc_dt=datetime.datetime.utcnow())
@app.route("/first", methods=["GET"])
def get_first_page():
return render_template('index.html', utc_dt=datetime.datetime.utcnow())
if __name__ == '__main__':
app.run(debug=True)
Hello guys
How can I render the JS and css additionally to my index.html?
This function renders only the html , I assume something wrong with the paths of my directories or similar ...
you need to put them in a static folder
<link
rel="stylesheet"
href="{{ url_for('static', filename='css/main.css') }}"/>
<script
type="text/javascript"
src="{{ url_for('static', filename='js/index.js') }}"
></script>
thnx appreciate
hey guys, where do you recommend learning django from?
try Corey Schafer's Django Tutorial
is it beginner friendly?
if you're familiar with python basics, then yeah. I'm using it right now
I started out with Corey Schafer's Django tutorial. Thoroughly recommend it.
will do definitely
DjangoGirls has a great tutorial.
Can anyone give me a good tutorial on how to deploy your flask app with uwsgi and nginx on windows?
Has learning Python only for webdev sense?
I'm getting started with flask
For me, yes. But there are tons of other cool stuff you can do with it
Ok, thanks. I was asking, because I'm not fan of AI, Data Science, ML.
Python is pretty good for web dev
Hello Guys, anyone have idea about how to get current logged username in usercreation form in django
hi
hello
@indigo orchid python isn't frontend, keep that in mind bro
request.user.username?
no it is not working in froms
class AddClientForm(UserCreationForm):
super_client_username = forms.CharField(max_length=32, help_text='First name',
widget=forms.TextInput(attrs={'placeholder': 'username'}))
username = forms.CharField(max_length=32, help_text='First name',
widget=forms.TextInput(attrs={'placeholder': 'username'}))
first_name = forms.CharField(max_length=32, help_text='First name',
widget=forms.TextInput(attrs={'placeholder': 'First Name'}))
last_name = forms.CharField(max_length=32, help_text='Last name',
widget=forms.TextInput(attrs={'placeholder': 'Last Name'}))
email = forms.EmailField(max_length=64,
help_text='Enter a valid email address',
widget=forms.TextInput(attrs={'placeholder': 'Email Address'}))
mobile_number = forms.IntegerField(
help_text='Enter a valid mobile number', widget=forms.TextInput(attrs={'placeholder': 'Mobile Number'}))
password1 = forms.CharField(max_length=32, help_text='Password',
widget=forms.TextInput(attrs={'placeholder': 'Password'}))
password2 = forms.CharField(max_length=32, help_text='Retype Password',
widget=forms.TextInput(attrs={'placeholder': 'Retype Password'}))
class Meta(UserCreationForm.Meta):
model = User
fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email', 'mobile_number',)
def save(self, commit=True):
user = super().save(commit=False)
user.is_client = True
if commit:
user.save()
return user
You want to automatically populate the form?
yes
but i want current logged username in super_client_username = forms.CharField(max_length=32, help_text='First name',
widget=forms.TextInput(attrs={'placeholder': 'username'})) and save in database
I think in your views you'll have to pass it into your form instance
Forms.bla_bla(Initial={super_client_username:request.user.username})
hey there! I have a django app where I signup and set a myuser variable (code below)
def signup(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
email = request.POST['email']
print(username, email, password)
if User.objects.filter(username=username).exists():
messages.error(request, 'Username already exists')
return redirect('signup')
if User.objects.filter(email=email).exists():
messages.error(request, 'Email already exists')
print("Email already exists")
return redirect('signup')
if len(username) > 25:
messages.error(request, 'Username must be under 25 characters.')
print("Username must be under 25 characters")
return redirect('signup')
if not username.isalnum():
messages.error(request, 'Username must be alphanumeric.')
print("Username must be alphanumeric")
return redirect('signup')
myuser = User.objects.create_user(username, email, password)
myuser.is_active = False
myuser.save()
messages.success(request, 'You are now registered and can log in. We have also sent you a confirmation email. Please check your email and verify your account.')
print("User was registered")
Users will be spending "tokens" on my application and so I want to save that into myuser or any thing that would grab 'tokens' from the current logged in user
for example,
def dashboard(request):
if request.user.is_authenticated:
tokens = myuser.tokens # or get current logged in users
ctx = {
'tokens': tokens
}
return render('dashboard.html', ctx)
or something along those lines
I'm sure you guys understand what I'm asking for.
I don't know how to tackle this and would appreciate you guy's help.
Thanks!
Can't you just return request.user in context and access user.tokens on the front end?
Or do you not want to return the whole user on dashboard?
what is your question then, not how to use tokens on the front end?
I want to find a way to add, edit and remove 'tokens' from a user
do you know how to save and edit objects in the database?
That's where you should start.
hm
When you click a button or submit a form, review how to add or edit an existing field in the database.
so wouldnt i use model forms
Then you can just edit the tokens on the user model as much as you want and how you want and access is via user.tokens on the front-end (if that's the field name)
I dunno, depends what you want to do. Forms are just a way to send data from a form to the views, where you do something with the data.
okay
Lookup a tutorial on how to submit data via a form and save it in a database in django.
That will walk you through it.
If you have trouble along the way, feel free to ask. 🙂
Sure
ya
like flask but worse
so just to make sure I have this right
I just tried FastAPI today
So questions r
How can I improve my web skills now
I've been alot of complex project's including video streaming platform n stuff
Now I wanna learn some front-end stuff n ajax ,etc also
What can I do to be better I've tons of projects
N how can I write efficient code on Python (django)
Also how can I learn unit testing to write quality code +resources
Last ,I'm pretty bad at writing django signals how can I improve that (includes automated testing via Tests.py)
Thanks in advance
N plz guide me through Django Channels
Cuz I really ain't able to understand
when the user is created, it will also be created with a seperate userdata model and ```py
class UserData(models.Model):
username = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
tokens = models.IntegerField(default=100000)
def __str__(self):
return self.tokens
basically it would pass in the current logged in user's info and then I can manage the tokens from there
Plz answer I'm gonna sleep will check answers n responses for sure
Thanks again
hey I want to use login_user with mongodb database I am giving a user dictionary to login_user which I set "is_active" to True when authenticating user but still getting dict has no attribute "is_active" error
what am I doing wrong
{
"_id": "f27fefedb3704a7abdbe5d5a3b3420d2",
"user_public_id": "aaaaaa-656531",
"username": "aaaaaa",
"email": "cdklsam@lcsnl.com",
"password": "$pbkdf2-sha256$29000$h3BuLWVMaW0thZDSOuccow$gqwJwsi3wxXkj0V/lZNnf9Hdovias3ydydQ7tLpmgg4", "is_active": true
}
this is the dict I pass
if in js i have a document.querySelectorAll().forEach, how can i fill content from an array in order
I got it working, thanks :)
i want to be able to redirect a user from my website to another website and be able to put some data into a form that is on that page. Is there any way i can do this with some python script? Is there a library that could help me greatly do this kind of stuff?
Im no web dev expert but the way i see it put that data in headers or in queries and have a js script check if the headers exist and if they do set the content of the form to the data
Idk about python but I think you can use the action attribute in html
Thanks. I'll look into it
You’re welcome
hello guys can someone help me? I'm having trouble with static files
here is my base.html
here is my settings.py
the images is working fine but It's weird why my css folder and js cannot read using static?
I've not worked with static files but try replacing STATIC_URL = '/static/' with STATIC_URL = 'static/'
@lethal junco did Toxid's solution work?
btw maybe you should use vscode with the jinja plugin
as your project seems big and pycharm is not very good for this frontend stuff
and jinja
because pycharm shows so many errors i just use vscode for all my frontend stuff
and imo vscode just has much better support for it
or maybe use atom idk
guys i am building video downloader. it takes video url as input. i am using wget module to download video.
then problem is, when i add it in flask. it does not launch download in browser. how do i make it download file in browser??
can someone tell me that the way i can make button in django other than is using form and make button in there and make it go to url i want and make it run fuction there and redirect the the url before
Is there any way to separate the python code in a separate file(like a linking a CSS stylesheet) in pyscript?
yo!
Can anyone recommend a good up-to-date sqlalchemy tutorial?
I have been trying to follow the official one but I have no idea what the creator is rambling about. I'm literally 20 mins in and he might as well speak Chinese to me, it'd be the same
If a request is being sent by a flutter mobile app instead from a website to my django backend is it still possible to set the request cookies?
So if you use nginx you can stream the data through the ports?
So I can attach localhost to an url?
I think you can do this with hosts file, no?
sqlalchemy documentation is good but it would take you some time to read
probably a ton of different ways
i was reading nginx docs last night and it showed it updated to handle asgi
Hello, what's the best way to query objects and use them as context in a view, I have a list of dicts , but the view expect only a dict
anyone doing the correy schafer django webapp
@golden hamlet long time since, need something?
yeah i seem to have a problem even though we have the same code
How to shuffle images in python ?
trying to render a page but it shows 404
Actually I sliced the images and I have to shuffle those images?
Is it possible
probably possible with random.choice()
@golden hamlet dm the code
@fickle basin can u give the code ?
@craggy flax dm @golden hamlet 😅
ah
i don't know how to connect it to images and such, as i'm new to webdeb
but i suspect you can use this module
https://www.w3schools.com/python/module_random.asp
mby you can put all the files in a list and then use random.shuffle() @craggy flax
var textareaContent1 = $("#name").val();
var name = textareaContent1;
var textareaContent2 = $("#status").val();
var status = textareaContent2;
console.log(name, status);
$.ajax({
url: '/device',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
"location": name,
"status": status
}),
dataType: 'json'
});
Can anyone please tell me, why name is applied and status not?
Show your html?
Well there is just 2 text fields and a button
Name and status are text field ids
Apply is button id
Can console.log even store 2+ variables?
yes.
Can you just paste in your html?
Did you set "use strict"; at the top of the file/script tag?
Then come back when you have it?
Hey thier,
I want to build a website for school project using python
So which framework should I go with flask or django, tell me which is more efficient and EASY to learn.
I know python basics- conditional, loops functions, dict,list etc, not classes(is it even required?)
Hey 🙂 I've been learning and getting to grips with Flask but I want to build larger web applications so I might need to change at a later date 😮 I still need to figure out what a WSGI server is and how to use that for production
Flask is pretty intuitive though
relatively new to Python but been in web development for easily a decade and change, so picking it all up as I go 😄
Huh im a highschool student
can I create a functional dynamic website using flask in 1.5 month? how is the learning curve?
if you know your basic python, and website file structures aren't new to you, then it should be relatively straight forward. but to be safe there are a TON of really helpful videos and tutorial series on YouTube that I found super useful. The below tutorial series helped me get my head around it a lot easier 🙂 hope it helps
https://www.youtube.com/watch?v=MwZwr5Tvyxo&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH
In this Python Flask Tutorial, we will be learning how to get started using the Flask framework. We will install the necessary packages and get a basic Hello World Application running in our browser. Let's get started...
The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Python/Flask_Blog
Djang...
I'd say that FastAPI is better suited for the job if you're building api's, apps that use template rendering aren't that popular nowadays
And it's pretty similar to flask too
Template rendering is still pretty popular (django, 99% of javascript frameworks, etc). But yes, in the python ecosystem frameworks that don't do rendering are getting more popular, but that's in large part due to people using python as a backend instead of a frontend. If you wanted to use it for a frontend too, those templating tools are still pretty popular
I wouldn't count js as template rendering, you do that on client and not server side 🤔
Also i see most people use drf
hmmm I'll definitely check it out, I'm eventually wanting to tie it into an online game as a companion application but still very early days yet 😮
I'd say that I'll probably be asking a load of (what I'm sure will be) dumb questions before I figure everything out fully lol
@native tide I meant things like Jinja2 and Django Templates, they're still quite popular and they're not bad, it's just easier for people to use js for more complex applications
There are many popular server-side rendering solutions built in JS. Next for example
Server side rendering isn't template rendering though
I mean template rendering is a much looser term than SSR tho. You can render templates in many contexts, including SSR. Unless you have a more specific definition of templates, I think I'd go so far as saying JSX is tempaltes lol
Maybe i'm mistaken but i'd say template rendering essentially involves no client-side JS code (e.g. Jinja2), SSR would involve some JS code that would be shipped to the client, and i mostly see it used with frontend frameworks to initially hydrate your page to speed up load time?
I essentially meant template rendering on backend (e.g. django, flask, etc)
Without using JS frameworks or with some vanilla-ish JS
I'm just checking out FastAPI and I've manage to setup to a point where it runs and the application starts on my linux server but it doesn't show when navigating to the domain name ... my web hosting has a dynamic ip address so put --host 0.0.0.0 at the end but still nothing ... anyone have any idea what I might be doing wrong? 😮
Can you elaborate a bit on your server's setup? Is the FastAPI app running behind a Reverse Proxy or is it directly running on a specific port?
I can try 😄 so it's a "Managed Dedicated Linux Server" with 1&1 IONOS which has SSH, Python, and all the other good stuff on it, but the domain name connects to the webspace using a dynamic IP address (and doesn't have a remote desktop), so when it successfully runs on SSH and shows "Uvicorn running on https://0.0.0.0:8000" the domain is showing a 403 error 😮
I might be being dumb tbh 😮 but if I don't mess up then I don't learn lol
I have no experience with IONOS, but you would only reach your app on port 8000 if there was a piece of software allowing connections on port 443 (https) or 80 (http) and forwarding the request to your app on port 8000 ... or if your firewall does allow incoming connections on port 8000 you could enter https://<your-domain-name>:8000/ in the browser ...
That's usually the way to learn, yes 😉 .. Don't worry. We all started sometime making all the mistakes ...
Can you try to connect via ip though? 🤔
hmmm that's a good point, it could be that (will have to figure out how to check), do you know if there is a way to check open ports via SSH? 😄 and I intend to make all the mistakes haha ... spent years getting really good with PHP, SQL, HTML, CSS and other web languages so just decided to leap into Python to help make more powerful systems 🙂
and I don't have a static IP one or I would do, unfortunately it changes regularly being dynamic, but I should definitely be able to check if the port is open 😮
Why not use php though? Just wondering, many people like it
Check against current ip 😅
doesn't work if you navigate directly to the ip cos it's a dynamic one lol ... I tried all the IP navigation hacks to get it to work but as @crystal stag said, it could be the port isn't open 😮
Do you have some kind of Website for your Managed Server? A Control panel of some sort? Often the firewalls are managed outside your machine ... otherwise it depends on the installed operating system, so which Linux Version (Ubuntu, etc.) is running.
Oh don't get me wrong I love PHP and I've used it (and continue to use it) in many applications, but I wanted to make applications with more functionality and scalability 😄
and I'm just having a look around to see if I can spot firewalls as an option, it has it's own IONOS version of a back end with Webspace, Databases and all that, just having a good look round now
I think scalability would depend on how you develop and design your app, not on the language itself
I completely agree, the language does not matter much. That said ... on this discord server Python is superior to all other programming languages 😉
That's true also, I'd say the framework I use definitely impacts the design and end product I end up with 😄 and can't find anything like firewall or port settings (and don't feel like messing with DNS until I know it's possible) ... why do I get the feeling that the hosting package I ACTUALLY need is only £10 per month more lol 😅
and in fairness Python is my new favourite language purely based on the fact it can interact with ANY other one 😄 , that alone is pretty useful for scaleability lol
I feel I might be in the right place to hold this belief lol
is there any noob friendly way to add range slider to html?
On the command line you could list firewall rules with "sudo iptables -L -v -n" if you got sudo rights ...
The different HTML5 input types are explained here: https://developer.mozilla.org/en-US/docs/Learn/Forms/HTML5_input_types#slider_controls
anytime I use sudo I get an error saying -bash sudo: command not found
I'm taking this to assume I don't have it 😮
Looks like it.
looks to me I'll be having a word with old IONOS in the morning ... it seems the "Dedicated Server" they sold me isn't all it's cracked up to be lol 🤦
thank you for all your help guys! 😄 I don't seem to have an issue running locally on my Windows laptop but the server seems like it's gonna be the death of me, was wrestling with pipenv earlier and just gave up in favour of venv lol
Maybe IONOS has a help forum or you can find documentation in the control panel? Or contact support? ... You are a paying customer after all ...
that's a good point, it does say 24/7 support with a phone number but it's like 22:28 and my fully British ass is worried about "calling so late" hahahaha 🤣 🤣 I'll do it first thing though lol 🤣 🤣
OK, have a good night then and good luck with your project!
for me to call outside business hours, the server would have to be offline and have customers on there lol 😅 And thank you, hopefully I'll get the teething problems out of the way then smooth sailing lol 😄
how would i make a web-browser inside a flask website?
what OS is it? (cat /etc/issue). you can probably install it with something like apt install sudo or whatever the package manager on that system is
I just started using selenium and the tutorial i'm following along has me making the following code but the window that pops up closes about a second or two after the page loads in. is there a reason why it does that? The video does not display this kind of behaviour as well
from selenium import webdriver
url="https://www.google.com/"
driver = webdriver.Chrome()
driver.get(url) ```
i'm using vscode to run it as well
Is there a best practice for Django in naming your project and the apps included in it? Like should you name the project the name of the website? and then apps like 'pages', 'blog', 'appointments'. I know the name of the project itself probably doesn't matter just wondering if there is a best practice
do you know django?
I went through a udemy course but they were never very clear on if there was a best practice for file naming conventions other then the double foldering of '/templates/myapp' etc.
I wish that django templates were more often written the way modern JS frameworks will often do HTML with a lot of attrs and inserted code of another lang
{% if messages %}
<ul class="messages">
{% for message in messages %}
<div class="container-fluid p-0">
<div class="alert {{ message.tags }} alert-dismissible"
role="alert"
>
<button type="button"
class="close"
data-dismiss="alert"
aria-label="Close"
>
<span aria-hidden="True">
×
</span>
</button>
{{ message }}
</div>
</div>
{% endfor %}
</ul>
{% endif %}
for me this is so much better than
{% for message in messages %}
<div class="container-fluid p-0">
<div class="alert {{ message.tags }} alert-dismissible" role="alert" >
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="True">×</span>
</button>
{{ message }}
</div>
</div>
{% endfor %}
While it's not always desirable to do it this way, its much easier for me to read it when its a mess. Especially code gets way more messy than this with templating syntax and multiple attrs long values.
I guess the main difference is... js frameworks have webpack and to minify all that.
how to make html page look the same throughout all devices?
Basically, you have to load the site up in every browser as you develop it and check all the features you use and they are supported by the browser you want them tow work in. In my opinion this is the worst thing about frontend
ya basically i have a button and it changes its location based on how zoomed in the person is or just resolution
so sometimes its where it is
or its just over text making it look awful
it all depends on the zoom part
yeah... The best thing to do is to open up developer tools and try identify differences in the css that make it do different things. and just hack it together.
I'm pretty sure ive had that problem before where things are not placed where they should be especially like... a container that is displaying not relative to other containers.
comparison
bottom is 100% other is 140%
ive compared it with a chromebook screen
the normal view for it is 140% on a windows laptop
so idk
its positioned absolute and you're specifying how far to the right to put it?
the position is relative because of the button which is prob the reason
heres the code if you wanna see for yourself
Im not really good at CSS like where I can make it do whatever I want without moving things back and forth. The way I do it is I just open the developer tools and I uncheck properties and change values directly in there and move things around until they work. If for some reason its not working that badly, its probably just bad design or something and you should find some templates that do what you're trying to do and imitate it.
if you wanna look and see what i see to get a better idea feel free
ill paste it so you dont have to type it
but one thing i know for sure is if you change any part of the design you have to check all browsers you want to support because the chances that something is going to look terrible in another browser without some work put into it are huge.
worst part of frontend for sure
#button-3{
top: -200px;
left:-450px;
}
#button-3 a {
position: relative;
transition: all .45s ease-Out;
}
#circle {
width: 0%;
height: 0%;
opacity: 0;
line-height: 40px;
border-radius: 1oo%;
background: #BFC0C0;
position: absolute;
transition: all .5s ease-Out;
top: 20px;
left: 70px;
}
#button-3:hover #circle {
width: 100%;
height: 100%;
opacity: 1;
top: 0px;
left: 0px;
}
#button-3:hover a {
color: #2D3142;
}```
<div class="button" id="button-3">
<div id="circle"></div>
<a href="redirect.html"> Home</a>
</div>
Hi, in Flask I’m having an issue that posting to a php file from a contact form gets 405. How could I allow a POST to the php form?
Could you help me with some easy task? I can't debug 1 thing, there is no error message i can see #help-croissant
alright, i'll drop it here)
{% extends "layout.html" %}
{% block content %}
<script>
$("#apply").click(function() {
var var1 = $("#var1").val();
var var2 = $("#var2").val();
var var3 = $("#var3").val();
var var4 = $("#var4").val();
console.log(var1, var2, var3, var4);
$.ajax({
url: '/url',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
"var1": var1,
"var2": var2,
"var3": var3,
"var4": var4,
"var5_int": 0,
"var6_str": "",
}),
dataType: 'json'
});
})
</script>
<div class="ui container">
<div class="ui input">
<div class="ui form"></div>
<div class="field">
<input type="text" id="var1" placeholder="variable 1"><br><br>
<input type="text" id="var2" placeholder="variable 2"><br><br>
<input type="text" id="var3" placeholder="variable 3">
<input type="text" id="var4" placeholder="variable 4">
<button id="apply">Apply</button>
</div>
</div>
</div>
</div>
{% endblock %}
expected result is when user enters var 1,2,3,4 and presses apply, json with var 1,2,3,4,5,6 (5 and 6 are constant) is sent to API endpoint
But nothing happens. When I change "var1": "some constant thing, not variable", it works
If there is only 1 variable it works as well
but for several variables it doesn't tho it should according to answers i could google
how can I at least check error message? Can't see any thing in pycharm or browser to find out what's wrong with it)
there is no response from server
on api side everything is set correctly, i.e. if i generate json from insomnia or fastAPI docs, it's fine
anyone can help with html and javascript
nope:)
looks like all the guys are busy atm
could you help me mister
i posted it above:0
can you see it?
for some reason it doesnt work with constants anymore\
wtf...
I hope to find python developer
- use
resetCSS technique
mentioned it somewhere above
!paste
you can probably find even stricter CSS reseter. but that one should be more or less generic
there is no 100% guarantee that it will be same... but 95% of problems will dissapear
- if u have non vanilla Javascript used in your html
better to apply babel for transpiling into lowest JS compatible with any browser. It will make it more supported at any browser as well
- for 100% assuraness that everything works well, it is better to write smth like Selenium tests, with running them automatically in all browsers u wish to support. But oh well, it is a choice if it is worthy of that effort.
<div class="ui secondary pointing menu">
<a class="item">
Home
</a>
<a class="item">
Messages
</a>
<a class="item active">
Friends
</a>
<div class="right menu">
<a class="ui item">
Logout
</a>
</div>
</div>
<div class="ui segment">
<p></p>
</div>
Guys can anyone tell me if I can use this menu without making several pages? I.e. i have 1 home page and just want to devide contents
Have anyone tried pyscript??
Can't see how to get started with it at the github page, like starting from scratch
anyone online?
i need a rating on a website
i have done
heres the link "cobratate.netlify.app" its for a client, its undo but if theres any helpful tips from anyone that would be good.
hi
any ui designer here?
i need a frontend developer to design a profile template for me which is responsive on all devices
var number = $("#number").val();
How can I make it defined as empty string if #number was not inputed?
I receive an error if #number has not input value because "number": "" is sent to API and it's wrong, coz it should be either null or some integer
Please help fix it)
try a ternary operator? something like $(isNumberEmpty ? "" : "#number")
Is anyone here good with django forms ?
^^^ thanks
Hi guys, I'm trying to change field value when returning a response with drf so that i can post lets say age: 10 and in response i get age: "ten", how can i achive this inside serializer? i tried with SerializerMethodField but its read_only and i cant post and save value of it as in the example as integer, help
does anybody know if there is another registry url i can use for npm? ive been having issues with the official one
can i somehow refresh web page (like F5) after FastAPI endpoint worked?
Any idea how this thing would have been got. Like I remember I learned something sorta this but how to serve files this way?
u can use javascript reload method
but js is on frontend side
isn't there a way to force refresh from backend?
i dont think u can refresh webpage from backend, not sure though
@login_required
def edit_todo(request,text):
if request.method == 'POST':
queryset=Todo.objects.get(text=text)
text=request.POST.get('text')
print(queryset,text)
if len(text)<2 and len(text)>200:
messages.success(request,'text must be from 2 to 200 chars')
return HttpResponseRedirect(reverse('app1:edit_todo'),args=[queryset.text])
queryset.text=text
queryset.save()
messages.success(request,'Updated')
return HttpResponseRedirect(reverse('app1:index'))
return render(request,'app1/edit.html',{'queryset':'queryset'})
i'm tryin' to find different ways to do
UPDATE operations
but idk why it's adding new post instead of UPDATING
Is djongo the best way to use MongoDB with Django? Looking at this post from MongoDB here: https://www.mongodb.com/compatibility/mongodb-and-django
is there any way to speed up the process to load brython? or
a way to run a function after the page loads
use javascript and ajax?
i wanna try to make everything with python, that's why i use brython
i have svg content in my html, but I want it to render as content-type: image/svg+xml , how do I do that?
P.S. I m using Django
Does anybody know the best resource/library to create sitemaps when given a start url, trying to create sitemaps for websites that don't have a good sitemap.
anyone know how to fix this?
npm ERR! syscall connect
npm ERR! errno ENETUNREACH
responsive design is hard and it takes a lot of learning to get good at it
but for what youre doing specifically, im guessing youre using margins with pixels?
its much better to use percentages for margins as they stay the same distance apart throughout screens
i would say do not use percentages for widths and heights of the actual object though
usually that ends up looking weird
Here
ok so its an interactive button
ohh i see what youre trying to do
the circle is a wave of color that occurs when i hover above it
i see, what youre trying to do is a harder way of instead using the psuedoelement ::after
any recommendations?
Hi guys!
$("#del_item").click(function() {
var del_item_by_id = $("#del_item_by_id").val();
console.log(del_item_by_id);
$.ajax({
url: '/item/deldel/del_item_by_id,
type: 'DELETE',
contentType: 'application/json',
data: JSON.stringify({
}),
dataType: 'json'
});
});
how can i edit this ajax request so that url is dynamic?
I mean del_item_by_id is variable
so url has a variable part too
json is empty
i just need to send DELETE to the url and it will work
tested with insomnia and doct, it works fine on API/server side
but i cant find the way to use variable in url
I know, jQuery is kinda old, but probably easier for a beginner to do what he wants to do asap, angular, react, vue would take longer to implement the same simple stuff afaic
so far jQuery works fine for POST requests with static url but I can't find a solution for changing url
in fact only del_item_by_id will change
Use template strings:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
hmm could you tell me what exactly i should look for?
let someId = 42;
`/path/to/your/endpoint/${someId}`
it should look something like this
It's an equivalent to python f-strings:
some_id = 42
f"/path/to/your/endpoint/{some_id}"
well it's funny but it worked exactly like in python
var del_task_id = $("#del_task_id").val();
console.log(del_task_id);
$.ajax({
url: '/task/deldel/'+del_task_id,
type: 'DELETE',
contentType: 'application/json',
data: JSON.stringify({
"del_task_id": del_task_id,
}),
dataType: 'json'
});
});
i just changed '/task/deldel/del_task_id' to '/task/deldel/'+del_task_id
You can use string literals instead ^
Is it more elegant approach?
Yep, i personally like it more
mhm, I see, thanks! Can you think off any disadvantages of either approach?
Not really, both are fine, for me personally template literals would be kind of easier to read
Also your url probably should look like
DELETE /tasks/{taskId}
If you want to follow REST
there is another DELETE for /tasks/{task_id}, i guess i can not use more than 1 DELETE for the same endpoint address
so I had to extend it
so far just for testing needs, but when i tried just /tasks/{task_id} there was some conflict
BTW i wonder why wouldnt this work for me:
An accordion allows users to toggle the display of sections of content
when I copypasted example into my html file, the result is static, i.e. no dropdown content, not clickable
@serene prawn do you have an idea what could go wrong?
Doesn't seem like it requires any additional scripting
I mean, you can have multiple operations per url
e.g. GET, UPDATE, PATCH, POST, DELETE
bot not 2 of the same type, am i right?
for example i can GET /tasks/42 but also i can DELETE /tasks/42
Yep
Why do you need two delete operations here?
I don't remember exactly, I'll probably clean my code later when all the features are tested
For now I'm just implementing the functionality, mostly learning on the go)
I want to implement accordion to make my page look cleaner, but something is wrong here
alright nwm, it needed some scripting now it works)
hi guys. i have a little issue with Axios in VueJs.
i want to post data to backend as json object and then display the returned code in the console.
however,
<button type='button' v-on:click="findHost()">Search</button>
findHost: () => {
axios.post('http://127.0.0.1:8000/api/host/get_data', {"hostname": this.form.hostname})
.then(function (response) {console.log(response.data.hostname);})
}
this code returns me error:
Uncaught TypeError: undefined has no properties
hi, im struggeling with my things
so i have a html for downloading my pc files
<a class="btn btn-primary btn-sm" href="{{link}}" role="button" download><img src="./static/images/download.svg" width="25px" height="25px"> Download PDF</a>```
i also dont forget to add {"link":"C:\Users\Documents\GitHub\284902.pdf"}
the button shown `file\\\C:\Users\Documents\GitHub\284902.pdf` but i cant download the pdf, so how i can doing it?. arl searching but cant get solution
am I right in thinking that when using an orm like sqlalchemy, you dont have to escape your data to prevent sql attacks
since the orm takes care of it all?
@deft crow anchor tag just looks to a page
just make it download anything
Yep, you don't have to do that
But it depends on how you use it 🤔
What do you mean by the second statement?
just links to a page**
If you issue raw sql statements through sqlalchemy it won't escape anything
Though other queries constructed with core or orm should be fine
actually I'm wrong, anchor tag should auto download @deft crow
uh ok
@deft crow checkout this thread, there is a bunch of solutions: https://stackoverflow.com/questions/2598658/how-to-force-a-pdf-download-automatically
but it doesnt on mine
ah okay, yeah no raw statements
its weird coming from node having to escape everything, to not having to do it
I just thought i'd double make sure there is no need
none help i think
the href will href you into another url not the docs
hi
I am full stack web developer.
now I am building my site btw I am going to integrate blockchain smart contract and token as payment gateway.
I hope your help.
from my code in Vue3 example:
my api.js file
import axios from 'axios';
import { API } from '@/settings.js'
export const Install = async (input_data) => {
const url = `${API}/worker/install`;
return await axios.post(url, input_data);
};
random component:
<template>
<div class="submit" @click="action_install_vpn_server">
<p>{{ $i18n.t(`install.InputServerForm.install_vpn_to_server`) }}</p>
</div>
</template>
<script>
import * as Requests from '@/api.js';
export default {
methods: {
async action_install_vpn_server() {
let data_for_sending = {
// data
}
await Requests.Install(data_for_sending).catch(function (error) {
// Code
}).then(function (response) {
// Code
});
}
},
}
</script>
thanks a lot but i have figured it out meanwhile
sure 🙂
made it like this:
data(){
return{
form: {
hostname: '',
tenant: ''
},
hostresult: ''
}
},
methods: {
findHost(){
axios.post('http://127.0.0.1:8000/api/host/get_data', {
hostname: this.form.hostname,
tenant: this.form.tenant
}).then(result => {
console.log(result.data);
this.hostresult = result.data
}).catch(err => {
console.log(err.response.data)
})
}
#django can you update a record using formset_factory
I am trying to write a script that parses a org file into json and sends that json to a discord webhook, how would I convert the file into json, and then load it in the payload for the requests url?
i believe you can use requests library to send JSON data with requests.post()
i believe that one method will convert and send the payload
I am opening the file, dumping it to json with json.dumps() and sending that resulting variable with the request, and I get: TypeError: Object of type TextIOWrapper is not JSON serializable
don't write it to a file. just pass the object to requests.post()
Hi everyone, i have a simple question about django deploy on heroku. Is it normal that everytime i do a git push heroku master it seems like it's rebuilding the entire app again?
it shows this logs everytime: remote: -----> Installing pip 22.0.4, setuptools 60.10.0 and wheel 0.37.1
remote: -----> Installing SQLite3
remote: -----> Installing requirements with pip
@fiery fulcrum probably a better question for #tools-and-devops , but short answer is yes
I am using open('path/to/file'), assigning that to file, and constructing the request as: r = s.post(fullURL, data=file, headers=headers)
uh, what is data?
oh sorry
fixed it
I am still getting: TypeError: Object of type TextIOWrapper is not JSON serializable
I am using session from requests and not request.post directly, not sure if that makes a difference
right... like I said, stop writing it to a file
you can try reading in and storing the file content into a data structure, and then use the data structure to output to JSON through post method
you may have to use a dictionary or list and not a variable to pass through json.dumps(). not sure what the data looks like though
hey guys
I wanna build react native app using backend
In order to do so, I need to use rest api
is it possibe to make my pc as my server and make my Phone to send data like when im not in my house network?
you may be able to provision a server on a smaller cloud platform for free or minimal cost (and less hassle)
check out heroku or pythonanywhere
AWS has free tier for 1 year
the direct answer is: yes, port forward from your router to your computer and leave your computer on whenever you want to hit it from your phone
even better :d
thats great, tnx!
so all I need is to send it to my router in a specific port?
send what?
the request from my app on the phone
yes
gotcha, tnx again
@gray gyro the above is not true exactly
you need to configure your router to do this
pyscript looks nice
i'm gonna try to do an app in flask and one in fastapi
just to see
i think i'm gonna like fastapi tho
Hii, Idk if it is the correct channel to ask the question, so correct me if I need to ask it somewhere else. I have been learning and doing backend development in python for sometime and have done some projects. Currently I am looking for some new challenging project ideas which can teach me advanced topics in backend development, beyond web server and CRUD operations. All the project ideas on the internet are basically building a CRUD app, which is quite boring for me now. So, can anyone suggest me project ideas which can teach me advanced backend topics and are quite challenging?
are you using flask, django, or fastapi Light?
build a bug tracker to track your project bugs
but i guess thats a crud app lol
thats what i'm doing next
because i have so many bugs.. lol
I am mostly using Django for big projects but if I just need to build lightweight APIs, I go with flask
nice, but yeah as you mentioned it's a CRUD app
I think Ima learn Flask first, Django is too much of a headache
but I can do mostly the same stuff in Flask like I would do in Django right?
webapps, db handling, logins etc
Yes but Django is way better. By learning it you could actually land a job while by learning Flask you gain nothing
Except time if you want to make a non complex app
I already got a job, Im not looking for programming job I just want to make few websites for personal use
for example one project I want to do is Tracking peoples work hours so they can go in, write how many hours which day
and later I can export it and check how many hours everyone was working this month, on what projects etc
from what I've understood, Django comes with a lot of prepackaged stuff while Flask is barebones and u can add stuff
Django has good support, good security etc. but
So Ive used both flask and django. Flask is easy but Django is a more complete approach to web dev. It will be hard in the beginning but when you kinda learn it it will be easy
mhm
I guess Django's structure
is hard to crack
while flask seems so much more minimalistic
I was making an app in Flask and then decided to remake it to Django and it was way easier
Django comes packed with a lot of easy to use login/registering methods. A ready to use db etc
well yes I guess if I learned the stucture of django it wouldnt be that hard
Flask was way easier to understand. The routes where easier to create.
If you understand this all the othef will be easier than flask
and what was harder to do in flask ? the login/registering ?
hmm aight gonna go with your advice, but do you have any good source just to learn the structure itself
cuz thats the biggest problem for me, making a map of how everything connects in django project
gotta look for some cheatsheets maybe
Yes i have a very useful tutorial series
Its Called Django Wednesdays
I understood everything very easily
allright, gonna watch it
I didn't make the app that he did but the guy explained django so well that i was able to make my own up without creating his
Hello, I create User model in Django, but is possible create useful login system with custom User model?
hello there 🙂 currently im implementing backend in faspapi. I dont seem to find docs on faspapi website. Does any of you know where to find the docs for fastapi ?
The first result on Google with a search of "fastapi docs"?
not that easy
https://fastapi.tiangolo.com/ but there are only code examples. no real documentation :/
FastAPI framework, high performance, easy to learn, fast to code, ready for production
You mean you want an API reference? Ah
The intro and advanced user guides are pretty good. But I don't think I've ever come across anything more granular than that
man sad life, this means that at some point i will need to read source code 😄
Seems that Tiangolo rejected a PR to include some auto-generated docs a few years ago which seems a bit odd
yeah, the more i read, the more i come across the criticism of the author
dude seems to be not so open minded
What kind of documentation you need? Fastapi docs cover nearly all aspects of it
heey guys, is there any way in flask to add header with some links to pages in all posts
??
it looks like there are few options here - https://flask.palletsprojects.com/en/2.1.x/api/#application-object
Is it possible to use pyscript to run a "voice recognition + speech to text program" on the front end?
do you mean http headers or headers element in HTML?
Any recommendations for cheap shared Linux hosting for Django projects? Prices I see are ~$15/mo unlimited. I'd like to get something ~$10. No real traffic.
I don't really want 'free' options. Just cheap 🙂
Aah i have fixed it
Can someone try and help me in #help-chili if you can, it's about web browsers and stuff like that in python.
DigitalOcean can host apps at $5/m. Vultr has VPS at $2.5/m. Not sure how easy or possible you can put Django in Vercel or Cloudflare workers
Hmm. DigitalOcean is a virtual machine. Droplets also have metered charges, no?
so you get cut off
no?
they have something called "App Platform" - https://www.digitalocean.com/products/app-platform
they have a Django sample for App Platform - https://docs.digitalocean.com/products/app-platform/languages-frameworks/python/django/
Is this what you're using?
I use several things, that's one of them 😅
Ok. Currently I have shared linux hosting, but it's php and doesn't support python. I'd like to be able to put a public project up, so that's easy enough with this. But in addition, I host my git repos. Do you get SSH access to your space on DO? Can you make sub-domains, email accounts like you can with that ol' warhorse cPanel?
Hello, how different the code would be for an API/website that serves few users vs a lot of users?
no SSH access to App Platform. Yes, you can setup subdomains to your Python/Django apps. Emails accounts like cPanel, I don't think so, unless you add an additional layer which I don't know which it is
is django wednesdays by codemy?
yes
Thanks for the info. I've found a few shared hosts who purport to offer python app hosting, bigrock.com, mochahost.com, icdsoft.com to name a few. Most of these are LAMP stacks which have added Python.
I use flask, and I extend a file which contains the footer and the navbar and my issue is: in a html page, I have an animation for everything but want to leave the animation out for the navbar and the footer: What would I need to do in the css? I tried to giving the navbar and footer an id and doing :not(Id), but that didn't work
Ping me on response please
you could put a div around the part where you do want the animation running and run the animation for that id/class
Hello, is somaone here able to help me with something regarding web scrapping using lxml?
My problem is that I get empty lists
can someone help me host a site? i did 90% of it but its not working for some reason
where are you hosting it
thats true, thanks!
frontend on netlify backend on heroku
Can anyone tell me how to implement the built in plugin supports for PyQtWebEngine, with the Pepper Plugin API, how would you make a plugin, how would you add them to your PyQt Web Browser and how would you make an extensions GUI button for removing and disabling plugins? I found some documentation, I how this can help some of you guys to at least make it a bit easier to help me: https://doc.qt.io/qt-5/qtwebengine-features.html#pepper-plugin-api
hey how do i input data in an empty array that I want to be a multidimensional array
for (let i = 0; i < seats.length; i++) {
let table_rows = 4;
let table_col = 2;
let table_input = 2;
let seats_new = [];
for (let z = 0; z < table_rows; z++) {
for (let j = 0; j < table_col; j++) {
for (let k = 0; k < table_input; k++) {
seats_new[i][z][j][k].push(seats[i])[0] ;
}
}
}
}```
i did this
it does not work
#bot-commands
Hi there, I'm building an API where users can register on the website by providing data like email, phone, and password.
I wanna check if the phone number is valid or not without using any 3rd party, I found this JSON file:
https://gist.github.com/anubhavshrimal/75f6183458db8c453306f93521e93d37
but doesn't provide the phone length for every country, as well I have no idea if should I check for only the length or if there is other stuff need to validate.
so is there any thought on how can I accomplish this?
can someone help me with some javascript
I usually use validate-js on frontend for all validation, so you could maybe look through their source and see how they do it, and implement it on the backend: https://github.com/validatorjs/validator.js/
Here you can see they use regex to check
thank you
Where do you guys think I can find a tutorial of webdev with raw python and html ONLY? as in, no frameworks or libraries
theres pyscript (a library), which allows use of raw python inside of html but its new. it could be doable for a small web app or site
other than that, I'm not sure you can do web dev with python without any libs or frameworks
if you are open to frameworks, might i suggest FastAPI for its ease of use
You can, but it's not really practical, as Olivertwist said - FastAPI is a nice choice for backend, if you don't want to use js frameworks you can use backend rendering with Jinja2
Hi there, I have an off-topic issue, related to gatsby, can anyone help me?
got some django related issues, #help-rice message is the question
in #help-rice feel free to @ me at any time about it though
hi
e
e
Do not needlessly spam - if you have a question, send it right way. No need for introductions or single-letter messages.
this is my question-
and if that's it, then you will have to be more specific.
@lunar wagonerror is it is not updating results.
everytime i have to close port and create new one again and again
The best way to ask questions is showing your code
its technical UwU
not code related
We have no context, what server, what it's doing? We can't help you since we're can't read your mind
Did you mean "live server" in "visual studio code"
live server an extension for vs code
me neither
zad :(
Did you save your file?
yes UwU
Don't ping random people ...
hes helper know :/?
Ok... I don't know why if that's all
If someone wants to help you they would
ok
🥲
Live server will inject some JavaScript code to your document
Did you see them?
and there will also be some network activities when you modified your file
are they working?
Our team mostly writes apps in Django.We recently bagged a project where we are creating all front end assets in ReactJS as a mix of SPA and PWA app.
The application talks to a vast bunch of APIs from six to seven vendors and other apps, and interacts with front end.
Normally these kinds of applications should have an ExpressJS NodeJS for doing all API calls ( store tokens etc). However all hands are occupied with ReactJS (steep learning curve), and only Python Django developers are around who is free. We estimate we can cut down development time by half with Python team, over ExpressJS/Node (more a question of experience and skills rather a comparison of frameworks).
However customer’s consultant points out that Django is relatively slower because of vast number of middleware compared to ExpressJS. They feel a lighter framework may maker sense.
I am not a huge believer in benchmarks, but I know there is some sense in some of that wisdom.
If we are having a Load Balance(AWS ELB) and which redirects to multiple containers with Nginx/AWS Cloudfront hosting ReactJS app, and a Python application(Django or something else), what are the concerns we need to think about.
My other question is, is Django really that slow? We have no reason in our 8 years experience to think Django is slow, but we have not build something of this scale.
Second, if we use Blacksheep (https://github.com/Neoteroi/BlackSheep) or FastAPI(https://fastapi.tiangolo.com/) are we likely to expect any challenge.
The project per se, does not require any of the bells and whistles that comes with Django. There are no templates, no database, no other magic. It is just accepting requests, some amount of sanitizing of the inputs, some minor calculations, and then API calls to external APIs with requests library accept the results, do some minor calculations and regenerate a JSON Response.
Kindly advise what is the best way to go?
I wouldn't say django is slow, but i recently found it's harder to work with compared to fastapi
Benchmarks clearly puts Blacksheep ahead of FastAPI. Any experience with that
Hi.
I'd like to create a dropdown for an input field that queries the database and returns the top 10 available elements (there are a ton of elements so only the first 10 would be enough), and every time a new character is added to the text, it refreshes the dropdown list accordingly
is there some javascript thing I could use for this? and if not, can someone help me write it? I'm not very good with JS
I don't have any experience with blacksheep, but it seems to have less features than fastapi
Hm, actually it has di, openapi generation and other features, i wasn't aware of that 🤔
It looks it fits well for our requirements, does not it ( check original thread)
If your team has experience with python and flask-like frameworks using either of them (fastapi or blacksheep) wouldn't be that hard
Also i think speed shouldn't be your main concern, ask your developers which tools they would want to use
Speed is a concern! There are tons of APIs, and there is a large number of users
There's only 20% difference between these, also it would still depend on your code
I am comparing Django v/s Blacksheep/FastAPI
Choice is between them
Well, django would probably be slower, also i'm not very fond of it's ORM
Point here is we don't need ORM, Templates and other Django stuff
This is a pure API driven app. All the other stuff are on React
You'd need some sort of database still
Not really
People mostly use ORMs on top
Backend is a mix of applications written in various other frameworks, and we are on a microservices architecture
At most I may log something into a database
we may as well use Redis or Mongo there instead of an RDBMS
Even Users are coming from a CRM application which is external
Even if we end up using any DB it will be having very minimail tables
Yeah, FastAPI or Blacksheep would be fine, SQLAlchemy is you need an ORM
You could also try some of the graphql frameworks, but they'd be slower
But it depends on your data
All data is coming in JSON
graphql is storage agnostic (you can use any data source with it)
If you data is highly relational you might find it easier to use graphql
But it seems unlikely in your case
Not just that, customer is an enterprise, there are limitations with new tech we can introduce
how can i do this by drf
Password reset will redirect to a new page to enter the new password and it should show me a form where the user can enter his new password and take token and uid64 id from the url and sent it
can we add custom html pages
on drf
;-;
REST API would likely be perfectly fine too
All are REST APIs
Anyway, just choose between FastAPI/Blacksheep
Sure
No reason to use Django here
Wait, I can? Where do you think I can find tutorials for that kinda thing, I wanna develop a web framework of my own from scratch.
Using python and html
and a few other tools and languages I won't list
So, yeah
I was bored today, so I added controllers to fastapi.
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi_services import ControllerAPIRouter, get
router = ControllerAPIRouter()
@router.controller("/hello", default_response_class=HTMLResponse)
class HelloService:
@get()
def hello(self, request: Request):
return f"Hello, {request.client.host}!"
app = FastAPI()
app.include_router(router)
curl -XPOST -H "Content-type: application/json" -d '{"name": "catty mcCatFace", "price": 5000, "breed": "bengal"}' '127.0.0.1:5000/add'
what's the translation of this command to window
If you want to develop your framework from scratch you probably won't find any tutorials for that
You'd have to do some research
powershell has curl aliased to its own invoke-webrequest
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-7.2
The Invoke-WebRequest cmdlet sends HTTP and HTTPS requests to a web page or web service. It parses the response and returns collections of links, images, and other significant HTML elements. This cmdlet was introduced in PowerShell 3.0. Beginning in PowerShell 7.0, Invoke-WebRequest supports proxy configuration defined by environment variables. ...
windows powershell , for pycharm terminal
need more help with django in #help-mango cos im stupid
99% of us are stupids mate, don't take it personally
how to learn pyscript
I made it so you can add dependencies to controller classes
from fastapi import Depends, FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi_controllers import ControllerAPIRouter, get
router = ControllerAPIRouter()
class HelloService:
def get_hello(self, name: str = None):
return f"Hello, {name or 'world'}!"
@router.controller("/hello", default_response_class=HTMLResponse)
class HelloController:
hello_service: HelloService = Depends()
@get()
def hello_world(self):
return self.hello_service.get_hello()
@get("/me")
def hello(self, request: Request):
return self.hello_service.get_hello(request.client.host)
app = FastAPI()
app.include_router(router)
the get() functions are basically being resolved to ```py
def hello(request: Request, hello_service: HelloService = Depends(), _controller: HelloController = Depends()):
_controller.hello_service = hello_service
return _controller.hello(request)
I think there were libraries that would provide class-based views/controllers for fastapi already?
How do I avoid using multiple/nested ifs in flask? I use it too much to control the flow. If x, go to this page.. etc
I don't know how it's work in flask, but it's easy in fastapi. Maybe it's good reason to move to fastapi. https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/
FastAPI framework, high performance, easy to learn, fast to code, ready for production
I Google it and found that flask have Flask.before_request or Blueprint.before_request, maybe it's what do you want
Hey guys
Can someone help me
How to check if one datetime obj is greater than the other?
just use a comparison operator. For example, d_1 > d_2
Yes it's giving me error
Saying it can't be used with datetime obj
But anyways I found the solution and if anyone wants it here it is:
d_1._gt_(d_2)
It works same as:
d_1 >d_2
hello
this is my project structure
i get this error when i try to import a funtion from summarizer.py in run.py (Code/Summarizer_Server)
Hey VOID, have you forgot to import something? Excuse the vagueness
Btw are you Finnish?
No, just because i thought you typed something in finish as a reply to my say anteeksi message
aberration is my most valued skill
✋ 😔
It is weird, because it say that sumarizer does not exist in your project.
ye
I am pretty new at this can you explain what 5,m means on the ride side of the module name?
Hey Void should there be a dot infront of summarizer during the import stage
Can you show me the insides of the summarizer module, please.
Ok tx i only got a headache.
I think that the answer is hidden in the error message. What do you think VOID?
Well, look i probably cannot help, but just keep trying to figure out the error message.
My advice for the swiftest path to the solution
🌸
Is there a chance that the order actually matters during the execution. Meaning what if run needs to be placed lower than summarizer in the structure of your project. The logic is that because in pycharm if you define a var on lane 11 let's say we cannot call it on line 7, it output var [name] not defined.
Will this be helpfull? https://pytutorial.com/how-to-solve-modulenotfounderror-no-module-named-in-python
@magic nebula
.
where
I need help with relative importing in python. This is my directory structure.
https://cdn.discordapp.com/attachments/366673702533988363/973166347930456134/unknown.png
When I try to import a function from summarizer.py in run.py which are present in Summarizer_Server. I get this error.
https://cdn.discordapp.com/attachments/697134086614941706/973171897070149632/unknown.png
I'm having a little bit of trouble with url() in css...
I'm using a background image
background-image: url('./images/person.jpg')
}```
And this works fine when I start a live server in VScode, but not when I upload the css to my server. I'm getting a 404 not found, even when I use a direct url. Could anyone advise please?
which framework did you used?
Django
ooo
How much networking knowledge do you need for web-development ?
You need to be pretty comfortable with your understanding of HTTP/S, and understand the foundations of how DNS works - but you don't really require much beyond that
(although being comfortable understanding HTTPS pretty much requires you to have a basic picture of the OSI stack and TCIP/IP)
Hello, i am looking for someone who know about some company or project which are providing web form validation. Something like https://foxentry.com/
I need that for inspiration what all it can do. Or if you know how and what to validate with web forms. For example i can validate email syntax, checking DNS or MX record of domain ...
Do you have any idea how to validate a phone number, for example?
Thanks ❤️
It's very strange, because it's work for me. Which is error? Which is python version?
Python 3.10.4 (tags/v3.10.4:9d38120, Mar 23 2022, 23:13:41) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2022, 5, 9, 23, 11, 3, 806314)
>>> a = datetime.now()
>>> b = datetime.now()
>>> a < b
True
>>> a > b
False
>>>```
Static and Media roots and urls
thanks
bro thanks a lot
i did some google search
and it is working fine now
hello, i have a question
can i use django and mern stack together to make a website or application ?
Hi everyone
Not sure if this is the right place to ask - might anyone know how well BS4 works works with react?
hello guys i am having some issues with VUE js.
i would like to implement this logic of importing stuff into a div with innerHTML:
const element = document.querySelector('#post-request .article-id');
const article = { title: 'Axios POST Request Example' };
axios.post('https://reqres.in/api/articles', article)
.then(response => element.innerHTML = response.data.id);
in a custom function, something like this:
getHostDetails(event) {
this.toggle_detials = !this.toggle_detials;
this.hostdetails = this.hostresult[event.target.id]
const element = this.$el.querySelector('#hostdetails')
element.innerHTML = this.hostdetails
so hostdetails is an json object and i want to import it into a div with id hostdetails
But unfortunately, i am getting error:
Uncaught TypeError: element is null
i have tried to use
const element = document.querySelector('#hostdetails')
const element = document.querySelector('.hostdetails')
const element = document.querySelector('#hostdetails .hostdetails')
as well, but that gives me the same error.
do you have any idea why queryselector not work ? in the <template> i have the line:
<div v-if="toggle_detials" id="hostdetails" class="hostdetails">
<p>host details.</p>
</div>
I think yes
when i type some text and then i hit the save button. I will have a link to share the text with others. How do I create a link? i use flask
What kind of contents are you sharing?
Is it related to social media?
Only text
Hi, I am debugging django source code
In django ORM it call set_group_by() function and after that the query SQL has changed.
There are many ways to do that
You can try to save them in a github repo and get the raw file
Here is an example
Or you can manually generate the url
Make new urls on your own project
I mean i want to build the web app to type text. I can save this text and share by link.
But set_group_by only modify self.group_by
when is query changed?
I use flask
This might help
You use this to generate urls and you use python files to create them in your code base
Hi guys, I have a problem.
I have these URLs.
When I try to pass the data I don't get the result.
await axios({
method: "post",
url: `${API_URL}/api/auth/login/`,
data: {
email: email,
password :password
}
}).then( res => console.log(res.data.key))
If I do this in Postman everything works well.
Thanks.
urls:
path('api/auth/', include('dj_rest_auth.urls')), -> path('login/', LoginView.as_view(), name='rest_login'),
what is the response in browser network?
nothing, I just don't get the key.
I think you dont understand what I mean. Look this https://developer.chrome.com/docs/devtools/network/
when i click run. text saved and we have link for share. belike ideone app. i don't know how to do this
The issue was that i used conditional rendering (v-if). and when it was not rendered it could not find it....
What in console?
i use it like this
myPost(){
axios.post(`${API_URL}/api/auth/login/`, {
email: email,
password :password
}).then(result => {
console.log(result.data);
this.myresult = result.data
}).catch(err => {
console.log(err.response.data)
})
}
I will try it
ye if error occurs, just show the console. maybe you have problem with CORS
do you use await or something like that?
no i dont use await i just use it like i posted. i newer tried it because i did not have to.
@gusty sky i get this error:
Web developement vs app development which takes more time to learn ?
@gusty sky do you have any tips?
depends on your starting point. If you've never touched a computer before, then app development is probably faster is my feeling.
how do i implement csrf protection on single page applications?
i have this login and register system in django rest framework
and um
well
it feels pretty bare bones
i wanna do more for the csrf protection
and so
i looked online
but didn't really find much useful stuff about it
is someone able to explain to me exactly how I can change my router to connect to the receiver in a different place than before?
hey guys, im learning django and in a tutorial the guy said templates arent used anymore, but on the other tutorial, half of it is spent on templates
what do you think?
Templates aren't widely used anymore, people mostly build REST APIs for frontend frameworks to interact with
mmmm i see
When using Django forms, how would I specify that a field is disabled on the instance, rather than in the class itself?
hi, i have a few questions
one) can i use fastapi and flask/django/etc in combination with eachother?
two) how do i return the contents of an html file in either flask/django/etc
also ping me if you have an answer
Need some help again with Django in #help-burrito
hi everyone following this tut https://www.youtube.com/watch?v=dam0GPOAvVI can anyone explain when making the flask app after installation the error I get is AttributeError: 'NoneType' object has no attribute ‘run’ . Ive followed the tut how it is exaclty and have pip installed with flask (new here I apologise)
In this video, I'm going to be showing you how to make a website with Python, covering Flask, authentication, databases, and more. The goal of this video is to give you what you need to make a finished product that you can tweak, and turn into anything you like. We're going to also go over how you create a new user's account, how you store those...
tech with tim is a G
loool
do you find his github code even works? I downloaded the template to start but comes with errors
Hello everyone, happy to be here, been coding for a few years now, and this summer planning on building a huge project with some friends, mainly an innovative idea based on a website but it will change a lot in the industry, currently looking for some fellow coders that are confident enough to code quite high-level items with as coding partners , thank you, please DM me if you are interested.
Flask is nice
Fastapi is better
Blacksheep looks nice too
When should I name my JSX files .jsx/.js?
I'm new to React, just trying to figure out the standard naming conventions
If you use xml in it, use jsx
I recommend django instead!!
This is my personal django website
https://novfensec.herokuapp.com/
It gave me an extraordinary experience working with django
Myself Kartavya Shukla Welcome you to the newest era of code with this website as Novfensec.
can someone help me with html and some javascript
i can't find any full project flask on youtube. I need to know stucture folder, blueprint, migrate,... 🥴
Yes
hey, anyone got some good project ideas? planning to make a project with django & JavaScript/React but i cant think of anything i wanna make. Tried looking up some but had no luck.
Make a realtime chat app hosted on heroku with features like video calling, chatroom , conference chats etc.
i was just thinking of making a chat app 😂
although i dont know if thats too advanced for me or not
something like you create or join chat rooms
1 on 1 chat
I'm a django web development expert
If you need any help just ask me
thank you, that means alot
Hi guys i am having a problem with nested Links, which means that i can't define a Link inside of another Link. Here is my code. I don't know if there is another way to solve this.
Thanks.
just ask
Is there a way to listen for sqlalchemy errors and return a generic response, instead of having to do try, except on every route?
I have 20 or so routes, but I need to catch errors and return a 500, but I don;t want to have to do it on every route
depending on what framework you're using there probably is some way to handle specific errors. example: fastapi https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Hello folks, how can i fix the "Extension activation failed" error. Am using python in vs code. Using Django. Am using the WSL (Ubuntu) on windows
Hi, can someone help me loop a python code to scrape multiple pages? Single page works
yo man, sry i havent been here. Have u checked json object which u are sending ?
hey guys, im really confused. in my terminal i see the GET request but it does not load the page. can you have a look at this please?
the post request before and the payment_complete view is bein executed properly
did you check browser console?
some times seeing nothing is related to JavaScript errors that can be shown in browser console
what happens if you go to /thank_you directly?
page loads as expected. just did a workaround and included a redirect after the post send in js
but im still very wondering
did workaround work?
yes
Why are you nesting a Link inside of a Link? Won't the inner Link be inaccessible? As well, it appears you're just pointing it to the same location as the outer Link..
I believe you load "payment_complete" through js
In this case redirect will not work in browser
You should do redirection in your JS code then
Okay i see, thank you. I don´t get exactly why but it does work with redirect in JS
redirection work for your xhr-request, if you open network tab in devtools you will see it
while we are here, how do i make the redirect link dynamic? because '''actions.redirect("{% url 'order-complete-page' %}"); ''' ain't doing it
its missing the root of the link but how do i include it?
In js file or html?
in html but in script tag. so its js right
In html file it should work, try to debug it
don't know how to debut, i´ll just leave it static for now (: dont want to bother - thank you for helping
I don't know actually what "actions" means in your case. For built-in JS you can use window.href = "{% url '...' %}"
Error: Invalid redirect url: /thank_you/ - must be fully qualified url
thats what it says then
FASTAPI vs Django Rest, which is better?
depends on your use case
if you want an answer that is little better than random choice, FastAPI
i am trying to web scrape https://www.wolframalpha.com/problem-generator/quiz/?category=Calculus&topic=BasicIntegrate
Online practice problems with answers for students and teachers. Pick a topic and start practicing, or print a worksheet for study sessions or quizzes.
and im trying to get the image of the problem generated
]and save it everytime a new is made
for some reason i cannot find the correct place for where that image is located
the inspect elements code is different from the page source
Hello, in the FastAPI docs, i came across this code:
class User(BaseModel):
id: int
name: str
joined: date
What does the colon mean? Is the class storing some kind of dictionary?
it's type definition
I see it seems like the new standard in the industry
I see, but how does it inner work inside python, like syntatically
Colon is defining the type of the attribute. It's saying, that User has an attribute name of type string
i've been facing a issue from long time
that's valid Python code. Not sure what you mean
when i create any post from admin panel

