#web-development

2 messages · Page 161 of 1

inland oak
#

hmm, doing some analysis, I think probably choosing React, though some info about Vue is quite sweet too
React looks like 4 times more popular solution and higher in demand

wraith cloak
#

how to setup a favicon :)

calm plume
#

Using raw HTML?

calm plume
#

Although I've heard that many people enjoyed Vue since it keeps JS and HTML separate a little more, which is more like Vanilla HTML/JS with a couple really nice touches

#

I've never touched Angular personally

prisma canopy
#

I am making a flask website with use of bootstrap. When I click on options provided on nav bar, sometimes some options changes their end point to the file from which they are being rendered and give not found error.pls help

obsidian rain
#

hey i want to know how should i start making websites should i learn html css or start with django and flask??

#

please please dm me with answers

calm plume
low glen
#

can i ask some general questions in this group , about web development

native tide
#

can anyone suggest a cousre for django, or should I go for flask, as i am a newbie

prisma canopy
#

Hi, Like I am having a contact page which is connected to sqalchemy database using xampp, but my contact is not working I mean when user fills and submits, I am not getting a entry on my database, can anyone help me with this please. It's some kind of urgent

dense slate
#

I am such a dope for asking this...
In SCSS, I can import a color file (@import 'whatever.js' which has export const Color ...) with my hexvalues and use $darkGray throughout the file. What's the equivalent for a CSS file when importing the colors?

#

Can't seem to find a way to use the variables from the color file in a basic css file.

calm plume
#

I don't believe that's possible in CSS, it's something that the Sass team added

abstract coral
#

anyone here with Python experience who can help me out 😭 ? I got this beginner python/flask project (+html+css+js+MongoDB) due in 9 days, been stuck for 48 hours now trying to get this CRUD functionality to work (building a comment section), if I can't get it to work soon I'll never submit this project in time. 😓

outer apex
outer apex
#

Got some code to share - the form and probably the model? Getting any exceptions raised?

wheat skiff
#

hi, im trying to build a chat with django channels or sockets
any one can help with it?

#

please contact me in private message

proven yew
quasi relic
#

hey everyone, is there a way to clear the users session after a specific time and logout them / in order of inactivity or anything else

#

like I made a configuration on my app for myApp.config['PERMANENT_SESSION_LIFETIME '] = timedelta(seconds=10) but still not workin

#

and also made a session config session.permanent = True

#

flask

outer apex
quasi relic
buoyant geode
#

any body here done any minimal application with flask and postgresl which involves models and some migration stuff??

#

please send me any resources or github repo

outer apex
#

You're not adding the correct object to db.session. You're adding an instance of the form, when you're probably wanting to add an instance of the model, I presume the Test model?

spice bane
#

How do you dynamically create divs from a JSON file?

outer apex
proven lily
#

@fair shale

#

You can't have two returns in a function

#

Oh nvm mb

#

You should really use code markup for readability

native tide
#

yo

#

can someone tell me the line of code for inserting an image from a link in html? cuz I cant find it anywhere lol

proven lily
#
print("Hello")```
#

So it looks like that

#

Nah it's

#

And the three at the end

#

You need three

#

In front and end

#

And you can add the lang

#

Etc

#

😂

#

It's back ticks

#

`

#

Copy it

#

Lolll

#

Np

outer apex
native tide
glacial plank
#

hey so im making a portfolio website and im trying to make it mobile responsive but am having issues.
This is what the page looks like when i inspect and put it into a mobile format, none of my changes (menu icon plus hidden slide nav bar) appear it just stays as the desktop version but terribly formatted. How would I implement responsiveness properly?

#

CSS for the mobile part

@media(max-width: 700px){
    .text-box h1{
        font-size: 40px;
    }

    nav img{
        width: 100px;
        padding-top: 10px;
    }

    .nav-links ul li{
        display: block;
    }

    .nav-links{
        position: absolute;
        background: #f44336;
        height: 100vh;
        width: 200px;
        top: 0;
        right: -200px;
        text-align: left;
        z-index: 2;
        transition: 0.75s;
    }

    nav .fas{
        display: block;
        color: #fff;
        margin: 10px;
        font-size: 22px;
        cursor: pointer;
    }

    .nav-links ul{
        padding: 30px;
    }
}
#

any help would be appreciated, im not very experienced in web dev

median loom
#

what are the apps needed in gunicorn?

#

not sure if they're the same apps used in django

quick cargo
#

Its a standard WSGI server with the ability to run ASGI workers

#

so pretty much any WSGI or ASGI framework

#

you dont need to

#

but its a very popular server for that

#

other forms include uwsgi, meinhead etc...

median loom
#

oh sorry, let me rephrase my question

#

because there's an app parameter when running gunicorn

#

what should i put there?

quick cargo
#

its basically a string

#

in the form of

#

file_name:app_varible

#

e.g.

#

if you file was called foo.py

#

and your app variable was called app

#

it would be

#

"foo:app"

#

If i remember correctly

#

in django you want to target the wsgi file

median loom
#

hmm ok

median loom
#

but i still don't know what that app specifically is

austere cairn
#

Y tf does this error

#

Ignore the phone coding

median loom
#

you forgot the end parenthesis on that format

quiet garden
#

anyone who knows about flask login

manic frost
scarlet spoke
#

I cannot find the live server button

#

i have the extension downloaded

unborn lion
scarlet spoke
#

the button to start the live server

unborn lion
#

na idk how to do tht sry

scarlet spoke
#

oh its fine

noble spoke
#

Is it not in the right click menu?

unborn lion
#

Ik what you should do

#

use one of the help channels

#

they will be able to help you better

scarlet spoke
#

never mind i found it

#

i used the command pallete

unborn lion
#

lol

scarlet spoke
#

lol should have done that first 🤣

unborn lion
#

😆

stark tartan
#

Any best book or video of Django Rest framework

near ravine
stark tartan
near ravine
#

and how do i make it work and adjust in all platforms

near ravine
#

why?

compact surge
#

Why i can't take the form from HTML?

#

The Table from Postgres

                          {% for i in Statements %}
                    <tr>
                        <td id="type_">{{i.id}}</td>
                        <td id="name_">{{i.name_id}}</td>
                        <td id = "url"><a href = "/testword" class="button" target="_blank">
                            <button type="submit">Сформировать</button>

The form with input

        <div class ='panel'>
            <b><label for = 'date'> Дата начала:</label></b>
            <form method="Post" action="/api/">
                <p><input type="text" id = 'datebegun1' name="datebegun1"></p>
                <p><input type="time" id = 'time1' name="time_begun"></p>
#

Python code

@app.route('/api/', methods=["Post", "Get"])
def testdate():
    if request.method == "Post":
        datebegun = request.form.get("datebegun1")
        print(datebegun)
        return datebegun 
    print(request.form)

def write(datebegun):
    doc = DocxTemplate('../sv_site/app/static/storage/vacation.docx') #исходный файл
    context = {'current_account': 'Name', 'id_account': (os.getlogin()), 'date_begun': datebegun,
               'days': "14"} #тэги в ворде
    doc.render(context)
    path = '../sv_site/app/static/storage/vacation1111.docx' 
    doc.save(path)

    return path

print('OK')


@app.route('/testword', methods=["Get"])
def test_word():
    """
    :return:
    """
    datebegun = request.form.get("datebegun1")
    path = write(datebegun)
    file = open(path, "rb") 
    return send_file(file, as_attachment=True, attachment_filename='File.docx')  
print("ok")
#

I just tried to grab the value from the datebegun1 in html and put it to the docx file

#

But the file opening with None

#

I try to send the form datebegun1 to the button and put the value from the form to .docx file

native tide
#

What is the best way to advertise my website?

buoyant geode
#

how to do migrations in flask

#

I want to do it from manage.py what code should be really included in that Im confused

jovial cloud
worn sail
#

yo guys im getting a error saying theres no such class for the find element by class name although there is a class by that name in the webpage can someone help,Thanks!!

jovial cloud
jovial cloud
# worn sail

To make that a single class, try using underscores or hyphens between words without the spaces. Like class='action-primary-checkout'

#

Since you're making a request, use of the classes that the button belongs to

worn sail
worn sail
jovial cloud
jovial cloud
# worn sail Its not mine

Alright. You can use one of the classes. However, note that you might get other elements which have the same class on it.
To avoid that, I would advise using another method instead of findbyclassname to get a unique element

worn sail
glass sedge
worn sail
worn sail
stark tartan
maiden jolt
#

