#web-development

2 messages · Page 230 of 1

vapid sapphire
#

I have to make a Fitness Tracker in html css and javascript

ornate flame
#

I use React, Next with django and its good.

ornate flame
# vapid sapphire I have to make a Fitness Tracker in html css and javascript

View the SOURCE CODE:
https://codepen.io/dcode-software/pen/vYpJXmG

In today's video we'll be building an exercise (workout) tracker with HTML, CSS, JavaScript and Local Storage. This project is perfect for beginner/intermediate JavaScript developers.

🏫 My Udemy Courses - https://www.udemy.com/user/domenic-corso/
🎨 Download my VS Code theme - ...

▶ Play video
timber jungle
#

Hello
How is it possible to implement HSTS in Flask, please?

ornate flame
ornate flame
timber jungle
#

Just this or there is more? 🙂

from flask import Flask
from flask_talisman import Talisman

app = Flask(__name__)
Talisman(app)
vapid sapphire
ornate flame
ornate flame
ornate flame
timber jungle
#

thank you, i will try to destroy my app 😄

vapid sapphire
ornate flame
ornate flame
timber jungle
vapid sapphire
ornate flame
hollow dragon
timber jungle
#

make the check in backend

hollow dragon
#

Alright

timber jungle
# hollow dragon Alright

You can implement this check in HTML as well. With this you can check before the user presses Submit
but everyone will be able to modify the HTML and bypass it.

This is why you should also make the check in back end as well.

hollow dragon
#

Yeah, I know about that, I'm also using password_hash, but since it's just a project for an internship I'm not really concerned about issues like that.

#

No one will use this but yeah, I'll look into that, thank you mate!

vapid sapphire
timber jungle
# hollow dragon No one will use this but yeah, I'll look into that, thank you mate!

even if it is internal, there will always be at least one person with malicious intents, just for the lulz.
if it is internal, it is better, because you can force users to enter only one type of email address.

This is my check, it only allows foo.bar@google.com

import re
        googleemail = re.compile(
            r"(\.|^)[\w]{0,64}(\w+[\.]\w+){0,54}@(google)\.com(\W|$)"
        )
hollow dragon
#

Thank you mate for the help

#

On the other hand, what do you think about the project? I know its not extra complex but im coming from frontend and I've learned a ton about flask and python making this.

timber jungle
#

I am not the right person to go into more details about it. I am new to flask myself.
from my pov, the mail seemed like an important subject . 🙂

hollow dragon
#

Ah sure, I really like flask tho, it's pretty good.

timber jungle
#

I sometimes wonder if it would be a good practice to put an NGINX reverse proxy in front of the Flask App.
and implement the security features in NGINX rather than in Flask

inland oak
#

If u find them sufficient

#

The point of flask Auth only in better flexibility

timber jungle
inland oak
#

or in any other way... you can implement any type of auth

#

attaching/removing cookies to the sent requests to flask, which will persist auth

#

or any data you will input to JWT tokens

#

Flask has 100% flexibility to make any kind of Auth

#

Nginx will allow only really limited auth, for example i often protect admin services with at least basic auth from Nginx

#

you can probably try hooking some other auth things, using nginx, but it will be... ugly monstrocity between different kind of systems

#

in best case, it will be highly likely making only hard coded user system which stores data directly at hard drive where nginx is located

#

So... really limited options to auth system with Nginx

#

and consider in addition that you are limited only to FREE version of nginx ;b

#

if Nginx is enough, sure, do it. But if you need any complexity beyond 1-3 users, better to use flask

timber jungle
#

I was thinking mostly in securing the web app with an Nginx or as a Reverse proxy
Something along these https://www.acunetix.com/blog/web-security-zone/hardening-nginx/

But i see that there are multiple Python modules for doing these ( Talisman Flask, Flask SSLify, etc - the hard part of this, is that i have to find them 😄 )

inland oak
#

Because... If u use flask with templating html stuff, u need to serve static files with nginx
And reverse proxing the rest of stuff into your gunicorn server

#

Although even when using flask as rest, u a still probably required to put nginx in front pithink at least if u wish stuff like before framework caching

native tide
#

any project ideas?

ornate flame
# native tide any project ideas?

I found these good for learning purposes:

  • Blog Website with auth, comments and crud.
  • Real time messaging app

You could do both of this with either just flask,django etc.. or make an api with that framework and connect with a frontedn like react/next.js(this would make it a fullstack project)

hollow dragon
#

that dopamine rush everytime when you solve something

#

it remains even after a year sheesh

nimble crow
#

https://github.com/Twxtter/Twxtter-main/blob/92a881279a795016a59a817e1a1a9ed3145896da/twitfix.py#L786 - https://paws.aaw.ooo/57tcy1.png

https://github.com/Twxtter/Twxtter-main/blob/92a881279a795016a59a817e1a1a9ed3145896da/twitfix.py#L825 - https://paws.aaw.ooo/o1deux.png

So the code is recognising appNamePost, but then not applying it to appname.

The config for appname is https://paws.aaw.ooo/ewp028.png, and this is what it's setting ti to as an output https://paws.aaw.ooo/ymeegr.png

Need help understanding why.

trying appname=f"{config['config']['appname']}{appNamePost}", also doesnt work

which leads me to believe that something isnt taking the template when it should be

Any ideas?

lavish prismBOT
#

twitfix.py line 786

print(" ➤ [ T ] vnf type is Image")```
`twitfix.py` line 825
```py
appname=config['config']['appname']+appNamePost,```
plain kettle
#

hi i need help with flask development and sql?

#

i would like it to post products as a product card here, however, they aren't showing up and not sure why

#

code for the html layout:

#
{% extends "layout.html" %}
{% block content %}

<h1> Asad's Shop</h1>

<div class="shop-container">
  <h2> Products </h2>

  <div class = "dropdown-menu">
    <a class = "dropdown-item" href = "{{ url_for('home', query= 'price-high')}}">Price - High to Low</a>
    <a class = "dropdown-item" href = "{{ url_for('home', query = 'price-low')}}">Price - Low to High</a>
    <a class = "dropdown-item" href = "{{ url_for('home', query = 'Eco-high')}}">Eco - High to Low</a>
    <a class = "dropdown-item" href = "{{ url_for('home', query = 'Eco-low')}}">Eco - Low to High</a>
</div>

<div class = "card-deck">
  {% for products in product %}
  <div class = "product card">
    <a href = "{{ url_for('products', products_id=products.id) }}">
      <img src = "{{ url_for('static',filename='products_pics/' ~ products.id~'.jpg') }}">
    </a>
    <div class = "card-body" style = "height: 20%">
      <a href = "{{ url_for('products', products_id=products.id) }}">
        <h3 class = "item_name">{{ products.title }}</h3>
      </a>
      <h5 class = "item_price" style = "colour: black"> £{{ products.price }}</h5>
      <h5 class = "item_eco" style = "colour: black"> {{ products.eco }}</h5>
      <p class = "item_description" style = "colour: black">{{ products.desc }} </p>
      <a href = "{{ url_for('home', addBasket=products.id) }}"><button type="button">Add to basket</button></a>
    </div>
  </div>
  {% endfor %}
</div>

{% endblock content %}
#
from shop.models import User, Product, Basket
from flask import Flask, render_template, url_for, flash, redirect, request
from shop.forms import sign_up, login_form, checkout_form
from flask_login import login_user, current_user, logout_user, login_required
from shop import app, db

@app.route("/")
@app.route("/home/<string:query>")
def home(query=""):
    products = []
    Product.query.all()
    if query == "price-high":
        products = Product.query.order_by(Product.price).all()
    elif query == "price-low":
        products = Product.query.order_by(Product.price.desc())
    elif query == "Eco-high":
        products = Product.query.order_by(Product.eco).all()
    elif query == "Eco-low":
        products = Product.query.order_by(Product.eco.desc())
        
    return render_template("home.html", products = products)
#

db

#

help would be greatly appreciated thank you very much

hollow dragon
#

this part:

<img src = "{{ url_for('static',filename='products_pics/' ~ products.id~'.jpg') }}">

#

take a look at it again

plain kettle
#

i wasn't quite sure how to use images, i was thinking if i make it a sql row as well, and have it stored there

#

i'm kinda lost

hollow dragon
#

just for testing, put an image into your static folder

#

then

#
<img src="{{url_for('static', filename='something.jpg')}}/>

#

Don't really think you can make a relationship between SQL and an img src command haha

plain kettle
#

ah solid i've got a few pictures already, i'll change the filename to that then

#

oh wait hold, i decided to change the folder name a while back to just pics

#

i'll try it now

#

changed it to 'switch.jpg' and nothing came up

rugged dagger
#

Yo. I need to create a YearOnlyField, and be able to filter by from_year & to_year. How would you do this?

hollow dragon
#

can anyone recommend me a good resource for learning about escaping flask & html?

velvet terrace
#

So I have this XML file, and when parsing with lxml I get element names like {urn:oasis:names:tc:opendocument:xmlns:container}rootfile

#

I'm trying to match with xpaths on just the rootfile part

plain kettle
#

hi flask users, what does this error mean

#
{% extends "layout.html" %}
{%block content %}

<h1>"{{product.title}}" &nbsp </h1>
<div class = "item-container">
    <div id = "image">
        <img src="{{ url_for('static', filename= 'pics/' + product.title + '.jpg')}}" width = "400" height = "400">
    </div>
    <div id = "info">
        <p> Price: {{product.price}}</p>
        <p> Ecological footprint: {{product.eco}}</p>
        <p> Description: {{product.description}}</p>
        <p><a href="/add_to_basket/{{ product.id }}" style="background-color:black;">Add to basket</a></p>
    </div>
    </a>
</div>
{% endblock content %}
eternal kestrel
#

@plain kettle hi

#

show your route response

#

what are you returning from the route

#

remove the ()

#

it's treating product as a function

#

...or it is a function

plain kettle
#

the route is this:

#
@app.route("/product/<int:product_id>")
def product(product_id):
    product = Product.query.get_or_404(product_id)
    return render_template("product_page.html",title = "Product", product = product)
#

wait i fixed it

#

it turns out i mistyped the product as products = Product.query

hollow dragon
#

I've come up with a really good solution: I just deleted the registration option from the app, so there is only login option. I have a user for the app so I'm the only who has access to the content. So it's fine because I can present it during the interview and I won't be able to store any user data outside of it. What do you guys think?

plain kettle
#

thank you for the help @eternal kestrel

eternal kestrel
#

np @plain kettle

nimble crow
#

Hey, is anyone offering web design? And if so what prices?

hollow dragon
nimble crow
#

I did, you didnt respond lmao

plain kettle
#

hi again stuck on registering

#

everytime i register on my website, it clears away the password field, seemingly suggesting it does not like the password

#
@app.route("/Sign_up", methods = ["GET","POST"])
def Sign_up():
    form = sign_up()
    if form.validate_on_submit():
        user = User(username=form.username.data, password = (generate_password_hash(form.password.data,method='sha256')))
        db.session.add(user)
        db.session.commit()
        flash("Sign up successful. Enjoy")
        return redirect(url_for('home'))
    return render_template('Sign_up.html', title = "Sign up", form = form)
#

this is the routing

#
{% extends "layout.html" %}
{% block content %}

<form action = "" method = "POST">

    <section id = "username_new">
    {{ form.username.label }} {{ form.username }}
    {% for error in form.username.errors %}
        <span style = "color: red;"> [{{ error }}]</span>
    {% endfor %}
    </section>

    <section id = "password_new">
        {{ form.password.label }} {{form.password}}
        {% for error in form.password.errors %}
            <span style = "color: red;">[{{ error }}]</span>
        {% endfor %}

    </section>

    <section id = "password_confirm">
        {{ form.ConfirmPass.label }} {{ form.ConfirmPass }}
        {% for error in form.ConfirmPass.errors %}
        <span style = "color: red;">[{{ error }}]</span>
        {% endfor %}
    </section>

<section class = "">
    {{ form.submit() }}
</section>
</form>
    
{% endblock content %}
#

the sign up

#
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key = True)
    username = db.Column(db.String(15), unique = True, nullable = False)
    password = db.Column(db.String(50), nullable = False)

    def __repr__ (self):
        return f"User('{self.username}')"```
