#web-development

2 messages Β· Page 216 of 1

swift wren
#

which is still causing error with this request

warped aurora
#

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?
swift wren
#
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')
        },
    })```
swift wren
#

its my personal flask structure

#

even after i added the jwt header, its still not accepting the valid jwt

thorn igloo
#

so what's the issue here? cors or jwt?

swift wren
#

its either, if i remove the jwt rquirement its cors

#

if i add the jwt requirement its jwt

swift wren
thorn igloo
#

so lets solve one at a time

#

i dont have experience with jwt, so i cant help there

swift wren
#

lets try cors first, because the request was never being sent

thorn igloo
#

sure

#

youre using the flask cors library i assume?

swift wren
#

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()
    
thorn igloo
#

arent you supposed to do something like cors(app)

swift wren
#
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
thorn igloo
#

i dont see this anywhere in your code

swift wren
#

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()
unreal zenith
swift wren
#

i did it and it worked

thorn igloo
#

ahhh

swift wren
#

how am i so fucking braindead, i've been on this problem for like 3 hours

thorn igloo
#

it happens

swift wren
#

okay, well, do you know about flask-login?

unreal zenith
#

seems this is the default auth of django so

#

xD

swift wren
#

you forgot the '' on admin.site.urls

#

or you didnt include it?

unreal zenith
#

the admin worked

#

but accounts/ later added

#

then stop working

#

aaah i see it 😦

swift wren
#

path('login/', auth_views.LoginView.as_view(template_name='todo/UserCreation/login.html'), name='login'),

unreal zenith
#

neeed to import this:

from django.urls import path, include
swift wren
#

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')
    
]
unreal zenith
#

okee cool!

swift wren
woeful hazel
#

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?

swift wren
#

is it pandas?

woeful hazel
#

Yep

#

Trying to delete the header column and index column

swift wren
#

i've forgotten man, sorry, try to print it out and see the row number

swift wren
# thorn igloo it happens

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

thorn igloo
swift wren
#

nah

thorn igloo
#

can i see the full route code?

swift wren
#

@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

thorn igloo
#

where did you define your function to get the user object?

swift wren
#
_localuser.query.filter_by(username=queried_username).first()
thorn igloo
#

i mean for flask-login

swift wren
#
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))
thorn igloo
#

why do you have two

swift wren
#

the other one is for OAuth for future

thorn igloo
#

but doesnt user loader expect 1 function?

swift wren
#

should i remove it?
i doubt that effecting anything

#

i dont think so, i did this before in ssr

thorn igloo
#

comment out the google one and tell me if it affects anything?

swift wren
#

did it

#

it didnt change anything

#

AttributeError: 'AnonymousUserMixin' object has no attribute 'email'

thorn igloo
#

can i see your user class for the db?

#

if you dont mind that is

swift wren
#

dw its public repo

#

its _localuser

thorn igloo
#

what's the anonymousUsermixin for?

swift wren
#

i tried to put it in there to solve the issue

#

i think its used for storing information of individuals that arent authenticated

thorn igloo
#

i see

swift wren
#

and its saying that even then its not found

#

because login_user isnt working

thorn igloo
#

your thing reaches the print statement right?

swift wren
#

yeah

#

i put it below the login function because i wanted to see if the login function does anything

thorn igloo
#

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

swift wren
#

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?

thorn igloo
#

why not remove the anonymous inheritence?

swift wren
#

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

thorn igloo
#

i'm primarily done this using the cookie session way

swift wren
#

how bro

thorn igloo
#

dont know if you've altered that

#

it's the default way

swift wren
#

but that wont solve my issue yk

#

im doing csr

thorn igloo
#

csr?

swift wren
#

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

thorn igloo
#

yes, i was using vue when i did that and it worked no questions asked

swift wren
#

no way

#

omfg

#

how dude

thorn igloo
#

im telling you

swift wren
#

with flask?

thorn igloo
#

yes

swift wren
#

fuckccc

#

bro im ready to refactor the 300 lines of code rn

#

how did you do it

thorn igloo
#

wait, let me look at my repo

swift wren
#

do you have a public repo or somthing

#

oh sweet

thorn igloo
#

it's not public lol

swift wren
#

no problem

#

just code snippets would workout

thorn igloo
#

yeah

#

let me see if i can figure this logic

swift wren
#

how did you do frontend authentication

#

cos i just store the jwt in storage

#

and check if the token exist

thorn igloo
#

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

swift wren
#

and you just made a fetch to see if its true or nah

#

bett

thorn igloo
#

yeah

#

so i have this

#

not the most efficient way

#

let me check my frontend

swift wren
#

wait how did you login a user though

#

cos my login is the issue

thorn igloo
#

user is the db object

swift wren
#

setUserSession?

thorn igloo
#

nothing special

#

that's the flask session

swift wren
#

did you use flask_session?

#

like the extension or just normal flask

thorn igloo
#

no

#

just normal

swift wren
#

ah okay

#

imma try to simplify my login

#

thanks mate

#

im praying that it works, im so tired of toying around with auth

thorn igloo
#

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

swift wren
#

so you did html

thorn igloo
#

cause i was planning to serve the files with flask

#

it's still a vue app

#

vue spa

umbral glen
#

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??

swift wren
#

ill do it anyway, im desperate

thorn igloo
#

alright,

#

let me test it out either way

thorn igloo
#

bruh

#

that just sounds complex

swift wren
#

lmao

#

"badam tiss"

#

that requires gpt-3 ai

umbral glen
swift wren
#

and if its a public app, its gonna need some strong servers

umbral glen
swift wren
#

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

umbral glen
#

Okay thanks

sly canyon
#

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'))
# [...]
swift wren
#

im gonna be so pissed off if its a python issue

thorn igloo
#

yeah, idk then

swift wren
#

what python are you on

#

im on 3.10.2

thorn igloo
#

did you do this?

swift wren
#

nah i havent

#

ive only done this

#

login_manager = LoginManager(app)

thorn igloo
#

oh, should be fine i guess,

#

this from the repo you sent?

swift wren
#

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

thorn igloo
#

i dont see it, unless you didnt update it

swift wren
#

go to API

#

and then

#
from backend import app
from backend.API.login import *

if __name__=="__main__":
    
    app.run(port = 5000,debug=True)
thorn igloo
#

i see

swift wren
#

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

thorn igloo
#

yeah, it's designed to always return 200 nomatter what

swift wren
#

and it immediatly shat it self when i told react to get request /get_user

thorn igloo
#

what happened?

swift wren
#

AttributeError: 'AnonymousUserMixin' object has no attribute 'username'

#

it sent like 12 requests in a second

#

but nothing new in error

thorn igloo
#

again, might have to remove the anonymous mixin

swift wren
#

crap i forgot

#

didnt do anything

woeful hazel
#

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?

golden bone
woeful hazel
golden bone
woeful hazel
woeful hazel
oak patio
#

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.

thorn igloo
#

must be something in your code mate

thorn igloo
#

basically a class

night sequoia
#

anyone have experience with django please help me

#

i need help to know how to edit cookies

woeful hazel
#

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

trim wolf
#

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

scenic furnace
#

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?

thorn igloo
#

with jinja2

hard whale
#

It has interactive elements in it to add to the web page?

thorn igloo
inland oak
#

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

hard whale
#

OMG so many scary words..

trim wolf
swift wren
#

i didnt know that flask_praetorian did jwts, and that it fetched the users

#

it all works perfectly now

thorn igloo
#

but why you using cors if you're allowing all domains?

swift wren
#

cos for some reason, cors always makes a issue some how

#

idk how, so i just allow cors everywhere

thorn igloo
#

defeats the purpose

swift wren
#

how

thorn igloo
#

you're basically allowing requests from any url to your server

#

CORS is there to prevent that

swift wren
#

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

thorn igloo
#

i see

rigid laurel
#

CORS is a client side thing. You can't just ignore CORS preflights if you want browsers to talk to you.

stable bear
#

how would i create a simple input output with a button on a webapp with django/python?

manic plank
#

hey, im getting an error when running a python program that scarpes crypto coins prices
can someone help?

stable bear
thorn igloo
harsh saddle
#

huh

swift lodge
#

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>
stable bear
thorn igloo
stable bear
#

how can one access the information entered into the form, which variable is it stored in?

thorn igloo
#

add a route with a post method

#

it must match the action route

#

then use request from flask

stable bear
#

this is in django

thorn igloo
#

yeah, then idk, i dont use django. just google how to handle post requests

stable bear
#

ok - what is the use of javascript in websites? ive never really understood its purpose

thorn igloo
#

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

stable bear
#

but cant changing the content of the page just be done with flask/django without using javascript?

thorn igloo
#

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

stable bear
#

ok

swift lodge
#

pls help

cerulean badge
#

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?
frank shoal
#

Use an enum?

#

those get serialized to an int

#

assuming it's mysql

eager hornet
#

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

dawn island
#

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

golden bone
dawn island
golden bone
dawn island
golden bone
#

Does it even matter though?

dawn island
dawn island
golden bone
split snow
#

how to remove values in the data?

[{'values': {"id": 1, "name": "sam"}}]

expected output

[{"id": 1, "name": "sam"}]

please help

whole fulcrum
#

val = val.values?

cerulean badge
#

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?

hard whale
#

Can anyone share an example of FastAPI/uvicorn chat? :)

unborn glacier
#

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
cerulean badge
west thunder
native tide
#

i need some help

swift lodge
#

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 :)

slender hamlet
#

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

native tide
#

hello guys

#

i need someone to help me coding python

#

plz

#

dm me if u can

hard whale
#

@Astro^^#8349 use help channel first

slender hamlet
#

hmm

strange charm
#

can someone help me with django-tailwind

hollow verge
#

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

#

remote-entrypoint.sh

#!/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 
native tide
#

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.

views.py

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 %}```
safe sequoia
#

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'

