#web-development
2 messages Β· Page 216 of 1
Need a little help with my flask app structure, how do i handle flask login_manager when using blueprints.
inside app/init.py
app = Flask(__name__)
app.config.from_object(config.ProductionConfig)
login_manager.init_app(app)
db.init_app(app)
# register blueprints
register_blueprints(app)
return app```
How do use the login manager with each blueprint?
axios(
{
method:'GET',
'url': 'http://127.0.0.1:5000/get_user',
mode: 'cors',
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin',
'Access-Control-Allow-Origin':'*', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json',
"jwt": sessionStorage.getItem('token')
},
})```
https://github.com/Wizock/fluantt-old carefully go through this repo
This is called fluantt. Read the README.md. Contribute to Wizock/fluantt-old development by creating an account on GitHub.
its my personal flask structure
even after i added the jwt header, its still not accepting the valid jwt
so what's the issue here? cors or jwt?
its either, if i remove the jwt rquirement its cors
if i add the jwt requirement its jwt
im thinking of abandoning jwts but i really want this to work
lets try cors first, because the request was never being sent
yep
app = create_app()
cors = flask_cors.CORS()
with app.app_context():
oauth = OAuth(app)
cors = flask_cors.CORS()
db = SQLAlchemy(app)
jwt = JWTManager(app)
from backend.models import _localuser
guard = flask_praetorian.Praetorian(app, _localuser)
db.create_all()
arent you supposed to do something like cors(app)
def create_app():
appvar = Flask(__name__)
appvar.secret_key = r"33pay9V7FYhHGpZOO_-KOOTS6saVUI-Si6tZKPQiuSvQk8Y9CBt8yatkIgNd1CkW2_tukyn6VfdNba67_h0PgO0vbvk2A2BSlPE6K1c4OFM_cPwHCIH_7HxI_MqUbBpVuds9dVHAfxH-fzGXo_rc-B7KJNciaI6H3ktNB_Zn_Xw"
appvar.register_blueprint(auth)
appvar.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database/todobutbetter.sqlite3'
appvar.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
appvar.config["JWT_SECRET_KEY"] = str(r"mIckCdpWcu75jCe6db8qLV9glgNVeoxQVKaFoZKtgE9AQwGEjHTsQZJkCWLnvs4JZzock_Gu4-1pqXCBlSVRr_pfIn64YhYShAGIidVwW-XOrYv3L9SYjnaBUl0CGq9zDKZLN1jrxQdgvW3JrRjTOD2BvvhQv31SvCjtBEC2vgw")
>>> CORS(appvar, resources={
r'/*': {
'origins': '*',
'methods': ["OPTIONS", "GET", "POST"],
"allow_headers": ["Authorisation"]
}
})
appvar.config['CORS_HEADERS'] = 'Content-Type'
appvar.config['SESSION_COOKIE_NAME'] = 'google-login-session'
appvar.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=5)
appvar.config['JWT_ACCESS_LIFESPAN'] = {'hours': 24}
appvar.config['JWT_REFRESH_LIFESPA'] = {'days': 30}
return appvar
well?
i dont see this anywhere in your code
im actually gonna cry
app = create_app()
with app.app_context():
oauth = OAuth(app)
>>> cors = flask_cors.CORS(app)
db = SQLAlchemy(app)
jwt = JWTManager(app)
from backend.models import _localuser
guard = flask_praetorian.Praetorian(app, _localuser)
db.create_all()
Hee guys i try to learn Django π
I follow the following tut to create a login/logout page with a authenticated page for users π
https://learndjango.com/tutorials/django-login-and-logout-tutorial
But my page stop working after i added:
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('django.contrib.auth.urls')),
]
It gives error Name include not defined
i did it and it worked
ahhh
how am i so fucking braindead, i've been on this problem for like 3 hours
it happens
okay, well, do you know about flask-login?
nope i do it step by step
seems this is the default auth of django so
xD
the admin worked
but accounts/ later added
then stop working
aaah i see it π¦
path('login/', auth_views.LoginView.as_view(template_name='todo/UserCreation/login.html'), name='login'),
neeed to import this:
from django.urls import path, include
this is my main router
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('todo.urls')),
path('',include('account.urls')),
path('login/', auth_views.LoginView.as_view(template_name='todo/UserCreation/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout')
]
okee cool!
https://github.com/Wizock/TodoButBetter this is my repo for the django crud app i made
Hey quick question maybe someone can help me I created a dataframe from a list and I am trying to delete the header and the row number thing can't seem to do it?
is it pandas?
i've forgotten man, sorry, try to print it out and see the row number
Alright thank you!
hey man, sorry for the ping, but im finding out that the user isnt being logged in, im using flask_login
login_user(currentUser, remember=True)
print(str(current_user.is_authenticated))
login_user doesnt cause an error but the print statement is suppose to say True
why do they have different indentation?
nah
can i see the full route code?
@auth.route('/token', methods=['POST','OPTIONS','GET'])
@cross_origin()
def login_route():
if request.method == 'POST':
queried_username = request.json['username']
queried_password = request.json['password']
data = jsonify(request.json)
data.headers.add('Access-Control-Allow-Origin', '*')
print('feafwe')
currentUser = _localuser.query.filter_by(username=queried_username).first()
if currentUser and currentUser.verify_password(queried_password):
login_user(currentUser)
print(str(current_user.is_authenticated))
if currentUser.is_authenticated:
access_token = create_access_token(identity=queried_username, fresh=True)
return jsonify({"access_token":access_token}), 200
else:
return jsonify({"msg":"bad username or password"}), 401
if request.method == "GET":
return "You didnt post"
the most mind boggling thing is, after login_user(), current_user should be defined automaticaly
and if i do this
login_user(currentUser)
print(current_user.email)
print(current_user.email)
AttributeError: 'AnonymousUserMixin' object has no attribute 'email'
which is not suppose to happen, its not suppose to be undefined after i've logged the user in
where did you define your function to get the user object?
_localuser.query.filter_by(username=queried_username).first()
i mean for flask-login
from backend.models import _googleAuthUser, _localuser
from backend import *
import os, json, sys
login_manager = LoginManager(app)
login_manager.login_view = "authentication.login_route"
@login_manager.user_loader
def load_user(user_id):
return _localuser.query.get(int(user_id))
@login_manager.user_loader
def loadgoogleuser(user_id):
return _googleAuthUser.query.get(int(user_id))
why do you have two
the other one is for OAuth for future
but doesnt user loader expect 1 function?
should i remove it?
i doubt that effecting anything
i dont think so, i did this before in ssr
comment out the google one and tell me if it affects anything?
did it
it didnt change anything
AttributeError: 'AnonymousUserMixin' object has no attribute 'email'
dw its public repo
its _localuser
what's the anonymousUsermixin for?
i tried to put it in there to solve the issue
i think its used for storing information of individuals that arent authenticated
i see
your thing reaches the print statement right?
yeah
i put it below the login function because i wanted to see if the login function does anything
hmm, ok, so, i want you to try this, just create a route to test whether current_user exists, and when you reach the if statement, just redirect to that route and execute the print from there and see if that does anything
way ahead of you bro
@auth.route('/get_user', methods=['POST','OPTIONS','GET'])
@cross_origin(origin='*',headers=['Content-Type','application/json'])
def fetch_user():
return str(current_user.username)
that just returns anonymous mixin issue
is that what you were talking about it?
why not remove the anonymous inheritence?
i post information to login route, then return a jwt to react, react redirects to users route which fetches information returned by the /get_user route
which displays that error
i tried before and it didnt change anything
imma do it again and im gonna delete the database
i'm primarily done this using the cookie session way
how bro
csr?
it would have been no sweat if it was ssr
client side rendering
instead of server side rendering
if you render_template in flask then you're doing ssr
yes, i was using vue when i did that and it worked no questions asked
im telling you
with flask?
yes
wait, let me look at my repo
it's not public lol
how did you do frontend authentication
cos i just store the jwt in storage
and check if the token exist
i just made a route in the backend that verifies if a user is authenticated
anytime i did something that requires authentication, i check the route first
setUserSession?
ah okay
imma try to simplify my login
thanks mate
im praying that it works, im so tired of toying around with auth
wait
ok, yeah, i see my axios requests just have the xsrf options, so should be nothing to worry about
i should mention i didnt try this cross origin though
so you did html
Has anybody worked on Django framework to build a web app that can auto-generate audio from a given transcript and merging of video & audio to create a Spoken Tutorial??
ill do it anyway, im desperate
I need help pls DM
haha okay fine
and if its a public app, its gonna need some strong servers
well i don't think so
forgot i made somthing like this before lmao
import sys, time, pyautogui, wikipedia, os, pyttsx3, datetime, random, webbrowser, keyboard, smtplib
import now as now
import speech_recognition as sr
from requests import get
import pywhatkit as kit
from playsound import playsound
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
print(voices[0].id)
engine.setProperty('voices', voices[0].id)
# text to speech
def speak(audio):
engine.say(audio)
engine.runAndWait()
def takecommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("listening...")
r.pause_threshold = 1
audio = r.listen(source, timeout=20, phrase_time_limit=20)
try:
print("Recognizing...")
query = r.recognize_google(audio, language="en-ru")
print(f"user said: {query}")
except Exception as e:
speak("say that again please...")
return "none"
return query
query = takecommand().lower()
print(query)
you can just write the query to a file
Okay thanks
Anyone have an idea on how can I perform TRIM(LEADING '0' FROM somecolumn) in the context of SQLALCHEMY QUERY-API ? I can't find the appropriate function to do it such as
db.session.query(*some_query)
# [...]
.filter(func.lstrip(SomeTable.somecolumn, '0') == some_variable.lstrip('0'))
# [...]
i was naive, login_user aint working, why would your solution work xD
im gonna be so pissed off if its a python issue
yeah, idk then
did you do this?
this is the repo
its not for public though
its really messy and unintuitive
fucking auth isnt even working whats the point making a readme
go to API
its login.py
and then
from backend import app
from backend.API.login import *
if __name__=="__main__":
app.run(port = 5000,debug=True)
i see
okay
i commited a change, i put my login_manage.init_app(app) into the context loop
its giving 200 for the route you made
the /session
yeah, it's designed to always return 200 nomatter what
and it immediatly shat it self when i told react to get request /get_user
what happened?
AttributeError: 'AnonymousUserMixin' object has no attribute 'username'
it sent like 12 requests in a second
but nothing new in error
again, might have to remove the anonymous mixin
Hey I was wondering about running a python program every hour or so, I have found two possibilities:
1st: using the Time module
2nd: using the Schedule module
what would be the better way of going about this?
Nah, use cron (or a scheduled task on Windows if you must)
Is there a reason it doesn't make sense to use these methods? (Just curious)
Your program would need to stay running all the time and if it crashes or closes, you're out of luck.
Cron will run your program every hour and then your program can close and it will still run again the next hour
Oh ok, so it's better for stability and I guess resources as well, is that it?
True
Alright well thank you, that is very good to know!
Hello
I need help solving a problem
I created a game using flask and after the game finish running, I want it to start again.
Automatically, but I can't seen to get it done.
I created a new function after the original function that runs the game and then included the original function to make it run but it won't go through.
welp, just made a small app to test this and everything, even with cross origins, it works
must be something in your code mate
use an object instead with a reset function
basically a class
anyone have experience with django please help me
i need help to know how to edit cookies
I was wondering what would be the best way to go about checking if a dataframe is empty, I have found the function df.empty, however I am not sure if this is the best way to do this
Is there any blog/video in which they show us how to connect both django rest framework and next auth for email authentication using JWT? I found a blog but in there they show us using Google Authentication but I want Email Authentication!!
The blog I found: https://mahieyin-rahmun.medium.com/how-to-configure-social-authentication-in-a-next-js-next-auth-django-rest-framework-application-cb4c82be137
I want to add a menu bar to the top of my webs. How can I make Flask insert the menu bar to each page without having to rewrite the HTML for it each time?
use templates, specifically, a base template
with jinja2
What is the benefit of jinja?
It has interactive elements in it to add to the web page?
what do you mean? it's just the default template engine for flask
no, it has just templating language
so you could reuse components to combine final html
it includes syntax like
inheritance / reusage of base html templates
inserting values into the template
loop iterations over array / dictionaries
if conditions
pipeline data filter/processing
Basically it is a good language to transition from your backend language/like python into the having ready for render HTML
considering that it is used in a backend language, in order to change information in the page, you would need new request to server to change anything
unless you augment it with JS / Jquery / or even straight including frontend library into it
it is possible to add frontend framework directly into the rendered backend page ;b
perversion, but possible
OMG so many scary words..
please someone help me π
https://github.com/Wizock/todobutbetterv2 i made it work.
i didnt know that flask_praetorian did jwts, and that it fetched the users
it all works perfectly now
i see
but why you using cors if you're allowing all domains?
cos for some reason, cors always makes a issue some how
idk how, so i just allow cors everywhere
defeats the purpose
how
you're basically allowing requests from any url to your server
CORS is there to prevent that
they cant really do anything
the main route that exposes information requires jwt
which idk how tf to protect rn
and other routes are just used for normal usages
i see
CORS is a client side thing. You can't just ignore CORS preflights if you want browsers to talk to you.
how would i create a simple input output with a button on a webapp with django/python?
what do you mean by that?
hey, im getting an error when running a python program that scarpes crypto coins prices
can someone help?
textfield input
i input something
click the submit button
the python program performs an operation on it
and displays an output
sounds like a post request to me
huh
hi, kinda dummy question. i have bootstrap textarea on my web, and i set custom width to it. and now i need to center it, but nothing works for me. thanks for help
<div>
<form action="", method="post">
<div class="form-group w-50">
<textarea type="text" class="form-control", id="exampleFormControlTextarea1", name="input", rows="3", placeholder="something"></textarea><br>
</div>
<input class="btn btn-primary" type="submit", name="submit_thing", value="send">
</form><br>
</div>
is this a post request?
part of the process
how can one access the information entered into the form, which variable is it stored in?
add a route with a post method
it must match the action route
then use request from flask
this is in django
yeah, then idk, i dont use django. just google how to handle post requests
ok - what is the use of javascript in websites? ive never really understood its purpose
it does a lot of things
i can't really summarize it in a sentence
for example, interactivity
dynamically changing content etc
it's a lot
but cant changing the content of the page just be done with flask/django without using javascript?
with django or flask, it produces static content, in order to change it, you need to reload the page etc
with javascript you can alter something without reloading the page
ok
bruh
pls help
django
BRANCH_CHOICES = (
("CIV", "Civil Engineering"),
("COMP", "Computer Engineering"),
("ELCL", "Electrical Engineering"),
("ENTC", "Electronics and Telecommunication Engineering"),
("IT", "Information Technology"),
("MECH", "Mechanical Engineering"),
("AIDS", "Artificial Intelligence & Data Science"),
("AR", "Automation & Robotics"),
)```
these are the choices for charfield, can you suggest better shortforms?
?
so I am working on a project where I need to get and respond to webhooks from a service, what framework would you recommend I use?
I am thinking about flask, but wanted to know if there are better options.
the only thing the project needs to do is to:
1. receive some json via a webhook
2. connect to another api and pull some data (planning to use requests for that)
3. respond to the webhook with json data
when I use http://localhost:8000/ the page is not loading for me,it is keep on loading, whereas if I use the ip address the page is loading, how to solve this?
while using ip address
Check your code... Most likely you're allowing one and not the other
you mean allowed hosts
Yes
I have set as ALLOWED_HOSTS = ['*']
Try adding both explicitly
Does it even matter though?
tried but having same issue
yeah, because I am trying to login users through microsoft id,which isn't accepting the http
Is the redirect your problem maybe, getting in the way of your app?
The only other possibility I can think of is some strange DNS nonsense... Maybe try pinging localhost to see how it resolves
how to remove values in the data?
[{'values': {"id": 1, "name": "sam"}}]
expected output
[{"id": 1, "name": "sam"}]
please help
val = val.values?
django
CLASS_CHOICES = (
("FE", "FE"),
("SE", "SE"),
("TE", "TE"),
("BE", "BE"),
)
BRANCH_CHOICES = (
("CIVIL", "Civil Engineering"),
("COMP", "Computer Engineering"),
("EL", "Electrical Engineering"),
("ENTC", "Electronics and Telecommunication Engineering"),
("IT", "Information Technology"),
("ME", "Mechanical Engineering"),
("AI&DS", "Artificial Intelligence & Data Science"),
("AR", "Automation & Robotics"),
)
DIVISION_CHOICES = (
("A", "A"),
("B", "B"),
)
class StudentProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
class_ = models.CharField(max_length=2, choices=CLASS_CHOICES, default="FE")
branch = models.CharField(max_length=5, choices=BRANCH_CHOICES, default="COMP")
division = models.CharField(max_length=1, choices=DIVISION_CHOICES, default="A")
roll_no = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1)])
created = models.DateTimeField(auto_now_add=True)
class Meta:
unique_together = ("class_", "branch", "division", "roll_no")
ordering = ("-created",)
def __str__(self):
return f"{self.class_} {self.branch} {self.division} {self.roll_no}"
I need to let students add multiple subjects to their profile which can be done by m2m field and Subject model and each subject should have multiple class_ and branch, how do I accomplish that? I am thinking of creating a model for class_ and branch but having a model to represent first, second, third and fourth year seems like not the right way to do it? alternatively I think I can use django-multiselectfield for the class_ and branch in Subject model, what do you suggest?
Can anyone share an example of FastAPI/uvicorn chat? :)
Hi, there!
I have trouble finding a pattern that matches className=id pairs one or more times. For now, I can capture just a single pair className=id using variable-resources mechanism provided by the python package aiohttp.
I have tried {{className}={id}:.+}, but it just doesn't work.
import
app.router.add_put("/{className}={id}", my_handler) # just capture a single className=id pair and it works
app.router.add_put("/{{className}={id}:.+}", my_handler) # wana to capture one or more times className=id pair but it failed
should I just create class and branch models?
Can somebody look at my django problem at #help-chili ?
i need some help
yooo, i have nooby question. in my web project i need to send mail, but for that i need store password from that mail in my code. i know about enviroment variables, but tutorials online kinda succ. thanks for help :)
umm hello
i need help in starting off web development, well what i want is to try out networking things but i myself am not sure if 'web development' is the correct term for that
even so i need help in kickstarting this networking / web development
like i need general theory unrelated to specific programming lang, but general concept and all
and lastly like i want to set up a client-server setup (the only meaning i know of this is: like sending messages/data between server and clients) -> and like i just need something to start off with
Take look at this, might be what you are looking for https://fastapi.tiangolo.com/es/advanced/websockets/
FastAPI framework, high performance, easy to learn, fast to code, ready for production
@Astro^^#8349 use help channel first
hmm
Hey guys I am using 2 flask app with docker-compose. I have build both images but when I try to do docker-compose up I get this
Starting gunicorn 20.1.0
gameplay_1 | [2022-02-12 13:49:13 +0000] [43] [INFO] Listening at: http://0.0.0.0:5001 (43)
gameplay_1 | [2022-02-12 13:49:13 +0000] [43] [INFO] Using worker: sync
gameplay_1 | [2022-02-12 13:49:13 +0000] [46] [INFO] Booting worker with pid: 46
gameplay_1 | [2022-02-12 13:49:13 +0000] [47] [INFO] Booting worker with pid: 47
gameplay_1 | [2022-02-12 13:49:13 +0000] [48] [INFO] Booting worker with pid: 48
gameplay_1 | [2022-02-12 13:49:13 +0000] [49] [INFO] Booting worker with pid: 49
In both flask app logs what is error can anyone tell?
Docker-compose file
version: "3"
services:
api:
build: ./services/backend
image: flaskapp
ports:
- "5000:5000"
volumes:
- ".:/app"
entrypoint: ["/app/services/backend/remote_entrypoint.sh"]
env_file:
- ./.env
gameplay:
build: ./services/gameplay
image: gameplay
ports:
- "5001:5001"
volumes:
- ".:/app"
depends_on:
- "api"
entrypoint: ["/app/services/gameplay/remote_entrypoint.sh"]
env_file:
- ./.env
#!/usr/bin/env bash
cd /app/services/backend;
# Python dependencies
pip install virtualenv
virtualenv venv
source venv/bin/activate
# pip install --upgrade pip
pip install -r /app/requirements.txt;
gunicorn -w 4 -b 0.0.0.0:5000 --chdir /app/services/backend app:app
Hey guys, I'm working on a django project trying to create a forum.
Now when a user creates a new thread, I need to have a new html file created with a unique url.
For example if a user creates a thread with the title "What's the best programming language?" a new html file with some standard template has to be created (and a function in views.py as well as a path in urls.py) and the url should be something like "mysitetitle.com/what's-the-best-programming-language?".
That would be relevant code of my project.
def create_thread(request):
form = CreateForm()
if request.method == "POST":
form = CreateForm(request.POST)
if form.is_valid():
f = form.save(commit=False)
f.benutzername = request.user
f.save()
messages.success(request, "Thread has been created.")```
create_thread.html
```html
{% extends "forum/index.html" %}
{% load static %}
{% block title %} Create Thread {% endblock %}
{% block content %}
<div class="container-create">
<h2 class="heading-create">Diskussion erstellen</h2>
{% if messages %}
{% for message in messages %}
<div class="thread-info">{{ message }}</div>
{% endfor %}
{% endif %}
{% if not user.username %}
<div class="guest-login">As <span class="guest">Guest</span> or <a class="login-link" href="../login">Login</a></div>
{% endif %}
<form method="POST" action="">
{% csrf_token %}
<label class="label-create-topic" for="create-topic">Topic</label>
{{form.topic}}
<label class="label-create-title" for="create-title">Title</label>
{{form.title}}
<label class="label-create-content" for="create-content">Content</label>
{{form.content}}
<button class="submit-create" id="submit-create" type="submit" value="Create">Create</button>
</form>
</div>
{% endblock %}```
hey guys, i'm building an app and in a particular model i'm trying to load a font from the model so instead of an imagefield, i'm using an svgandimagefield but it keeps giving an error, this is the code.... The error output is: AttributeError: 'GoalForm' object has no attribute 'urls'
need help
anyone
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'pages'
so i have app
called pages
about django channels, is there a way to make it connect to an externally running socket?
than it waiting for a connection..
hey guys i want to play around with ar for the web, found three.js but i want to be able to move 3d objects overlayed on camera video in real time, any suggestions/material to give?
maybe go to #help-cake
or any other available help channels
https://docs.opencv.org/4.x/d6/d00/tutorial_py_root.html
I haven't used Open CV myself
object tracking is in there
you can build and opencv.js for the client
Looking for some guidance on Flask and Nginx logging. Where should I be creating the root logger to be called for flask, since Nginx is creating 5 separate PIDs?
Should this be in uwsgi_run.py program? Or should logging be setup in the init file with the rest of the packages?
It's slightly due to my lack of full understanding on how nginx/flask interact... as in, is nginx just creating 5 separate instances of flask all of which are going to be completely separate?
hey folks, i have a login authentication in flask setup to check username and password against the db > auth the user and redirect them to profile page - i also have an if statement which should redirect to profile page if they try to access login page manually but this doesn't seem to work - here is my auth code
@auth.route('/login', methods = ['POST', 'GET'])
def login():
if current_user.is_authenticated:
redirect(url_for('views.profile'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and bcrypt.check_password_hash(user.password, form.password.data):
login_user(user, remember=form.remember.data)
return redirect(url_for('views.profile'))
return render_template('login.html', title='Login', form=form)
I am following a Tech With Tim video to make a website, and I ran into an error.
It says it cant find run, and I have no idea what to do with it
I am using replit.com
You imported a function. If you want to run that function, just call it as a follow: app()
guys i should learn flask first or django ?
flask then django
although django has better backend
Can someone help me please? #help-donut
diff between client side scripting nd server side scripting
hi, i do not know if this is the place to ask this, but i guessed you guys do webdev, so you might know. Is there any way, system or protocol, to ensure backend code?
Say test.com publishes some code and says "this is our backend", is there any way to verify that?
I know there is no way the way usual web works, what im asking is if there's any sort of project or thing that attempts to achieve that
a sort of server transparency
say, maybe the server is on a transparent cloud vm that has public read permissions, or sth like that?
i can imagine a way to verify frontend js via a diff against a github or sth like that. Say you got a browser extension that performs these checks before running any js file
but what about backend?
I guess the maximum it is possible to check that endpoints in the code match the endpoints of a real server
The code should be showing which answers we are supposed to get for every end point
If those two things match, we can conclude, that highly likely it is code looking truthful to be a backend of the web site
mm but what if the code is doing something else?
say test.com lets me get into my bank account
We can't know for sure this
test.com returns me my bank account
how can i know it doesn't also save my password?
You can't
thats kinda my question
A matter of trust only, and what security audits by third party people they made
i know i can't the way we do things today
yep, thats a thing too, you are right
trusted third party audits
but what if they show one code for the audit and then run another after they leave?
lol
but why?
say, doesn't the js verification sound nice?
nobody does that today, but wouldn't that fix a bunch of mitm?
I don't get your idea
js verification should not fix anything
it is just a clientside part
anything can be part of backend
in the end the only thing we can usually check for sure, is making external security audit that they don't have security breaches by mistake
and use self raised open source software to be sure that it is what we asked for ;b
CLASS_CHOICES = (
("FE", "FE"),
("SE", "SE"),
("TE", "TE"),
("BE", "BE"),
)
BRANCH_CHOICES = (
("CIVIL", "Civil Engineering"),
("COMP", "Computer Engineering"),
("EL", "Electrical Engineering"),
("ENTC", "Electronics and Telecommunication Engineering"),
("IT", "Information Technology"),
("ME", "Mechanical Engineering"),
("AI&DS", "Artificial Intelligence & Data Science"),
("AR", "Automation & Robotics"),
)
DIVISION_CHOICES = (
("A", "A"),
("B", "B"),
)
class StudentProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
class_ = models.CharField(max_length=2, choices=CLASS_CHOICES, default="FE")
branch = models.CharField(max_length=5, choices=BRANCH_CHOICES, default="COMP")
division = models.CharField(max_length=1, choices=DIVISION_CHOICES, default="A")
roll_no = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1)])
created = models.DateTimeField(auto_now_add=True)
class Meta:
unique_together = ("class_", "branch", "division", "roll_no")
ordering = ("-created",)
def __str__(self):
return f"{self.class_} {self.branch} {self.division} {self.roll_no}"
field names must not end with an underscore, so what should I rename class_ to? cls, clas, classs or something else?
it would fix js though
well thats kinda my point
imagine a world where web services are what open source software is like
with oss i download the code, can read it and verify it (which i don't, of course, lol) and compile it myself
frontend can be fixed by just making a sort of protocol where websites publish their frontend and i can crosscheck the js file returned by the server against their own published code
that way (assuming the code publishing is secure) i can check that the server wasn't hacked and the js changed, and most importantly, that i didn't get mitmed
the second question is how to ensure backend code is what its published to be
one answer would be to have trusted third parties, say aws
and have a sort of public reading servers
if i trust aws, i trust that the code running in it is what i can see it is
of course this isn't enough, as i can't see what the interpreter/compiler does, but at least is a step forwards
can someone suggest a free of course web dev course 
Better than any courses
i don't wanna read a book
Freecodecamp maybe
anyone experienced with making a chat application?
i was thinking of making a discord clone
but don't know where to start
it would be really helpful if someone could guide me
what kind of technologies and concepts would i need to know beforehand to be able create something like this
Assuming you want this to be a web app, you'll want to know a JavaScript framework of some kind. React is the most popular but there are others that might be easier. If you want to avoid JavaScript maybe HTMX would work but what I know for sure is that a Python framework isn't enough to have an interactive frontend for web-based chat.
#help-chocolate first time trying to run a flask api in a ubuntu droplet. anyone experienced this before?
django
def is_student():
def decorator(view):
def wrapper(request, *args, **kwargs):
if request.user.is_student:
return view(request, *args, **kwargs)
else:
raise PermissionDenied()
return wrapper
return decorator
def is_verified_student():
def decorator(view):
def wrapper(request, *args, **kwargs):
if hasattr("student", request.user):
return view(request, *args, **kwargs)
else:
raise PermissionDenied()
return wrapper
return decorator
I have these 2 decorators, should I just merge them using a verified parameter?
Hello,
How can I use two user loader in my flask app because I have two different type of users in my website, first one is Student and second is Teacher when I am using user loader something just like this
@login_manager.user_loader
def load_user(user_id):
return Student.query.get(int(user_id))
It is using student as current_user and not teacher(of course it will not)
i have two different Models- Student and Teacher both having UserMixin in in them
How can i use two user loader.
I hope I am able to ask my question clearly, please ask if having any doubt or need more information
Can anyone help me with free domain name. I've student program in GitHub :)
https://desec.io/ use this
they give 16 free domains
Can you help me?
already did
hello darkwind see my question above please and help me
@ocean slate #βο½how-to-get-help
He guys I created a django project > in settings.py there static_url "/static/" but no folder was there so in top folder i created one. Placed it there but website doesnt give CSS back
I am using fastapi to do predictions on a ml model. Because a single prediction is taking more than 2 minutes I have made the prediction to run as a background task using fastapi background tasks. Now when i deployed to digital ocean i was unable to run background worker. I am getting 504: Gateway Timeout Error.
startup command
gunicorn --worker-tmp-dir /dev/shm --config gunicorn.config.py main:app
gunicorn.config.py
bind = "0.0.0.0:8080"
workers = 4
worker_class = "uvicorn.workers.UvicornWorker"
main.py
response = {}
async def predictions(solute, solvent):
mol = Chem.MolFromSmiles(solute)
solute_graph = get_graph_from_smile(solute)
mol = Chem.MolFromSmiles(solvent)
solvent_graph = get_graph_from_smile(solvent)
delta_g, interaction_map = model([solute_graph.to(device), solvent_graph.to(device)])
interaction_map_one = torch.trunc(interaction_map)
response["interaction_map"] = (interaction_map_one.detach().numpy()).tolist()
response["predictions"] = delta_g.item()
@app.post('/predict_solubility')
async def post():
return {'result': response}
@app.post('/predict')
async def predict(background_tasks: BackgroundTasks,solute,solvent):
background_tasks.add_task(predictions,solute,solvent)
return {'success'}
response_two = {}
async def predictions_two(solute):
for i in data:
delta_g, interaction_map = model([get_graph_from_smile(Chem.MolToSmiles(Chem.AddHs(Chem.MolFromSmiles(solute)))).to(device), get_graph_from_smile(Chem.MolToSmiles(Chem.AddHs(Chem.MolFromSmiles(i)))).to(device)])
response_two[i] = delta_g.item()
@app.post('/predict_solubility_json')
async def post():
return {'result': response_two}
@app.get('/predict_two')
async def predict_two(background_tasks: BackgroundTasks,solute):
background_tasks.add_task(predictions_two,solute)
return {'success'}
if __name__ == "__main__":
uvicorn.run(app,host="0.0.0.0", port=8000, reload=True)
I have added worker in digital ocean from components even though i am getting still server timeout. I am not sure whether i have not implemented background tasks using fastapi for is their any problem with my startup command
Any recommendations on a free translation API?
Hello, is anybody here?
Can someone help me understand how the logging dictConfig works?
I have a handler for wsgi, which is working, and I'm trying to create a handler for a different module, priority_bot, and I can't seem to figure out the relationship.
Does the handler name need to be the file/module name?
import logging
import logging.handlers
from logging.config import dictConfig
from os.path import join
def Config(logPath='/var/log/', logName='logs.log', logSize=1024000, logBackup=5, logDebug=False) -> object:
level = 'DEBUG' if logDebug else 'INFO'
dictConfig({
'version': 1,
'formatters': {'default': {
'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S'
}},
'handlers':
{'wsgi': {
'class': 'logging.StreamHandler',
'stream': 'ext://flask.logging.wsgi_errors_stream',
'formatter': 'default'
},
'priority_bot': {
'class': 'logging.handlers.RotatingFileHandler',
'maxBytes': logSize,
'filename': join(logPath, logName),
'backupCount': logBackup,
'formatter': 'default'
}},
'root': {
'level': level,
'handlers': ['wsgi', 'priority_bot']
}
})```
@old hound is this django framework or logging in general?
How do I add simple authentication to my web page to avoid unwanted random access? I.e. no registration required for now, just 1 login 1 password
this is with Flask @lament nest
@hard whale https://www.digitalocean.com/community/tutorials/how-to-add-authentication-to-your-app-with-flask-login
I use FastAPI, must be something like that
@old hound I believe the python documentation and examples are really detailed & will help you. https://docs.python.org/3/library/logging.config.html
@lament nest zzz it was dumb, issue was I wasn't creating the root logger before everything else, and didn't initiate root logger to DEBUG... I always forget that you have to create the root logger before you can create other handlers.
would like a little bit of folder or file naming "advice"
So on my website, I have another page that will list the tools, and other webpages that are on the site....
should it be "sitemap" ... or "browse" .. or... What? I've become lost lol
I have a html button with an onclick event that reads to javascript
I want that button to print to the server console not the webconsole
this is running on a python webserver
the way i access the html is with <ip>:<port>/<name-of-file>
is this possible?
hey guys how are you supposed to set a URL to flask?
so that when I do request.base_url, I get a url rather than some ip address?
ok
I think u need a domain
I do have a domain
Ohh, lemme see
Where u hosting it?
it works now thanks
hey enslo
would you also like to build a netflix for free?
best and simplest/smallest pure-python templating package?
Jinja2
there are no alternatives ;b
curious, why do you need exatly smallest
are you writing script that uses just templating?
for docker image
well, i've resumed work on https://github.com/amogorkon/justuse and there are complex exceptions i want to turn into interactive html
using brython and templating
since i need to ship things along, it should be small and pure python
presenting a list/table of sha hashes isn't exactly friendly on the terminal for instance
so i'm templating it into a table of checkboxes that produce a line of code the user can just copy&paste
two other things i need that for is the idea of an internal dependency graph
and with aspectizing to display/filter everything that has been decorated
all things that are very hard to present efficiently and human-friendly
wip scrapy, fastapi, docker, celery, etc etc project:
I appreciate this is js related, but it is on a django web app and I'm hoping someone has an idea. I'm using jquery and have the following:
<script>
$("#recurring_event").change(function() {
if ($(this).val() === "yes") {
$('#recurrence_pattern').show();
} else {
$('#recurrence_pattern').hide();
}
});
</script>```
and
```html
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<div id="event_name">
{{ form.event_name|as_crispy_field }}
</div>
<div id="recurring_event">
{{ form.recurring_event|as_crispy_field }}
</div>
<div id="recurrence_pattern">
{{ form.recurrence_pattern|as_crispy_field }}
</div>
</fieldset>
<div class="form-group pt-4 pb-2">
{% if page_type == 'Update' %}
<button class="btn btn-BlueGray" type="submit">Update Event</button>
{% else %}
<button class="btn btn-BlueGray" type="submit">Create Event</button>
{% endif %}
</div>
</form>
</div>```
Any ideas?
Can someone help me understand why I'm receiving this error?
Hey there! Can some1 help me, pls. Why django.utils.translation.gettext_lazy do not work with capital letter (app verbose_name)? And how I can fix that? (I have RU accept language)
UPD: if u face same problem, read about makemessages
self explanatory, querydict doesn't exist
I am in
can i ask a question about docker compose here ?
so i have this in my .dockerignore
# Django project
/media/
/static/
*.sqlite3
but the files are not ignored in the containers made by docker-compose up
version: "3.9"
services:
# db:
# image: postgres
# volumes:
# - ./data/db:/var/lib/postgresql/data
# environment:
# - POSTGRES_NAME=postgres
# - POSTGRES_USER=postgres
# - POSTGRES_PASSWORD=postgres
web_collectstatic:
build: .
volumes:
- .:/app
command: python manage.py collectstatic --noinput
web_migrate:
build: .
volumes:
- .:/app
command: python manage.py migrate --noinput
web_createsuperuser:
build: .
volumes:
- .:/app
environment:
- DJANGO_SUPERUSER_PASSWORD=${SU_PASSWD}
- DJANGO_SUPERUSER_USERNAME=bfportal
- DJANGO_SUPERUSER_EMAIL=superuser@bfportal.com
command: python manage.py createsuperuser --noinput
web_run:
build: .
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/app
ports:
- "8000:8000"
and do i need to specify volume and build for each ?
Hi there
i see specifying volume overrides .dockerignore in a sense
a little dated as usual but a helpful conversation on the subject
Anyone got hands on filtering dropdown bars?
Need to filter this, location depends on location group, pretty killing my mind rn.
ummm... context?
what is the go-to flask auth package? My udemy course has Flask-JWT but it hasnt been updated since 2015
Someone just recommended this, haven't tried it; https://www.digitalocean.com/community/tutorials/how-to-add-authentication-to-your-app-with-flask-login
It never ends.
But I felt proficient after about 2 years of personal projects.
Any ideas why I might be able to reach a website, but the data on a website won't fetch if I'm behind certain firewalls? On my work's public wifi, I can access my prod page but it won't fetch data or let me access the admin panel behind the firewall. @inland oak
It's been a 6 months i felt like that
i dont think this space if for advertising
@native tidehello, we do not allow recruitment
Perhaps u just use js features Which aren't supported in older browsers.
U need to have set Babel if u wish high support across many browsers versions
Latest js features, like promises and etc are rarely supported. Only by the latest browsers I think
With Babel, we make them supported by everyone
Babel transpiles into average old JavaScript(es5? π€ ) supported by anything
Work.. hmm. Which port do u use for APIs?
Some admins forbid everything, which is not 80/443 port in work networks
Perhaps few more ideas can be generated what went wrong, but honestly I am weak in networking stuff
Hmm that might be it. It's not the browser or the code because it works on mobile on my phone but if i jump on my work wifi, the site works give but the data doesn't fetch from the server..
Probably just blocking the server port
But then it's there a way maybe with nginx to route through 80 so networks don't block it?
Is funny because our private med center internet we use on our laptops, which is secured, doesn't block it. Just the open public wifi π
Django: Request method question...
Do I need "form" to make simple button that run some srcipts in Django template?
Nope, you can run an ajax request onClick that connects to an url that runs the function you want.
Hello <@&267628507062992896> ,
Is it allowed here to share project work? Please let me know.
@zealous tundra Sure, I'll ask him.
I've posted a question in SO (django web app - trying to conditionally display fields) here: https://stackoverflow.com/questions/71117716/django-form-conditional-field-display-using-jquery
This got answered. Turns out JQuery library was old, and the JS needed a bit of tuning. Also, crispy forms names elements quite nicely behind the scenes. Learning of this - learn how to inspect the DOM π
I am trying to use an api, but I have to get multiple endpoints in one request. To do that, I want to try to put an array of elements at the end of the api url.
For example: https:/example.api.com/users/{arrayOfUsers}
There are no docs on this api, thus I have to test it myself. However, I don't know how it would look like, so I would appreciate if someone could give me an example of an api with an array at the end.
I'm not very experienced with a wide range of APIs but I've never seen this. Maybe you could post a list, but if you don't have any reason to assume this is possible, I would assume it isn't
https:/example.api.com/users/{arrayOfUsers} was an example
I would just try sending a comma separated list of user ids
didnt work
Why do you have to get multiple in one request?
Because I am making a leaderboard with players data, and it would be too slow to get users' data one by one
And do you know what the API is accepting in the request? What it wants as an input?
Well, you still would be doing one request, but the API needs to return a list of the users' data - unless they don't have that setup.
they have very little docs so thats what I am trying to test if they have set up
Yea so it looks like they only allow one user at a time.
They don't have an option to return multiple users at once.
then the only solution for me is to do multiple requests and insert the data into a database and get the data from there
Yea but you can only do one request per 2 seconds, doesn't sound like that will work for you.
Yeah, but I can make the database update every now and then
Sure, yea I guess.
Might be better to just have a list of users, and when someone clicks on a user it fetches that users data.
Also, I tried doing multiple requests without a delay inbetween, and it worked without it taking 2 seconds
It works, but they can ban you. They are relying on you to throttle it.
Why dont they just have a mechanism that only allows a request to be sent every 2 seconds?
Ask them.
I guess I have to stick with a very slowly updating leaderboard
Oh well maybe they do throttle it. I dunno why it would work then, never used it.
Maybe you can email them and ask how to update more users at once.
adding a delay is just good etiquette isnt it ?
Seems that should be an option.
It is, yea.
They state that they dont help with programming. Or doesnt that fall into that category?
Yea but you can ask if they support an option to return a list of users' data versus one user.
You're not asking them how to get the data or anything.
they are prob gonna answer me in a month
Patience is a virtue.
did you try with just https://api.fortnitetracker.com/v1/profile/{platform}/ ?
whats the difference
don't include the {nick-name}
Ah crap.
Hi, anyone have experience with Oso, Casbin, or other RBAC solutions?
I'm looking for something that isn't explicity tied to Django ORM objects. 
The first two are very generic solutions and I'm wondering if there's anything else out there.
Ok, but basically it is required
What is?
Flask?
well, I'd be using Flask then.
Is FastApi better or django rest api framework?
I have heard django has a steep learning curve
So I am thinking to go for fastapi
I like flask for API, it is very nice and easy to use
go for fastApi
It implements the functions of the shopping mall site.
I want to print out the presence or absence of a shopping cart product, but there is a problem with branch processing.
I want to get help.π«
- Log in after accessing the shopping mall > Move your shopping cart.
- If there's no prize in the shopping basket...Pop-up output.
- If there's a prize in the shopping basket... Print print.
The shopping mall site is Coupang.
to where?
https://account.t-mobile.com/eui/v1/initSession
It implements the functions of the shopping mall site.
I want to print out the presence or absence of a shopping cart product, but there is a problem with branch processing.
I want to get help.π«
- Log in after accessing the shopping mall > Move your shopping cart.
- If there's no prize in the shopping basket...Pop-up output.
- If there's a prize in the shopping basket... Print print.
Please Help me.
hi, i was wondering if there was a python framework i could use to do my backends faster
if anyone is experience with this side of things please help, it would be awesome i am not "great at python" just ok.
Thanks!
Nothing is faster in development than Django
Python backend is...
- Flask 2. Sanic 3. Vibora 4. Japronto
- Falcon 6. AioHTTP 7. Tornado 8. Django
It might be the case.
First of all, "Django" is popular all over the world.
But please pay attention to other languages.
Even if we consider all other languages, still valid phrase
Python is the highest level language that sacrificed everything for faster development and more readable code
@inland oak I don't think I can deny it.
I'm sure you all understand with this image. π€ (lol)
When I submit a text entry from a webform to my Python's Flask server, a different page /results page doesn't get shown (which I expect it to do)
When I do submit the form data over, I am proceeded to a page but I get the following message displayed on the screen: Method Not Allowed The method is not allowed for the requested URL.
hey
After creating code for a website, if you buy a domain name, how do you link your code (in the server) to the specific domain name?
You need to point your domain to the ip hosting the server.
Probably. Read the documentation for those sites
Though you might be limited to static html
does javascript make websites dynamic? thats what ive heard
Yes. To a degree
so in that case if you have html, css, js, why need a backend like python with django/flask?
if the logic can be done with javascript
i am learning django, and how i see the website is by typing python manage.py runserver in the terminal which gives a x.x.x.x:x link that i click on to see my website
however if you dont use a backend, how do you view your website?
Most frameworks have a web server builtin
yes but if you have a html and css file only? no django framework - how would the website be viewed?
Apache or nginx
There's plenty of web servers to use.
Your web host may choose for you
what is the differences between redux &react-redux&redux/toolkit?
after a 15 second search, react for js components , redux state container
i didn't ask for react itself i'm asking about redux and its variety
when and where should i use redux and when use react-redux
or redux/toolkit
I know that redux/toolkit it's the recommended one but i still see a lot of programmers use redux or react-redux
you're better off asking in a react js server
We're a large, friendly community focused around the Python programming language. Our community is open to those who wish to learn the language, as well as those looking to help others.
on that page is a link to some other communities
oh! there is a server for react
yes - or at least for JS - I'm afraid I don't know the best one, but the resources page links to something like the "Awesome Programming Discord" list
and there should be something helpful in that
ok i'll give it a shot thank you β€οΈ
Does anybody know what "ssn" prefix is for at the time of setting a namespace for a suds.sax.element.Element object?
Reference: https://suds-py3.readthedocs.io/en/latest/#custom-soap-headers
I kiiind of understand what a "namespace" is for, but I don't get what the "ssn" is there for
I don't have many hopes since this is all SOAP related, and it's an old thing, but I really don't find ANYTHING that explains what the hell is "ssn" for
All I get is that it may mean "Social Security Number", and well, Security is a word that has to do with this context, since I'm specifying some credentials (an example is in the URL, #custom-soap-headers)
Hm, I don't know why it didn't come to mind to just see the raw representation of the Element object haha, gonna give it a try
ssn=session namespace?
Oh, yes maybe :) thank you for the input
SOAP is much more complicated (I'm yet to learn it, so I don't know a real advantage yet, if there's one) than a REST architecture, that's for sure
There are basically no advantages to SOAP in the real world
No one enjoys XML now for CRUD operations
I suspected that! Never worked with it until now, which is for consuming really old APIs. Just gave it the benefit of the doubt
Hi everyone, I'm following the Python Crash Course book and making the Django project and I'm getting an error when I try to run makemigrations. When using models.CASCADE it seems to be trying to look for CASCADE in the tkinter package and I can't figure out why since I've imported django.db.models and used specifically models.CASCADE
This would mean that tkinter is not installed, generally.
Or that's not the name to use when importing.
Update: I change "ssn" to whatever string, and the thing works the same. I even change it to None and same thing!
How do I make a site using Python? I want to make an interactive guide to python and a variety of projects and I don't know how to actually make the site.
Use a web framework based on python like Django or Flask.
There are lots of tutorials to get you started.
Django Girls is a great one.
Got any links to the tutorials?
Just search django girls.
Can we use that if we're not a girl?
Yes but the point is tkinter shouldn't have to be installed, it's a library for desktop GUIs, it isn't relevant to Django. I've checked and this is exactly how you use models.CASCADE in Django and the imports are all correct so I don't see why it's flagging up tkinter
What is best practice in websites for making sorting function for guest/users - that touch td header and filter form high to low price : on backed or ? frontend (js)
Not exactly web development but likely the best place to ask. I'm automating a simple JavaScript game (with Selenium) that allows it's variables to be accessed by the browser's console. Is there a way within my Python code to read the values of those variables?
global vars in javascript are stored in window
It's all good, I found the execute_script() method was a thing and I'm just returning the value of the variable from that!
With the Sanic webserver framework, I had a server running on my computers localhost(using port 8080), and when I switched the port to 80 and pushed it to my vps the server doesn't work. I can do curl localhost and it will give me the server contents, but if I curl the domain I have linked to the ip adress, it won't work. Is there a way I can fix this?
Are you using a reverse proxy?
I have no clue what that is
I don't know how to find out if I am, all I know is that node.js webserver worked, but this one, which is almost the exact same(Except of course the fact that things are done differently between the languages), does not work
How do I do that?
use --host 0.0.0.0 as a start arg
I am new to sanic, throughout the years I've only done node webservers
that's the usual argument for that. (uvicorn and gunicorn)
That worked, thanks a lot
The reason it wasn't working was because the server was listening to connections to the ip, not to the host.
Well when running the server I passed None through the host, and it worked on my localhost so I didn't think anything of it
It seems that vscode imported CASCADE from tkinter on line 1 (probably by mistake), your image starts from line 2. What's on line 1?
im trying to create a view that will display a list of users of my app and ive been getting this error => TypeError: 'ModelBase' object is not iterable, my code : class GetOccupier(APIView): def get(self,request,format=None): occupier = Occupier.objects.all() serializer = OccupierSerializer(Occupier,many=True) return Response(serializer.data)
We don't allow posting of unapproved ads or polls, please message @hexed spoke to request approval.
#help-orange pls help
From where can I learn django
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Thereβs some Django resources here
Wouldn't you just use models.CASCADE? I don't think you would need it from tkinkter to begin with.
Or do you have to use a tkinkter version for what you're doing?
Can anyone recommend me a book i can use for learning web development
Choose in which part of web development you wish to start your path, and I'll try to recommend the book
https://roadmap.sh/frontend
https://roadmap.sh/backend
https://roadmap.sh/devops
I am quite a book guy
hii, I have a database which contains diff organization username and password, I want is that when the organisation logins with that credentials they get logged in, otherwise, it shows error..
like in my models.py there are diff org name and pass, and when the client login with those cred, they get logged in
means there is no sign up feature for the client
How do I verify the cred from the client with those in my admin database?
pls help?
Urgh. Don't tell me your have plaintext passwords?
π±
the password can be anything.. combinations of text, numbers, symbols..
but is it related?
I mean, do you store them without encryption?
I haven't thought of that till now..π
till now no encryption
π
but the admin will give those cred to the particular clients, and those cred will be visible to the admin only..
So i think no prob
it is so wrong on many levels
I could do the encryption later..
but for now how to do this?
class organisation(models.Model):
name = models.CharField(max_length=255)
password = models.CharField(max_length=255)
No never ever ever.
<form method="POST" action ="/authenticate/">
{% csrf_token %}
<label>Username</label>
<input type="text" placeholder="Username" name ="username" required> <br> <br>
<label>Password</label>
<input type="text" placeholder="Password" name ="psw" required> <br> <br>
<input type ="submit" class="btn btn-success" value ="Login">
</form>
No one should see user passwords.
Especially administrators π
yes, u r right..
I m saying i will do encryption.. but first after doing this functionality to verify the client
i made special sure protecting my software against system administrators xD
What framework are you using?
Django
Django handles all the login functionality out of the box.
You just need to use the existing functions.
Yes, ik there is an inbuilt function
but if want to do like this, is there a way..?
Do like what?
You create a form and then run the form through your function that checks user credentials.
From the Django Docs:
from django.contrib.auth import authenticate, login
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
# Redirect to a success page.
...
else:
# Return an 'invalid login' error message.
...
def userauthenticate(request):
username = request.POST['username']
password = request.POST['psw']
organisation = authenticate(username = username, password = password )
if organisation is not None:
login(request, organisation)
messages.add_message(request, messages.ERROR,"You are logged in")
print("You are logged")
return redirect(customerwelcome)
if organisation is None:
messages.add_message(request,messages.ERROR,"Invalid Credentials")
print("Invalid credentials")
return redirect(home)
is the above change correct for this model..?
Did you try it? π
yes, not working..
Basically i want to ask what is wrong in this
Well, what error are you getting?
I feel like such a fool. Seems for some reason the code to import CASCADE from tkinter was on line 1, though I don't remember writing that, I've just been following the tutorial line by line so not sure how that happened. Deleted that line and now it works, thanks!
it is going to the organisation is None: part even though I m using correct cred
if you print username and password, are you getting the values you expect?
yes
your authenticate call is missing request as well
u mean i should do this?
organisation = authenticate(request, username = username, password = password )
this is also not working
Hmm, are you sure the credentials are correct?
And that your user's is_active is enabled?
no, i haven't done this..
They won't be able to login if that is false.
So unless you want them to confirm their account signup, you should make is_active=True during account creation.
let me see that
i couldn't figure it out
there is no signup, only login with the cred from the models data
.
organisation = authenticate(username = username, password = password )
after this, organisation is still None
you have a database holding the username/pw?
yes, this model contains the data
and you tried adding request like it shows in the example?
is this in your settings.py?
django.contrib.auth.backends.ModelBackend
yes
def userauthenticate(request):
username = request.POST['username']
password = request.POST['psw']
organisation = authenticate(request, username = username, password = password )
print(organisation)
# organisation.is_active = True
if organisation is not None:
login(request, organisation)
messages.add_message(request, messages.ERROR,"You are logged in")
print("You are logged")
print(username)
print(password)
return redirect(customerwelcome)
if organisation is None:
messages.add_message(request,messages.ERROR,"Invalid Credentials")
print("Invalid credentials")
print(username)
print(password)
return redirect(home)
no
still not logging inβΉοΈ
i added this AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend'] at last of settings.py
and tried this also
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.AllowAllUsersModelBackend' ]
try putting it first
okay
no luck
the problem is in the authenticate, it is returning False, bcoz the passwords are generally hashed, but in my case they r not
But still i have not figured out how to resolve..
trying to do it
Resolved
I am doing Django
in urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path(r'C:\Users\Waseem\PycharmProjects\TryHackMeWebExploit\TryHackMeWebExploit\main_page', include('main_page.urls'))
]
in settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main_page'
]
I ran thses commands:
python manage.py startapp main_page
python manage.py migrate
Now I am getting this error:
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'main_page.urls'
??
why is this happeining?
Did you import main_page.urls?
if you have urls in apps, you need to import them into your main urls.py to use them there
importing main_page.urls into your global urls
oh wait, does include let you import it that way?
looks like this in the docs: path('blog/', include('blog.urls')),
urlpatterns = [
path('admin/', admin.site.urls),
path(r'main_page/', include('main_page.urls'))
]
same error:
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'main_page.urls'
this is where I am running the migrate command
it doesn't matter, what are the contents of main_page
I don't think so
but that's only if you have urls in the main_page/urls.py that you need to use in your django project.
Now, let's go ahead and create a very simple app:
-
Create an app using a command from Unit 2 and call it whatever you like. I will be using 'Articles' for this lesson.
-
Head over to settings.py and include your app name in INSTALLED_APPS:
ok so you probably will end up putting something in urls.py, so you need to create that
I am not sure about why
ooh so now I should create a urls.py file inside migrate?
ooh wait
Migrate has nothing to do with this, you're just trying to migrate when there is an error in your code.
As seen, Django automatically creates files inside your app folder. We are going to go through their purposes as we continue creating our website.
So it won't let it finish.
according to tryhackme it creates it automatically
Yea, it should be, but it's not, so make it.
Anything to write in it?
"""TryHackMeWebExploit URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('main_page/', include('main_page.urls'))
]
this in which urls.py?
the one in the app (main_page) or the one in the parent folder of the app
that looks like your global urls.py
because you're importing the other one
I dunno, maybe in your tutorial they will put someting in the main_page/urls.py file. Maybe not.
You don't have to do anything there otherwise.
- Head over to urls.py (located in the main folder!) and include a path to your app there:
yup yup so this is in the main folder
but
after adding this in the parent urls folder they ask me to migrate
ango.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'main_page.urls' from 'C:\\Users\\Waseem\\PycharmProjects\\TryHackMeWebExploit\\TryHackMeWe
bExploit\\main_page\\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular impo
rt.
Ahh alright, wow nvm
They explain the rest in the other section of the guide π€¦ββοΈ
@dense slate Thanks!
Figured. π
can I connect my Vue frontend with regular Django without DRF? I'm confused because in Flask it's rest apis out of the box and then you can add Flask-Restful for more concise code, but is Django like that? or is Django basically template language or bust unless you add DRF?
as long as you can return json, it should work
if you want a way to connect them, I use nginx-unit
Here's an example project I created showcasing nginx unit, fastapi, and vue with docker. https://github.com/killjoy1221/nginx-fastapi-vue-docker
You can look at GraphQL as well.
is there any chance I can get ws communication for free
most web hosts out there uses something like AWS Lambda
and there's a timeout
so ws communication isn't really possible
How do I configure a apache2 server on Windows 10
or should i just use nginx
because it is simpler
how do you make a login form with django
i have tried multiple different tutorials and couldn't find anything that worked
Xampp does the job for you... don't try to invent the wheel if it's already there...
Or Wamp
Were you doing Django tutorials? Because that is a really basic functionality that most of the tutorials probably have as part of them.
Now if there's a specific part that's not working, feel free to share your code/errors of what you've tried and we can work with you to figure out why a certain step might not be working.
i saw a website use a
https://something.com/index.py
how is that even possible?
ping when replying pls
Can you share the link?
I don't think it is.
Unless it downloads a file?
Hello everyone
Is anyone here comfortable with flask_googlemaps package ?
I've followed their tutorial (even copy pasted their code) but the map doesn't seem to show up
I've tried the google maps tutorial which embeds a static map with a simple js script and it works. So this tells me it's not an API key problem
Hey is anyone here knowledgeable at html
Like how difficult is it to make a simple website with html
Iβve exhausted every other option for what I want to do
check free website templates to get some inspiration
yeah, looking at free templates are great
and you can use bootstrap or tailwindcss to easily style it
which libraries are used to create AI chat bots in python that is efficient and executed by C++ like numpy?
numpy is written in C
pytorch is written in C++ but not sure if it's used to create "AI" chat bots
fixed my issue with googelmaps. It was a bug from their side. They have a patched version.
You can downlaod it here https://github.com/flask-extensions/Flask-GoogleMaps/releases/tag/0.4.1.1
Recommended CSS framework to be used for Django?
From what i understand about Django, it doesn't matter which css framework you use. If you want easy pre-made UI components use bootstrap. For more custom control (increased config), tailwindcss is best. You can also check out others such as, Skeleton, and Foundation.
they might've coded it raw
like route "index.py" would return filesystem.ReadFile("path/to/py/file.py") with like text/py
hi
i got a problem with flask
basically it keeps returning this errors even when im entering all the data right
these are the validations
and this is the route part
does anyone know why this keeps happening?
Hello π
Im unsure of how to integrate vue into html :/
<script type="module">
import { createApp } from "vue"
createApp({
data() {
return {
message: "Hello World from vuejs!"
}
}
}).mount("#app")
</script>
<div id="app">
<h1>{{ message }}</h1>
</div>
this is the file index.html
this is what my webserver is layed out as
/dir
|
-----------------------------
| | |
server.js /node_modules /dir2
|
index.html
when i run the server i can only see the string {{ message }} on the webpage
@weary mica thanks bro but do you recommend Tensorflow?
!voiveverify
You are not allowed to use that command.
can you try this out?
password1 = PasswordField(label='Password:', validators=[
Length(min=6),
EqualTo('password2'),
DataRequired()
])
password2 = PasswordField(label='Confirm Password:', validators=[
Length(min=6),
DataRequired()
])
are you getting any errors in the console?
no it just doesnt render the 0
i might just not have vue installed correctly
i did run npm install vue --save
I've been thinking about making a dashboard for my bot and have hard about flask, dijango and quart, which of these do ppl recommend. I'm making the bot itself in hikari which includes a rest API so should I just use that instead?
I have question does a website can be consider as dynamic website when it uses JS
im trying to create a list of all my users and i keep getting this error => TypeError: 'ModelBase' object is not iterable
my code => class GetOccupier(APIView): def get(self,request): occupier = Occupier.objects.all() serializer = OccupierSerializer(Occupier,many=True) return Response(serializer.data)
it depends on how JS is used
as far as I know, dynamic web site is usually web site which has content like different new appearing blogs/comments
I usually assumed for myself, dynamic web site is the one that can't be served directly as static files from web server like Nginx (this is actually a different definition from the phrase above)
Well, more appropriate would be to say, is it Client Side Rendering or Server Side Rendering web site with dynamic content
π€
all right. If the web site is not having CSR or SSR content dynamic changing, that it is definitely not dynamic at all ;b
So i conclude, that website using JS can be dynamic in three ways
- It just having some transitions / actions with JS
- JS is actually pulling some data from backend
- JS is used as server side renderer for dynamic render
I would say first case is not dynamic at all
second is sort of dynamic, but technically it can be dynamic in this way even without JS. Html forms will work fine too for this purpose. Depends on how far we stretch definition dynamic
and third one is dynamic for sure
So I've been watching this video on flask websites https://youtu.be/dam0GPOAvVI and after advice I decided to make my dashboard website in Django, would it just be a case of changing imports if I was to somewhat follow the vid or does djnago do a lot of things differently
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...
Either your hmtl for the page or in your flask source decorarator
Figured it out it's via Admin(name='name')
admin.init_app(app, index_view=MyAdminIndexView(), url=url_for('main.index'))
url_for errors here what would I do
Attempted to generate a URL without the application context being pushed. This has to be executed when application context is available.
# base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Page1</title>
</head>
<body>
{% block content %} {% endblock %}
</body>
</html>
why's there an error with the DOCTYPE thing?
nowhere, except I am not sure if you are allowed having comment before that
tech with tim is a really good youtuber check freeCodeAcademy aswell!
it seems okay but maybe remove the comment?
yeah I found a GitHub repo for a jango website in Tech with Tim's GitHub so followed that to the YT vid series and am following along with that, adding in the discord related stuff as I go
oh okay, keep adding what you find. i might check it aswell
can someone help me
this is the repo if your interested https://github.com/techwithtim/Django-Website It's last commit was 2 years ago but I'm thinking it won't have any major differences and the flask one's last commit was a year ago so i'm not seeing it as much of a problem
I don't know if i will be able to but we will never know if you don't provide a question π
thanks for the source, ill check into it
i did
oh my bad
look
.
is it producing any error's?
no
nothing no error thats y i cant figure out the problem
there is an error about image but ill fix that later
you are passing it data right?
You need to make a POST request, i.e. with a <form> tag
yes you can check in code
i am fetching it from the form and sending it to data base but its only fetching data not sending
Needs to be POST
something like this
methord
?
should be method
restart the server
If you're not using a debug mode, it's probably caching the template
i am and i did
Is it fixed now?
nop
manually
Hey @inland solar!
It looks like you tried to attach file type(s) that we do not allow (.rar). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
Hello, I am attempting to use jQuery getJSON() from this apache2 website I am hosting
http://ec2-16-162-102-37.ap-east-1.compute.amazonaws.com/api
with a simple .html local file of
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script>
$.getJSON( "https://ec2-16-162-102-37.ap-east-1.compute.amazonaws.com/api", function( data ) {
console.log(data)
})
</script>
Only getting this error from chrome console log , same error from icognito chrome and edge browser
GET https://ec2-16-162-102-37.ap-east-1.compute.amazonaws.com/api net::ERR_CONNECTION_REFUSED
Website side apache2 conf etc/apache2/apache2.conf
. . .
Header set Access-Control-Allow-Origin "*"
<Directory /var/www/html>
Order Allow,Deny
Allow from all
AllowOverride all
Header set Access-Control-Allow-Origin "*"
</Directory>
<VirtualHost *:80>
Header add Access-Control-Allow-Origin "*"
</VirtualHost>
. . .
Website side have header module
$ a2enmod headers
Module headers already enabled```
Apache2 already been restarted by `sudo service apache2 restart` after modify conf file
`var/www/html/init.py`
```py
. . .
@app.route('/api')
def api():
f = open("/var/www/html/data.json", "r")
return jsonify(json.loads(f.read()))
. . .
fixed by
@app.route('/api')
def api():
f = open("/var/www/html/data.json", "r")
response = jsonify(json.loads(f.read()))
response.headers.add('Access-Control-Allow-Origin', '*')
return response```
Hi guys i just wanna know about the general process while making a website (for e-trade)
What are the main things that you should do
Oh yes good question
https://www.amazon.com/Systems-Analysis-Design-Alan-Dennis/dp/1119496500
For starters reading a book how to plan programming product
With the overarching goal of preparing the analysts of tomorrow, Systems Analysis and Design offers students a rigorous hands-on introduction to the field with a project-based approach that mirrors the real-world workflow. Core concepts are presented through running cases and examples, bolstered ...
The rest would be planned in the process
In general you are highly likely to encounter need in
Backend development
DevOps/infrastructure development
Having SQL database, and how to have backups and their restorations
Since it is e trades, perhaps u will need quite good database knowledge, and perhaps even separate guy DBE for this
Payment gateway, which requires having official company status
Optionally a bit better frontend development as a separate process
Also obviously u will need UI designer of your web site
So.
Being backend Dev
And official company status for payment gateway is the minimum.
The rest are optionals, but without good infrastructure knowledge I think it will be as good as dead
And without good database/SQL knowledge there is a high chance to mess up
Thx
how do you do this in django: if you have a button, when you click on it, the contents of the page change
using bs4 how can i do this:
for example i have an html code:
<div class="SRDC">
<a href="youtube.com/">
</div>
how can i find the <a href="youtube.com/"> element (he has no class id or name)
a[href="youtube.com/"]
I think
maybe also div.SRDC > a
I'm using css selectors. Not sure if it's the same in bs4
Be more precise how you wish to have changed the content
really any content - like a paragraph going from hello to goodbye
Just wrap button into
<a href={{Django reverse URL to path name}}> your botton </a>
And make in Django served different content from the URL
could the same just be achieved with some javascript code?
Reuse base template, so only paragraphv would be changed
what is the difference between using django/python for the logic and using javascript for logic?
JavaScript can make data changed without additional requests to server
No white screen delay too
so is the only thing that uses django just forms?
That is if using client side JavaScript.
If we use server side js, there would be no difference
yes client side is what i had in mind
I don't understand this phrase
do programmers only use django, for the purpose of making forms?
No, main purpose of Django to serve at its endpoints data in JSON format and accepting JSON requests.
In this way Django can be invoked from client side JavaScript with something like Axios requests library
ok
Forms can be made freely in client side js
We can change making request to anything, making any js action, instead of standard Post request
I haven't worked with Django but I've worked with a lot of javascript. Should you think of Django as just a rest api that serves an html doc and if you'd like the make your page interactive, you'll need to use js to make that happen?
Usually main purpose of Django to provide work with SQL database π€
Or doing any other similar server side job, which can be invoked by python
This stuff makes no sense
I'm asking this because most questions on here are how to make my page interactive with python
#help-donut pls help
django, and python in general, does not do client-side interactivity AFAIK. You can use plotly to kind of fake it but that's using JS under the hood, but has a python SDK you can work with. You could also use HTMX
the reason being you cannot just send a blob of python code to someone's web browser and they know what to do with it, like you can with JS
The talk will include four high level parts.
Part 1 is a discussion of common Django / JavaScript architectures. These include:
- The most common "ad-hoc" approach, where JS just gets incrementally added to templates until you find yourself in a mess
- The "completely decoupled" JS front-end and Django-API back end, which is popular, but com...
you can also use HTMX which is a kind of new but very neat looking thing: https://www.youtube.com/watch?v=Zs0DXR1S03M
I developed my first CGI script in 1998. Since that day I have seen a lot of hypes coming and going.
The talk will consist of three parts:
- My humorous odyssey of trying to find a great frontend framework
- Retrospective: What do I want from the frontend?
- I finally found: HTMX: HTML Fragments over the wire
Besides simplicity, good Web Vita...
.
use default attribute
@night sequoia that's the model not a form
Yet another micro frontend framework
It would be smarter just to use Vue.js in this case I think
i think maybe null=True and default attribute dont go together
It can be statically linked too
how do you mean "micro frontend". normally I would think you mean microservice-powered frontends, but HTMX-in-django is not that. Django is rarely deployed as anything but a monolith
try removing null=True
htmx is cool
alright
a little bit of javascript, as a treat
it's really the ideal depedency for when you want an interactive form
and without having to deal with everything yourself but also not setting up an entire build toolchain
Do you think following and copying Django tutorials will be good for learning how to make an application?
Im running windows 11 and im going to be hosting an html website on my computer anyone know a good webserver software for it. Itβs going to have time backend stuff going on as well
hey guys im front end beginner , to make the website works on the backend, what backend languages should i learn?
can i have sample code for a basic django login