#

the database

tender moat
#

anyone have experience deploying flask app on raspberry pi to web?

outer smelt
#

so i was watching corey schafer's tutorial part 2 where he talks about bootstrap and the things he pastes into his code from the bootstrap website is different from what i'm seeing in the website, what do i do?

#

(flask btw)

scenic dove
#

yeah

#

i think it is just version differences

outer smelt
#

i'm assuming that there wont be any difference in code syntax if i use the newer version?

forest berry
#

I’m making a flask app rn and I’m wondering what’s the best practice for making web apps. When using a database like SQLAlchemy or SQLite3, should I make a REST Api to go along with it? Or is it not necessary?

dusk sonnet
#

hey, how can i go abouts creating sort of pagination for a Chat App ( Using Django Channels) whereby when visiting a chat room, only e.g. 10 messages are loaded and if the user scrolls through the chat log, every time they reach at the top load another 10 and so on depending on how many messages have been saved in that chat room.

eternal blade
#

django-channels question
How can I read cookies from a WebSocketConsumer

hexed ether
#

hey guys is it possible to create just backend projects with django?

plucky wadi
timber jungle
#

Hello

I am not using Flask Login.
I am using session

Is there a possibility to show an html element only if certain users have logged in?
These users are stored in a database.

plucky wadi
#

Template tags like user.is_authenticated would get the job done ig.

rugged dagger
serene matrix
#

Hey. How do I integrate a pdf reader into my website?

#

Does anyone know any pdf reader plugins? Not any of those comic-like ones

#

That'll work well with django

proper current
#

is it possible to use pyqts .ui files to build a website instead of directly writing html? at least with flask it shouldnt, but maybe im missing something?

ionic raft
# forest berry I’m making a flask app rn and I’m wondering what’s the best practice for making ...

My experience is mostly (now) with PostgreSQL and Django. sqlite3 is solid for getting started. But lately, I've opted to connect to a production ready DB (PostgreSQL) even for initial dev work. This saves time in the long run for me. SQLAlchemy is well regarded but I've not used. PostgreSQL is rock solid and scalable in any production scenario. As for making a REST API, that would be use case specific. I could see value in that if I've built a web app, for example, and want to also release an ios or Android app. I get asked a lot about if I've used a REST API, but my experience is doing the Django-tango and working with the ORM. As my experience grows I'm finding that serving me really well. But then, I've not as yet built a web app where an API was required. Is a REST API necessary? That depends. If you want to facilitate something other than your Flask application connecting to the DB, then yes.

golden bone
golden bone
forest berry
#

I was also wondering, how come in this Tech w/ Tim vid,

https://youtu.be/f_bml-MILAs

he doesn’t use an API in this case? It seems like the front end needs to make changes to the backend a lot, but he doesn’t use one. Is there any particular reason why? Or is it because he wasn’t planning to deploy the website and so he didn’t use one. I’m guessing if he was actually planning to deploy it, he would have needed to make an API rather than directly communicating w/ the database right?

Welcome back to another video in this blog tutorial series! In this video, I will be showing how we can create posts and have those posts show up on the home page. I'll also show how you can view all posts posted by a single user.

💻 AlgoExpert is the coding interview prep platform that I used to ace my Microsoft and Shopify interviews. Check it...

▶ Play video
ionic raft
# forest berry I was also wondering, how come in this Tech w/ Tim vid, https://youtu.be/f_bml-...

I have not watched that particular tutorial. However, I've seen some of Tim's tutorials and he's quite good. As for your question, at a guess this would come back to the requirement being coded for. This appears on the surface to be a tutorial to walk you through creating a blog web application with Flask. Blog's are a common topic for dev tutorials because they cover core elements of web app development that will lay a good foundation (you will learn about DB and CRUD, using the application layer to work with the DB/presentation layers, and the presentation layer for the end-user to interact with the app). At a guess, I'd imagine he's not using an API because the requirement isn't there. You do not need to craft an API to deploy. I have two deployed web applications, being used by real-world clients, neither of which have an API. The second may end up requiring an API, but only if market demands push for smartphone apps.

forest berry
ionic raft
# forest berry Oooh ok thanks!! I had always thought that if u don’t use an API, it would mean ...

That's a great question. My learning path to development in Python started with a 100 day boot camp where this was laid out nicely. One challenge with tutorials is that they are focused on a specific requirement and don't often get into the underlying realities. I can speak for Django, but I did spend about 1.5 months with Flask before I went to Django. However, at their heart there is a fair bit of overlap. The simple answer is that the application layer is the middleman. You build an object model to tell the ORM how to structure/build the DB. You build the view at the application level to do the talking with the DB. The view takes care of building web pages to send to the browser (the front end), and receiving user input. Your code at the application layer is really the key part in all this. The application layer (the middle) is what speaks to the back end and the front end.

grave terrace
#

Hey All,

Been fighting with a problem all day and just can't seem to figure out a solution or find one online and was hoping to get some help....

The short and long of it is I'm using flask and wtforms as a front end for a tool I'm building and I'm struggling with dynamic form creation:

I have a python list of devices I pulled from an api and I want to create a form that prints this list and allows a user to select any or all of the items in it and pass the list of selected devices back to be processed against, I have no problem printing the list but can't figure out how to make each item a selectable form field and have it append that item to a new list on submission...

I thought this would be a relatively simple task but either I'm missing something or it's a lot harder to create a dynamic form than i thought

forest berry
ionic raft
# forest berry Oooh got it thanks!! So from my understanding from what u said, using an applica...

Indeed, an API and the application layer are two ways of communicating with a DB. I would not advise going directly from the front end to the DB. There are good reasons for the current N-tier approach (presentation-application-data). The main one is focus. The presentation layer shouldn't include logic, it presents. The application layer does the logical grunt work. When you bring logic into the presentation layer things can become challenging.

forest berry
serene matrix
hard whale
#

Any jinja gurus here?🤔

#

Can anyone help my donut? My donut is sad, can't find any solution that works... #help-donut

worthy lake
#

I'm a little disappointed that I put so much effort into getting my docker-compose project perfect to throw up django, postgres, nginx, cloudflare tunnel, redis... and now I get started with learning DigitalOcean to find that they don't support docker-compose. They can translate apps made with a Dockerfile into something they all their "App Platform" but like... if I would have known this, I would have spent all this time learning their "App Platform" and not how to get docker compose just perfect

And now im thinking, do I even still want to use Digital Ocean if it cant just deploy from docker-compose directly.

Does anyone have any advice for where I should get my cloud service?
I know that places like heroku and whatever will let you serve a free python app, but Im more interested in learning learning a cloud service that is a little more... reputable for real apps.

#

I know that i dont want to do Azure. There is what else? AWS? Linode?

hidden marten
worthy lake
#

sorry, I
realized it was not suited for here when i saw that there was a devops channel

solid hedge
#

When you send a link in a discord chat, discord usually just displays the picture / gif associated the link. How is that done? does discord send a get/post request or something to the link and displays whatever it finds?
Just curious
I'd think it would be a waste of resources to be sending http requests to every link someone sends though

quick cargo
#

It's part of a HTML document's metadata

quick cargo
solid hedge
#

That's hella interesting thanks much!

frank shoal
solid hedge
#

Thanks!!

ionic raft
# worthy lake I'm a little disappointed that I put so much effort into getting my docker-compo...

I stumbled into the exact same realization. In the end though, I opted with Digital Ocean and a Docker Image. The outcome...it is an OUTSTANDING service. I'm using DO for production deployment of Django apps in docker and I am truly blown away with the ease of management. And to be clear, there's not much time needed to "learn" their app platform. If you have a docker image and deploy, it does a very good job.

golden bone
#

I see now someone already told you that, this is why you shouldn't crosspost 😩

worthy lake
#

yeah, i didnt cross post on purpose... I just started here and I realized there was a better place to talk about it after. And I should have edited my old post if was gonna do that but i didnt.

#

anyway...

#

the main thing im discovering is that... like a few people have said, the tools they have may not be what I expected, but if I ignore them and work out of docker compose exclusively, im missing out on the power in their services.

#

i imagine everyone is like that.

#

Right now i have a mix of cloudflare and DO. I'm gonna stick with it and try to learn how they do things.

wispy crest
wispy crest
#

oh thanks...how can the data in a html file be updated without refreshing the page

#

they say ajax or xmlhttp reqs and stuff

serene prawn
#

Yeah, you have to send request to your backend using javascript if you don't want to refresh the page

wispy crest
#

hm

inland oak
native tide
#

.NET Core API?

azure pecan
#

hey I am quite new to web dev, I was wondering if anyone knows why I am seeing the horizontal line in the middle of my tables?

#

could it possibly be I am missing a closing tag or smth

serene prawn
ionic raft
serene prawn
zealous elk
#

I am getting an error in this Flask app that I am working on. The details are in #help-burrito, please help me if you can

zealous elk
#

So I am getting another error while running the app, and the #help-burrito channel is still up so please help me :/

wooden hearth
#

Hi, so I have the following question:

#

Say I have a website for my car dealership

#

and I want to give the user, the option to "recommend" cars

#

meaning that say some user wants to sell their car to me, they will enter their email, phone number and the car's model for example

#

what's the correct way to implement something like this with django-rest framework?

#

Do I need a separate app for this? If I do then wouldn't that result in code duplication since I will have to rewrite the car model + the user information (email and phone number for example)?

#

I was thinking of just creating a new class that extends my Car model class and just add user email and phone number in there

#

and then create a new endpoint /recommend or something which will be connected with that model

olive hazel
#

is python a good framework for web development. when i say python i mean python not django even tho they are the same thing but i don't think so

serene prawn
somber plover
#

I hope this isn't needlessly pedantic, but python is a language and django is a web framework for python (one of many).

#

The question appears to be whether the python language is good for web development. I can only say it appears a lot of people think so. :) I haven't yet embarked on that journey. It will be interesting after many years of suffering with Ruby on Rails.

somber plover
#