random sand
#

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

grim helm
#

about django channels, is there a way to make it connect to an externally running socket?

#

than it waiting for a connection..

indigo oasis
#

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?

indigo oasis
#

or any other available help channels

fickle garnet
#

object tracking is in there

#

you can build and opencv.js for the client

old hound
#

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?

sonic hearth
#

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)
ruby jackal
#

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

random wedge
#

You imported a function. If you want to run that function, just call it as a follow: app()

sinful flare
#

guys i should learn flask first or django ?

random sand
random sand
ocean harbor
native tide
#

diff between client side scripting nd server side scripting

native tide
#

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?

inland oak
#

If those two things match, we can conclude, that highly likely it is code looking truthful to be a backend of the web site

native tide
#

mm but what if the code is doing something else?

#

say test.com lets me get into my bank account

inland oak
#

We can't know for sure this

native tide
#

how can i know it doesn't also save my password?

inland oak
#

You can't

native tide
#

thats kinda my question

inland oak
#

A matter of trust only, and what security audits by third party people they made

native tide
#

i know i can't the way we do things today

native tide
#

trusted third party audits

#

but what if they show one code for the audit and then run another after they leave?

inland oak
#

Surely possible.

#

Don't trust anyone ;)
Choose where you are less likely to be fooled

native tide
#