Hey, what would be the best way to share data from a C program to a web page?
I have a C program doing stuff and i want to share a buffer of 1kB of data. And i'd like to draw rectangles on a webpages based on the data from the C program.
I'm currently using P5js to draw on the page.
To share the data I'm writing in a file with the C program and reading from it with loadBytes(). It works fine when i'm doing it once, but i'd like to do it every 100 ms or so. but when i try i'm not getting any data with the loadBytes() function, probably because the C file is already writing in it...
Is there any faster way to share those data ? UDP socket? other things i don't know?
Thanks.

compact surge
#

That what i see

vestal hound
compact surge
#

When i print(request.form), the python put the value of the form and in file its looks like that ImmutableMultiDict(['datebegun1', 123456])

near ravine
jovial cloud
compact surge
#

everybody

#

its just my first project in python

#

i found my problem.

#

I have 2 <form>

#

Now,i had 2 form

#

/testword and /testdate i made the Post method

jovial cloud
compact surge
#

Yes

#

It wasnt in the <form>
{% for i in Statements %}
<tr>
<td id="type_">{{i.id}}</td>
<td id="name_">{{i.name_id}}</td>
<td id = "url"><a href = "/testword" class="button" target="_blank">
<button type="submit">Сформировать</button>

buoyant geode
#

Hi I am trying to do migrations in flask i.e, trying to add table users but not happening pls some one help

jovial cloud
thorny nest
#

hey, i have this code

async def get_json(url: str = 'https://discordpy.readthedocs.io/en/stable/'):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as req:
            return await req.json(content_type='text/html')

but i keep getting this error

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

can someone please help

crystal rover
#

Why do you expect that url to return json?

#

(if I curl it it just returns html, like I expected)

thorny nest
#

so is there anyway to convert it to json?

crystal rover
#

what would you even expect the output to look like?

thorny nest
#

havent ever worked with json before ¯_(ツ)_/¯

crystal rover
# thorny nest havent ever worked with json before ¯\_(ツ)_/¯

ah, okay. Json isn't some magic bullet, it's just a way of representing objects. If you have a document (website, api endpoint, config file, whatever) that uses json as its format, great! It's really easy to work with. If you don't, you can't trivially convert it to json.

thorny nest
#

oh

#

cool thanks a lot!

crystal rover
thorny nest
#

wokie

cinder leaf
#

Hey fastapi’s users, I have a few classes that I use in all my app, but I only want one instance of each for all my handlers (no need to create them again as there are things like database connection etc). Could I just use globals?
I’m not sure it’s the right pattern with fastapi as there is the dependency Injection pattern that is well established.
After doing some research people proposed a lot of different solutions but it just seems to be over engineered globals (lru_cache, global factory class…)
So in the end I think I’ll use globals, how do managed this?

void wagon
#

How to make Flask scroll to a part of the page?

compact surge
void wagon
#

I did not find my answer thats why I copied the question

neat briar
#

Hi guys
I am facing a problem in Django forms
This is what I need :

There is a ChoiceField with two choices.
If a user selects the first choice, one text field is shown
If seond choice is selected, two text fields are shown.

Can somebody help?

glad patrol
#

Make the fields hidden when you select the corresponding choice field call the textfield with it's label

golden plank
#

Hello. Who can help me. I do not understand how to write a code in which each letter moves to the next. For example ABC - BCD. Thanks a lot in advance

compact surge
#

ord('b')
98

compact surge
#

На здоровье/bless you

hollow sparrow
#

can u provide me with some good resources for starting with django and flask?
which one do u think i shiud be going with, django or flask? Im a beginner in web development
i would be glad to receive suggestions

minor patrol
#

Helloo I am looking for a Discord server based around browser extensions/add-ons. Does anyone know any?

wide canyon
#

I use django. I hear flask is good for lighter stuff. If your OOP is decent by all means Django. If it's not and you still go with Django you'd have to learn as you go. I prefer books to courses. I'd suggest django 2 by example. That's what I started with. Adrian Holavary's "The django book" can be used as a supplementary material too. Follow the JustDjango channel on YouTube. Really good content. Remember to visit the docs. If you find a good material for flask you can tell me about it. I'd like to try my hands at that too. Cheers.

wide canyon
#

Hello everyone. Please suggest projects a backend dev could work on to build his portfolio. I'm comfortable with django,drf, channels etc. I just never paid attention to building a good porfolio till now. Most of the things I've worked on don't belong to me so I can't really use them. Suggest projects that would impress you if you were tohire a junior developer. Thank you

native tide
#

How do i access a instance of a user in my javascript with django

#

The questoin is hard dm me plz

weary pond
#

hello everyone is it possible to define a foreign key before django model ? like this :```py
class Model1(....):
test = models.Foringkey(Model2 .... )

class Model2(....):
...

austere cairn
#
@app.route('/check')
def access_param():
  key = request.args.get('key')
  hwid = request.args.get('hwid')
  discord = request.args.get('discord')
  return "key:"+str(key)+"\nhwid: "+str(hwid)+"\ndiscord: "+str(discord)
  database = cluster["test"]
  collection = database["info"]
  post = {"_id": 123, "Key": key, "DiscordId": discort}
  dbi()
  collection.insert_one(post)
  

im using flask and this wont add the stuff into the database, whats wrong, ive been trying for over 30 mins

rain wren
#

hello good day, in creating a Django project, is it really necessary to create an virtual environment to a single Django Project?

#

or is it okay to have 1 virtual environment for multiple projects?

calm plume
rain wren
#

Like I will install the virtual environment to a root folder

rain wren
#

I was so confused cause the tutorials that I looked up to are different

rain wren
calm plume
#

Are you using a manager like poetry or pipenv?

rain wren
#

uhm I'm sorry I could not get terms cause I am a beginner when it comes making Django projects 😅

#

well now my guide is the django docu

calm plume
#

How are you installing your dependencies?

rain wren
#

oh wait is this the requirements.txt ?

covert prism
#

from werkzeug import generate_passord_hash, check_password_hash
when I use this it is showing me an error how can i fix this?

hoary ibex
#

now i made an index.py, but i get a 403 forbidden. I look in the logs and i see this: AH01276: Cannot serve directory /var/www/vhosts/tekx.it/tekxitdev/tekxitDev/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml,index.htm,index.shtml) found, and server-generated directory index forbidden by Options directive, referer: https://*******.ultrasrv.de:8443/

#

so apparently it's not looking for an index.py i assume? anyone has experience with this?

#

when i turned on ngix reverse proxy and changed the additional directives from apache to ngix ones
AH01276: Cannot serve directory /var/www/vhosts/tekx.it/tekxitdev/tekxitDev/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml,index.htm,index.shtml) found, and server-generated directory index forbidden by Options directive

#

i had those settings in the top boxes first with ngix reverse proxy disabled, then enabled reverse proxy and moved it down one as i read online

#

it's not in the default httpdocs since this is a subdomain (a development subdomain, the regular one works normally and is a standard html (and a bit of php/JS) site

austere cairn
#
def access_param():
  key = request.args.get('key')
  hwid = request.args.get('hwid')
  discord = request.args.get('discord')
  #return "Key:" + str(key) + "\nHwid: " + str(hwid) + "\ndiscord: " + str(discord)
  database = cluster["RegisterableKeys"]
  collection = database["UsedKeys"]
  penis = collection.find_one({"DiscordId": discord})
  sorted_string = json.dumps(penis, indent=4, sort_keys=True)
  return sorted_string

it returns null, idk y

hoary ibex
#

If you need a more precise file structure

#
*****
httpdocs
-(working apache html/php page)
****
tekxitdev
-python-app-venv
--(venv stuff)
-tekxitDev
--manage.py
--tekxitDev
---__init__.py
---asgi.py
---index.py
---settings.py
---urls.py
---wsgi.py
-tmp
--restart.txt
-passenger-wsgi.py
#

the passenger_wsgi.py

import sys, os
ApplicationDirectory = 'tekxitDev'
ApplicationName = 'tekxitDev'
VirtualEnvDirectory = 'python-app-venv'
VirtualEnv = os.path.join(os.getcwd(), VirtualEnvDirectory, 'bin', 'python')
if sys.executable != VirtualEnv: os.execl(VirtualEnv, VirtualEnv, *sys.argv)
sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory))
sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory, ApplicationName))
sys.path.insert(0, os.path.join(os.getcwd(), VirtualEnvDirectory, 'bin'))
os.chdir(os.path.join(os.getcwd(), ApplicationDirectory))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', ApplicationName + '.settings')
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
#

i got a new error now: changed these settings

#

no longer proxy mode and those boxes are filled in different

#

24487#0: *235 connect() to unix:/tmp/passenger.jRn0OxH/agents.s/core failed (111: Connection refused) while connecting to upstream

#

nvm that error log in invalid, this is the only thing that appears

buoyant geode
#

ImportError: cannot import name 'CarsModel' from partially initialized module 'flaskapi' (most likely due to a circular import) (H:\crossplatfrom_flutter\flask_api\f laskapi.py)

#

how to resolve this error

#

pls some one help me

hoary ibex
#

so you have 2 or more files importing eachother in a circular fashion

buoyant geode
#
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_restful import  Api
from index import HelloWorld
app = Flask(__name__)
api = Api(app)
api.add_resource(HelloWorld, '/')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://postgres:1234@localhost/flask"
app.debug = True

db = SQLAlchemy(app)
migrate = Migrate(app, db)

class CarsModel(db.Model):
    __tablename__ = 'cars'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String())
    model = db.Column(db.String())
    doors = db.Column(db.Integer())

    def __init__(self, name, model, doors):
        self.name = name
        self.model = model
        self.doors = doors

    def __repr__(self):
        return f"<Car {self.name}>"
#
from flaskapi import CarsModel
from flask import request, json
from flaskapi import db
class HelloWorld(Resource):
    def get(self):
        cars = CarsModel.query.all()
        cars = cars.dump(cars).data
        return {"status": "success","data":cars}, 200

    def post(self):
        json_data = request.get_json(force=True)
        if not json_data:
            return {'message': 'No input data provided'}, 400

        data, errors = json.load(json_data)
        if errors:
            return errors, 422
        user = CarsModel.query.filter_by(name=data['name']).first()
        if  user :
            return {'message': 'User already exists'}, 400


        cars = CarsModel(name = json_data['name'],
                id = json_data['id'],
                model = json_data['model'],)

        db.session.add(cars)
        db.session.commit()

        result = CarsModel.dump(cars).data

        return {"status": 'success', 'data': result}, 201```