A couple of the strongest reasons to go with RoR were unhelpful in our case (at work) but it was only years in that we realized it. First, ORM (didn't use it - had to make it work with weird OS / architecture at the backend, so ended up hand-rolling our models in a non-ActiveRecord way). And second, the whole notion of an "opinionated framework", while I could see the appeal, actually worked against a lot of things we wanted to do differently. :p

#

I now believe the "opinionated framework" idea was largely a reaction against some of the flaws baked into Ruby as a language, and the Ruby coding culture at the time.

#

If I were to rewrite it today in Ruby, I'd probably go more lightweight (e.g. Sinatra) while continuing to use Vue for the front end (as we still do today). In Python (my hobby coding projects, not work), therefore, I'm looking to not repeat that sort of mistake. Therefore, I'm planning a webapp in Django + Vue (or if I'm up to the challenge, React instead, though I'd have to learn that first).

gray agate
#

Hello guys, i am learning django. I'm trying to bind html with css but failed
Who can help me

hearty copper
#

I learned about Flask during a workshop.

opaque brook
#

I need help with Python

covert yew
edgy marsh
#

is there any discord server completely for web dev ?

golden hamlet
#

anyone knows why i'm getting this error in django?

TemplateDoesNotExist
#

when the template does exist

rigid laurel
#

Either the filename is wrong or you haven't set Django up to look in the right place

golden hamlet
#

how do i set django to look elsewhere

#

it finds a non existing source, it does \templates\templates\

#

instead of \templates\projectname\

#

it works normally for other apps

#

but for this app it can't find the templates for some reason

golden hamlet
#

ait ill read up on that thank you

minor kelp
#

I have a Database and Post related question in #help-ramen. Any assistance at all would be appreciated, thank you so much 😄

mystic wyvern
#

can anybody help me in oauth ?

golden hamlet
#

it didnt help

#

django was looking for the index.html inside of templates/templates automatically so I just changed the file name from templates/appname to templates/templates

#

and it works now

ionic raft
#

Regarding the on-going conversation about using a REST API framework for Django verses using the ORM. If you're using the ORM you've got extra layers of protection from vectors such as SQL injection attacks. If you're using a REST API framework you had better be paying extra attention. I found this post very informative. https://www.stackhawk.com/blog/sql-injection-prevention-django/

StackHawk

Let's dive into SQL injection with a quick overview, some examples, and how to prevent such attacks, using the Django framework.

kindred coyote
#

can some one tell me how i can read the id out of this <button type="button" id="userbtn" class="btn btn-sm btn-danger" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> that i can make my browser.find_element_by_css_selector(" ").click() click it

#

i got send here from generall chat but idk if thats the right place

lean owl
#

read it how

#

like literally, you have that HTML as a string, and you want to read the ID?

neat cave
#

I dont know if the web-development channel is the right one but does anyone has experience with the socketio library ?

kindred coyote
#

like i want the programm to click the button but i am to dumb to finde the id of it

lean owl
#

beautifulsoup would be best

kindred coyote
#

i am really new at that so pls dont blame

lean owl
#

but if you literally just need to solve this one problem, you could get away with just some string search operations

kindred coyote
#

ehh and how can i do that

lean owl
#

so like

#

say we have

a = """<button type="button" id="userbtn" class="btn btn-sm btn-danger" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">"""
#

you could do a = a[a.find("id=") + 4:]

#

and that'll get rid of everything before the part where it says id="

kindred coyote
#

ehhh then how

lean owl
#

and then a[:a.find("\"")] would give you the ID

kindred coyote
#

ehhh could u do that fore me

#

cause idk how to do that and my englisch is bad

#

so i am not really understanding what u mean

lean owl
#

you can literally just copypaste those three lines of code into a file to see it working

#
a = """<button type="button" id="userbtn" class="btn btn-sm btn-danger" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">"""
a = a[a.find("id=") + 4:]
result = a[:a.find("\"")]
print(result)
#

if you put that in a file and run it, it'll print the ID

kindred coyote
#

<button type="button" id="userbtn" class="btn btn-sm btn-danger" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

#

wait lemme try

#

how can i runn this

lean owl
#

same way you'd run any python program

kindred coyote
#

i runned it but it dident do anything cause i runned it wrong i guess

lean owl
#

I think you might need to slow down a little and just go through some basic python tutorials/courses before coming back to this problem

#

it seems like you're lacking some fundamentals

kindred coyote
#

bro pls could u do that fore me i just need that 1 line

#

i just need to copy paste it in then then i am done

lapis spear
#

hello
i am learning django and trying to create a voting website i am on the models part and trying to create the databases
this is what i came up with is this correct or proper at least?
what i want to create is a voting website with dynamic positions where the positions can also be altered like for voting for organization for classroom for election something like that

potent sluice
#

i don't think it applies to web development but i have this doubt on beautiful soup, i posted it on #help-potato but i don't think anyone understood what i wrote :')
Can you have a look at it please ? :)

heavy crater
#

anyone here have experience with flask?

frank shoal
#

Flask is a popular framework

ruby tree
#

can someone help me send data from my views into django class field (trying to set IntegerField's max_value) during run time....

My Django Template:

{% extends 'main/base.html' %}
{%block title%}Delete List{%endblock%}

{%block content%}
    <form method="post" action="/delete/">
        {%csrf_token%}
        {{form}}
        <button type="sumbit" name="Delete List">Delete List</button>
    </form>
{%endblock%}

my function inside view:

def delete(response):
    if response.method=="POST":
        form1 = DeleteList(response.POST)
        print(f"delete button pressed: {form1.is_valid()}")#just checking
        if form1.is_valid():
            ""
            print("valid form: {}".format(form1.cleaned_data))#just checking
            return HttpResponseRedirect("/display")
    else:
        #form1 = DeleteList(10) -- i want to do this...and use a number to set maxVaue of a field
        form1 = DeleteList()
    return render(response,"main/deleteList.html",{"form":form1})

my django forms class:

class DeleteList(forms.Form):
    #i was trying to make this __init__ work but seems to be buggy
    """def __init__(self,maxValue:int, *args, **kwargs):
        super(DeleteList, self).__init__(*args, **kwargs)
        self.fields['id'] = forms.IntegerField(label="Enter id",min_value=1,max_value=maxValue)
    #id = forms.IntegerField()"""    
    
    id=forms.IntegerField(label="Enter id",min_value=1,max_value=10) #-- only this seems to work
#

to elaborate , am trying to do something like form1 = DeleteList(10) in my functions inside view and with the int value i pass in there , iam trying to set the IntegerField's max_value on forms class
every time this form runs , the max_value of integerField will to be different
sorry if this seems to be lengthy , do ping me if this is confusing , i can explain
Thank for anyone trying to help 🙂

prisma heath
#

anyone here who uses python in block-chain development??

native tide
#

anyone used quart before? im convertin my flask app to quart and i cant use request.environ any more

normal nacelle
#

Any recommended Web Development course with Python?

zealous elk
#

My flask app is returning an error for some reason. The details are there in #help-cookie so please help me if you can

short flax
#

Hello i have a recruitment task to make DRF API for uploading images, one of the requirements are to have user account tiers like: basic, premium etc and they have more privilages by the tier. I'm wondering how to implement that? Using admin groups is ok? Or there should be some other ways?

golden bone
zealous elk
#

That was the thing that returned an error

marsh ginkgo
#

Anyone familiar with URL internalization in Django?

golden hamlet
#

anyone has an idea why my static css doesnt work in django

#

i made a folder inside the app folder 'appname/static/appname/styles.css

#

but django doesnt seem to register it

#

SOLVED..

i put "{% static 'newyear/styles.css' %}" inside rel, instead of href

lean wasp
#

How can i route traffic through a FastAPI server to another server(s)?

worthy lake
#

class AbstractBaseSettings:

    relpath_to_envfiles = Path.cwd().parent.parent.parent.iterdir()
    deploy_conf_map = {
        "dev": [
            f for f in relpath_to_envfiles if "env" in f and 'dev' in f
                and not 'prod' in f and not 'sample' in f
        ],
        "prod": [
            f for f in relpath_to_envfiles if "env" and 'prod' in f
                and not 'dev' in f and not 'sample' in f
        ]
    }

    assert all([(True if penv not in deploy_conf_map["dev"] else False)
            for penv in deploy_conf_map["prod"])


    def __int__(self, system_context=None, env_file=None) -> None:

        self.system_context: Literal["dev"] or \
                             Literal["prod"] or \
                             None = None

        self.env_file: str or Path or None = Path(env_file) \
            if isinstance(env_file, str) else env_file \
            if isinstance(env_file, Path) and env_file is not None \
            else None

        if not self.env_file.exists():
            pass
        
        # Alright, this is how I know I need a break.

#

lots of errors in there but to fix up but the last comment says it all

#

I'm just gonna conclude with... I tried the deploy config where you have ten million env files.

#

It sucks. Horrible way to do it.\

#

im gonna reduce the number of env files to where i know what is coming from where exactly and cant get confused when its importing incorrectly into the conf file as None or something else. Instead there will be several conf files that figure out what goes in place of what after the env is loaded in. Not before.

frank shoal
lean wasp
frank shoal
#

it would be nginx -> fastapi, and nginx -> other backend.

lean wasp
#

And how would authentication work in this case?

frank shoal
#

handled by the other backend

#

What kind of backend is it?

#

some third party api?

lean wasp
#

GraphQL server(Strawberry)

frank shoal
#

Do you manage it?

lean wasp
#

Yes

frank shoal
#

are you using jwt?

lean wasp
#

That will the backbone of the API

#

That is the plan

#

May i pm you, to not flood this channel?

frank shoal
#

something like that.

golden hamlet
#

as a beginner django user, you guys all seem like geniuses tbh :))

frank shoal
#

nginx is a server you should definitely look into

#

You can use it with docker even

lean wasp
# frank shoal You can use it with docker even

Thank you!
My use case is a game server and match state is going to be stored on server and the GraphQL API would do the state update. So the incoming requests have to reach a specific server(where the state is stored).
Every match has an ID so... do you think i could make the routing based on this information with Nginx?

frank shoal
#

Why not just host it on a different domain?

lean wasp
# frank shoal Why not just host it on a different domain?

Sorry, i know what is a domain, but i dont understand why would i do that? So it is a round based strategy game, doesnt require lightning fast responses. Probably there wouldn't be region locked servers, so all requests would go through one "gate"/"entity" (auth and load balancing/routing) and matches would run on servers served through GraphQL API and they would scale if there are too many matches.

frank shoal
#

new domain, like a subdomain. You should be able to do it in your cloud provider.

lean wasp
#

So the game server would send the info to the game clients in which subdomain it runs and after that the client would only send requests to that subdomain?

frank shoal
#

Yes.

#

for example, minecraft uses several subdomains

lean wasp
frank shoal
#

Yes

lean wasp
#

thanks a lot for the thoughs @frank shoal

lean wasp
frank shoal
#

note that minecraft's backend (and client) is proprietary and closed source. Nobody but mojang has access to it.

bronze cedar
#

Hey

#

I’m new here

#

Does anyone know from where can I learn programming as a total beginner? (Any online free courses, YouTubers…??) I’m trying to create my own website so hopefully I can find someone to teach me programming 🙏

rigid laurel
#

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

main jasper
#

Good day, peeps. Newbie here. Short question. When do you know your flask web app needs an API?

(app not yet developed, so structural planning stage) Only to expose app's data externally, or are there some internal use cases for API?

quartz yarrow
#

where can i ask a about web scraping?

#

is this channel good? or help channel?

inland oak
quartz yarrow
split sluice
serene prawn
wheat pike
#

Hi there
Can someone explain what the point of "defaults" parameter in this example is?
def printer(positional, defaults, *args): print(positional, defaults, args)

It mean something like this:
def printer(positional, default="defparam", *args) ?

If so, and I want to call the function with default value I make call like that:
printer('positional', 'args1', 'args2', 'args3')

Output should be this:
positional defparam (args1 args2 args3) but it is not.
Instead it is:
positional args1 (args2 args3)

This is topic from args, kwargs lessons.

native tide
#

can any one help me
django

somber urchin
#

Hi 🙂 anyone can help me please ? i got this javascript

#

(function lazy() {
function lazyLoadMedia(element) {
let mediaItems = elems(element);
if(mediaItems) {
Array.from(mediaItems).forEach(function(item) {
item.loading = "lazy";
});
}
}
lazyLoadMedia('iframe');
lazyLoadMedia('img');
})();