lol

#

but why?

#

say, doesn't the js verification sound nice?

#

nobody does that today, but wouldn't that fix a bunch of mitm?

inland oak
#

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

cerulean badge
#
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?

native tide
native tide
#

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

native tide
#

can someone suggest a free of course web dev course pithink

native tide
mental summit
#

Freecodecamp maybe

upbeat flax
#

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

golden bone
#

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.

tender drift
#

#help-chocolate first time trying to run a flask api in a ubuntu droplet. anyone experienced this before?

cerulean badge
#

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?

ocean slate
#

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

ashen pond
#

Can anyone help me with free domain name. I've student program in GitHub :)

ashen pond
inland oak
ocean slate
fickle garnet
unreal zenith
#

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

sacred crane
#

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

rugged geyser
#

Any recommendations on a free translation API?

lament nest
#

Hello, is anybody here?

old hound
#

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']
        }
    })```
lament nest
#

@old hound is this django framework or logging in general?

hard whale
#

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

old hound
#

this is with Flask @lament nest

hard whale
#

I use FastAPI, must be something like that

lament nest
tulip scroll
#

django rest framework Question

#

any hero ?

old hound
#

@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.

rustic sky
#

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

crisp barn
#

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?

boreal slate
#

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?

hasty magnet
#

i need a team to make a movie streaming website

#

hello

#

guys

boreal slate
#

ok

hasty magnet
#

so

#

can u help

#

me

boreal slate
#

errr ok

#

u want me to make the next billion dollar Netflix for free?

boreal slate
#

I do have a domain

drifting apex
#

Ohh, lemme see

drifting apex
boreal slate
#

google

#

it works now thanks

#

hey enslo

#

would you also like to build a netflix for free?

chrome belfry
#

best and simplest/smallest pure-python templating package?

inland oak
#

there are no alternatives ;b

chrome belfry
#

right on.

#

there should be one and only one correct way of doing things ^^

inland oak
#

are you writing script that uses just templating?

#

for docker image

chrome belfry
#

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

worn basin
#

wip scrapy, fastapi, docker, celery, etc etc project:

ionic raft
#

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?
vocal anchor
#

Can someone help me understand why I'm receiving this error?

wraith dagger
#

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

thorn igloo
ocean slate
worn aurora
#

can i ask a question about docker compose here ?

worn aurora
#

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 ?

tired kraken
#

Hi there

worn aurora
#

i see specifying volume overrides .dockerignore in a sense

fickle garnet
#

a little dated as usual but a helpful conversation on the subject

tired kraken
#

Anyone got hands on filtering dropdown bars?

#

Need to filter this, location depends on location group, pretty killing my mind rn.

fickle garnet
#

ummm... context?

worn aurora
#

filter ? a queryset ?

#

or u mean the options in the dropdown ?

fickle garnet
jaunty magnet
#

what is the go-to flask auth package? My udemy course has Flask-JWT but it hasnt been updated since 2015

golden bone
valid pelican
#

Hey , guys

#

How much time it took to become fullstack developer

dense slate
#

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

valid pelican
fickle garnet
#

i dont think this space if for advertising

dapper tusk
#

@native tidehello, we do not allow recruitment

inland oak
#

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

inland oak
#

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

dense slate
#

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 πŸ˜‚

real edge
#

Django: Request method question...
Do I need "form" to make simple button that run some srcipts in Django template?

dense slate
toxic forge
#

Hello <@&267628507062992896> ,
Is it allowed here to share project work? Please let me know.

zealous tundra
#

please DM @hexed spoke

#

the short answer is: it depends

toxic forge
#

@zealous tundra Sure, I'll ask him.

ionic raft
#

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 πŸ™‚

left grail
#

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.

golden bone
left grail
#

https:/example.api.com/users/{arrayOfUsers} was an example

indigo kettle
#

I would just try sending a comma separated list of user ids

dense slate
left grail
dense slate
#

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.

left grail
dense slate
#

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.

left grail
#

then the only solution for me is to do multiple requests and insert the data into a database and get the data from there

dense slate
#

Yea but you can only do one request per 2 seconds, doesn't sound like that will work for you.

left grail
#

Yeah, but I can make the database update every now and then

dense slate
#

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.

left grail
#

Also, I tried doing multiple requests without a delay inbetween, and it worked without it taking 2 seconds

dense slate
#

It works, but they can ban you. They are relying on you to throttle it.

left grail
#

Why dont they just have a mechanism that only allows a request to be sent every 2 seconds?

dense slate
#

Ask them.

left grail
#

I guess I have to stick with a very slowly updating leaderboard

dense slate
#

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.

fickle garnet
#

adding a delay is just good etiquette isnt it ?

dense slate
#

Seems that should be an option.

dense slate
left grail
dense slate
#

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.

left grail
#

they are prob gonna answer me in a month

dense slate
#

Patience is a virtue.

weary mica
left grail
#

whats the difference

weary mica
#

don't include the {nick-name}

left grail
#

didnt work

#

it isnt an endpoint

weary mica
#

Ah crap.

tepid lark
#

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. ohhh

#

The first two are very generic solutions and I'm wondering if there's anything else out there.

real edge
dense slate
#

What is?

tepid lark
#

well, I'd be using Flask then.

burnt cedar
#

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

nova sky
native tide
#

go for fastApi

rich ravine
#

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.😫

  1. Log in after accessing the shopping mall > Move your shopping cart.
  2. If there's no prize in the shopping basket...Pop-up output.
  3. If there's a prize in the shopping basket... Print print.

The shopping mall site is Coupang.

native tide
#

Stuck on this, can't find any resource online ffs

#

when sending a post request

tepid lark
native tide
rich ravine
#

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.😫

  1. Log in after accessing the shopping mall > Move your shopping cart.
  2. If there's no prize in the shopping basket...Pop-up output.
  3. If there's a prize in the shopping basket... Print print.

Please Help me.

calm lance
#

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!

inland oak
ashen ice
#

Python backend is...

  1. Flask 2. Sanic 3. Vibora 4. Japronto
  2. Falcon 6. AioHTTP 7. Tornado 8. Django
ashen ice
inland oak
#

Python is the highest level language that sacrificed everything for faster development and more readable code

ashen ice
#

@inland oak I don't think I can deny it.
I'm sure you all understand with this image. πŸ€— (lol)

pulsar copper
#

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.

dusk portal
#

hey

stable bear
#

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?

frank shoal
#

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

stable bear
#

does javascript make websites dynamic? thats what ive heard

frank shoal
#

Yes. To a degree

stable bear
#

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

frank shoal
#

Mostly for storage

#

And secret stuff, like database credentials

stable bear
#

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?

frank shoal
#

Most frameworks have a web server builtin

stable bear
#

yes but if you have a html and css file only? no django framework - how would the website be viewed?

frank shoal
#

Apache or nginx

#

There's plenty of web servers to use.

#

Your web host may choose for you

mystic wyvern
#

what is the differences between redux &react-redux&redux/toolkit?

fickle garnet
#

after a 15 second search, react for js components , redux state container

mystic wyvern
#

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

rigid laurel
#

you're better off asking in a react js server

#

on that page is a link to some other communities

mystic wyvern
rigid laurel
#

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

mystic wyvern
#

ok i'll give it a shot thank you ❀️

ruby palm
#

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)

ruby palm
#

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

native tide
#

ssn=session namespace?

ruby palm
#

Oh, yes maybe :) thank you for the input

native tide
#

it's weird

#

I haven't found anything on it yet

ruby palm
#

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

quick cargo
#

There are basically no advantages to SOAP in the real world

#

No one enjoys XML now for CRUD operations

ruby palm
#

I suspected that! Never worked with it until now, which is for consuming really old APIs. Just gave it the benefit of the doubt

balmy frigate
#

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

dense slate
#

This would mean that tkinter is not installed, generally.

#

Or that's not the name to use when importing.

ruby palm
real root
#

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.

dense slate
#

There are lots of tutorials to get you started.

#

Django Girls is a great one.

real root
#

Got any links to the tutorials?

dense slate
#

Just search django girls.

frank shoal
#

Can we use that if we're not a girl?

balmy frigate
real edge
#

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)

alpine nacelle
#

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?

frank shoal
#

global vars in javascript are stored in window

alpine nacelle
#

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!

steel delta
#

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?

frank shoal
#

Are you using a reverse proxy?

steel delta
#

I have no clue what that is

steel delta
# frank shoal Are you using a reverse proxy?

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

frank shoal
#

It might be a quirk with the way the server binds.

#

try to bind to 0.0.0.0

steel delta
#

How do I do that?

frank shoal
#

use --host 0.0.0.0 as a start arg

steel delta
#

I am new to sanic, throughout the years I've only done node webservers

frank shoal
#

that's the usual argument for that. (uvicorn and gunicorn)

steel delta
frank shoal
#

The reason it wasn't working was because the server was listening to connections to the ip, not to the host.

steel delta
#

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

sudden sierra
manic crane
#

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)

open forum
#

We don't allow posting of unapproved ads or polls, please message @hexed spoke to request approval.

agile pier
topaz thunder
#

From where can I learn django

mental summit
#

!resources

lavish prismBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

mental summit
#

There’s some Django resources here

dense slate
#

Or do you have to use a tkinkter version for what you're doing?

surreal pasture
#

Can anyone recommend me a book i can use for learning web development

inland oak
#

I am quite a book guy

agile pier
#

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?

inland oak
#

😱

agile pier
#

but is it related?

inland oak
agile pier
#

till now no encryption

inland oak
agile pier
# inland oak 😞

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

agile pier
#

I could do the encryption later..

agile pier
#

class organisation(models.Model):
    name = models.CharField(max_length=255)
    password = models.CharField(max_length=255)
agile pier
#
<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>
dense slate
#

No one should see user passwords.

inland oak
#

Especially administrators πŸ˜‰

agile pier
inland oak
#

i made special sure protecting my software against system administrators xD

dense slate
#

What framework are you using?

agile pier
#

Django

dense slate
#

Django handles all the login functionality out of the box.

#

You just need to use the existing functions.

agile pier
#

Yes, ik there is an inbuilt function

agile pier
dense slate
#

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.
        ...
agile pier
# dense slate From the Django Docs: ```py from django.contrib.auth import authenticate, login ...
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)
agile pier
dense slate
#