#

these are the two files

hoary ibex
#

could you do this please?

#

!code

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

buoyant geode
#

!code

hoary ibex
#

but i see it already i think

#

in the flaskapi.py you import from index import HelloWorld

#

if you look at index.py you import from flaskapi import CarsModel and from flaskapi import db

#

so you see these 2 files are importing each other in a circular fashion

#

and that's the error

#

you following me?

buoyant geode
#

so what should i remove

hoary ibex
#

not have a circular import

buoyant geode
#

i get u r point

hoary ibex
#

so you will need to rework your code so that 2 parts of your code are depending on one another in a circle

#

so flaskapi has a class which depends on the class helloworld from index, but that helloworldclass depends on the carsmodel class in flaskapi

#

can't have it 2 ways like that

buoyant geode
#

okay

#

then how to make HelloWorld as a resource

hoary ibex
#

and looking at it, in flaskapi the import index is unused, so you can just remove it

#

and that will probably make it work

buoyant geode
#

okay

#

from index import HelloWorld app = Flask(__name__) api = Api(app) api.add_resource(HelloWorld, '/')

#

I am using it

hoary ibex
#

ah whoops missed it

buoyant geode
#

I want to access helloworld as resource how to do that

hoary ibex
#

i'm not familiar with flask in any way so i cannot help beyond this sadly

buoyant geode
#

np

#

I just started using flask

hoary ibex
#

haha nice

#

i wanted to get started with django but i'm not getting it started either

buoyant geode
#

okay

hoary ibex
#

apparently the passenger_wsgi.py needed a chown to ngix

formal dragon
#

hi, are there any Jinja2 config experts around?

mint folio
agile cobalt
#

With gunicorn it's adviced to use nginx or something similar. Is that only because of the thundring herd / buffering problem or are there more benefits of using nginx as a reverse proxy ?

formal dragon
#

I need to change the {{ }} to another pair. I have a solution that works for Flask, but I need a general approch that will work in FastAPI.

boreal garden
#

I am trying to get my page to show "Hello World" when I run the code there is no error but it also doesn't show hello world only the default beginning rocket animation, here is the code

main.urls code:

from django.urls import path

from  . import views 

urlpatterns = [
path("", views.index, name="index"),
]

main.views code:

from django.shortcuts import render
from django.http import HttpResponse



# Create your views here.

def index(response):
    return HttpResponse("<h1>Hello World!</h1>")

And mysite.urls code:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include("main.urls")),
]
#

please ping if you have come up with a solution 🙂

outer turtle
#

Can you look at a website and guess what types of architecture they used?

austere relic
#

and then there's aiohttp that adds a "server" header on each response

vestal hound
cyan lotus
boreal garden
#

ok

boreal garden
cyan lotus
boreal garden
#

wdym?

cyan lotus
boreal garden
#

yeah thats what I've been doing

#

idk

#

my code seems fine

#

but it won't work

cyan lotus
#

try delete all pycache folders and re-run the server

boreal garden
#

alr

#

nope

#

that didn't work either

#

@cyan lotus anymore recommendations?

#

I followed the video two times, two different folders and line for line

#

I'm just at a loss

cyan lotus
boreal garden
#

ok

#

this is the code

cyan lotus
#

django didn't try the index url

#

at this point I'd reinstall django

boreal garden
#

damn

cyan lotus
#

also it's index/ with/

#

try index/ before reinstalling

#

my bad

bronze palm
#

his django isn't recognizing his app I suggest setting up a new virtual enviroment and recreating the app

mystic badge
#

Hello, I am begineer just looking for a lot of fun in web development, i am unsure which framework to do, FLASK / DJANGO

inland oak
mystic badge
#

Ok, flask then

#

thank you :0

#

🙂

grim seal
#

I'm following a Django tutorial, and I am busy copying three basic models from the tutorial. My Profile class:

class Profile(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.PROTECT
    )
    website = models.URLField(blank=True)
    bio = models.CharField(max_length=240, blank=True)

Then in my Post model, I have this line:

author = models.ForeignKey(Profile, on_delete=models.PROTECT)

How does this foreign key magic work? I would have thought that for an FK, I must specify a name for the foreign property.

vestal hound
grim seal
#

I mean the property in the other class that that is the foreign key field that links to the property marked as type ForeignKey. E.g. what property links my author property to the Profile class.

vestal hound
#

by default it'll be {model.__name__}_set

#

oh wait hold up

#

yeah so a Profile will have a post_set

#

because it's one (profile) to many (posts)

vestal hound
#

through metaclasses (I think)

grim seal
#

Ah, dark voodoo indeed 😆 . Thanks

vestal hound
#

but Django was really made more for people who weren't programmers first, IIRC

#

yw! 👋

#

lastly

#

you can change this with the related_name kwarg in your ForeignKey

grim seal
#

Aah, more sense now. Cool beans

hollow sparrow
past oar
#

I'm using Linux on AWS Lightsail to host my django project with Apache. I connect using SSH. I cannot seem to get the db to work without setting permissions to 777, I see that it's not recommended as any user can write to the file. But, if somebody manages to connect to my server as a user, I am not screwed anyway? Am I correct to think that I am protected by SSH anyway and setting permission 777 doesn't matter as I'm the only user?

hoary ibex
#

there's built in protection still but you're removing one layer of protection

past oar
#

Okay thanks!

buoyant shuttle
#

How dk I make my website mobile responsiveness

#

Like what is the ideal width, that indicates it's a tablet or phone

austere relic
#

Ideal width of what?

calm plume
#

And sometimes a larger one

coarse haven
#

whats the point of media queries when flexbox and grid exist?

buoyant shuttle
#

Are there any screen bigger than 1200px?

calm plume
buoyant shuttle
#

There should be a way to move an element 70% of the width

#

That way it would be consistent

calm plume
#

width: 70%; exists, which would make it take 70% of the parent

buoyant shuttle
#

I'll set the parent to 100%

calm plume
coarse haven
#

but why do you need media for that, flexbox and grid will already do that

buoyant shuttle
#

I want to place a graph consistent in all platforms

buoyant shuttle
#

Sorry

calm plume
coarse haven
#

o. is there a reason why you wouldn't want to flex or grid? in my very new to frontend experience i was feeling like media queries were the way like 10 years ago and now you just flex and grid

calm plume
buoyant shuttle
#

Move the position 70% of the parent, moving the element

#

With position relative

#

I'm playing with inspect and if I move my screen width to more rbag 1600 my graph doesn't seem all that left it would feel centered

calm plume
coarse haven
#

like fully removing the columns on a smaller screen, or just moving them below the other columns so like 1 2 3 4