native tide
somber urchin
#

and i just want to not apply the lazy loading attribute to a particular image (which would be identified by it's source/name) is someone has a clue in this 🙂

sacred willow
#

quick question, should this set the var, and if so why would it error at len() 0 if i can see that the element has a value in the inspector

#

newDateTime = driver.find_element_by_xpath("/html/body/div[2]/div[6]/form/div[1]/div[2]/table/tbody/tr[2]/td[10]")

onyx lava
#

How could I get the browser/machine language with flask?

#

I didnt quite get how I could use requests.accept_languages where does the request come from? 🤔

#

well, i know about that one, yeah, but I got this error

#

So I thought something was imported as requests

serene prawn
onyx lava
short oyster
#

so i have this repeating code something like if entry not found: raise http exception 404 in each of my API methods.. get.. put.. post ..delete... wondering what would be best practice for eliminating the repetition

onyx lava
#

thanks!

sullen cave
serene prawn
eternal blade
#

How can I build the absolute url of an image from a WebSocketConsumer?
I looked into consumer scope but that doesn't provide everything I need.
What I'm currently doing to get the absolute url is py dict(self.scope["headers"])[b"host"].decode()) + settings.MEDIA_URL + value.name but how can I get wether the server is using http or https

eternal blade
#

Is there something like request.build_absolute_uri but for WebSocketConsumer

odd belfry
dusk sonnet
#

HI, when i try to serialize my datetime field it doesnt end up outputting the same date thats in the database. Anyone know how i can solve this?

class ChatRoomMessage(models.Model):
    room_name = models.CharField(max_length=100)
    user = models.ForeignKey(User, related_name="user_messages", on_delete=models.CASCADE)
    content = models.CharField(max_length=255)
    date_sent = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.content} {self.room_name} {self.date_sent}"

    # Must change the time its not displaying right
    def serialize(self):
        return {
            'room_name': self.room_name,
            'user': self.user.serialize(),
            'content': self.content,
            'date_sent': self.date_sent.strftime("%b %d %Y, %I:%M %p")
        }

dusk sonnet
#

So i already have USE_TZ = TRUE, same with USE_L10N and have already set the timezone for TIME_ZONE,

#

But ye idk why its happening

native tide
#

Trying to get this link , but its returning empy list

native tide
serene prawn
#

Date should be the same, maybe your db browser converts dates into your local time or your django app does that

#

You can also manually convert it into utc time via .astimezone(tz=datetime.timezone.utc)

dusk sonnet
dusk sonnet
worldly bone
#

Which is better for fullstack mern or python

serene prawn
serene prawn
dusk sonnet
serene prawn
#

What's the time?

worldly bone
serene prawn
#

You can use both mongo and react with python

dusk sonnet
serene prawn
dusk sonnet
#

oops

serene prawn
dusk sonnet
serene prawn
#

Weird, not sure why there's a difference of 2 hours 🤔

#

Python app is using aest tz?

serene prawn
#

Ah, i see

#

How did you create your record in db?

dusk sonnet
dusk sonnet
# serene prawn How did you create your record in db?
chat_messages = await self.save_messages(self.room_name, message, get_user_instance)

@database_sync_to_async
    def save_messages(request, room_name, content, user_name):
        messages = ChatRoomMessage(room_name=room_name, content=content, user=user_name, date_sent=timezone.localtime())
        messages.save()
        return messages
serene prawn
dusk sonnet
#

like in the above image

#

this line seems to be changing the time for some goddamn reason and i cant figure out why

'date_sent': self.date_sent.strftime("%b %d %Y, %I:%M %p")
serene prawn
dusk sonnet
serene prawn
#

Hm 🤔

#

It should convert datetimes to your local time

dusk sonnet
dusk sonnet
wet dock
#

I need a little help

#

I recently got into flask web dev

#

and I was working with checkboxes

#

I'm trying to create this in flask

#

I made it in tkinter

#

but

#

is there a checkbox method to detect if a checkbox is checked?

#

in flask

#

in kinter we would have to set the on and off value but how do I do that in flask?

frank shoal
#

flask deals with backend, not html frontend.

#

You need to use javascript.

#

if you use jquery, you can do if ($("#check_id:checked").length)

#

If not jquery, you can do document.getElementById("check_id").checked

wet dock
#

thanks

outer apex
# wet dock is there a checkbox method to detect if a checkbox is checked?

In what context are you trying to detect if a checkbox is checked?

If the checkbox is part of a regular HTML form submission and you're processing the data within Flask, and has a name attribute set, you can do `flask.request.form.get('<name of the checkbox input>'). It'll return a truthy value if checked or None if unchecked.

As well, if you had a group of checkboxes for a related value and they're using the same name attribute (example is a selection of pizza toppings), you can use flask.request.form.getlist(...) to get all the options checked.

However if you're trying to detect outside of a form submission within Flask, and say you were trying to toggle DOM elements depending on a checkbox's status, then as others mentioned, you can use regular JS, JQuery, or even HTMX.

torpid juniper
#

hey every one does any one know how do i catch exceptions onflask_apispec use_kwargs decorator ????

frank shoal
#

!d flask.Flask.errorhandler

lavish prismBOT
#

errorhandler(code_or_exception)```
Register a function to handle errors by code or exception class.

A decorator that is used to register a function given an error code. Example:

```py
@app.errorhandler(404)
def page_not_found(error):
    return 'This page does not exist', 404
```  You can also register handlers for arbitrary exceptions...
frank shoal
#

use that.

rugged oxide
#

hello... im looking for a german guy who build us an web app for planing workers

hollow dragon
#

is it normal to one day feel like i know so much but the next day feel like i know nothing?

torpid juniper
#
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>422 Unprocessable Entity</title>
<h1>Unprocessable Entity</h1>
<p>The request was well-formed but was unable to be followed due to semantic errors.</p>
#

this is the return i am getting and i could't figure out where to add the error handler

golden bone
uncut parcel
#

im serving personalized content dynamically, is it a better experience for the user for their time to first paint to be lower and the content to not be as personalized straight away or a long time to first paint and a more detailed webpage (which takes longer for the server to process due to db calls etc)

hollow dragon
golden bone
hollow dragon
#

Sure, you are right. Thank you

toxic bay
#

Hello, a question: how can I change a header in flask? I have tried with

class localFlask(Flask):
    def process_response(self, response):
        response.headers["Server"] = "Server1"
        return(response)

but only another header with the same name is created

native tide
#

What are the best languages for front and end developement?
Also, could you suggest any youtube course (any length) for web developement?

native tide
#

Also I have heard Django isnt really great when it comes to back-end developement what do you think about that?

terse ermine
#

Hii. Question. I'm making a web app where a user can upload a sudoku puzzle image and the backend solves and returns the solution on the web page. My question is would that change be reflected to all users? How do I make it so that the specific user is returned his specific solution. Can anyone shed light on this?

golden bone
terse ermine
#

Yes but I mean say you upload an image of some sudoku. Backend solves it and dynamically updates the page. Would I (another user) see your solution? How would i make it so that you see your solution, and I see mine.

#

If that makes sense lol

#

I just figured it out. Thank you!!!

fiery hornet
#

i am using websocket library to connect with a server i am not understanding how to communicate with the client and server ! anybody help me plzz

#

??

solemn folio
#

Hi...does any one know any frameworks or work arounds to enable live or on demand streaming possible while using storage buckets to hold the video files

dusk sonnet
#

Hey im having an issue relating to DateTimeField in django. I use timezone.localtime() when saving objects into the database in order to display the correct time for my location. I have the following enabled in settings.py TIME_ZONE = 'My location', USE_L10N = True, USE_I18N = True, USE_TZ = True. The problem that im having is that in the admin dashboard, the time is displayed correctly and as intended however when i query in python to get certain objects, the time is printed out in UTC even tho im querying from the database. 1st image is essentially the result when querying from the database, 2nd image is viewing the same object/message from the admin dashboard.

elder nebula
#

It might be just what you want.

solemn folio
flint harbor
#

I am trying to create a todo list in Django, when I want to delete an item, I have to create another html page for deleteing it. I redirect the user there and then wait for it to confirm the deletion of an item, is there a way to simply click on a button a just delete the item, or just clicking a button and doing some sort of function, without creating a form or another html template

astral ledge
#

why this no workey 😦

#

what am I missing

astral ledge
#

nvm im dumb dumb forgot .name

hollow dragon
#

hey guys

#

i have an 'edit' function in my web app, which just allows me to edit the input value from the SQLAlchemy table, so basically the rows, for example the 'title' of an object.

#

It works perfectly fine, except for the first item

#

So I can use the 'edit' function on all the items except the first one

#

Have no clue why

hollow dragon
#

edit: solved it

delicate coyote
#

does somebody has an Idea how to make a bidirectional client Python/Web and the Server Python Flask. There are framework like socket.io, signalR, which would you recommend?

elder nebula
craggy flame
#

Heyho,
i hope im am correct in here with django and an sql issue 😄

I am trying to add an String "Name" and an Int "ItemID" into an model and into the database.

My Model is this:

    itemid = models.IntegerField()
    name = models.CharField(max_length=50)

    def __str__(self):
        return f'{self.itemid}'```
#

Everytime i run

new_item.save()```
#

it shows Field 'itemid' expected a number but got 'New Item'.

#

If i run
new_item = items(1, 123456,"New Item")
it works

#

After opening sqlite db with dbweaver, i see an column called ID. Shouldn't be the column autoincrement?

lapis spear
#

i have these code

from django.db import models
import uuid


class User(models.Model):
    id = models.UUIDField(
             primary_key = True,
             default = uuid.uuid4,
             editable = False)
    lastname = models.CharField(max_length=100)
    firstname = models.CharField(max_length=100)
    mi = models.CharField(max_length=20)
    age = models.IntegerField()
    gender = models.CharField(max_length=20)
    birthdate = models.DateField()
    vote_status = models.BooleanField(default=False)
    poll_status = models.BooleanField(default=False)


class News(models.Model):
    id = models.UUIDField(
             primary_key = True,
             default = uuid.uuid4,
             editable = False)
    title = models.CharField(max_length=100)
    headline = models.TextField(max_length=300)
    content = models.TextField(max_length=2000)
    date_posted = models.DateField(auto_now_add=True)

class Comments(models.Model):
    id = models.UUIDField(
             primary_key = True,
             default = uuid.uuid4,
             editable = False)
    user_id = models.ForeignKey(User, on_delete=models.CASCADE)
    news_id = models.ForeignKey(News, on_delete=models.CASCADE)
    comment = models.CharField(max_length=500)
    date_posted = models.DateField(auto_now_add=True)

and this table relations

for these 3 tables the user,news, and comment did i implement it correctly on my code?

next river
#

Can anyone recommend a good tutorial for building a basic website with Flask, where they also build the HTML and CSS from the ground up? Lots of the material I see online has pre-made templates, or they are copy/pasting code snippets and I'm not learning much from that. I want to learn how to cook, not just follow a recipe, if that makes sense.

delicate coyote
next river
rigid mist
#

Should you still use PHP to keep track of logins and sign ins if you're using Flask python backend?

radiant geode
#

I have a question.

rigid laurel
frank shoal
#

If you use a corporate ldap server, use flask-ldap-login

#

flask-msal if you use microsoft accounts

brave grail
#

I'm making a flask app

#

...and wondering if there is some way to dynamically choose dimensions for an image that is generated for a html page so that it fits on the screen?

#

For my specific example, I am making images from pdf file. (just the first page) ```py
def pdf_preview_image(pdf_path, image_destination):
"""

:param pdf_path:
:param image_destination:
:return:
"""
# Turn the pdf filename into equivalent png filename and create destination path
pdf_filename = split_path(pdf_path)[-1]
preview_filename = ".".join(pdf_filename.split(".")[:-1])
preview_filename += ".png"
output_path = os.path.join(image_destination, preview_filename)