Did you try it? πŸ™‚

agile pier
#

yes, not working..
Basically i want to ask what is wrong in this

dense slate
#

Well, what error are you getting?

balmy frigate
agile pier
dense slate
#

if you print username and password, are you getting the values you expect?

dense slate
#

your authenticate call is missing request as well

agile pier
#

this is also not working

dense slate
#

Hmm, are you sure the credentials are correct?

#

And that your user's is_active is enabled?

agile pier
dense slate
#

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.

agile pier
#

let me see that

agile pier
#

there is no signup, only login with the cred from the models data

agile pier
#

organisation = authenticate(username = username, password = password )

#

after this, organisation is still None

dense slate
#

you have a database holding the username/pw?

agile pier
dense slate
#

and you tried adding request like it shows in the example?

#

is this in your settings.py?
django.contrib.auth.backends.ModelBackend

agile pier
#

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)
dense slate
#

you should have that in your authentication_backend

#

in settings

agile pier
#

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' ]

dense slate
#

try putting it first

agile pier
#

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

forest copper
#

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?

dense slate
#

if you have urls in apps, you need to import them into your main urls.py to use them there

forest copper
#

wait

#

what's that step

#

import it in which file

#

@dense slate

dense slate
#

importing main_page.urls into your global urls

#

oh wait, does include let you import it that way?