calm plume
coarse haven
calm plume
#

For example, take a look at stripe.com. They have grid columns in the background, and if you change the size of your browser window, you can see the number of columns that you see in the background get smaller as it gets smaller

buoyant shuttle
calm plume
#

Uh, relative probably

#

Here's a gif showing how the columns on that site adjust based on width

buoyant shuttle
#

Still don't know the main difference between 2,

#

Lol

calm plume
coarse haven
calm plume
#

Do you see those column dividers in the background?

#

Those were generating using css grid

coarse haven
#

lexbox

#

with a css grid to setup inside

#

the flexbox is choosing how wide it is

buoyant shuttle
calm plume
#

Yes, flex is choosing the column width

#

But media queries are choosing the actual column count

coarse haven
#

👍

#

ok i see

coarse haven
#

your site changing the content of the column i understand i guess, but not this

calm plume
coarse haven
#

oh, so media queries can keep it uniform but grid by itself cannot

#

theres no way to tell grid that if it has to wrap, to fill both rows evenly?

calm plume
#

Uhhhhh, no idea

coarse haven
#

fair enough

#

well thanks dawn you opened my eyes a bit 🙂

coarse haven
#

see the orange box difference from relative, in the flow with all the others, to absolute, takes it out of the flow and throws it in the top left

buoyant shuttle
#

Np

coarse haven
#

my understanding is you generally want to not use it unless you absolutely have to since it makes for hard debugging, but dont trust me im as new as you are haha

coarse haven
#

Never use selenium unless you are testing your own site. If you really need the js to run use requests-html or something that can render it

#

But you generally don't need the js to run, more rather you are doing the wrong thing

#

Cant help with ytdl that's against tos

#

Not at all

#

It's like a tank compared to a pistol. Do they both shoot things? Sure. What do you want to use in your backyard for hitting a pop can

#

And you still don't need that js to run 9/10 times

#

What's the js doing?

#

lol... At least have a specific instance in mind before trying to argue you need the js to run

#

None of that requires js to run on your end

#

Just make the same final login request that the js put together and called

#

Rendering a video? Where's it rendering from? Make the same request

#

You need to hang out more in your network tab

#

Learn what the site is doing under the hood

#

Yes

#

Wow your logged in

#

Without the sites js running to build a form. Without even loading the login page at all.

#

Wouldn't be parameters that's the = stuff inside of a url

#

But yeah you send the login as a post

#

Tank vs gun example

#

Selenium for instance comes with support for like 5 different browsers and a shit ton of other crap

#