# create png preview and save it
fitz_doc = fitz.open(pdf_path)
first_page_pix_map = fitz_doc.load_page(0).get_pixmap()
first_page_pix_map.save(output_path)
return output_path
#

fitz is like a pdf library

#

pdf files range from 8.5x11 to 42x36 so the images can be quite big.

outer apex
brave grail
#

I guess I'm wondering if there is a way to determine the user screen size so that I could adjust the dimensions likewise. Or is there like a standard image size web developers consider a maximum size?

radiant geode
#

What I should start learning if I want to work on websites??

frank shoal
#

html

hollow dragon
#

is it possible to tell if a web app to heroku was deployed with docker?

frank shoal
#

You usually can if you have access to the filesystem

#

But not from the client.

soft trout
#

anybody good at beautiful soup, need help parsing specific information from a page that has wonky text

outer apex
native tide
hollow dragon
#

If I have a registration form for users, is it safe if it only has "username" and "password" section in it? I removed the "email" section.

#

Or storing any user data is always unsafe?

#

I mean, only "username" and "password" shouldn't be personal data, right?

#

Or just use Two-factor auth ?

#

Or provide "dummy users" for testing my app?

proper hinge
#

Yes.

dusk sonnet
#

Hey, how can i force scroll to the bottom of the container as soon as page is loaded? (javascript)

native tide
#

Hey, im writing an application in django. Parts of my app need to be in django, like the login, registration, main page and some other pages. But i want the user dashboard to be in react. How could i have this part of the website written in reactjs?

vapid osprey
#

Hi! Can anyone tell me how can i refresh the screen in kivymd on a click of a button. Actually i'm creating a fact app in which i will get random facts in click of a button. But i unable to do it on a click on button.
My code: https://paste.pythondiscord.com/arekewirul

ruby tree
#

after reading the docs i came up with this: but this never seems to work

$('#display_table').bootstrapTable({
    onClickRow: function (row, $element, field) {
      alert("testing");
    }
})
#

anyone here used jquery with bootstrap ? and know how to get a row clicked listener (sort of)...?

somber plover
#

dunno. it's not just you. doesn't work for me either. try chaining .on() from the bootstrapTable() object instead.

#
$('#display_table').bootstrapTable().on('click-row.bs.table', function (e, row, $element, field) {
  alert("testing");
});
#

note as per the API doc, e (the event itself) is passed as the first argument with this form.

somber plover
ruby tree
#

Ahhh

somber plover
#

once upon a time, i used to use jQuery. don't anymore. it has all been replaced with vue + webpack + babel

ruby tree
#

I wish the stuff they put in the docs would just work just like that

#

Alright let me try what u posted

somber plover
#

checking their issues ...

ruby tree
#

this is a old answer ^ but this seemed have worked for them

#

maybe something got changed in recent years , idk

somber plover
#

this.

#

dunno what that's all about though ... i'm just using the "getting started" example code and in the jQuery load handler, attach the bootstrapTable there. ... no vue at all.

small linden
#

I’m trying to click a button on a webpage with selenium, but for some reason I cannot find any element in the page

#

It either says stale element or element not found

ruby tree
#

iam trying to make my code similar to a example visible on that link u posted , will update !

somber plover
#

you mean the "welcome.html" they linked?

#

i only see the .on() form in there, too. but nowhere in the doc explains why onClickRow no longer works if you aren't using Vue. :p

ruby tree
#

oh

somber plover
ruby tree
#

mhaaaa i got it to sort of work via vue

#
<script>
new Vue({
    el: '#table',
    components: {
      'BootstrapTable': BootstrapTable
    },
    data: {
      columns: [
        {
          title: 'Item ID',
          field: 'id'
        },
        {
          field: 'name',
          title: 'Item Name'
        }, {
          field: 'price',
          title: 'Item Price'
        }
      ],
      data: [
        {
          id: 1,
          name: 'Item 1',
          price: '$1'
        }
      ],
      options: {
        search: true,
        showColumns: true
      },
      onClickRow() {
          //on click row
         alert("testing");
    }
    }
  })
    </script>
#

so now this onClickRow() functions would get called everytime a row is clicked on

#

but i still dont know how to access the values tho , testing

somber plover
#

Vue is certainly nicer. looks like progress! :)

ruby tree
#
 onClickRow(row, $element, field) {
         alert("field:"+field+"-"+"row.name:"+row.name+"-"+"row.id"+row.id);
    }
#

@somber plover thanks , this seems to work for now

#

so apparently onclickrow works on vue

#

and not on js i have no idea

#

but seems to work for now

somber plover
#

shrugs

#

that's great!

ruby tree
#
<div id="table">
            <bootstrap-table :columns="columns" :data="data" :options="options" @on-click-row="onClickRow"></bootstrap-table>
          </div>
#

this is how i create the table for it to work with vue ^

#

but there is one big problem here

somber plover
#

it is a heck of a lot less mysterious to have the handler explicitly put in the template like that ...

ruby tree
#

:data="data" ...... iam creating data on vue and i hope there is some way to just use my old html tables oops

somber plover
#

than the more mysterious binding on load of the handler when the table is instantiated

#

personal taste.

#

(and is one of many reasons why I no longer directly write jQuery ;) )

ruby tree
#

haha

#

and this is the js

new Vue({
    el: '#table',
    components: {
      'BootstrapTable': BootstrapTable
    },
    data: {
      columns: [
        {
          title: 'Item ID',
          field: 'id'
        },
        {
          field: 'name',
          title: 'Item Name'
        }, {
          field: 'price',
          title: 'Item Price'
        }
      ],
      data: [
        {
          id: 1,
          name: 'Item 1',
          price: '$1'
        },
        {
          id: 2,
          name: 'Item 2',
          price: '$2'
        }
      ],
      options: {
        search: true,
        showColumns: true
      },
      onClickRow(row, $element, field) {
         alert("field:"+field+"-"+"row.name:"+row.name+"-"+"row.id"+row.id);
    }
    }
  })
#

it works , i just need to experiment with it for sometime to learn how it works... all i know rn is it just works like magic , iam new to vue , this is goona be interesting

wraith dagger
#

Hey there!
Am I able to generate object like this

filter_obj = Q(field1=value) | Q(field2=value) | ...  # Some other fields

and then filter over this object? As initial data I have fields: Iterable[str], value: str and QS

split swift
#

can someone help me with css

#

there is a white outline around my input field

plucky wadi
#

Can i get vote on using sqlite3 for production.(django)

solemn quest
#

Someone know how to print pinged ip adress in html?

covert yew
#

does someone know of a good tutorial to design apis?

covert yew
frank shoal
frank shoal
#

Plus it's too easy to lock up the database by forgetting to close a connection.

plucky wadi
frank shoal
#

You're still limited to one session at a time.

plucky wadi
#

The thing is i'm facing a lot problems using postgres inside docker.

frank shoal
#

What kind of problems?

plucky wadi
#

and i'm not familiar with postgresql

#

so thinking sqlite3 might be an easy solution.

frank shoal
#

How are you deploying?

#

heorku gives you a free database

plucky wadi
#

its a project for my college association , so on a local server

frank shoal
#

then it might not matter much.

bronze cedar
#

Hey I have a question

#

Let’s say someone wants to hack their old instagram account? What do they have to learn? And how long will it take them?

#

(Sorry sent this on the wrong chat)

glass wren
#

I got a take home project to create a chat application in Django and I built it using channels following channels documentation tutorial but I'm quite confused on how to make them secure(end to end only)
This is what the requirement said:

Third part of this project is for you to make this web socket secure. You don’t have to add any certificates to make the protocol ‘wss’ instead of ‘ws’. But you have to come up with a way to make sure just using the socket link no third party can see the streams. That mean you have to add a layer of security to view the stream.

I've looked into https://channels.readthedocs.io/en/stable/topics/security.html but I don't think that is it, would appreciate if anyone could push me in the right direction.

native tide
#

ok

native tide
#

did you guys use django to code a website

proper hinge
#

Yes

native tide
#

Yes

worn crystal
#

I'm using the builtin webbrowser library

import webbrowser

I uploaded my flask app with a requirements.txt and i don't know how to include webbrowser as a requirement since I'm used to only putting stuff from pip in there
here is an example of what is in my requirements.txt
could someone help me out with this? I have some code not behaving correctly because of this

urllib3==1.26.9
Werkzeug==2.1.0
wsproto==1.1.0
zipp==3.7.0
proper hinge
#

It's part of the standard library, so you do not need to and should not include it in requirements.txt

#

requirements.txt is for third-party dependencies

astral pagoda
#

I am trying setting up flask-mail email for outlook. I had it working with gmail
I found this link
https://superuser.com/questions/1521236/how-to-allow-less-secure-app-access-in-microsoft-email

I tried

    MAIL_SERVER= 'smtp.office365.com'
    MAIL_PORT  = 587
    MAIL_USE_TLS = True
    MAIL_USE_SSL = False
    MAIL_USERNAME = os.environ['EMAIL_USERNAME']
    MAIL_PASSWORD = os.environ['EMAIL_PASSWORD']

and I tried

    MAIL_SERVER= 'outlook.office365.com'
    MAIL_PORT = 995
    MAIL_USE_TLS = True
    MAIL_USE_SSL = False
    MAIL_USERNAME = os.environ['EMAIL_USERNAME']
    MAIL_PASSWORD = os.environ['EMAIL_PASSWORD']

https://imgur.com/a/luH7JSb
What am I doing wrong?
Thanks for the help

quiet harbor
#

anyone here ever made a purchase shop code in python?

ruby tree
#

hmmm

#

guys, in my django project , i have a js function set up that would trigger based on clicks from a bootstrap table, so the part visible on the code is only of importance here , iam looking for ways by witch i can delete id received in this function ,, can someone help me go in a correct direction -iam clueless as of now

..
...
.....
else if($(this).data("delete-id")){      
id=$(this).data("delete-id");
alert("delete clicked: "+id);  //was just testing to see if it works and it works..

//in here i need to make some way to connect to my django models and delete that perticular id...
}

i have already setup a delete page and this is the view function for it :

def delete(response):
    temp = models.ToDoList.objects.all()
    max_id=0
    for i in temp:
        max_id=i.id
    
    if response.method=="POST":
        form1 = DeleteList(max_id,response.POST)
        if form1.is_valid():
            "if valid input , then delete that id"
            temp.filter(id=form1.cleaned_data["id"]).delete()
            
            return HttpResponseRedirect("/display")
    else:
        form1 = DeleteList(max_id)
    return render(response,"main/deleteList.html",{"form":form1})

i think the way to go forward is to somehow make my js function do a post method so that i can just handle it in my delete views function .... is this correct ? how do i do this btw

wide shuttle
#

Hey guys, have a django question, I use the login_required decorator to redirect the user to the login page, but after loggin in, it redirects user to the index page, not the view that triggered login_required, how will I fix it?

stark tartan
native tide
#

showing error UnboundLocalError at /
local variable 'cartItems' referenced before assignment