forest copper
#

no idea I am following some guide

#

Tryhackme if you ever heard about it

dense slate
#

looks like this in the docs: path('blog/', include('blog.urls')),

forest copper
#
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'

dense slate
#

do you have a file in main_page apps folder called urls.py?

forest copper
#

this is where I am running the migrate command

dense slate
#

it doesn't matter, what are the contents of main_page

forest copper
#

I don't think so

dense slate
#

so why are you including it in your urls.py? create an urls.py file if you want to do that

#

but that's only if you have urls in the main_page/urls.py that you need to use in your django project.

forest copper
#

Now, let's go ahead and create a very simple app:

  1. Create an app using a command from Unit 2 and call it whatever you like. I will be using 'Articles' for this lesson.

  2. Head over to settings.py and include your app name in INSTALLED_APPS:

dense slate
#

ok so you probably will end up putting something in urls.py, so you need to create that

forest copper
#

ooh so now I should create a urls.py file inside migrate?

dense slate
#

You create an urls.py in the main_page folder

forest copper
#

ooh wait

dense slate
#

Migrate has nothing to do with this, you're just trying to migrate when there is an error in your code.

forest copper
#

As seen, Django automatically creates files inside your app folder. We are going to go through their purposes as we continue creating our website.

dense slate
#

So it won't let it finish.