Puppeteer (what's under the hood of requestshtml) does not

#

That's why it's way lighter and better

#

Takes 1/3 of the time plus faster to code

#

But again, you generally don't need to render the js your doing something wrong 9/10 times

#

I mean, I hate bs4 personally. I'd just use requests html. It's a fork of the normal requests by the same core dev with bs4esque commands added in

#

But if you use requests or urllib bs4 is needed to parse

#

Most people seem to prefer using the bs4 way but I wonder if that's just memes being spread around like selenium usage

#

Idk

#

Maybe you prefer one way over the other

#

Maybe bs4 is a millisecond faster

#

Idk

#

👍

topaz basin
#

how can i solve it

lunar igloo
#

hey there! i've never worked on server side dev in python, but i have used nodejs before, i'm debating between django and flask, which one is easier to pick up?

calm plume
#

Flask is easier to start off with since it's a microframework

lunar igloo
inland oak
#

Wait a second.
If I have data stored in memory of application running with Gunicorn...
...and during interaction with one of workers I stored in memory some changed state...
does it mean that it got recorded only into memory of ONE of workers?

#

All other workers will have their memory clean from this record?

#

uhuh. So if I'll have situation like that I need to organize a way for a shared memory across workers.

mossy hamlet
#

Hi!
Anyone experienced with Flask and fcgi?
I have an issue that when I run the code via the fcgi file in the server then none of the paths are found unless they are defined in the fcgi file directly.

On my local, I don't have fcgi file but a regular run.py that basically just creates the app.

What extra config do I miss to get the blueprint routes to the server instance?

scarlet spoke
#

I have a question about python web developement

#

lets say i have a website, and there is a button there

#

on the button press, can python code be executed?

ivory bolt
#

it's not really that hard

#

There's a great introductory video by freecodecamp on yt

ivory bolt
scarlet spoke
#

thanks!

#

is django another language or library?

ivory bolt
#

it's a framework

scarlet spoke
#

What does it do?

ivory bolt
#

for web-development in python

#

an oversimplication -- it handles the backend

scarlet spoke
#

ohhh

ivory bolt
#

so you can add the entire site logic

scarlet spoke
#

Alright

#

Django doesn't handle front end then?

ivory bolt
#

it's a VERY good framework in my opinion

scarlet spoke
#

like how the website looks

ivory bolt
scarlet spoke
#

Dang.

#

Seems like a good framework to study.

ivory bolt
#

but it's not a frontend framework. It works well withother front-end frameworks like reactjs, angular, etc

hard patrol
#

!code

inland oak
quick cargo
#

I think you're looking for print in python bloblul

idle moss
#

can someone quickly dumb down how python can be used to do some stuff in another app/website, thanks

quick cargo
#

backend

idle moss
quick cargo
#

cant really be used to do frontend work (although it can do server sided rendering of HTML with things like jinja2)
Backend wise they can act as the content server rendering content like the aforementioned point on frontend, it can be used as REST api / other API backends. Just what ever really

#

APIs are just a general term used for on thing communicating with another thing really

idle moss
idle moss
quick cargo
#

litterally anything

hasty cosmos
#

Does anybody have experience with multi-part forms in aiohttp? i think i get the server side stuff but i cant understand client side for the life of me

honest crescent
#

how can i make an image circluar in css? or that not possible

quick cargo
#

border-radius: 9999px

austere relic
#

what if my screen is very large?

vestal hound
#

in the simplest case (square image), border-radius: 50%

#

otherwise, specify height/width (along with object-fit

honest crescent
#

so i could do that

inland oak
#

Besides print
from pprint import pprint
pprint(yourdata) is nice too. It has auto formatting, identations for easier reading

weary belfry
#

hello can anyone come in help banana

#

?

tight dust
#

Everytime I make some small changes in CSS and reload the website, the flask server doesn't load the new CSS file

#

is there any solution to this?

#

I tried disabling caching by changing headers as suggested in a SO answer, but that doesn't seem to be working

#

@app.after_request def add_header(r): r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" r.headers["Pragma"] = "no-cache" r.headers["Expires"] = "0" r.headers['Cache-Control'] = 'public, max-age=0' return r

light apex
#

anyone here working with wolframalpha api?

#

is this the right channel for api though 😅

mossy hamlet
#

Hello.
I have been struggling with this issue for a long time now and I can't find answers online.

I'm trying to deploy a Flask app to an Apache server, with fcgi.
The file that runs the app, dispatch.fcgi, is below.

The issue is that when deployed, it can only find the routes that are @spare ridge.route in the same file.
It does not find any of my blueprints or blueprint routes. Nor can I create blueprint routes in this file after creating the app.

The application works on my local. Only difference is that instead of this file I run a run.py which just creates the app without extra config that Apache wants.

How can I get it to find my blueprint routes?
PS: It's a shared host, therefore I don't have root access so the fix I'm looking for should probably be on py side.

#!/usr/bin/env python3.7

import os, sys
sys.path.insert(0, "/www/apache/domains/www.somedomain.com/hinnang/hinnangapp")
from hinnangapp import create_app

os.environ['REQUEST_METHOD'] = "GET"
os.environ['SERVER_NAME'] = "somedomain.com"
os.environ['SERVER_PORT'] = "80"
os.environ['SERVER_PROTOCOL'] = "HTTP/1.1"
DOMAIN = "somedomain.com"
PREFIX = "/www/apache/domains/www.somedomain.com/"

sys.path.insert(0, os.path.join(PREFIX, ".virtualenvs/hinnangapp/lib/python3.7/site-packages/"))

from flup.server.fcgi import WSGIServer
from flask import Flask

app = create_app()
@app.route("/")
def hello(): #<- this works
    return "Hello World! <a href=\"test/\">to test</a>"


class ScriptNameStripper(object):
   def __init__(self, app):
       self.app = app

   def __call__(self, environ, start_response):
       environ['SCRIPT_NAME'] = ''
       return self.app(environ, start_response)

app = ScriptNameStripper(app)

#@main.route("/home") #<- tried to create a route for a blueprint here, didn't work
#def home():
#    return "home"


if __name__ == '__main__':
    WSGIServer(app).run()
late gale
#
class InboxDetailView(LoginRequiredMixin, FormMixin, DetailView):
    model = Contact
    template_name = 'dashboard/inbox_detail.html'
    form_class = ContactForm

    def get_success_url(self):
        return reverse('Inbox_Detail', kwargs={'pk': self.object.id})

    def get_context_data(self, **kwargs):
        context = super(InboxDetailView, self).get_context_data(**kwargs)
        context['form'] = ContactForm
        return context

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        form = self.get_form()
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

    def form_valid(self, form):
        form.save()
        return super(InboxDetailView, self).form_valid(form)

Hello can someone please help me how to make the form save to the current model form because it saves into different model

thorn igloo
mossy hamlet
#

@thorn igloo Yes, in init.py in the create_app function it does this

        from hinnangapp.users.routes import users
        from hinnangapp.companies.routes import companies
        from hinnangapp.main.routes import main
        app.register_blueprint(users)
        app.register_blueprint(companies)
        app.register_blueprint(main)
#

And also, it does work when running locally in pycharm, so that's what makes it difficult

late gale
#
class InboxDetailView(LoginRequiredMixin, FormMixin, DetailView):
    model = Contact
    template_name = 'dashboard/inbox_detail.html'
    form_class = ContactForm

    def form_valid(self, form):
        post = Contact.objects.all()
        myform = form.save(commit=False)
        myform.post =  post
        form.save()
        return super(InboxDetailView, self).form_valid(form)

Can someone help please here im trying to save a form field to a model
Forms.py

class ContactForm(forms.ModelForm):
    class Meta:
        model = Contact
        fields = ['reply']
#

so i want reply field be saved into model form

#
class Contact(models.Model):
    name = models.CharField(max_length=12)
    email = models.EmailField()
    subject = models.CharField(max_length=12)
    message = models.TextField()
    reply = RichTextField(null=True)
    created= models.DateTimeField(default=timezone.now)     
    
    def __str__(self):
        return f'{self.name}'
native tide
soft copper
#

i still think flask is better than django

#

no offense

late gale
native tide
#

Use self.object.save()

#

In the view

late gale
#

not working

#

it creates this

#

but it dont save it to the same model

#

oh self.object returns the model name so thats cool is there a way to check like Contact.objects.get(name = self.object) then i say Contact.objects.create

#

cant explain it but let me try

random lava
#

Hi, does anyone know if its possible to call a js function from flask?

late gale
#
        reply = Contact.objects.get(name=self.object)
        reply.save()

@native tide mind if u help im stuck here ik it doesnt have save function but cant type it in code like i want to add the form to it

#

oh so self.object refers to the model so how to add the form field to the self object cause self.object.reply returns none

#

ooh waait let me try

#

ooh i solved it thank you

native tide
late gale
#
    def form_valid(self, form):
        self.object.reply = form 
        self.object.save()
        return super(InboxDetailView, self).form_valid(form)
#

That helped me

#

but why it's showing me like this

Reply: <tr><th><label for="id_reply">Reply:</label></th><td><div class="django-ckeditor-widget" data-field-id="id_reply" style="display: inline-block;"> <textarea cols="40" id="id_reply" name="reply" rows="10" required data-processed="0" data-config="{&quot;skin&quot;: &quot;moono-lisa&quot;, &quot;toolbar_Basic&quot;: [[&quot;Source&quot;, &quot;-&quot;, &quot;Bold&quot;, &quot;Italic&quot;]], &quot;toolbar_Full&quot;: [[&quot;Styles&quot;, &quot;Format&quot;, &quot;Bold&quot;, &quot;Italic&quot;, &quot;Underline&quot;, &quot;Strike&quot;, &quot;SpellChecker&quot;, &quot;Undo&quot;, &quot;Redo&quot;], [&quot;Link&quot;, &quot;Unlink&quot;, &quot;Anchor&quot;], [&quot;Image&quot;, &quot;Flash&quot;, &quot;Table&quot;, &quot;HorizontalRule&quot;], [&quot;TextColor&quot;, &quot;BGColor&quot;], [&quot;Smiley&quot;, &quot;SpecialChar&quot;], [&quot;Source&quot;]], &quot;toolbar&quot;: &quot;Full&quot;, &quot;height&quot;: 291, &quot;width&quot;: 835, &quot;filebrowserWindowWidth&quot;: 940, &quot;filebrowserWindowHeight&quot;: 725, &quot;language&quot;: &quot;en&quot;}" data-external-plugin-resources="[]" data-id="id_reply" data-type="ckeditortype">&lt;p&gt;Reply 2&lt;/p&gt; </textarea> </div></td></tr>
native tide
#

(Little and unrelated: super doesn't need those arguments, they are not recommended, super() is enough)

late gale
#

I tried |safe but it didnt fix it

native tide
#

Ok, let me have a look at this

late gale
#

Im using Ckeditor and i read documents it says add |safe but it didnt help

#

let me look again

fluid olive
#

I'm trying to make a Parallax website demo using Html and CSS but the parallax effect is not working. 😕
Can somebody help?

twin hamlet
#

Actually I want to provide a functionality like a user can able to update details

frank loom
#

no

twin hamlet
#

Means He would be able to make changes in profile

twin hamlet
late gale
twin hamlet
late gale
#

oh let me send u a video that explain it very well

twin hamlet
#

And I really need to provide functionality because working on a proj

twin hamlet
late gale
#

Corey Schafer is cool

twin hamlet
late gale
#

what type of views u want class views or function views

#

there are two types of views u can use in django

#

I personally prefer class views for profile

twin hamlet
twin hamlet
#

So that you can better understand

late gale
#

class views are very easy to use you just need a tutorial to learn from but let me send u someone used function views for profile

late gale
#

I believe that might help

#

But I still recommend class views for this

native tide
late gale
#

@twin hamlet U can watch corey schafer trust me everyone love this man

late gale
jovial sigil
#

I'm making a sort of social media app with Flask, and when people post, I want it so if they put HTML in their post it's displayed raw. The post code is injected as a variable with Jinja, like {{ postcode|safe }}.
Like, they post:

<h1>Hello</h1>

The post would show up as:

<h1>Hello</h1>

However, I also want to support injecting HTML (like in their post, \n would be replaced with <br>. So far, however, it's seemed to be either one or the other. How can I pull this off?

jade lark
#

For instance. I could add a script tag to the site and do some pretty big damage.

late gale
#

can someone please help me I added |safe but it shows me like this here's the code

    {% if object.reply %}
    <div>
        {{ object.reply|safe}}
    </div>
...

<p>Hey Thank you for your contact</p> on the web site there

#

Im using ckeditor this reply is RichTextField

broken mulch
#

i need to make threading work on Quart

#

is there any ways

late gale
#

it's just a simple problem idk why it occurs

random lava
#

Hi, does anyone know if its possible to call a js function from flask?

late gale
#

Try this

#

I wish i can help u myself but im not a flask dev

random lava
#

Tried this but in my case it was too slow and the function had to be called constantly

#

Thanks for the help tho

honest crescent
#

how can i get an icon, in the tab name

#

if that made any sense

late gale
#

Can someone please help me here

#
    def form_valid(self, form):
        self.object.reply = form.cleaned_data['reply']
        self.object.save()
        email = Contact.objects.get(email=self.object.email)
        print(email)
        subject = "Replied"
        message = render_to_string('dashboard/reply_email.html', {
        'reply' : self.object.reply ,})
        sendingEmail = EmailMessage(subject, message ,to=[email])
        sendingEmail.content_subtype = 'html'
        sendingEmail.send()        
        return super(InboxDetailView, self).form_valid(form)
ionic idol
quasi relic
#

hey all, if I had to create two tables for sqlalchemy like : user and emojis should I use one to many relationship? like one particular emoji could have X users and every user could have just only own one specific emoji , like a smile emoji you can have only one of it, actually any answer would be great and also if you know some good explanation when to use one-to-one, many-to-many , thank you in advance

late gale
jovial sigil
#

I want them to be able to share html code, but it doesn’t run or anything

austere relic
#

How do I make my asyncio server work with both https and http, or redirect http to https?

#

nvm. I can start a separate server and have that one redirect

leaden carbon
#

hey guys how can i set the port for my heroku application? or this isnt necessary?

#

im have a local project that works fine but when i deploy i get application error

#

and a lot of forums said that maybe my process.env.PORT variable is wrong

#

but i never heard of the term

native tide
#

@leaden carbon did you look into the logs of heroku? they're pretty accurate about the error and then it's mostly obvious what's missing/wrong. And the process.env.PORT variable is just the variable for the port you want to serve it, in debug usually 8000 but I never set it.

ancient thicket
#

Is django the best way to do the back end of a website?

#

im p new to this stuff

#

and ill be working on my first website project with a friend

#

so im wanting to do the back end

#

looking for something thats a bit more beginner friendly

#

someone told me they recc flask though

#

so not really sure what the best route is

restive pine
#

djangos good. They are both really great its just comes down to whats the website going to be?

ancient thicket
#

so im making a website for my uni club

#

and within that site

#

i wanna incorporate a section that allows students to look up previous syllabi

#

for math courses offered by my uni

#

and i have the website that allows you to search up previous syllabi

#

so im not sure if i would have to like download every syllabi one by one

#

if there is an easier way to do it

#

without doing all of the grunt work of downloading and uploading the file one by one

restive pine
#

sounds cool both will work for you but i guess django will already have the ORM built in

ancient thicket
#

what is ORM?

restive pine
#

so yeah object relation mapping* for your db

ancient thicket
#

ah

#

so would i have to make a data base with all the syllabi i want to use?

restive pine
#

design choice

#

i would say it depends what format they are in and whats the functionality you want form it

ancient thicket
#

i have a feeling im going to have to download each syllabus one by one

#

that will be a bit harsh but its doable

#

okay thanks so much ill prob end up using django

restive pine
#

you can write a script that scrapes them

ancient thicket
#

hmm asked a friend he told me selenium might be able to do the job for me

restive pine
#

yeah i like requests and beautiful soup both are great

#

i have my own question i have a site where you can upload large files 30MB wondering what my options are with that. Where should I hold them? i cant save it user side and i would be worried keeping it in memory. I was thinking a bucket and then just deleting them after the session ends any other ideas?

warm igloo
#

Using AWS? Throw them in s3 bucket, set a lifecycle rule to autoexpire them after 1 day. Unless you want them dead sooner than that. At least this way you don't have to code around it, you can just let the lifecycle rule do that work for you.

still root
#

hey can someone explain why this is not working

#
<script>
    function display(){
        var x = document.getElementById("hello");
        var y = x.getElementsByTagName("ul").getElementsByTagName("li").getElementsByTagName("a");
        y.style.color = "red";
        if (x.style.display == "none"){
            x.style.display = "block";
        } else{
            x.style.display = "none";
        }
    }
</script>
<button onclick="display()">Press</button>
<div class="test" id="hello" style="display: none;">
    <ul>
        <li><a href="#">1</a></li>
        <li><a href="#">2</a></li>
        <li><a href="#">3</a></li>
        <li><a href="#">4</a></li>
    </ul>
</div>
#

after I add the 4th and 5th line the onclick function does not work

#

but before I do it works perfectly

dusk portal
#

hey anyone's up?

outer apex
# still root hey can someone explain why this is not working

getElementsByTagName returns an HTMLCollection object. HTMLCollection objects do not have the method getElementsByTagName. If you look at the console on your browser, you should see this error as well. You could simplify that whole process with something like this:

document.querySelectorAll('#hello > ul > li > a').forEach(a_elem => a_elem.style.color = red)

To toggle the style, you could use a ternary 😉

x.style.display = x.style.display === "none" ? "block" : "none"

A quick final note, if you think the functionality behind this styling or certain elements of this styling are going to be applied elsewhere, you might as well write some CSS, and then with your JS, modify the class on the element.
For instance with the hiding business, you could have a class hidden where display: none. Then you can do the toggling for #hello like this x.classList.toggle('hidden') and it'll handle the toggling for you.

stark tartan
#

I want to implement multiple user types of user authentication with different login and signup pages with django allauth can you explain any strategy to do THIS.

steep island
#

One question :

Django or flask which is better?

vagrant owl
#
ancient thicket
#

Yeah I used django spent the whole day figuring out

#

Really enjoy it so far

vagrant owl
#

First of all ask yourself why you wanna use python for building a project and why not Nodejs or Ruby. Once you are satisfied with your answer, ask yourself what you wanna build using that language. Django, pyramid and other frameworks/libraries all have some specific scenarios they excel in.

#

You can do everything in one framework that can be done in the other. Whatever you choose, focus on learning the concepts.

vagrant owl
ancient thicket
#

Yeah it’s fun

#

I’m finally starting on my app

#

Spent the whole doy figuring out environments

#

Using pipenv command and finding out all the stuff I can do with it

#

Making new directories

haughty shadow
#

Bro i need help in django

#

in my poll app please could someone help me

muted scaffold
violet thistle
#

Guys, is there a telegram chat for python web dev?

#

I would like to post random memes to random people, have noone to share with ):

deep yoke
#

how can I do so that I don't have to go to the flask website every time?

@app.route('/login', methods=['GET'])
def login():
    return redirect(Oauth.LOGIN_URI)


@app.route('/dashboard', methods=['GET'])
def dashboard():
    code = request.args.get('code')
    access_token = DiscordOauth.get_access_token(code)

    user_object = DiscordOauth.get_user_raw(access_token)

    username, _id = user_object.get('username'), user_object.get('id')
    return f'User: {username}, User-id: {_id}'
late gale
#

ofc

#

U've to choose either flask or django both are powerful backend technologies for python

#

I personally recommend to try them both and choose your comfort

merry vortex
late gale
#

There are big companies use Flask such as Netflix and Samsung Also there are big companies use Django such as Instagram ,Youtube and Spotify

#

and I still recommend to try both , they are very close to each other

#

are u web dev beginner ?

#

do you know html css js

#

and what python level do you have

#

no worries what about web technology ( html css and js)

#

they are necessary for any web dev

#

They called frontend technology which means anything u see ( Texts , buttons , images , animations )

#

if u don't learn those , how you will display your site

#

to the user

#

Also

#

Don't panic , they are easy

#

Except javascript it's more challenging

#

Backend technology is completely the opposite it's mostly about database , security , tests and its not easy as frontend

#

you want to learn backend without html and css ? then how will you build ur website

#

U need both

#

but i will provide some links for html css and js and also backend

#

though i said there are two backend frameworks django and flask but since you are beginner i will recommend flask , its easier

#

those two links are frontend

#

now i gonna send u flask

#

that all u need

merry vortex
#

i want it to look something like this

#

im takling about page 2

untold hull
#

should i go for php or python for webdev?

static spade
#

whats the best way to integrate react with flask

late gale
# merry vortex

oh u mean u dont want images to get stick to each others like u have

late gale
late gale
static spade
#

i see

#

i saw another method online that just uses flask as an api to query database and such

#

is this similar to that or different?

tulip beacon
#

hey guys anyone good at react?

opaque rivet
#

@tulip beacon yes what's the Q

sullen hound
safe cypress
#

That is fairly hard to answer since it depends on what you want to do. Also, React is JS, this is a Python server 🙏

#

You are asking about React, this is a Dicord server for Python, not JavaScript. React is in JavaScript. Hope that helps.

native tide
#

yes

finite ingot
#

from my experience, let the frontend convert it, in general it can be advantageous to keep backends fairly agnostic

manic crescent
#

anyone has experience with Twitch API v5?

opaque rivet
#

does anybody know why a decorator on my APIView is giving me the following error?
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a <class 'NoneType'>

class GetEquityStats(APIView):
    @valid_equity_required
    def get(self, request, equity):
        return Response(data="success", status=status.HTTP_200_OK)```
#

the decorator works, it does not throw any errors and is used in other places in the code.

#

wondering how you guys use decorators for class-based API views?

astral pagoda
#

Can you get circular imports if you use blueprints in flask?

inland oak
#

in the mean time my question, can I check in django which app names for startapp command are forbidden?

#

I think I will have possible issue with translator app name

opaque rivet
# inland oak show the code of the decorator

the decorator works:

def valid_equity_required(func):
    """ Decorator for ensuring passed equities are valid. """
    def wrapper(*args, equity, **kwargs):
        if equity_is_valid(equity=equity):
            func(*args, equity=equity, **kwargs)

        else:
            raise InvalidEquity("The equity is invalid.")

    return wrapper
opaque rivet
inland oak
#

I had experience with translator app I think broke my imports too

#

it conflicts with already existing django libraries

#

they aren't written in a perfect way to avoid collisions

opaque rivet
#

ah true, that makes sense

#

say you were importing something from your app django, it may be confused with the actual package

inland oak
#

where is return 😉

#

raise InvalidEquity("The equity is invalid.")
not sure if is good way to handle error. I usually cover it with another Response object which has error inside

opaque rivet
#

do I need to return the function?

inland oak
opaque rivet
#

oh actually yes. Because otherwise I will be returning None

#

ahhh...

inland oak
#

also recommending to get functools.wraps

opaque rivet
inland oak
#
import functools

def my_decorator(func):
    @functools.wraps(func)
    def wrapper_repeat(*args, **kwargs):
        # my staff
        return func(*args, **kwargs)

    return wrapper_repeat
#

add decorator @functools, it will transfer meta information

#

from decorated function to its wrapping

#

it makes more reliable working in django

autumn hedge
#

I learned a while ago that using static methods can be used as decorators

mighty meadow
#

any method that returns a method is a decorator

opaque rivet
#

I see. I'll do that, what really is the use of transferring metadata? Will I really benefit from having the docstrings transferring through my functions?

inland oak
inland oak
#

I needed it in order for my Sphinx generator to get info properly

#

or in some other cases also

opaque rivet
#

Oh that's a good point

inland oak
#

there are sometimes other things you function has

opaque rivet
#

Thanks! I appreciate the help. I was dead set that my decorator was working too, that's what coding at 6AM does!

inland oak
#

__call__, __iter__ and etc. there are many things, you never know for sure when it will break without them 😉

opaque rivet
#

tbh, I've never even seen __call__ or __iter__. I'll give em a read

autumn hedge
#
@staticmethod
def do_stuff(dec_func):
   def some_action(*args, **kwargs):
        return dec_func(*args, **kwargs)
   some_action.__name__ = dec_func.__name__
   return some_action
#

@inland oak I haven't read that book.

inland oak
# opaque rivet tbh, I've never even seen `__call__` or `__iter__`. I'll give em a read

erm. There are too many of them. Better to have some full course meal about it....
I am at the moment reading through all of it in the awesome book clean code in Python
https://www.amazon.com/Clean-Code-Python-Refactor-legacy/dp/1788835832
quite awesome reading

waxen lion
#

Hey guys.
Django newbie here . How do I pass data from html file to my python script?
Please help!

tulip beacon
#

hey guys

#

my webapp has a scroll bar at the bottom which is moving the entire webapp, what should I do?

outer apex
inland oak
dusk portal
#
def detail(request, question_id):
    try:
        n1=Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request,'app1/detail.html',{'n1':n1})``` my try expect is correct ig then too when i go to localhost i doesnt show this error it shows that default error
wanton ridge
#

can someone help me here?

hardy shale
#

Is sharing own stackoverflow question to seek help allowed here?

#

Its related to django

native tide
#

may as well just copy and paste it

#

I'm also working with django, out of interest do you know whats the advantage of running django from the commandline, when you can run it from within pycharm

#

like what's the deal with running a virtualenv from the commandline? I don't understand sorry I'm new

#

to this

hardy shale
#

Can you please have a look at it? or should I open a help-channel?

inland oak
# native tide like what's the deal with running a virtualenv from the commandline? I don't und...

those two are different questions.

virtualenv should be always used for python projects
probably even your pycharm has it inbuilt by defeault.
it makes sure to store dependency for your projects locally, which you can unload into requirements.txt for easy reinstall on another PC.
storing dependency in global pip is really bad.

running django from the commandlike has advantage of really lazy/easy approach
since it is not requiring to configure your IDE.
if you can configure your IDE, it is usually better and more coomfortable way, because it enables for you additional features, like visual debug and + million of plugins.

hardy shale
#

'probably even your pycharm has it inbuilt by defeault.' - Yes.. PyCharm creates a virtual environment for new projects by default.

native tide
#

not sure but I think it's called the console no?

inland oak
#

small advantage of using console is...
you will know how your project works when you will install it somewhere else.

#

using super tools should be a step only after you know how to work without them I think

native tide
#

so are you saying learn with the commandline

#

but later on I ought to use the pycharm editor

inland oak
#

yup

native tide
#

okay fine, thanks for the explanation

hardy shale
#

The advantages I personally gain from running django server from command line is quite a few for example

My terminal just has everything setup to have full workflow, vim as IDE, server std outputs, database consoles etc.

I don't always want to run on debug mode and test the server using gunicorn or stuffs alike. Being in a terminal you can have mulitple instance running in multiple variants. (you can do this from PyCharm too)

With a complex systems where frontend is on a different stack, there's cache running, you want to toggle between stuffs as fast as possible.

native tide
#

I appreciate it

hardy shale
#

Apart from those, I like my customized terminal more than PyCharm's one.:P

native tide
#

not that I have much a clue what I'm doing but I learn

dusk portal
#
def detail(request, question_id):
    try:
        n1=Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request,'app1/detail.html',{'n1':n1})``` when im trying to render this error
#

it's showiing the default error

sudden steppe
#

i m recruting people for projects send me a message !

violet dock
#
async def get_items(request):
    prices = prices_collection(request)
    async with async_closing(prices.find({}, {"_id": False})) as results:
        async for row in results:
            items = await results(length=None)
            return web.json_response(items)```
how to get everything in my database and return it on web?
mighty meadow
native tide
#

can anyone check out what i asked in help-pretzel? its a very quick question any help would be much appreciated

#

Can I share my project here

calm plume
native tide
#

It’s a library

pine trellis
#

path : register.models.py
class User(AbstractBaseUser):
username = models.CharField(max_length=150)
but after python manage.py createsuperuser
i have :
django.core.exceptions.FieldDoesNotExist: User has no field named 'register.User.username'
does anyone why is that happened?
i also have added at setting.py the AUTH_USER_MODEL = 'register.User'

toxic forge
proven lily
#

im using flask and trying to get my navbar to show on everpage

#

im using the extend but then

#

it wont show the pages content

#

how do i set a navbar on everypage

balmy lintel
#

It sounds more like a Jinja question. If you are using template inheritance then you probably want your top level template (base) to have the appropriate navbar. Your lower level templates will extend that base template and inherit the nav bar. Load your page in the browser and inspect the source html to verify the inheritance works as you expect. https://jinja.palletsprojects.com/en/3.0.x/templates/#template-inheritance

weary pond
#

hello everybody, i m new to Django web dev, and i want to make a workflow is there any good library that anyone can recommend expect viewflow, cause i want to make my own REST API and front-end

toxic forge
pine trellis
#

@toxic forge have you ever mess around with Extending the existing User model?

#

with django i mean

toxic forge
#

@pine trellis yes in Django

pine trellis
#

you did it with AbstractUser or AbstractBaseUser ?

#

because i have a lot of issues

eternal frigate
#

you use AbstractBaseUser if you want to remove all default fields including permissions

lofty ingot
#

I would like to interact with a webpage, lets say writing "hello world" to pastebin and post it. How would I do that?

lofty ingot
#

Thank you, I will look into that 🙂

dusk portal
#

hey

#

anyones up?

quasi relic
#

anybody have experience with heroku deployment?

naive panther
#

I'm getting this when I try to deploy my flask app to heroku, can anyone help me with this?

warm igloo
#

did you read the error and go the the link with more info on your failure?

#

You're using a buildpack and it says your app isn't compatible. Follow the link and see why.

outer apex
#

@forest hawk instead of return str(output) you can use return render_template_string(output). Jinja automatically escapes a provided string for safety reasons.

forest hawk
#

oehh thanks, let me try @outer apex

outer apex
#

Could you share a bit more code where you're doing this loop?

latent cosmos
#

Solved, thank you everyone for any tips/help/interesting on all sub channels 🙂

strange notch
#

how can i complete my code?

#

hello I wanted to complete my code by just comparing to a tutorial it's different

#

how can i do that?

mighty meadow
#

os.path is missing

strange notch
#

that didnt work

mighty meadow
#

why didn't work, we need error log when we are debugging

strange notch
#

can you come to code help 1

mighty meadow
#

ok

#

I have no right to speak...umm

calm plume
ivory bolt
lavish prismBOT
#

Hey @strange notch!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

strange notch
#

!code-blocks

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

strange notch
ivory bolt
#

ideally, to your 'DIRS' key in the settings.py, you should write:
DIRS: [os.path.join(BASE_DIR, 'templates')]

ivory bolt
#

If you want I can just help you out myself

#

what tutorial vid are you looking at?

strange notch
# ivory bolt what tutorial vid are you looking at?

Python tutorial - Python for beginners - Go from Zero to Hero with Python (includes machine learning & web development project).
🔥 Want to master Python? Get my Python mastery course: http://bit.ly/35BLHHP
👍 Subscribe for more Python tutorials like this: https://goo.gl/6PYaGF

👉 Watch the new edition: https://youtu.be/kqtD5dpn9C8

📕 Get my FREE ...

▶ Play video
#

this is the last 5 mins

strange notch
ivory bolt
#

oh, I don't recommend you follow MOSH for django

mighty meadow
#

yert I failed to help him out due to some mysterious syntax error

ivory bolt
#

there's a very, VERY, good & easytounderstand course that I can send you specifically for django

#

I'll send it

mighty meadow
#

😆I recommend Flask for beginners

ivory bolt
#

I suggest you first take a break from doing anything: that 6 hour course is pretty hefty, you might get fatigued

strange notch
ivory bolt
#

Here's the video link: https://www.youtube.com/watch?v=F5mRW0jo-U4

The first few steps are about setting up a virtual environment, then the basic settings of django (where you're stuck at), and the entire foundations of django

Learn the Python Django framework with this free full course. Django is an extremely popular and fully featured server-side web framework, written in Python. Django allows you to quickly create web apps.

💻Code: https://github.com/codingforentrepreneurs/Try-Django

⭐️Course Contents ⭐️
⌨️ (0:00:00) 1 - Welcome
⌨️ (0:01:14) 2 - Installing to Get ...

▶ Play video
#

it is VERY good

ivory bolt
lavish prismBOT
#

@ivory bolt Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!

Our server rules can be found here: https://pythondiscord.com/pages/rules

daring gust
#

@ivory bolt from the looks of it, that wasn't a valid invite anyway.

ivory bolt
strange notch
daring gust
#

@ivory bolt This does count as promotion and you need to ask permission via @hexed spoke first.

daring gust
ivory bolt
#

it's a linktree, though I fully understand

#

just put it in case anyone needs anything

strange notch
ivory bolt
#

also run pip freeze to see wether you have all valid packages or not

#

in your virtualenv

ivory bolt
lavish prismBOT
#

Hey @strange notch!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

strange notch
#

!code-blocks

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

ivory bolt
#

@strange notch as a codeblock, not as a file

mighty meadow
#

or pastebin?

lavish prismBOT
#

Hey @strange notch!

It looks like you tried to attach file type(s) that we do not allow (.html). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.

Feel free to ask in #community-meta if you think this is a mistake.

strange notch
ivory bolt
#

or you copy paste your code, select it, and double click

#

*right click

#

chose code-bock

lavish prismBOT
#

Hey @strange notch!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

strange notch
#

I Just Cant

#

when i paste it

ivory bolt
#

it's really not that hard

#

just click on this link so we can join on a vc

#

or dm me

strange notch
strange notch
#

it says this invite is invalid

ivory bolt
#

hmm

ivory bolt
#

it should work

#

@strange notch

#

Feel free to join in any time tomorrow, I'd be happy to help you and others in your situation out

#

though I think this channel has a lot of resources to offer

ionic raft
#

Getting ready to make the shift from learning Python to building the web application I have in mind.
The web app is going to have a few things involved:

  • Forms for collecting data through wizards (for new users)
  • canvas for building diagrams
  • The glue to convert info in the wizard into diagrams
  • and other persistent web app goodness such as user, support form, and a few more things to boot.
  • Phase 1 is about mapping. Phase 2 is about automation. Phase 3...well, that's a ways off 😉

Assuming that made sense, I welcome any thoughts/questions that immediately surface.
The current landing page is https://www.lanesflow.io/ (built on WordPress, slated to be retired)

I anticipate a combination of custom building and leveraging some already invented wheels 🙂

west peak
#

Hi, i have a litte question

#

What is the best way to storage products for my shopping cart?

deep tinsel
#

Shoutout to local storage:

west peak
#

Cookies are an option?

deep tinsel
#

Could be too much data for cookies

#

Yet, yes

west peak
#

Thanks for the data, ill be watching it

manic frost
#

Also, I'd like to be able to try the main product out without having to sign up

#

like a demo or something.

terse vapor
#

In the web version of Discord, I tried using bs4 to copy the element, but it displayed "None". What should I do? The only messages I can see are those while inspecting the element, so how should I proceed?

native tide
#

How to make a django notes app?

#

I have experience of making a blog app but In this I gotta avoid posting some content

celest bobcat
#

hey so i am making an website that uses react with django rest. The site has some info that has to update real time, firstly i was thinking of having the frontend send a request every 0.5 s to the rest api. Will doing this be a bad idea because i think of so many requests the website will lag a lot so what other solution is there?

deep tinsel
#

but, a request every 0.5s isn't TOO bad

celest bobcat
deep tinsel
celest bobcat
#

k thanks

haughty shadow
#

hi bro

#

i need help in django plz

#

can someone help me with my poll ap

#

app

stark tartan
haughty shadow
haughty shadow
stark tartan
haughty shadow
ivory bolt
rugged scarab
#

Hey guys, I am stuck web scraping something using XPath, anyone who can help me out ??

#

I am using selenium, python

ivory bolt
#

can you specify where you're stuck

stark tartan
#

How to get started with django rest

rugged scarab
#

I wanna get the values of the highlighted part like DL1 D1 D2 etc. And for this I an using the value of the class to get the XPath. But it's not giving me anything

#

ie an empty list

fickle plank
#

How do I start learning Django/Flask?

rugged scarab
scenic dove
#

it has a great tutorial

#

also the Django documentation is a good one

fickle plank
#

Okay, thanks! I know all the basics of Python, should I learn anything else before starting Django/Flask?

scenic dove
#

well you will know what to learn after you start
like when you come to urls you will likely go and read about POST and GET

#

and so on

#

i started django with only python in my mind just like u now

rugged scarab
#

''' info=train.find_element_by_xpath("./following-sibling::div[1]")'''
something might be wrong with selecting the sibling element

fickle plank
#

Okay, thanks a lot! Btw, I'm a highschooler and started coding 3-4 months ago :)

scenic dove
#

that's good things will probably be easier for u

#

im not an expert BTW i just started couple monthes ago
u may catch me up!

#

u may wanna start with polls app they made in the documetation
a simple good start

cerulean badge
#

i am creating a function based login view and using AuthenticationForm for it. my question is how can i change the label of the username field for that form? (context django)

scenic dove
compact surge
#

hi guys!
How i can change the format of date YYYYMMDD to DDMMYYYY?

#

i put form type='date' from html to python code

scenic dove
wispy bison
#

hello everyone,
I'm trying to setup python app on my web hosting by using cpanel but i couldn't install a module named "mysqlclient" it gives error. I have been google it around 2 days but i couldn't find a solution. Could you help me please ?
also the hosting provider is godaddy

fiery mason
#

if i want to create a website where you would make a new room for a game should i use python if i am a bit better at it and don't really have much experience in js

#

And what framework would I use with python

inland oak
inland oak
#

depends on which on you are more familiar. If you are better with python, go for python.
But JS would be still used anyway, just in less amount.

#

It is possible to go without JS completely though

#

But most people like having more dynamic interactivity on their web sites. Just python usage makes web site a little bit limited

#

as well as just using Javascript can feel as limited too. Like... I don't believe in JS to work well for backend (to hell with Node.js)

mighty meadow
#

you can use something like Dash, PyWebIO, to avoid frontend coding

cerulean badge
#

is django docs down rn?

fiery mason
#

I've found some really specific libraries on js tho

#

Like colyseus

mighty meadow
#

fastly boom.

inland oak
#

i like Django pretty much (with its plugin DRF)

#

as alternative FastAPI I heard is good too

fiery mason
#

But yeah it seems like js has really specific libraries that cater to my needs

#

I'll have to read up more

opaque rivet
#

@fiery mason for JS, express is the most popular backend lib. For python, its django.

fiery mason
#

I'm thinking of using colyseus

#

Because it seems made for game rooms

dusk portal
#

my lyf man!!!!!! noone can figure my issue

#

i'm gonna give up learning django now

opaque rivet
#

Never heard of it tbh

#

For small libraries you really only rely on their docs, theres not as many dev resources as more popular libs

dusk portal
#

any1 else wanna try to help

#

😢

ivory bolt
shadow belfry
#

Hello, sorry to disturb you. I trying to send file with html form with my python "web server" (http.server). I use cgi to recover it. The file is an .wav audio but when I upload it I only have a part of the file (for exemple if the file last 1 min, I only recover few secondes of it). Can someone help me please ? Thx ^^'

compact surge
#

Try this

shadow belfry
#

With my form ?

compact surge
#

And you try to send file with html form????

#

And use cgi?

shadow belfry
#

Currently I have a form with file input and his action is "save_file.py" and in it I use cgi