#
    def get_cart_items(self):
        orderitems = self.orderitem_set.all()
        total = sum([item.quantity for item in orderitems])
        return total```
#

time:33min

chilly falcon
#

were can i put my image of my project so that when i send mail from my app those image can be view by receiver

#

i want my image in internet

wind dove
#

How can I have two OneToOneFields in a single Django Model?

#

This works:

from django.db import models
from django.conf import settings


class FriendRequest(models.Model):
    author = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)

This doesn't:

from django.db import models
from django.conf import settings


class FriendRequest(models.Model):
    author = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    recipient = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)

The second one throws:

interactions.FriendRequest.recipient.
interactions.FriendRequest.recipient: (fields.E304) Reverse accessor for 'interactions.FriendRequest.recipient' clashes with reverse accessor for 'interactions.FriendRequest.author'.
        HINT: Add or change a related_name argument to the definition for 'interactions.FriendRequest.recipient' or 'interactions.FriendRequest.author'.
interactions.FriendRequest.recipient: (fields.E305) Reverse query name for 'interactions.FriendRequest.recipient' clashes with reverse query name for 'interactions.FriendRequest.author'.
        HINT: Add or change a related_name argument to the definition for 'interactions.FriendRequest.recipient' or 'interactions.FriendRequest.author'.
wind dove
desert nexus
#
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
from pprint import pprint

"""
options = Options()
options.binary_location = r'C:\Program Files\Mozilla Firefox\firefox.exe'
options.headless = True
driver = webdriver.Firefox(executable_path=r'D:\Documentos\pythonProject\api_test\geckodriver.exe', options=options)
url = "https://banguat.gob.gt/cambio/historico.asp?kmoneda=02&ktipo=5&kdia=16&kmes=05&kanio=2022&kdia1=20&kmes1=05&kanio1=2022&submit1=Consultar"
driver.get(url)
xpath = '/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/div/table'
element = driver.find_element(by=By.XPATH, value=xpath)
rows = element.find_elements(By.TAG_NAME, "tr")
dollar_dict = []
for row in rows[1:-1]:
    cols = row.find_elements(by=By.TAG_NAME, value='td')
    dollar_dict.append({cols[0].text: float(cols[1].text)})


pprint({'dollar': dollar_dict})
"""
url = 'http://www.banguat.gob.gt/variables/ws/VariablesDisponible'
my_obj = {'xmlns': 'http://www.banguat.gob.gt/variables/ws/'}

x = requests.post(url)

content2 = x.content

soup = BeautifulSoup(content2, 'html.parser')

print(soup.prettify())  ```
viscid token
#

i'm working at a django project for school, i want to use a css file but he don't recognized it as a css file. Someone that knows why?

wide shuttle
#

fixed by giving a hidden input tag value of the redirect site and fetching it during authentication and then redirecting there

sonic sun
#

How do websites display(render) images of different size but the image looks pretty much the same despite the difference in aspect ratio? Is there a specific formula? or have I misunderstood anything?

feral thunder
#

hi guys, how do i connect my apache web server to the internet??

frank shoal
#

First, you open your ports

#

Local, firewall, router, etc

#

Maybe do some port forwarding (ports 80, 443 TCP)

#

(optional) assign a dns name to your public ip

#

You should probably go through a reverse proxy and cache service like cloudflare if you expect a lot of traffic

native tide
#

Hello guys, how can I run my python script in web asynchronously (Without refreshing the page). Can it run on ajax?

frank shoal
#

Use JavaScript to poll your endpoint and update the page dynamically using the DOM api

native tide
#

Hey, i have a django webserver where certain code does not run on my production server but it does run on my machine. I have isolated some things that cause the error, but cannot get django to write the error log to a file, somehow. When i allow error logging, it just causes all of my requests to return an error 500...
what do i do?

#

It also just does not log
this is my logging config

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/var/www/debug.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}
narrow basin
#

What are the differences/benefits to using aiohttp's websocket support vs using websockets?

regal lotus
#
resp = requests.get('https://wax.api.atomicassets.io/atomicmarket/v1/assets?collection_name=nfsocialexgg&schema_name=nfse&page=1&limit=1&order=desc&sort=asset_id')
data = resp.json()
asset_id = data['data']['asset_id']
print(asset_id)


### And the error I get is 

TypeError: list indices must be integers or slices, not str

ashen yew
mental summit
native tide
#

can we talk about web scraping here?

rapid jasper
#

is it possible to run a flask function without the route ?

lime dust
#

What do I need to know to make a website that is accessible on the internet?

golden bone
golden bone
native tide
#

Like there is a page with some words

#

And I need to take these words

golden bone
# native tide And I need to take these words

There are various tools you can use depending what you need to do exactly... here's a relatively simple approach: https://timber.io/blog/an-intro-to-web-scraping-with-lxml-and-python/

scenic dove
#

Hello

native tide
#

What do people use for deploying django projects for free?
Ive been trying to get Heroku to work for hours upon hours and it just isnt working, does anyone have any good alternatives or can anyone help me troubleshoot my problem?

native tide
#

No matter what I do I always get the same error:
Heroku will not recognise django_heroku

#

Ive gone through two tutorials multiple times, looked at probably 20+ forum posts, nothing has worked, the error message never changes

#

Ive made a new git account and repository multiple times

#
remote: -----> $ python manage.py collectstatic --noinput
remote:        Traceback (most recent call last):
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 259, in fetch_command
remote:            app_name = commands[subcommand]
remote:        KeyError: 'collectstatic'
remote:        During handling of the above exception, another exception occurred:
remote:        Traceback (most recent call last):
remote:          File "/tmp/build_d1951427/manage.py", line 22, in <module>
remote:            main()
remote:          File "/tmp/build_d1951427/manage.py", line 18, in main
remote:            execute_from_command_line(sys.argv)
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
remote:            utility.execute()
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute
remote:            self.fetch_command(subcommand).run_from_argv(self.argv)
#
remote:            settings.INSTALLED_APPS
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 87, in __getattr__
remote:            self._setup(name)
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 74, in _setup
remote:            self._wrapped = Settings(settings_module)
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 183, in __init__
remote:            mod = importlib.import_module(self.SETTINGS_MODULE)
remote:          File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module
remote:            return _bootstrap._gcd_import(name[level:], package, level)
remote:          File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
remote:          File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
remote:          File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
remote:          File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
remote:          File "<frozen importlib._bootstrap_external>", line 850, in exec_module
remote:          File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
remote:          File "/tmp/build_d1951427/ostexp2/settings.py", line 15, in <module>
remote:            import django_heroku
remote:        ModuleNotFoundError: No module named 'django_heroku'```
#

Its in the requirements.txt file

#

Ive tried django-on-heroku

#

Every single person who gets this error message online seems to have a different problem and different solution so it may possibly be the most unhelpful error message ever made

#

Are you talking about this?

import django_heroku
django_heroku.settings(locals())```
Because yes I have this
#

I also included it in the requirements.txt file

#

I also installed psycopg2 and psycopg2-binary which apparently you need

#

i know you have it in the requirements.txt file but do you need to run a console command in heroku?

#

like pip install -r requirements.txt?

#

Ill try it

#

it's what I need to do on pythonanywhere, heroku might work differently

#
(ostexp2) osboxes@osboxes:~/ostexp2$ pip install -r requirements.txt
ERROR: Could not find a version that satisfies the requirement apturl==0.5.2 (from versions: none)
ERROR: No matching distribution found for apturl==0.5.2```
#

Weird

#

Is this normal?

remote:        Installing initially failed dependencies...```
jaunty depot
#

hey guys
I'm not sure if I understand correctly the documentation - I wanted to ask, if I wanted to make a django project that is connected to mysql database, do I need to make a User model as well, so that it will be migrated to mysql database? I'm reading, that Django by default contains "User" model in it, but will it also be available when using outer (not sqlite3) database?

golden bone
jaunty depot
#

no no, I'm not building the project yet - I'm just finding out and reading about it. I wanted to make a project that will allow registration of new users, logging in/out etc

#

and just wanted to know how does that work, that Django offers built-in user models

#

I know that I will build some other models and wanted to know how it will cooperate

golden bone
#

Your User model will be stored in whatever database you use, shouldn't matter

jaunty depot
#

ah, okay, so now I know
thanks!

whole crow
#

I want to have an img with a caption, so I tried <figure><figcaption>.  But <figure> implies the end of a <p>, where <img> does not.  Is there a way to add a caption to <img>, or to keep the inline nature with <figure>?  I know I can style it display:inline-block, but HTML validators complain, and it's parsed as if it ends the paragraph.

serene matrix
#