forest copper
#

according to tryhackme it creates it automatically

dense slate
#

Yea, it should be, but it's not, so make it.

forest copper
#

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'))
]
#

the one in the app (main_page) or the one in the parent folder of the app

dense slate
#

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.

forest copper
#

but

forest copper
#
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!

dense slate
#

Figured. πŸ˜‰

forest copper
#

hehe hopefully

#

any tips for nick pain

jaunty magnet
#

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?

frank shoal
#

as long as you can return json, it should work

#

if you want a way to connect them, I use nginx-unit

dense slate
broken mulch
#

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

orchid knot
#

How do I configure a apache2 server on Windows 10

#

or should i just use nginx

#

because it is simpler

tawny dove
#

how do you make a login form with django

#

i have tried multiple different tutorials and couldn't find anything that worked

white basin
#

Or Wamp

dense slate
#

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.

hollow dune
#

ping when replying pls

dense slate
#

I don't think it is.

#

Unless it downloads a file?

weary mica
#

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

warm cove
#

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

weary mica
#

check free website templates to get some inspiration

quiet wigeon
#

yeah, looking at free templates are great

#

and you can use bootstrap or tailwindcss to easily style it

pallid lily
#

which libraries are used to create AI chat bots in python that is efficient and executed by C++ like numpy?

weary mica
#

numpy is written in C

#

pytorch is written in C++ but not sure if it's used to create "AI" chat bots

weary mica
brazen bane
#

Recommended CSS framework to be used for Django?

quiet wigeon
#

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.

broken mulch
#

like route "index.py" would return filesystem.ReadFile("path/to/py/file.py") with like text/py

slim crow
#

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?

crisp barn
#

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

pallid lily
#

@weary mica thanks bro but do you recommend Tensorflow?