Where do you guys put your process-codes(I don't know if that's what it's called)?

For instance: a function that sends an email.

Do you just drop them in views.py or do you put them in utilities.py?

foggy bramble
#

Hello
is there a way to access get the remaining countdown time of celery apply_async
Under certain circumstances, lets say worker countdown was 15 secs, if a specific event occurs i need to revoke previous task (lets say it now has 10 sec left), and I need to get remaining time of previous worker, sum it with 15 (in this case 20) sec and create new worker with new countdown, and this process should be cycled

agile pier
granite lintel
#

ive got a question, is flask better than django or not

serene matrix
serene matrix
native tide
agile pier
serene matrix
agile pier
serene matrix
#

I feel things could be more organized keeping it organized

digital lily
#

can anyone help me code

#

I followed along with a youtube video but my code isn't returning a value

granite lintel
#

i'm also a beginner so

digital lily
viscid bough
digital lily
#
import bs4
import requests
import openpyxl

wb = openpyxl.load_workbook(r'C:\Users\Demar\Document\Vinny.xlsx'')
sheet = wb['Vinny']

r = request.get('https://finance.yahoo.com/quote/AAPL?p=AAPL&.tsrc=fin-srch')
soup = bs4.BeautifulSoup(r.text, features='html.parser')
priceAAPL = soup.find_all('div', {'class', 'D(ib) Mend(20px)'})[0].find('span').text('.','.')

print(priceAAPL)
#

@viscid bough its not returning a value

viscid bough
#

M not cruntly at my machine... But it look like.. Something is wrong there

viscid bough
native tide
#

not sure I am in the right place here, if I am creating a class , how can I stop a user using the terminal to create custom attributes or overwrite existing ones?

torpid grove
undone heath
zealous elk
#

I am having trouble with a flask app that I am working on. The details are in #help-popcorn so please help me if you can

covert ibex
#

Hey, I am having an issue with django , details are in #help-peanut , please help if you can.

floral steppe
#

I built a deep learning model that classify texts into two categories positive and negative, the negative is any text that contains racial slurs or any kind of threatening or doxing, I want to integrate it with another project it is similar to twitter, I want to categorize posts with the model to make it easier for the admin to review them but I don't have any idea how to merge these two projects together, any ideas or references on how to do that

agile pier
#

@covert ibex u can add (blank=True, null=True)

native tide
#

Does anyone know how to update my django code on pythonanywhere?

obtuse robin
#

you go to the files section

#

and you can edit whatever file it is from there

#

it has its own console as well

native tide
#

Is there a way I can just do a 'git clone ...' sort of thing again?

#

I tried but it wont let me

obtuse robin
#

i don’t know, i haven’t tried

native tide
#

Anyone understand this?

(ostexp-venv) 14:14 ~ $ git pull
fatal: not a git repository (or any parent up to mount point /home)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).```
#

Got it working, did:
git init
git remote add origin (url)
git pull

#

Is SQLite able to be used for Python Anywhere?

covert ibex
crimson violet
#

Guys any recommendations on how to set up automatic payments with crypto on a flask server?

plucky wadi
wide harbor
#

I've a Django issue/ question in help-chocolate. Regarding adding data to existing models via form. Help would be appreciated but no worries if not.

lavish prismBOT
#

Hey @left kelp!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

native tide
#

i have this site

#

i need to take the extension

#

like .com , .it , .eu , ecc

#

but there is cloudfire

#

it block my API to scrap the page

#
from selenium import webdriver

PATH = r"C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get(r"https://dotdb.com/search?keyword=crypto&position=any&page=1")```
#

wrong chat

lone thunder
#

Just want to say hello to the house

#

okay am sorry

plain bough
#

So I have this code: (app is just a normal aiohttp.Application)

async def main():
  async with aiohttp.ClientSession() as client:
    app.client = client
    try:
      runner = web.AppRunner(app)
      print(runner)
      await runner.setup()
      site = web.TCPSite(runner,port=3308,host="127.0.0.1")
      print(site)
      await site.start()
    except KeyboardInterrupt:
      await runner.cleanup()
asyncio.run(main())
``` and it prints the `AppRunner` and `TCPSite` object, but then exits and doesn't actually run my site, how can I fix this?
native tide
#

hi im trying to pass some variable for a dynamic site however when i do so i get TypeError: redirect() got an unexpected keyword argument 'username'

#

flask return statement > py return redirect(url_for('D1'),username=username)

#
<a href="default.asp">
   <img src="{{ url_for('static', filename='images/{{username}}.png') }}" alt="Profile Pic" style="width:200px;height:200px;">
</a>
<p style="padding-left:15%;padding-right:15%;font-weight: bold;text-align: center;">{{username}}</p>```
#

template html

buoyant star
woeful loom
native tide
#

does anyone know how to monetize a website with banner ads besides using google adsense
website monetization isnt listed as an eligible product for my account

stiff pebble
#

Hi everyone, does anyone have good knowledge of deploying Django on heroku using waitress as the web server on windows. It's almost seem impossible

nova garnet
lavish prismBOT
#

Hey @hollow shell!

It looks like you tried to attach file type(s) that we do not allow (.pdf). 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.

nova garnet
#

I have JavaScript in my html and I’m running it with Python flask

native tide
#

in python format is used like this chart.labels('{}').format(what_wanna_put)'

nova garnet
#

Also I actually don’t understand the variable {%name} in the tutorial. Where does it come from? Is it from what’s inside data?

rigid laurel
#
chart.labels().format('{%name}');
#

the name comes from the data you define above presumably

#

but this is specific to whatever random graph library this is - not anything more generalisable

nova garnet
#

flask doesn't seem to like chart.labels().format('{%name}'); so now I'm trying the suggestion of abstract

rigid laurel
#

oh it's obvious why

#

the {% is being mistaken for the opening of a Jinja tag

#
{% raw %}
chart.labels().format('{%Name}');
{% endraw %}
lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @native tide until <t:1654506849:f> (9 minutes and 59 seconds) (reason: mentions rule: sent 6 mentions in 10s).

nova garnet
nova garnet
#

it works but I'm still not getting a tooltip when hovering over the diagram with my mouse... I'll try copy pasting the whole thing with the {% raw %} {% endraw }

#

I finally got it working! thanks a lot!

#

I figured out why i didn't see a tooltip. apparently I can't have a transparent background AND a tooltip

nova garnet
#

turns out i can have a transparent background with tooltip. just had to use chart.background().fill('white',0); instead of chart.background().enabled(false);

native tide
#

Im using Django
My website is used for seeing all songs in game soundtracks
I have it so if the url is ' ' then it directs to index.html
And if the url has anything else it attempts to find all songs from whatever it got ( 'url/game_name/' gets all songs from game_name)

I want it so if the game does not have any songs then it redirects to index.html
Heres what I have:

from django.shortcuts import render
from django.http import HttpResponse
from .models import Game, Song

def AllGames(request):
    return render(request, 'index.html', { 'games' : Game.objects.all() })

def GameHTML(request, game_name):
    allsongs = Song.objects.all()
    game_songs = []

    for song in allsongs:
        if song.game.name == game_name:
            game_songs.append(song)

    game_songs.sort()

    #Problem Area:
    if (game_songs.count == 0):
        return render(request, 'index.html', { 'games' : Game.objects.all() })

    return render(request, 'songs.html', { 'game_name' : game_name, 'all_songs' : game_songs})```

If you can see the problem thats great but if not does anyone know a way to write stuff to a console or something so I can check game_songs.count whenever I try putting in a url?
#

Forgot to mention my problem is that if (game_songs.count == 0) never gets called when it should

#

I added this but I dont know where it shows up, its not in the web dev tools

logging.basicConfig(level=logging.INFO)
    logging.debug(game_songs.count)```
paper yacht
#

who teach you to name function using camel case?

paper yacht
native tide
#

Database?

#

I think its many-to-one not one-to-many as well

#

All songs store what game they belong to

#

A game can have multiple songs

paper yacht
native tide
#

Alright so Im not sure what you want me to do

#

So your saying I can find the ID of the game_name
Then using get_or_404 I can filter through all songs which have that ID in them

#

Maybe something like this?

def GameHTML(request, game_name):
    game_ = Game.objects.get(name=game_name)

    game_songs = get_object_or_404(Song, game=game_)

    game_songs.sort()

    if (game_songs.count == 0):
        return render(request, 'index.html', { 'games' : Game.objects.all() })

    return render(request, 'songs.html', { 'game_name' : game_name, 'all_songs' : game_songs})```
#

get_object_or_404 seems to throw an exception if it returns multiple songs which is what I want

#

pls

#

i need help

paper yacht
#

and what the purpose of sorting the songs?

native tide
#

What is pk?
Im sorting them so when they are in order on the website

paper yacht
native tide
#

Should I be changing this?

urlpatterns = [
    path('', views.AllGames),
    path('<str:game_name>/', views.GameHTML)
]```
paper yacht
native tide
#
game_songs = get_object_or_404(Song, pk=game_.id)```
#

This only returns one song and throws an error when I try to sort it

#

Cant I do something more like this

game_songs = Song.objects.filter(game=game_)```
native tide
#

Cool, just need to figure out how to sort a QuerySet now

native tide
#

Does anyone see anything wrong with this search bar?
When pressing the button it just reloads the page with url 'server.com/?'

<input class="form-control me-2" type="search" id="gameSearch" placeholder="Search for a Game" aria-label="Search">
        <button class="btn btn-outline-success" type="submit" onclick="Find()">Find</button>
        <script>
            function Find(){
                var input = document.getElementById("gameSearch").value;
                window.location.assign(`${window.location.hostname}/${input}/`)
            }
        </script>```
sudden sierra
native tide
frank shoal
#

Usually a search is done like this via a normal form. ```html
<form action="/gameSearch">
<label for="gameSearch">Game Search</label>
<input type="search" name="q" id="gameSearch">
<input type="submit" value="Search">
</form>

#

Submit will send the user to https://<hostname>/gameSearch?q=<searchstring>

native tide
#

What is name=q referring to

frank shoal
#

its naming the input. it's determines what query string to use.

#

in this case, ?q=value

#

where q is the key

native tide
#

Ill try it

native tide
frank shoal
#

What are you using on the backend?

native tide
#

Im not 100% how to answer that but I think VSCode, Django, SQLite and PythonAnywhere

#

One of those is probably the answer

frank shoal
#

django, then use request.GET.get("q")

native tide
#

Where do I put that?

frank shoal
#

in your endpoint for /gameSearch

native tide
#

In <form action=... ?

frank shoal
#

no, in your backend.

#

You know how to define an endpoint, yes?

native tide
#

No Im not sure

#

I mean maybe I do and I just dont know what its called

#

Very new to web dev

#

Is this what you meant?

urlpatterns = [
    path('', views.AllGames),
    path('<str:game_name>/', views.GameHTML),
    path('?q=<str:game_name>/', views.GameHTML)
]```
#

Doesnt seem to work so I guess not

paper yacht
native tide
#
urlpatterns = [
    path('', views.AllGames),
    path(r'?q=<str:game_name>/', views.GameHTML),
    path('<str:game_name>/', views.GameHTML)
]```
For the regex one, is the string meant to be all red except for the ? which is orange?
#

Am I supposed to use re_path?

#

Something like this? I really need help

re_path(r'(?q=<str:game_name>)/', views.GameHTML),```
#

|
|
|
Let me start again

Im trying to make a search bar
This is my HTML:

<form action="/gameSearch">
          <label for="gameSearch">Game Search</label>
          <input type="search" name="q" id="gameSearch">
          <input type="submit" value="Search">
        </form>```
When I use it the url ends up as:
```hostname/?q=value```
I want it so it either ends up as:
```hostname/value```
Or a way to modify this so the first url works:
```py
urlpatterns = [
    path('', views.AllGames),
    path('<str:game_name>/', views.GameHTML)
]```
zealous elk
#

I am getting an error in this flask app I am working on. The details are in #help-bagel, please help me if you can

olive hazel
#

it took me about 2 months for html. i am planning to do Javascript and css in 3 months is it possible and is that much knowledge any worthy. (hour for each every day)

paper yacht
olive hazel
#

time to time i was bit stuffed up

#

still am but ready to put in the effort

paper yacht
olive hazel
#

how bout that

paper yacht
#

i spend one hour a day, maybe a bit more deepends on the content (documentation, video or just practise coding)

paper yacht
#

don't remember

olive hazel
#

can u guess months?

native tide
# native tide | | | Let me start again Im trying to make a search bar This is my HTML: ```htm...

Still looking for an answer to this but in the meanwhile for this code why does the {{ game.img }} work but {{ game.color }} doesnt?
Says it wants a property value:

{% for game in games %}
            <div class="col">
            <div class="card" style="width: 13rem; background-color:{{ game.color }};">
                <div class="card-body">
                    <img src="{{ game.img }}" class="card-img-top" alt="">
(Removed, unimportant)
        {% endfor %}```
paper yacht
#

@native tide do you have color attribute in Game model?

native tide
#

Anyone know of any servers where I might be able to get more answers? I mean I would think these are like noob beginner questions

#

Hello guys, for updating a ressource on django (non REST framework), would you suggest a post or a put request?
Is it best practice to make CRUD operations even on an app that is not an API?

native tide
#

@native tide Such as: if len(game_songs) == 0:

glacial wigeon
#

i need someone to point me in the right direction, I want to create a webapp that essentially takes an upload from the user(which is stored temporarily and deleted after processing) (pdf, doc, txt file) and well reads some text and spits some output out, I need to know what technologies are involved in the taking upload part

viscid bough
#

Sonds crazy.. When its full stack

frank shoal
#

basically have a web server that accepts uploads and stores them in S3, then have a worker (like celery) connected to a store like redis or rabbitmq

glacial wigeon
#

i dont know much about webdev, a c++ coder here

native tide
frank shoal
#

a process to accept uploads, a place to store them, and a process to process uploads individually

native tide
#

Django - Docker - Heroku

glacial wigeon
#

is heroku better than the s3 free tier?

frank shoal
#

heroku doesn't come with storage.

#

it just comes with a database (postgres)

#

I personally use both

glacial wigeon
#

i see, i'll learn a bit of s3 tom and see if it fits the bill

#

probably will

frank shoal
#

note: s3 charges for bandwidth, not storage space

#

I believe internal access (i.e. from aws servers) is free.

abstract socket
#

django-heroku installation error how can i solve it???

frank shoal
#

Have a log or error message?

abstract socket
#
  Using cached psycopg2-binary-2.9.3.tar.gz (380 kB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error
  
  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [23 lines of output]
      running egg_info
      creating /private/var/folders/60/4zbgw8rd0m9_h_h7ldx47vhm0000gn/T/pip-pip-egg-info-zwowilp6/psycopg2_binary.egg-info
      writing /private/var/folders/60/4zbgw8rd0m9_h_h7ldx47vhm0000gn/T/pip-pip-egg-info-zwowilp6/psycopg2_binary.egg-info/PKG-INFO
      writing dependency_links to /private/var/folders/60/4zbgw8rd0m9_h_h7ldx47vhm0000gn/T/pip-pip-egg-info-zwowilp6/psycopg2_binary.egg-info/dependency_links.txt
      writing top-level names to /private/var/folders/60/4zbgw8rd0m9_h_h7ldx47vhm0000gn/T/pip-pip-egg-info-zwowilp6/psycopg2_binary.egg-info/top_level.txt
      writing manifest file '/private/var/folders/60/4zbgw8rd0m9_h_h7ldx47vhm0000gn/T/pip-pip-egg-info-zwowilp6/psycopg2_binary.egg-info/SOURCES.txt'
      
      Error: pg_config executable not found.
      
      pg_config is required to build psycopg2 from source.  Please add the directory
      containing pg_config to the $PATH or specify the full executable path with the
      option:
      
          python setup.py build_ext --pg-config /path/to/pg_config build ...
      
      or with the pg_config option in 'setup.cfg'.
      
      If you prefer to avoid building psycopg2 from source, please install the PyPI
      'psycopg2-binary' package instead.
      
      For further information please check the 'doc/src/install.rst' file (also at
      <https://www.psycopg.org/docs/install.html>).
      
      [end of output]
frank shoal
abstract socket
#

ok solved

#

brew install postgresql
pip3 install psycopg2
pip3 install django-heroku

#

these three steps

plucky wadi
#

Has anyone encountered this error before , "<static_files> was blocked due to MIME type {"text/html"} mismatch {X-content-options : nosniff)
Tech stack : django app running on docker with nginx as reverse proxy and gunicorn as my web server.

verbal surge
#

Hi everyone! I would like to try using Python instead of JS for web development. I've seen Django, Flask, and FastAPI mentioned, but does anyone have a recommendation for which one I should start with?

plucky wadi
verbal surge
plucky wadi
#

Django has a lot of built in features. I'd prefer you use it.

verbal surge
verbal surge
#

Good to know! Thanks for the info

native tide
#

Does anyone know how to save a todo list to local storage

past cape
#

how do you get "Connection is secure" for your website?

#

like this

#

ping when replying, thank you

whole crow
pine yew
past cape
#

ah okay, thank you

pine yew
# past cape ah okay, thank you

basically Google pays someone like Symantec to give them a certificate (where Symantec is the certificate authority [CA]) and Google uses that to encrypt the the traffic they serve to you using HTTPS (HTTP over TLS).

This is seen as secure because 1. you trust the CA, 2. they've established their identity with the CA so you know they served the traffic

#

there's a lot more complexity when it comes to CAs and certificates, but that's the gist of it

#

what "trust" breaks down to usually is which vendors the operating system vendor has established trust with and includes their root certificates in your OS certificate store

past cape
#

make much more sense

#

ty sir, appreciated

pine yew
#

or something like Firefox which includes its own certificate store

#

or Java which provides its own store as well (usually inherited from the OS, though)

past cape
#

so they can just approve themselves as certified?

pine yew
past cape
#

ah right

#

im not gonna keep asking questions, but i got the gist of it, ty

pine yew
#

but anyways, the easiest way to serve HTTPS traffic (and thus get the "trusted" lock for your domain) is to subscribe to Let's Encrypt service which can auto-renew your certificates and hands them out for free @past cape

whole crow
#

@pine yew what is the right word to use instead of SSL?

lofty sentinel
#

Looking for a saas boilerplate with social logins, background tasks, great components, stripe etc. Can pay $$$ but like, saas forge demo doesn't even work lmao

#

I would appreciate a good BP

#

if have to, doesn't have to be python but would be great... Just not PHP.

tawny nest
#

This project got me a full time software job. Follow Along as I walk you through tricks I Used. This project got me a full time software job. youtu.be/UGsRT53hgqM
Follow Along as I walk you through tricks I Used. https://youtu.be/UGsRT53hgqM

#web-development

#Frontend #UiUx #SoftwareDevelpment #HTML #CSS #CrashCourse #responsive #websites

In this crash course, I will show as much about HTML as I can. This is meant for absolute beginners. If you are interested in learning HTML but know nothing, then you are in the right place. We will be creating a cheat sheet with all of the common HTML5 tags, attr...

▶ Play video
mystic wyvern
terse sorrel
#

hey i'm building a react django app and i wanna create an admin interface (a customized one)and idk how to proceed, how would you guys do it ?

zealous elk
#

I am not getting the desired output in this flask app I am working on. The details are in #help-coconut, please help me if you can.

wet hinge
#

Hi, is there an option to use django admin panel while having ONLY an in-memory database?

native tide
#

Does anyone know how to set var(--color) as game.color here?

{% for game in games %}
  <div class="col">
    <div class="card" style="background-color: var(--color);">
    // Code
    </div>
  </div>
{% endfor %}```
Usually Id use {{ game.color }} but it seems theres special rules when inside CSS
unique shore
wet hinge
native tide
#

Is it normal for image links to be over 12000 characters long? In a tutorial I was told to make the max length ~2000 but it seems like every time I copy an image link they just keep growing in size

gritty vapor
#

Can someone please suggest me some Flask projects. I'm a beginner in Flask. Thanks in advance 🙂🌟

inland oak
# past cape ah okay, thank you

Let's encrypt is a hard way
Just use Cloudflare, it has it as inbuilt feature to have verified certs
U need to have self signed certs active at your address though

zealous elk
#

How is it that websites have custom links for every profile? For example, if I visit someone's profile on IG or FB, they have custom links to their profile that is unique to them, how can I implement the same system into my own flask website?

zealous elk
gritty vapor
gritty vapor
wet hinge
#

not sure how new you are, you might start with a very, very basic CRUD, just to communicate with a database

#

and build more advanced ones later

#

to-do app could be the very very basic CRUD

#

just a simple list with buttons to add a task, edit a task, delete a task

#

no fancy stuff

#

no user login

#

then you can make one with user accounts, each user would have his own to-do list, @gritty vapor

vernal kindle
#

.code

#

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

gritty vapor
#

@zealous elk & @wet hinge thanks for the help and suggestions 🙇🙂🌟

sinful isle
#

hello guys i got issue in ''''''

#

'''py
class CreateItem(CreateView):
model = Item;
fields = ['item_name', 'item_desc', 'item_prce', 'item_image']
template_name = 'food/item-form.html'

def form_valid(self, form):
    form.instance.user_name = self.request.user --> i didn't understand this line of code
    
    
    return super().form_valid(form)

'''

fading herald
#

Heyy

native tide
#

hi

fading herald
#

Heyy

#

Can u help me

native tide
#

just ask, ill see if i can

fading herald
#

Ok

#

Dm?

native tide
#

perhaps? to your preferences

fading herald
#

Ok then dm

turbid furnace
#

I might actually cry...
Why is web app development so incredibly complex and hard...

proven hawk
#

Most people know how to solve something as they’ve seen the same/similar problem in past. Just takes time to build that xp.

ornate island
#

Hey folks, I'm looking for an old Python 2 project that I can run in a test environment to practice migration to Python 3. I'm working on a migration of a legacy app at work, and I want to try out some techniques I've learned recently. Anybody have any antiques they are willing to share?

candid meteor
#

what r some things i should remember before shutting down my website considering that i will later host it again in some time

#

digital ocean btw, i want to stop hosting and continue exactly where i left in a year or two

frank shoal
proven hawk
ornate island
jaunty sentinel
#

nice to meet you

#

how are you?

latent ginkgo
#

I dont know if this belongs here but I am creating a website using Flask and I am trying to make a login feature but It doesnt work can anyone help, ps if asked for I will send the full code, please @ me

frank shoal
#

Are you using flask-login?

wind dove
#

Quick question, is the built in hashing system for passwords in django a good up to date one? Or is it smart for me to implement a different algorithm?

pine yew
whole crow
deft osprey
#

I'm not sure if this is the right channel for this, but I was wondering if anyone knew of how to send emails through a gmail account since Google changed their policy on 5/30?

hollow dragon
#

can i learn in one day how to deploy a flask app to heroku with docker?

golden bone
hollow dragon
golden bone
deft osprey
#

Yea sorry that's exactly what I mean, on 5/30 Google decided they would no longer allow "less than secure apps" which smtplib falls under I guess

hollow dragon
#

damn tho, deploying can be so freaking complex

golden bone
deft osprey
inland oak
round shard
#

Hi. I have this section in my website where the user fills up some inputs. After the user fills all the data, there is a save button, how can I assign a python script to a button? I would like this python script to use a POST method to send the data the user filled in as a json. Anything you know like a video or doc that could help me? Or by any chance someone want's to help me 😄 Thanks in advance to you all 🙂

visual harness
#

help how do i make something move if i hover over another thing in css

vivid whale
#

Using Python Django and Github together for a personal website, is there a better way to update my github repo website without having to copy and repaste the code from my IDE to GitHub and see the changes in almost real time?

river ember
#

Hi, does anyone have experience sending data to a browser using flask?

hollow dragon
#

is it normal for docker build (container image) to take more than 10 minutes+?

quick cargo
#

that really depends on your build stage and app

hollow dragon
#

oi mates i just made my first docker container sheesh

quick cargo
#

pithink What

golden bone
golden bone
austere isle
#

how to fix this error , in the tutorial of cs50 the instructor didn't do anything on the file settings.py > templates and it worked for him but for me this error occured

novel stream
austere isle
austere isle
novel stream
austere isle
novel stream
# austere isle actually i am a beginner

what I think you're missing is to setup the DIRS key in your TEMPLATE. Could you show us how's your BASE_DIR being generated? It's in the same file and usually at the beginning of the settings.py

hollow dragon
#

im tryna run my docker container and this is what I get:

[2022-06-08 11:40:15 +0000] [9] [INFO] Worker exiting (pid: 9)
[2022-06-08 11:40:16 +0000] [7] [INFO] Shutting down: Master
[2022-06-08 11:40:16 +0000] [7] [INFO] Reason: Worker failed to boot.

#

i guess i have to change something in my procfile or gunicorn settings

novel stream
#

For things like that we would need to take a look at those files

austere isle
hollow dragon
#

maybe i should try to do it for heroku?

novel stream
novel stream
novel stream
#

for running locally your docker setup shouldn't depend on the procfile, which is a specific file for heroku

novel stream
# austere isle ok

OK so now try the following: in the TEMPLATES you will see a key called DIRS where its value for now is an empty list. Try putting there the following:

"DIRS": [BASE_DIR.join("templates")],
#

it will do so that Django will look for templates inside your apps

hollow dragon
#

its a flask app btw

novel stream
novel stream
#

I still have some time until start working 🙂

hollow dragon
novel stream
austere isle
novel stream
# austere isle \

I'm sorry, let's try this here instead: 'DIRS':[os.path.join(BASE_DIR,'templates')]

austere isle
novel stream
#

Nice!

hollow dragon
#

Hope it works 💀

novel stream
hollow dragon
#

Because of the WSL?

novel stream
#

but it seems to be a nice blogpost