iron ginkgo
#

!voiveverify

lavish prismBOT
#

You are not allowed to use that command.

quiet wigeon
# slim crow does anyone know why this keeps happening?

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()
])
quiet wigeon
crisp barn
#

no it just doesnt render the 0

#

i might just not have vue installed correctly

#

i did run npm install vue --save

jovial blaze
#

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?

hot rampart
#

I have question does a website can be consider as dynamic website when it uses JS

manic crane
#

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)

inland oak
#

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

inland oak
#

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

glass island
#

flask admin

#

how do I change the name of "Admin"

#

and it's redirect url

jovial blaze
#

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...

β–Ά Play video
jovial blaze
glass island
glass island
#

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.

forest copper
#
# 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?

inland oak
ocean raft
ocean raft
inland solar
#

hi

#

m not able to send data to database can anyone help me out

#

plz

jovial blaze
ocean raft
inland solar
#

can someone help me

jovial blaze
# ocean raft oh okay, keep adding what you find. i might check it aswell

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

GitHub

A very minimal website I build while learning Django. - GitHub - techwithtim/Django-Website: A very minimal website I build while learning Django.

jovial blaze
ocean raft
jovial blaze
#

oh my bad

jovial blaze
inland solar
#

nothing no error thats y i cant figure out the problem

#

there is an error about image but ill fix that later

jovial blaze
frank shoal
#

You need to make a POST request, i.e. with a <form> tag

inland solar
#

i am fetching it from the form and sending it to data base but its only fetching data not sending

frank shoal
#

Needs to be POST

inland solar
inland solar
frank shoal
#

methord

inland solar
frank shoal
#

should be method

inland solar
#

wait whatπŸ˜‚

#

nop still nothing

frank shoal
#

restart the server

#

If you're not using a debug mode, it's probably caching the template

frank shoal
#

Is it fixed now?

inland solar
inland solar
lavish prismBOT
#

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.

autumn birch
#

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()))
. . .
autumn birch
#

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```
tall sentinel
#

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

forest copper
#

Oh yes good question

inland oak
# tall sentinel Hi guys i just wanna know about the general process while making a website (for ...

https://www.amazon.com/Systems-Analysis-Design-Alan-Dennis/dp/1119496500
For starters reading a book how to plan programming product

#

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

stable bear
#

how do you do this in django: if you have a button, when you click on it, the contents of the page change

autumn veldt
#

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)

frank shoal
#

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

inland oak
stable bear
#

really any content - like a paragraph going from hello to goodbye

inland oak
stable bear
#

could the same just be achieved with some javascript code?

inland oak
#

Reuse base template, so only paragraphv would be changed

stable bear
#

what is the difference between using django/python for the logic and using javascript for logic?

inland oak
#

No white screen delay too

stable bear
#

so is the only thing that uses django just forms?

inland oak
stable bear
#

yes client side is what i had in mind

inland oak
stable bear
#

do programmers only use django, for the purpose of making forms?

inland oak
stable bear
#

ok

inland oak
#

We can change making request to anything, making any js action, instead of standard Post request

quiet wigeon
#

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?

inland oak
quiet wigeon
#

I'm asking this because most questions on here are how to make my page interactive with python

inland oak
#

U have too vague non answerable question

#

Make it somehow formulated better

agile pier
night sequoia
#

need help in django

#

how to set default value in select model form

steel night
#

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:

  1. The most common "ad-hoc" approach, where JS just gets incrementally added to templates until you find yourself in a mess
  2. The "completely decoupled" JS front-end and Django-API back end, which is popular, but com...
β–Ά Play video
#

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...

β–Ά Play video
agile pier
night sequoia
#

yeah but it doesn't work

#

look at city

steel night
#

@night sequoia that's the model not a form

inland oak
night sequoia
#

how i can add default attribute in form.py

inland oak
agile pier
# night sequoia

i think maybe null=True and default attribute dont go together

inland oak
#

It can be statically linked too

night sequoia
steel night
agile pier
tepid lark
#

htmx is cool

night sequoia
#

alright

tepid lark
#

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

agile pier
native tide
#

Do you think following and copying Django tutorials will be good for learning how to make an application?

warm cove
#

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

atomic sentinel
#

hey guys im front end beginner , to make the website works on the backend, what backend languages should i learn?

tawny dove
#

can i have sample code for a basic django login

glacial kelp