#web-development

2 messages · Page 221 of 1

outer apex
#

You could use url_for

wheat verge
#

*args allows you to do is take in more arguments than the number of formal arguments that you previously defined

def myFun(*argv):
    for arg in argv:
        print (arg)

myFun('Hello', 'Welcome', 'to', 'Django')

output
Hello
Welcome
to
Django

mild vapor
#

print("django is cool")

honest wigeon
#
async def test(pep_):
    pep = f'{pep_:04}'
    ssl_context = create_default_context(cafile=where())
    conn = TCPConnector(ssl=ssl_context)
    
    async with ClientSession(connector=conn) as session:
        async with session.get(f'https://peps.python.org/pep-{pep}/') as response:
            soup = bs(await response.text(), 'lxml')
            even = [i.text for i in soup.find_all(class_='field-even')]
            odd = [i.text for i in soup.find_all(class_='field-odd')]
            
            even = dict(zip(even[::2], even[1::2]))
            odd = dict(zip(odd[::2], odd[1::2]))
            
            even.update(odd)
            return even

any speed improvements can be made here?

sharp gyro
#

Hey

compact glacier
#

Hey guys, I'm working on a web project based on python-django and trying to push it to heroku. but I get a rather strange error.

remote: -----> Building on the Heroku-20 stack
remote:  !     No default language could be detected for this app.```

when forcibly putting ```heroku buildpacks:set heroku/python```

it returns ```
 remote: -----> Building on the Heroku-20 stack
remote: -----> Using buildpack: heroku/python
remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz
remote:        More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure

but since I'm making a site according to the guide, it looks rather strange.

code source: https://github.com/KoTeD0/learning-log

if someone can help me with push and build on heroku i'll be very helpful

GitHub

Django from "Python Crash Course- A Hands-On, Project-Based Introduction to Programming" by Eric Matthes. - GitHub - KoTeD0/learning-log: Django from "Python Crash Course...

compact glacier
#

omg... just fixed my problem. i just fucked-up with name requirements.txt it was ```requirments.txt

covert yew
#

lol

ripe zenith
#

so i have this html with some variables on it, can i get it using bs4? I replaced the variables with #

<div class="gameTimes">
    <div class="localTimes">
        <p>Local Reset Time: #</p>
        <p>Time Until Reset: #</p>
    </div>
    <div class="serverTimes">
        <p>Server Reset Time: #</p>
        <p>Current Server Time: #</p>
    </div>
</div>
whole knoll
#

can css interrupt an image hyperlink?

#

for example, on hover css

turbid raven
#

hey guys, i am coding a small web server that can return different kickstart files according to the username passed. My current thing is, when i send something like http://ks.myserver.com/kickstart.ks?user=myname I get kickstart.ks?user=myname back as filename. which is not what i want. i just want a kickstart.ks file

#

i think this is called scrubbing?

#

i want to tell the client to save the file in the correct filename

#

or do something on the python server side to return the correct filename

high breach
#

Hi guys,
I have a flask app, so when I hit on routes which are not in the same file, it always throws 404 not found error:
Directory structure:

-> user
    -> __init__.py
    -> models.py
    -> routes.py
-> app.py

app.py:

from flask import Flask
app = Flask(__name__)

from user import routes

@app.route('/') # THIS ROUTE WORKS
def index():
  return '<h1>HOME</h1>'

if __name__ == '__main__':
    app.run(debug = True)

routes.py:

from app import app

@app.route('/register', methods=['GET']) # THIS DOESN'T WORK - 404 NOT FOUND ERROR
def register_user():
  return '<h1>Register a user!</h1>'
gray lance
#

so i'm guessing you're running only app.py, and so routes.py is never run, and thus that route is never registered

#

you need some way to make sure that routes.py is run as well; one way would be something like

-> main.py
-> app.py
-> user
    -> __init__.py
    -> models.py
    -> routes.py
```,  and the `main.py` would be something like
```py
import user.routes  # importing it runs the file and hence the routes there are registered
from app import app

app.run(debug=True)
``` and then run the main.py file instead
#

there are possibly other ways but i remember doing something like this once 😅

#

@high breach

high breach
gray lance
#

oh i just answered your question, figured i'd ping in case you'd miss it

high breach
#

@gray lance ?

gray lance
#

hm?

agile pier
#

how do I remove the first div of the parent div with id='myTable11_wrapper'?

visual lily
#

Sorry for the off-topic question, but perhaps someone knows. How can I deploy a FastAPI application on IPFS hosting like Pinata or other? Are there any instructions?

#

I need to process requests like this one : domain.eth/request

native tide
#

how can i use text-align: center; on <a> tag i've tried css display: inline-block; text-decoration: none; color: black; text-align: center;

glacial zodiac
#

change display to block

native tide
glacial zodiac
# agile pier pls help
<script>
        const parent = document.getElementById('myTable11_wrapper')
        parent.children[0].remove()
</script>
agile pier
#

i m using d3 svg map and i have 2 data, one for map, and another my custom data to plot the data points on the map

#

this is the map data const mapDataUrl = 'https://d3js.org/world-50m.v1.json'

#

i want to colour the country which has the data point in my custom data

#

this is the sample of my custom data to plot the data points, like here the country is US, so i want to fill some colour to US

#

pls help me do this

#
// load map data
d3.json(mapDataUrl, mapData => {
  const countries = topojson.feature(mapData, mapData.objects.countries).features

  g.selectAll('.country')
    .data(countries)
    .enter().append('path')
    .attr('class', 'country')
    .attr('d', path)
    .on('mouseover', function (d) {
      d3.select(this).classed('hovered', true)
    })
    .on('mouseout', function (d) {
      d3.select(this).classed('hovered', false)
    })
    .on('click', clicked)

  // load ip data
  d3.json(dataUrl, data => {
    const colorScale = d3.scaleOrdinal(d3.schemeBlues[2000]);

    g.selectAll('.meteor')
      .data(data.features)
      .enter().append('circle')
      .attr('class', 'meteor')
      .attr('r', d => calcRad(20000))
      .attr('fill', d => 'blue')
      .attr('cx', d => projection([d.properties.loc.split(', ')[1], d.properties.loc.split(', ')[0]])[0])
      .attr('cy', d => projection([d.properties.loc.split(', ')[1], d.properties.loc.split(', ')[0]])[1])
      .on('mouseover', handleMouseOver)
      .on('mouseout', handleMouseOut)
  })
})
lone hedge
#

question on Flask \w Jinja templates, is it possible to pass a function to a view as a variable and reference that python function in an onclick property for some button in the view? looking for the best way to do this if possible

outer apex
lone hedge
proper hinge
#

The browser cannot run Python code directly. If the click handler needs to modify something on the client side, then you're going to have to write it in JS.

#

You can trigger a function to run in your Python backend if you set up a way to communicate between the client and server (e.g. an API)

lone hedge
#

yep, have an api

proper hinge
#

Then you need to write JS code that will make a request to your API

lone hedge
#

got you 😦

faint ferry
#

how can i make a dashbord for my discord bot

unique shore
#

use a framework and interact with your bot through an API

native tide
#

What's the best way to return an image to the user from an external url such as ibb.co in a way such that it acts like it is a local image?

#

Im wanting to replace a send_from_directory return to get an external image and return it in the same way

#

flask btw

#

i figured out a work around, but this would be nice to know for future projects if anyone knows ^^

dull frigate
#

Hi

#

What framework(s)/setup/configuration do you recommend for a project that is asynchronously and constantly reading live data, processing it and then showing it in a website? At the moment, I'm using asyncio loop that runs forever that feeds an object and asyncronously detects changes in a "communication object" and send those changes through a websocket. But I feel it is very clunky, a lot of global variables, while True loops, etc

#

How would you "structure it"

inland oak
dull frigate
#

together or one or the other?

#

very new to this kind of development

inland oak
dull frigate
#

looking for orientation here

#

these support live 2way communication?

inland oak
#

Dunno. Never worked with web sockets.
I only know that Django channels allows to work with web sockets and had as a example how to make a chat

#

Django is pretty structurized out of the box

#

If u look for some enforced structure

#

FastAPI as far as I know, best async framework

#

So could be nice choice too

#

I dealt only with django before though

dull frigate
#

thanks

sacred crane
#

hey i was Unable to set default value while using useState in react. I am working on a project where i give the input number in the input box and it returns the graph contains the same number of data samples for that i am using splice to list the desired number of samples from the data list. But when i give 5 i am getting 4 i dont the reason.

scenic dove
#

Hello
is it possible to be a web dev without learning JS ?

#

im learning django rn

small coral
scenic dove
#

React uses only JS ?

#

i mean its main language like with python and django?

inland oak
#

At least basics of it

#

Ideally yeah, js is used to make properly frontend in react/Vue.js

#

Then the person becomes backend person that can pretend to know some frontend

#

And yes, js is the main language of Frontend languages

#

There are no alternatives

#

Only things like typescript, which is just mypy'ed(static typed) extension of javascript

#

If u make some normal pages in python backend, u still need to use sometimes js as addition

#

But usage of vanilla js is a great perversion and ugliness

#

If u need js in python backend, better to make static linking to vue.js, to use it for much easier js syntax.
It is possible to use vue.js inside of any backend framework

#

Ideally frontend is made separately though

#

Because then person has full access to all things with js npm package manager

willow sundial
#

Guys I need urgent small project
For web development using css html bootstrap java script, and my sql

chrome belfry
#

how to force a redraw of the browser content in brython (js)?

full crane
#

im gonna do it

velvet gazelle
#

Omg-

full crane
velvet gazelle
#

Damn xD

#

Look nice 👀

#

For a domain name I mean x)

full crane
#

or like

#

{urname}.py

#

its paraguay managed domains tho so its cheap, but id guess their servers are asscheeks

velvet gazelle
#

Probably, but how chep? It's 170€ as I can see

full crane
velvet gazelle
#

Damn-

full crane
#

big yikes

velvet gazelle
#

Wrong site for me then xD

full crane
#

yeah right

#

probably the name tho

#

main is literally taken for everything but .store and .tech

velvet gazelle
#

Hmmm

#

Who would use this name tho?

full crane
#

i mean

#

i have a friend that literally has his whole career branded as {hisname}.py

full crane
delicate ore
#

it does look pretty well made for it's time

#

They even have animations

wide pulsar
#

but still it's nice

lusty smelt
#

Hey everyone! I've got a help channel open but it was suggested I post here as well. I've got a pretty specific question I'm hoping for some guidance on.

#

I have a Flask application that uses HMAC headers for authorization. I have all the documentation for how to properly format your headers and I need to insert the info into an API page.

#

So I need to make a custom security scheme for my HMAC authorization. I am having trouble finding a good example to follow.

#

It appears Redocly doesn't support HMAC headers out of the box. Like it does for OAuth1.0 and others

#

I'm over in #help-chili if anyone has some assistance for me

pearl vigil
#

Anyone used Django-Signature before?

#

having trouble getting it working

mild vapor
#

i am having trouble with authentication

pearl vigil
#

Anything?

wide pulsar
pearl vigil
#

looking to get signatures on django forms

ember adder
#

In Django I have a form with a ModelChoiceField which queryset can have 1k+ entries. That would be pretty heavy performance side and I want to avoid the user to scroll a huge list. What are good alternatives?

gleaming kernel
#

Im setting up a tiny form but I cant get the "submitted" part to stay on the screen before it reloads

#

can I set up a timer?

#

or stop the page from reloading?

jade minnow
gleaming kernel
#

ill try that

agile pier
#

as it is advised to change the secret key in django settings.py
so while changing the security key, do I need to make some other changes also somewhere?

native tide
#

It's just a key that is used in the some of the security features that if a malicious person knew it, they could invalidate the built in CSRF protection and stuff like that

#

if you're talking about preparing a production server, there is a lot of things to go over to really be ready to do that.

#

i just generate one with import secrets;secrets.token_hex(32) and stick it in there.

agile pier
agile pier
native tide
#

well, they are a great deal of things that you really will have to read about extensively because those things you mentioned are just getting started.

as for the key, no. You just change it and it automatically does its job as long as no one knows what it is and its sufficiently unguessable.

If you're not pushing to production or anything dont worry too much yet but eventually digital ocean has good guides

https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04
https://www.digitalocean.com/community/tutorials/how-to-harden-your-production-django-project
there's tons of them

agile pier
native tide
#

thee thing to remember is dont take production lightly. There isnt a checklist to be secure. You make mistakes and its not secure. so you have to know all the things that can happen and stay read up on all of it. As long as you knw that going in, and dont think it's magic and safe, you'll learn it as you go

native tide
#

it helps imo when you start playing with having you own test production server to dabble a bit into penetrating testing on it. You dont have to go all in on the career of professional pen testing for clients. Just... try to break your own server.

#

and look up how to do it

#

common misconfigs etc

#

but run your test server pretending its a real production server and having it set up exactly like one.

austere acorn
#

If an API uses cursors to paginate its results, how am I supposed to send concurrent requests to fetch multiple pages ? Because in cursors each page depends on the previous one

unkempt haven
#

Hi everyone its my first time scripting a website and i need help

#

I run my code and it gives me a link to open it (im using flask)

#

but i keep on getting problem

austere acorn
#

Also did you write any view ?

formal gull
#

how would i go about determining if my sqlite database has been updated and send that to my websocket i have working now in django?

#

i've read some about redis, but im not sure as most things using websockets are just chat apps and im not sure of what is exactly what i am looking for

austere acorn
formal gull
#

from just skimming does this sound about right, when someone else submits something/updates something i attach a signal to that to tell the websocket to update?

austere acorn
#

Yeah exactly

#

I am sure there are ways to subscribe to events from the db itself but I don't know much about that, I think for what u need this should suffice

formal gull
#

i could of swore i read something about subscribing to db events, but i dont see why signals wouldn't work in my case for the amount of users ill have

#

thanks!

dim smelt
#

hi

#

how can I add HTML and CSS and JavaScript into flask web?

#

I mean whole file of HTML

native tide
#

learn how to pass a jinja2 template to the view. Then in the template, you would load in the javascript somewhere.

#

and css

#

a template is just an html file with special syntax to conditionally load the html and other types of normally static content

lost snow
#

hey guys
I am a beginner web dev
I am interested in learning more about web security and how to become the guy who protects websites from being hacked....
I have been browsing about it but can't find anything useful related to it
I want to know how to become one...
so, If anyone knows anything about this please share....

small coral
mint folio
#

There is obviously more, but the ones listed above as well as the comment above about server security should be enough for the basics.

wooden hemlock
#

Does anyone know if there's a decent way to use flask_login and firebase? I've found documentation from a couple of years ago but I think it's deprecated by now. There's not really anything else that's clear on using the two now.

covert seal
#

hi

dusk portal
#

im getting a error while submitting the form

#
Direct assignment to the forward side of a many-to-many set is prohibited```
#

but working fine via admin panel

#
class Product(models.Model):
    title=models.CharField(max_length=50)
    price=models.IntegerField(default=0)
    pic=models.ImageField(default='default.jpg',upload_to='images')
    published_by=models.ManyToManyField(User)
    desc=models.TextField()
    published_date=models.DateTimeField(auto_now_add=True)
    slug=models.SlugField(max_length=35)

    def __str__(self):
        return self.title```
#
@login_required
def seller(request):
    if request.method=='POST':
        title=request.POST.get('title')
        price=request.POST.get('price')
        pic=request.POST.get('pic')
        published_by=request.user
        desc=request.POST.get('desc')
        slug=request.POST.get('slug')
        if Product.objects.filter(title=title).exists():
            return messages.warning(request,'TITLE ALREADY EXISTS')
        if Product.objects.filter(slug=slug).exists():
            return messages.warning(request,'ENDPOINT ALREADY TAKEN')
        added=Product(title=title,price=price,pic=pic,published_by=published_by,desc=desc,slug=slug)
        added.save()
        messages.success(request,'Product added')
        return HttpResponseRedirect(reverse('index:home'))
    return render(request,'index/sell_product.html')```
serene depot
#

I want to make library management system with crud operation in django ? Please can tell how to do that?

dusk portal
#

first make models

#

for that imagine all the functionality of the web-app u're gonna make

serene depot
#

I want it create
Add a book
Update entry book
Delete a book
Get all books

serene depot
dusk portal
#

yeah!

#

class Books()
#fields here u want

#

n if want any class to be on child/connected/linked
use can create below n use rdbsm

kindred carbon
#

What is the easiest way of making async calls in django
With ajax or there is a native way in django
I have to make loading screen

jade minnow
inland oak
#

If u wish more Frontend, use frontend Frameworks.
Or at least make static linking of frontend Frameworks like vue.js into Django to enable it from inside

inland oak
kindred carbon
#

Yes I have done it in react but not in any django only site
Thanks for the help 👍👍

inland oak
#

Continue using react. Use Django as rest API to react ;)

jade minnow
#
counter {
  transition: --num 1s;
  counter-reset: num var(--num);
}
counter:hover {
  --num: 31;
}
counter::after {
  content: counter(num);
}

how can i make this count up without needing to hover over top of it? Like can i edit this with js? without needing the hover?

inland oak
#

On page load?

jade minnow
#

i tried using settimeout and making the hover a counter.animation {}

#

but it didnt seem to work and my js is lacking

inland oak
#

Turn hover into class

#

And add it when to start

jade minnow
#

i did that using ```js
setTimeout(() => {
document.getElementById('counter').classList.toggle('anim'); }, 2000);

#

it didnt seem to work

#

my js is bad dont bully me

torn timber
#

It's set interval btw

inland oak
jade minnow
#

oh.

inland oak
#

Frontend frameworks for the win

jade minnow
#

well i started using a different script

#
$('.counter').each(function() {
          var $this = $(this),
              countTo = $this.attr('data-count');
         
          $({ countNum: $this.text()}).animate({
            countNum: countTo
          },
        
          {
            duration: 7555,
            easing:'linear',
            step: function() {
              $this.text(Math.floor(this.countNum));
            },
            complete: function() {
              $this.text(this.countNum);
              //alert('finished');
            }
          });  
         
        });

css:

.counter {
  display: table-cell;
  margin:1.5%;
  font-size:50px;
  background-color: #0077B6;
  width:200px;
  border-radius: 50%;
  height:200px;
  vertical-align: middle;
}

html

<div class="counter" data-count="31">0</div>

output:

inland oak
# jade minnow oh.

Check svelte out of curiosity.
Although I would usually recommend only react or Vue. Js

jade minnow
#

the circle im def gonna format to the middle

inland oak
jade minnow
#

might get rid of the text

jade minnow
#

it just feels better personally

inland oak
jade minnow
#

thats why

inland oak
#

Frontend frameworks much better

jade minnow
#

omg im so dumb

#

if this works

#

im sorry

#

but like

#

nvm

#

didnt work

#

anyways

#
<h3>Now in <div class="counter" data-count="31">0</div> servers!</h3>
    <script>
      $('.counter').each(function() {
          var $this = $(this),
              countTo = $this.attr('data-count');
         
          $({ countNum: $this.text()}).animate({
            countNum: countTo
          },
        
          {
            duration: 7555,
            easing:'linear',
            step: function() {
              $this.text(Math.floor(this.countNum));
            },
            complete: function() {
              $this.text(this.countNum);
              //alert('finished');
            }
          });  
         
        });
    </script>

didnt seem to work

#

i did alot more than i needed

#
const box = document.getElementById('count-up')

let count = 0

const countUp = setInterval(() => {
  let boxCount = box.dataset.count
  if(count == boxCount) clearInterval(countUp)
  box.innerHTML = count + box.dataset.unit
  count = count + Math.floor((boxCount/31))
  if(count > boxCount) count = boxCount
}, 20)

css:

* {
  margin: 0;
  padding: 0;
}

html, body {
  width: 100%;
  height: 100%;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #1E1F26;
}

#count-up {
  font-size: 2em;
  color: lightblue;
  font-family: Verdana;
  font-weight: bold;
  letter-spacing: 4px;
}

html:

<div id="count-up" data-count="31" data-unit=" servers"></div>
#

i hate my life

#

ended up creating a settimeout so i could activate it after the splash is finished

hidden kettle
#

Hey folks

#

What approach do you use to integrate react and Django together?

  1. Build a standalone react app and host it separately
  2. Serve react app from Django.
    Please share your insights and why do you prefer your approach.
inland oak
#

Better scalability with code growth

#

Using methods less than that makes sense only in some pervert situations with really silly restrictions

hidden kettle
inland oak
#

Already with docker compose it should not be an issue

hidden kettle
#

@inland oak And what mechanism do you use to build real time apps with django? Channels or some third party services like Pusher

inland oak
#

And because people don't know Auth methods

inland oak
hidden kettle
#

How is this related to authentication? Can you please explain this to me

frank shoal
#

I serve vue with nginx

hidden kettle
frank shoal
#

I specifically use nginx-unit because it can run my asgi app too

hidden kettle
#

For backend- Django I deploy it with containers on Google Cloud. I also use app engine

jade minnow
#

i have some questions about this:

should i have the text inside?
should i use just the number itself?
if i do; would people notice its the amount of servers and users with the icons i have in place?
should i use a gradient? or have a still color?
should i use animations on them? or just the static images itself?

#

i get alot of hate because of how this looks and im now finally going to change it. i dont want it to look like complete shit

inland oak
inland oak
# hidden kettle How is this related to authentication? Can you please explain this to me

There are different ways to Auth users in order to keep them authed. In built Django methods for frontend Frameworks we can probably find in DRF.

The point is... With microservices architecture, we have multiple backends, and we Auth only in one from frontend, and to be not validating in one database?. How do we achieve it? How to create tokens for temporal URLs of email verifications and password resets, which we could create in backend, and accept in frontend?

The answer to everything is JWT.
Which is the way to keep a dictionary of key values with user info and rights, validated by your secret key.

#

People at the beginning not really familiar with Auth stuff to use microservices freely

#

With one just Django they could use inbuilt methods with minimal understanding how it works pithink

lapis sierra
#

is there anyone to help me

steady kelp
#

whats the different between css and scss

frank shoal
#

scss is css with sass

#

scss supports pre processors and nested rules

#

You can also get variables via ```scss
$red: #FF0000;
body {
color: $red;
}

jaunty magnet
#

Do I have to manually set a httponly cookie? I'm getting it in the login POST response, but then when my flask backend tries to access it on another request, I get no access_token cookie response message

quaint wagon
#

ping me if you know, but whats the advantage of using python over html for web dev?

ember adder
#

Django-rest-framework: If I put the token authentication class in the class list settings in config, Token Authentication does not work. It only works if I put the class in the view class variable

# does not work
# myproject.config.settings.base
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ]
}

# works
# myproject.views
class MyListApiView(generics.ListAPIView):
    authentication_classes = [authentication.TokenAuthentication]
    serializer_class = serializers.MySerializer

I really don't understand why TokenAuthentication class specified in the settings won't work, but if provided in my view it will. SessionAuthentication works fine and it's specified in settings....

molten ember
#

can i get help with hugo here?

bronze palm
#

i might be mistaken but isn't hugo writen in go?

molten ember
bronze palm
#

thats just markdown its a fancy text file

quasi olive
#

anyone that can help me with js?

frank shoal
quasi olive
# frank shoal ask away

im tryna make a small zombie game where some zombies chase after 2 players, but i can only get it to only go after one or have it so that one of the players control X axel and the other one Y

                 if (zombie.x < player1X) {
                     zombie.x += zombie.speed;
                    }
                 else { zombie.x -= zombie.speed;}
         
                 if (zombie.y < player1Y)
                     zombie.y += zombie.speed;
                     
                 else { zombie.y -= zombie.speed;}
                 ```
this what i use, you know how to fix it?

tested adding the same script twice but change the variables for the other but it wouldn't work
frank shoal
#

uh oh, logic errors

quasi olive
#

you know how to fix it?

frank shoal
#

nope.

quasi olive
#

ok, thx anyway

frank shoal
#

My suggestion

quasi olive
#

fair

frank shoal
#

that's also my typical debugging strategy

native tide
#

hello if anyone knows selenium and they are free can you dm me plz

hidden kettle
#

Has anyone integrated django channels and react together?

#

Can anyone share link to such projects?

inland oak
#

it looks like not a hard problem to rewrite from vanilla js to react

hidden kettle
#

Thanks ..

thin minnow
#

I am formatting a book in a HTML file and I only want it to be in a single HTML file. I was wondering how I could make the table of contents clickable so that I can click a part and it will scroll to that part

wooden ruin
thin minnow
#

Thank you so much! It worked as I wanted it too

#

Is there a way I can make it so the text isn't blue though?

#

I found out how

stable bear
#

How do you send a post request after a button click or after any other action except sending input to a form?

stable bear
#

using django/flask/python/javascript/html/css as this is a python server

quiet river
#

Or something

#

Ah

#

Html

#

<a href

#

Or javascript on click

#

Html for ur example is easier

stable bear
#

but what about if you want to click a button to search a database and then outputs a result?

quiet river
#

Php

#

Thats the only thing i know

#

Idk about flask but for that i use php

#

Common use for that

#

Just search on google lmfao

outer apex
# stable bear How do you send a post request after a button click or after any other action ex...

Check out events and how to add event listeners. If you're in a form, you can catch the submit event. If it's a button, you can catch the click.
Here's some docs for the click event:
https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event

Check out Fetch API for sending requests and handling the response
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Hopefully with these two resources you can string them together to do most of what you're asking about..

stable bear
#

thanks! is it also possible for a button to make a form with no inputs and just a submit button, and send a post request in that way?

serene depot
#

Hi please

#

I want to No column want increment

outer apex
serene depot
outer apex
serene depot
#

It's working 🎉

inland oak
#

https://www.synopsys.com/glossary/what-is-owasp-top-10.html start from OWASP 10 and go further
The worst security paranoia is intended for any web sites that deal with user payments
and even 10 times worse security paranoia for web sites which KEEP user data for payments
and even Worse than that, if the web site have a really big amount of transactions
In order to pass those security measures, the person is required to go through PCI DSS complaince https://stripe.com/guides/pci-compliance here you can find documents regarding that

As far as I remember electronic commerce web sites which do not store user data, need to pass only lightweight 80 pages PCI compaince version
And those who keep user payment data, there should be document for 300-600 or more pages

The OWASP Top 10 is an awareness document for Web application security. The list represents a consensus among leading security experts regarding the greatest software risks for Web applications. Find out at Synopsys.com.

Here’s a step by step guide to maintaining compliance, and how Stripe can help.

#

Found

#

Lightweight PCI DSS compaince is SAQ A-EP category

#
A-EP    
E-commerce merchants who outsource all payment processing to PCI DSS validated third parties, and who have a website(s) that doesn’t directly receive cardholder data but that can impact the security of the payment transaction. No electronic storage, processing, or transmission of cardholder data on merchant’s systems or premises.

Applicable only to e-commerce channels.
#

Here is the lightweight, 55 pages security check for the situation A-EP above

#

Security is a thing going all over the architecture of the web sites, in frontend, backend, infrastructure. PCI DSS Compaince summarized all the weak spots the organization should check and security measures to implement for any type of product

#

Security can be in your code, to fix all the default settings
Security can be different ways you implement encryption / storage of user data at server and client side
Security can be using Vault secret storages
Security can be in setting up permission managing system for your system admins
Security can be tools that make automatic checks for the password leaks to to git or docker images

#

Multiple was, PCI DSS complaince tells you that

#

Lets say, there is a reason why big corps have Security departments and even DevSecOps profession was born 😉

#

Yes. compiling to PCI DSS compaince is part of Stripe 😉 They help to guide to to make the ride as smooth as it is possible

#

I discovered about PCI DSS complaince because I tried to add Stripe in the past

#

it should be the easiest possible way to get Stripe and being security complaint, just 55 pages

#

as long as u make sure

A-EP
E-commerce merchants who outsource all payment processing to PCI DSS validated third parties, and who have a website(s) that doesn’t directly receive cardholder data but that can impact the security of the payment transaction. No electronic storage, processing, or transmission of cardholder data on merchant’s systems or premises.

Applicable only to e-commerce channels.

inland oak
#

¯_(ツ)_/¯

native tide
#

help mee plz the content comes up i import the navbar by include django

graceful flax
#

Hi, I needed some help with datetimefield serializer

native tide
next turret
#

using selenium webdriver, how do i tab between buttons? not the tabs, but the tab button
because if you press tab, you cycle through pressable UI stuff, even on discord
i want to do that in selenium, but to any (clickable) element i want
this means no pyautogui or keyboard simulating

#

ping me pls

sweet delta
#

Anyone got an example of a django login/sign up split page ?

surreal shuttle
#

Guys, I have a question. If user request page that consists only from empty form that I think can be done on front. Should I send any data with DRF views or process GET request? Thank you in advance

still verge
#

oi is any1 here free to hold my hand a bit? i got thrown into a html class and im kinda lost

feral spindle
next turret
#

wdym?

#

what does that have to do with what my question?

feral spindle
#

There is a little I’m not a robot thing, just letting you know before your hopes get high, also I believe that there is suck a way to simulate key presses, look in documentation, I used it once

#

Such*

next turret
#

bro

#

i told you i want to "tab" with selenium

#

like select what (clickable) element i want

feral spindle
#

Did you want to select an element or press tab

next turret
#

select an element

#

which is basically what tab does when you press it

#

but when you press tab it won't select whatever element you want

feral spindle
#

getelementbid or something

#

byid*

next turret
#

and how do i select it

feral spindle
#

focus or click probably

next turret
#

ok

#

but help me for this:

feral spindle
#

You should really read the documentation

next turret
#

i need to do this for video thumbnails

#

how do i do it?

feral spindle
#

Documentation explains how to select stuff, Reading it for selenium is especially important because it’s designed for this stuff and tells you about it

next turret
#

show me where it says how to select stuff

next turret
feral spindle
#

Google selenium select elements

next turret
#

bro

#

that's basically "do it urself"

#

which is bs

#

because that is why i am seeking help

#

to get help not be told "do it yourself"

#

if you have an open page of the docs, then give me that page

next turret
next turret
#

doesn't say how to focus

feral spindle
#

There are also search bars for this on the documentation

frank rampart
#

im following tech with tims tutorial on flask and im getting this error
sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Note.notes - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.
the line of code it says is wrong is the following
new_user = User(email=email, first_name=first_name, password=generate_password_hash(password1, method='sha256'))
if you need the full script i can send it to you

covert yew
#

can I see the class of User

frank rampart
#
  id = db.Column(db.Integer, primary_key=True)
  email = db.Column(db.String(150), unique=True)
  password = db.Column(db.String(150))
  first_name = db.Column(db.String(150)) ```
covert yew
#

whats the note model

#

can I see that?

frank rampart
#

sure

#
  id = db.Column(db.Integer, primary_key=True)
  data = db.Column(db.String(10000))
  date = db.Column(db.DateTime(timezone=True), default=func.now())
  user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
  notes = db.relationship('Note')
covert yew
#

move the notes in the Note model to the User model

frank rampart
#

the notes variable to the user or the entire thing?

covert yew
#

Like this

class User(db.Model, UserMixin):
  id = db.Column(db.Integer, primary_key=True)
  email = db.Column(db.String(150), unique=True)
  password = db.Column(db.String(150))
  first_name = db.Column(db.String(150)) 
  notes = db.relationship('Note')

class Note(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  data = db.Column(db.String(10000))
  date = db.Column(db.DateTime(timezone=True), default=func.now())
  user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
#

works?

frank rampart
#

im not getting the error anymore but im running into a different problem

covert yew
#

whats that

frank rampart
#

so i get a POST request in my terminal when i submit the sign up but it isnt redirecting to the home page like i want it to. else: new_user = User(email=email, first_name=first_name, password=generate_password_hash(password1, method='sha256')) db.session.add(new_user) db.session.commit() flash("account created!", category="Success") return redirect(url_for('views.home'))
but when i click it twice to see if that works it sends me this error. sqlalchemy.exc.IntegrityError

covert yew
#

Send the whole error message

frank rampart
#
[SQL: INSERT INTO user (email, password, first_name) VALUES (?, ?, ?)]
[parameters: ('jim@tim.net', 'sha256$P71mjW74TbTnzQXT$bb2c0dc2a7b50933f7a1ab3a6450e85e7863a4c4c261be536d1fc68a68b2d7f0', 'jack')]
(Background on this error at: https://sqlalche.me/e/14/gkpj)

wheat verge
#

I try to migrate this but i get one error,even after deleting the whole salary field i get the same error

covert yew
#

If u have debug on

frank rampart
#

that is the error on the website

covert yew
frank rampart
#
def sign_up():
    if request.method == 'POST':
      email = request.form.get('email')
      first_name = request.form.get('firstName')
      password1 = request.form.get('password1')
      password2 = request.form.get('password2')

      if len(email) < 4:
        flash('Email must be greater than 3 characters!', category='error')
      elif len(first_name) < 2:
        flash('First name must be greater than 2 characters!', category='error')
        
      elif password1 != password2:
        flash("passwords dont match", category='error')
        
      elif len(password1) < 7:
        flash('password must be at least 7 characters', category='error')
        
      else:
        new_user = User(email=email, first_name=first_name, password=generate_password_hash(password1, method='sha256'))
        db.session.add(new_user)
        db.session.commit()
        flash("account created!", category="Success")
        return redirect(url_for('views.home'))
        
      
    return render_template("sign_up.html", user="current_user")


covert yew
#

can you send a screenshot on what is says in the website

frank rampart
#

wait its working now

#

so i guess since im using repl.it, if you try it in the preview window it doesnt work. But if you open your website in a new tab it does work

#

thank you so much for your help

covert yew
#

np

frank rampart
#

python communities are so much nicer than javascript communities

frank shoal
#

javascript community:
is trusted maintainer of widely used library
Uses it as a protest platform

hidden dragon
#

I'm looking for a hobby project to work on. If you are working on something and you need help please let me know and I'll be happy to help you if it interests me.

agile pier
limpid hull
#

please suggest me some of the django projects videos/tuts for practice ..

swift elm
native tide
#

yo guys, whats good to start with for learning web dev, js or html and css?

wheat verge
agile pier
brave tulip
#

how do i add a loading animation with flask ?

molten ember
#

can anyone help me with a question i have on hugo the website builder

sturdy idol
#

I’m new to flask and have been looking into creating my first login page. Most of the documentation that I have read uses a database to pull username and password then verifies it. I was wanting my program to login by confirming the username and password with an external API, so when the login form is submitted, an API get request is made on an external server, if you get status 200 then login if 401 then credentials failed. Is this something that’s possible?

frank shoal
#

You'll want to look into oauth

#

!pypi flask-oauth

lavish prismBOT
frank shoal
#

!pypi authlib this is also an option. it supports many backends

lavish prismBOT
#

The ultimate Python library in building OAuth and OpenID Connect servers and clients.

proper hinge
#

In Django, is it possible to update a relationship "backwards"? For example, model.objects.update(x=[1, 2, 3]) where x is the related_name of a foreign on some other model.

#

I know it is possible with .set(), .add(), or .remove() if I have a specific instance of the model. But I want to do it in bulk like shown above.

#

By the way I tried it with that exact syntax and I get the cryptic AttributeError: 'ManyToOneRel' object has no attribute 'get_db_prep_save' which comes from some Django internal stuff but ultimately originates from that update() call.

fair agate
indigo kettle
#

but I think it's still possible to do in bulk

proper hinge
#

I thought I already gave an example but I can elaborate. I have two tables, A and B. Table A has a FK to B, and its related_name="x". Thus, B.x exists.

Let's say I have a three rows in A with IDs 1, 2, and 3, respectively. I want to make all three rows relate to the same B. I want to be able to do something like B.objects.filter(pk=1).update(x=[1, 2, 3])

indigo kettle
#

yes sorry, it just still wasn't clear to me.
So instead you should get the queryset for the A model and I think you can update the foreignkey in bulk

#

A.objects.filter(id__in=[1, 2, 3]).update(b=B.objects.get(pk=1))

proper hinge
#

Thanks. For some reason I was imagining it to be more complicated to do in the other direction but that's not bad at all.

indigo kettle
#

np

#

A.objects.filter(id__in=[1, 2, 3]).update(b=1)
I think it's valid to just give the pk of the foreign key

untold scroll
#

I'm trying to execute a .py I created inside a django app, but it keeps giving me this error everytime I try to import a model from models.py:

django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

I wanted to dump some scrape into the database, and the scrape.py (file I'm trying to execute) works completely fine until I import the BlogPost model, which comes from model.py

The app is already added to the "INSTALLED_APPS" area, that's why I'm not understanding why it's saying it's not configured. I did run migrations already.

indigo kettle
#

some set up happens when you start up a server or get into the django shell that doesn't happen if you just try to run a script directly that tries to utilize django's models

#

you'll want to run that script inside of the django shell or maybe it's possible to do what they're saying and run settings.configure() at the beginning of your script after importing from django.conf import settings

#

if it's just a one time thing, I'd just do the 3rd option

#

if you'll use this over and over again, I think making a management command is good
Then you can call it easily like python manage.py mycommand

#

@untold scroll

untold scroll
#

thanks a lot @indigo kettle I'll try it now

indigo kettle
proper hinge
#

I'm trying to apply this constraint in Django, which is supposed to disallow a null sensor_id if the type is NOT "man"

models.CheckConstraint(
    name="auto_sensor_not_null",
    check=~models.Q(type="man") & models.Q(sensor_id__isnull=False),
),

However, the migration fails with an error stating that some row violates this constraint.

When I print the rows of the table, there is only one row that has a null sensor_id, but that is the one case where it acceptable since the row has "man" as the type.

1 param1 None man
2 param2 0 auto
3 param3 1 semi

What am I missing? Did I write the condition incorrectly?

#

Ah yeah I forgot something. It's failing because the type is manual. I need an | models.Q(type="man") to allow it

#

But then it just simplifies to models.Q(type="man") | models.Q(sensor_id__isnull=False)

#

So yeah, problem solved.

muted ether
#

Hey guys, this is probably a more opinion-based question rather than one with a definite answer, which is why I'm posting here. I currently have a Django app set up so that it auto-generates a secret key, and writes it into its settings directory when it doesn't detect a key file. Are there any major security implications I should be worried about, or is this approach solid?

shadow salmon
inland oak
#

You need to keep the same secret key
In order to have users auths kept valid

#

Depending on where is it used, their passwords hashes can depend on it

inland oak
#

It is not great. Better to keep it as stateless as possible

#

While moving all persistent data to dbs

#

It is more... Cool for future infrastructure development

#

More room for flexibility with it

#

Like deploying in AWS your app as container application directly

#

Secret keys should be injected as env variables

shadow salmon
#

Well he said it only occurs when it doesn't detect a key file. So it's just a one time thing. It would be the same as going into your python REPL, generating the key, and pasting it into your .env file once.

#

So it should be fine if that's what he meant.

indigo kettle
#

if you deploy an app with this strategy I assume the key will get overwritten on deploy because the secret key shouldn't be stored in the repo. I supposed it could be, assuming that the repo is private but then why would you generate a key at all, just hardcode it

inland oak
#

plus defaults should be treated carefully. And in my opinion, secret key is the thing you don't want to fall back to random default, better to get an error if the env is not provided

shadow salmon
#

Yeah, absolutely that's all true. Wasn't thinking about that since all he asked about was security implications.

muted ether
glass island
#

what's a good way of versioning?

#

I want to do url path versioning

#

isn't making another app better then just point the url to that?

#

django btw

white owl
#

does anyone know how to get the image metadata uploaded UploadFile method of fastapi? as per docs, it only declared filename and filetype, but i need specific metadata like image dimension and dpi

serene depot
#

Hello i getting error in template of html
NoReverseMatch at /
Reverse for 'edit-book' with arguments '(1,)' not found. 1 pattern(s) tried: ['edit/\Z']

ocean slate
#

Hello everyone.

#

I want to make a website where I can write code and execute or run the same code and it gives the output. Basically the problem is that I want an online code editor or compiler which supports multiple languages, how can I do this?

jade minnow
ocean slate
jade minnow
#

right

ocean slate
jade minnow
#

i have no idea

#

you probably need to setup like

#

virtual envs

#

and storage, vcpus, vram, etc

ocean slate
bright spindle
#

does webhooks ever return error codes

#

and is there any standard to it

unique shore
#

I mean if the content isn’t found, can’t be retrieved, can’t be parsed there would be an error

bright spindle
unique shore
feral spindle
#

I 100% reccomend replit

ocean slate
bright spindle
#

budget ide

#

nah jk, web-based ide

feral spindle
#

It’s easy to install stuff, run discord bots, websites, tkinkinter etc

bright spindle
#

doe it's superseeded by pycharm, better than vsc(web version)

unique shore
#

Don’t use it. Check out VSCode

feral spindle
#

If you want free and online I recommend

ocean slate
#

yes I want free

unique shore
feral spindle
#

The ide got a theme update which I hate but hey it’s great for free

ocean slate
#

it supports all langguaes?

unique shore
#

VSCode supports almost all languages

ocean slate
#

?

feral spindle
#

It supports a ton considering it’s free

bright spindle
#

just get visual studio code, or PyCharm Community (for more... difficult projects)

feral spindle
#

He wants online

bright spindle
#

ah

unique shore
#

GitHub workspaces allows you to use a VSCode like editor in the browser

bright spindle
#

yeah vsc and replit is only options

#

github workspaces is snailspeed

unique shore
#

Just get VSCode app

bright spindle
#

also its ran by vsc

ocean slate
#

Should I clear my complete project details to you all so that you can suggest me which is goo

feral spindle
#

But you can deploy a flask server hella damm fast on replit

ocean slate
#

good?

bright spindle
#

why do online code editor tho

feral spindle
#

I know a guy who runs s api and discord bot on it

unique shore
#

Please don’t use replit…

feral spindle
#

And I’m setting up a bandwidth miner on it

ocean slate
#

I work on flask

feral spindle
#

Ye I recommend

#

Don’t ever publish anything unless you are fine with people stealing code

jade minnow
feral spindle
#

It’s free u gotta love it

jade minnow
#

also can i use the exact same paramaters for text-shadow as i can for box-shadow

ocean slate
#

I am creating a website for my college for coding contests. In which questions will be there and when a student click on a question a new page loads having that online code editor(or compiler) and run the code on same time

#

I can do front-end, backend, database

jade minnow
ocean slate
#

Only problem I am getting is how to add that editor

bright spindle
#

flask, underdeveloped websites, mostly for people who gonna make lightweight/low knowledge stuff

feral spindle
#

They have editor embed

jade minnow
bright spindle
#

except for a few who goes all the way with it, api's can be done efficiently (using multiple libraries)

ocean slate
#

the answer(or output) of that question only

jade minnow
#

literally thi

feral spindle
#

Experience everything then choose

jade minnow
#

any language

#

same output

ocean slate
jade minnow
#

it already exists

ocean slate
#

How I can use and apply it to my website

jade minnow
ocean slate
ocean slate
jade minnow
#

use codepen

#

or somethign

#

you can make the problem

#

share it to them

#

give them the task

ocean slate
#

I am new in this please help

jade minnow
#

are you doing in-person?

#

for your coding thing

#

just like

#

walk around

ocean slate
jade minnow
#

if they get it

jade minnow
#

you arent on like

#

a meeting

#

call

unique shore
#

Instead of replit, try a beginner friendly IDE like Mu or Thonny

ocean slate
bright spindle
#

im still bummed over how webhook exception handling is done, if i get error in code do i just... leave it

unique shore
bright spindle
#

i got a no module named project.chat.models error when attempting to do import .models from project/chat/consumers.py to the directory project/chat/models.py. Settings file is located at settings/base.py, and project, chat and settings folder all contains __init__.py. Additionally, chat is added to the INSTALLED_APPS variable, and contain the correct apps.py format to be detected. Of course git forgot to commit the file

gritty vapor
#

Hello everyone 🖐️😃

#

I'm new to python web development (extreme beginner), can someone help me from where should I start the basics to web dev using python like some tutorials or some advice will be helpful.
Thanks in advance innocent

covert yew
vapid jay
#

Anyone have experience with azure hosting?

gritty vapor
sand sail
covert yew
ocean slate
#

I am creating a website for my college for coding contests. In which questions will be there and when a student click on a question a new page loads having that online code editor(or compiler) and run the code on same time
I can do front-end, backend, database

#

Only problem I am getting is how to add that editor

sand sail
# ocean slate dm me

look into "ace editor", there's a few prebuilt js code editors but you'll have to handle compiling/testing the code yourself

echo geyser
#

Is this the right channel to ask for elasticsearch help?

unkempt juniper
stable bear
#

flask beginner project ideas?

outer apex
# unkempt juniper <#828685652542750800> i'm using flask, need help

Just saw your message in the channel. I think you might need to provide an absolute path to the tokens.json file. I don't think your app is able to find that file, hence that TypeError's message
Can you share the complete exception? Hopefully it'll show specifically where it's erroring out

bronze palm
#

are you already past register and login Saki?

#

other wise a login, and register system are always a good start

#

@stable bear

stable bear
#

i would like something involving login and register as i know how to implement those

bronze palm
#

just make a simple system for it and load a page

#

so not logged in go to x page other wise go to y page

stable bear
#

done that

bronze palm
#

alrighty next thing is then have you done much with databases yet?

#

with sql alchemy?

stable bear
#

i have done some but not much

#

i made a to-do list

#

for each user who logs in

bronze palm
#

I'd suggest focusing on a blog site with articles, or if that is to much a permission system with users

#

where different users can access different pages that others can't

#

that should help you getting used to the relational database system

jovial blaze
#

Hi, I seem to be having some issues with aligning these three images side by sidehtml <a href="https://github.com/anuraghazra/github-readme-stats"> <img align="left" src="https://github-readme-stats.vercel.app/api?username=SnowyJaguar1034&count_private=true&include_all_commits=true&show_icons=true&theme=nightowl" /> <img align="center" src="https://github-readme-stats.vercel.app/api/pin/?username=SnowyJaguar1034&repo=Zupie&show_icons=true&theme=nightowl&show_owner=true"/> </a> <a href="https://github.com/anuraghazra/convoychat"> <img align="right" src="https://github-readme-stats.vercel.app/api/top-langs/?username=SnowyJaguar1034&theme=nightowl" /> </a>

untold scroll
# jovial blaze Hi, I seem to be having some issues with aligning these three images side by sid...

You should probably aim doing that with CSS or Bootstrap instead of inline HTML. It's much easier and makes the html less messy. There are a few articles that should be able to help you with that, I think this is a good place to start:

https://www.w3schools.com/howto/howto_css_images_side_by_side.asp

jovial blaze
untold scroll
#

but if it's for github I'm afraid they don't support it. It kind of goes against the purpose of .md files anyway to make things simpler.

jovial blaze
#

Yeah it's for GitHub. It's annoying that CSS isn't supported but I kind of expected that

pastel citrus
#

Hello everyone ! is anybody here familiar with CGI scripts ?

frail wedge
#

Hello ! I kinda wanted to learn web development using flask, but i found myself stuck.
Basically; i can't manage to call any "extern" css file, it just won't load, and i don't really know why since there is no output in the console.

( The screen at the bottom show how the folders inside my project are sorted )

main.py file :

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/home')
@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

base.html

<html>
    <head>
        <title>Shrek Mania - {% block title %}{% endblock %}</title>
        <link rel="stylesheet" type="text/css" herf="{{ url_for("static", filename="styles/style.css") }}">
    </head>
<body>
    {% block body %}
    {% endblock %}
</body>

style.css

body {
    background-color: black;
}
radiant hemlock
#

Hello I want to run a pick a number game that is made all out of python on a website how could I do this with minimal code needed

untold scroll
half bough
#

I’m building a Django web application. I need to build a user authentication system where a user can play the game three times, then after that get prompted to sign up or login. High level, don’t need the code, what would I need to do this?

#

I’ve already built the signup and login but how do I do the other part with letting the user access some features then making them sign up?

native tide
#

hey everyone..

#

can anybody help me understand this.. below code is a django CBV inherited from
class ProductSearchView(FacetMixin, HaystackViewSet)
this have a method called get_queryset... but i don't understand how this filtering going on..

        queryset = super(ProductSearchView, self).get_queryset()
        q = self.request.GET.get('q')
        queryset = queryset.filter(owner_id=self.request.user.id)
        if q:
            update_stats.delay(self.request.user.id, q)
            return queryset.filter(SQ(title=AutoQuery(q)) | SQ(sku=AutoQuery(q)) | SQ(text=AutoQuery(q))).highlight()
        return queryset```
strange charm
#

can someone help me with? i tried google as well. But i cant understand whats wrong

obtuse robin
#

idk if its it but maybe its the space at the {% else % }

#

maybe you could also try an elif not recipe.cover?

radiant hemlock
ocean slate
#

I will try to help you

radiant hemlock
#

Ok

native tide
#

how do i fix this

whole knoll
#

can someone help me

autumn tendon
agile pier
#

in new password and confirm new password, I m using regex pattern, bcoz of this the focus attribute is not working correctly as u can see

#

how do I make them work like the old password field?

#
<div class="user-box">
          <input type = "password" name="oldPsw" id="passwordOld" required>
          <i class="bi bi-eye-slash" id="togglePasswordOld"></i>
          <label>Old Password</label>
        </div>
        <div class="user-box">
          <input type = "password" name="newPsw" id="password"
          required pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$" title="Minimum of 8 characters. Should have at least one special character and one number and one UpperCase Letter.">
          <i class="bi bi-eye-slash" id="togglePassword"></i>
          <label>New Password</label>
        </div>
#

pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$" is causing the problem

jade minnow
#

im adopting

royal river
#

Hi.

#

How do I add a variable for userId in this scenario:

#

On the underlined from the picture,
I tried to do the
f'{userId}'
and the triple quote method and the .format(userId)

#

It didn't work..

warm gale
#

If my only option of retrieving something in javascript is calling this.a.b.c.target, whats the proper way to make sure a, b, and c are not undefined?

Also, does this situation have a name? Where you're calling the child of a child several layers deep?

#

Thanks

fiery lake
#

@royal river can u be more clear and please mind sending the code?

wheat hamlet
#

I'm fairly new to web development and want to make a web application that I can use to communicate between 2 separate applications. My only concern for now is, how do I make some sort of event in python? An event that is triggered when someone requests the web server?

swift wren
#

flask or django orrr

wheat hamlet
#

flask

#

since it will just be a small project

swift wren
#

yeah so flask only does something if you send a request to it

#

if you send a request to a flask server its going to trigger a response naturally

wheat hamlet
#

doesnt django also do that..?

swift wren
#

yeah django does that as well

wheat hamlet
#

since im new, i will explain what im trying to make

swift wren
#

all backend frameworks work off requests

wheat hamlet
#

yeah ive made some practice websites with both django and flask

#

but for now thats really the only thing i understand

#

what i want to know is how i can communicate between this web server and another separate application

#

for example

#

how can i trigger an event in a discord bot if a request is sent to the web server

#

something like that

#

thats where im stuck

#

and its frustrating

ivory kiln
#

i'm a bit confused what the file structure is supposed to look like in a standard django application

#

im trying to render a html

#

using django.shortcuts.render

#

but when i pass the html path its just saying it doesnt exist

#

i printed os.listdir() and it showed its in the root

#

but i tried every path and its just not workin

worldly pawn
#

@ivory kiln I'm working on a Django project now (first) so I'll see if I can help. I assume you made the basic html template and stored it in the app_dir>template>app_name>html_file? From there you should have referenced it in app_dir>urls.py as a path on the urlpatterns? You also need to make sure to include the app_dir.urls in the urls.py under the project directory.

inland oak
#

Wow. FastAPI looks sick

#

like Flask, but way cooler

ivory kiln
#

i have a question

worldly pawn
#

cool stuff

ivory kiln
#

im doing ```py
def index(request: wsgi.WSGIRequest) -> HttpResponse:
response = Response(request)
html = response.to_html()
return HttpResponse(html)

worldly pawn
#

I'm trying to get view to only display when logged in. i got the logic done, but I kind of wanted to have a base.html that will be the same throughout, and then only show other elements when logged in. is the use for {% extends %}?

#

boom. love it!

royal river
#

How do I add a code in this chat with properly quoted one btw.

native tide
#

When I enter something in the input, and submit it, it won't show up. Can anyone help me figure out why?

templates/editor.html

<form method="post">
  {% if results %}
    {{ results }}
  {% else %}
    {{ editor.console() }}
    {{ editor.run() }}
  {% endif %}
</form>

main.py

from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import validators, SubmitField, TextAreaField
import os

app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('key_thing')

class EditorForm(FlaskForm):
  console = TextAreaField("Let's make some W# Code!", [validators.optional()])
  run = SubmitField("RUN")

@app.route('/', methods=['GET', 'POST'])
def index():
  results = None
  editor = EditorForm()
  if editor.validate_on_submit():
    results = editor.console.data
    editor.console.data = ''
  return render_template('editor.html', results=results, editor=editor)

if __name__ == '__main__':
  app.run('0.0.0.0')
outer apex
native tide
#

Ahh okay

#

Thanks

covert salmon
#

How can I run a Python script in PHP with arguments? Do I just have to insert arguments after path like escapeshellcmd('path', args)?

wheat verge
#

Can someone explain how this function is working how is the result argument getting the "done !"String

frank shoal
#

after 1000ms, it calls resolve("done!"), which is a callback set to alert

#

it can be rewritten as this. ```js
(async () => {
try {
const result = await promise;
alert(result);
} catch (e) {
alert(e);
}
})();

indigo ether
#

hi, I need help, I am making a hover animation for my navbar, but I only want the text to have the hover animation and not the main logo, anything I can do, essentially I want to remove the hover animation for specifically the main logo (btw I am currently hovered over the logo to demonstrate

sturdy idol
#

I’m wanting to write a web application that takes user form input, adds that to a queue, then once the user specifies they are done, it will run a python script for each set of variables (each form) that the user inputs. Is this something that’s doable in Flask? Should I look into other options? If so, could I get pointed to some documentation?

surreal portal
#

Forever thanking my bootcamp teacher for discovering Streamlit

#

Now that it's in version 1.x it's so useful

wheat hamlet
#

If I have a flask web app, how is it possible to trigger some sort of event in a separate python application once a request is sent to the web app?

sand sail
sand sail
wheat hamlet
wheat hamlet
sand sail
wheat hamlet
#

alright, how do you just make an event in python

#

just in general

#

a general event my code can wait for

sand sail
wheat hamlet
heavy kayak
#

Have any of yall used the mediapipe hands library for any web development?

#

Or even for experimenting purposes?

obtuse mantle
#

I am new in web development can you suggest me to how to start it

heavy kayak
#

@obtuse mantle Do you know how to code?

obtuse mantle
#

only html and css

#

I know

heavy kayak
#

What I did a while back to learn how to code and create a website is create a web calendar. Kinda like google calendar. I made a small database to save all the dates and made a nice user log in interface that would also be stored in a database. And there are plenty or resources to use to learn how to make all the components of that.

obtuse mantle
#

So how create a database

heavy kayak
#

You can use videos like this as refrence. https://www.youtube.com/watch?v=o1yMqPyYeAo But the more you do yourself the more you will learn

UPDATE: Unfortunately there is a glitch in the tutorial, the statement "monthDays.innerHTML = days;" should be placed outside of the for loop!!!

In this tutorial, we will build a Calendar with HTML, CSS, and JavaScript

SOURCE FILES: https://github.com/lashaNoz/Calendar

Support the Channel - https://www.paypal.me/codeandcreate

Udemy courses:
...

▶ Play video
#

If you wanna create a real database you are gonna have to learn some sequel, if you wanna make a fake one, you can just make a json file that stores all the info, just go online and search "how to make a database"

obtuse mantle
#

Can i should start js

heavy kayak
#

I would use js yeah

#

for all the interactive items on the sight, such as clicking on the calender, or adding elements

#

html and css will just make the shell of the website. the JS is all the interactive code, clicking on a button and a message popping up for example

obtuse mantle
#

I know web HTML and CSS that you tell to me this is not understandable to me

#

make it simple

heavy kayak
#

HTML and CSS is all the pretty stuff on the website. This is how you make things

#

Html put pictures

#

css make picture look pretty

#

javascript make pictures move and do things by user interaction

obtuse mantle
#

ok and??

#

what is database

heavy kayak
#

its where you store all the information of the site. User login infromation like username and password.

obtuse mantle
#

if any user sign up in our website where the data goes?

#

of sign uping

heavy kayak
#

to the database, which can be stored on a server, your local machine, it could really be stored anywhere, just a place that reads that infromation

#

just forget about the database for now

#

work on the javascript first

#

later do the database

obtuse mantle
#

when we get host our website then where the data goes of sign up

heavy kayak
#

Some hard drive that is run on the server

obtuse mantle
#

Is bootstrap relevant in today's world

heavy kayak
#

yeah it is, its a framework that helps you develop a website and make it easier

obtuse mantle
#

Can you use it

heavy kayak
#

yes you can

obtuse mantle
#

bootstrap or tailwind.css

heavy kayak
#

bs

obtuse mantle
#

why taillwind not

heavy kayak
#

Prefrence

obtuse mantle
#

ok

heavy kayak
#

I havent really used it

#

And tailwind is not a ui kit

#

while boost strap is

#

some people prefer one over the other, it all depends

obtuse mantle
#

what is ui kit

heavy kayak
#

A UI kit is a set of files that contains critical UI components like fonts, layered design files, icons, documentation, and HTML/CSS files. UI kits can be fairly simple with a few buttons and design components, or extremely robust with toggles that change fonts, colors, and shapes on the fly.

obtuse mantle
#

can we us both bs and tw

#

in same file

heavy kayak
#

You CAN but you shouldent unless you know what you are doing

#

Some of the stuff in both can overlap causing problems later on

obtuse mantle
#

have you any resource for webdevelopment

#

??

heavy kayak
#

google lol

#

any question you ask it will have an answer for

obtuse mantle
#

where you learn it

heavy kayak
#

10% school, 90% google

obtuse mantle
#

you not watch any tutorial??

heavy kayak
#

I did, on google, mostly read though

obtuse mantle
#

you understand by only reading????

heavy kayak
#

yeah usually, and testing

obtuse mantle
#

I am using vs code is it good

heavy kayak
#

yeah

obtuse mantle
#

what if I not use any framwork???

heavy kayak
#

thats okay

#

You dont need it

obtuse mantle
#

so why people use it

heavy kayak
#

So make large scale development easier

obtuse mantle
#

ok

#

In which age you start webdevelopment

heavy kayak
#

Idk around 15-16

#

im 21 right now

obtuse mantle
#

ooh

#

I am just 17

heavy kayak
#

Thats good! Its always fun to start learning new things, if you have any questions just use google

#

itll be your best friend

obtuse mantle
#

are you doing job

heavy kayak
#

yeah

#

and school

obtuse mantle
#

so what you study

#

in school

heavy kayak
#

computer science, web and software development

obtuse mantle
#

how much time you take to frontend

polar haven
#

is there any channel for django ?

tired shuttle
#

hi everyone

#

im just new to the community

#

im 18 and Im interested in web development

#

I would appreciate any guides in this field, eg: what libraries i should know or which framework is better?

unique shore
#

@tired shuttle what type of web dev do you want to do? frontend or backend

#

or full stack

tired shuttle
unique shore
#

ok

#

so thats exactly what i do

#

i would still learn basics of HTML, CSS, and JS (JS mostly as you can do backend with JS)

#

i recommend this roadmap

tired shuttle
unique shore
#

i personally use Rust and C# for backend dev. i dont use Python much anymore

tired shuttle
unique shore
#

yeah you should a bit

#

it should take a week to do that lol

unique shore
#

like Rust and C# more

#

and C# is growing massive recently. it has an extremely large ecosystem

tired shuttle
unique shore
#

well Rust is miles faster than python

#

and I choose it because it incorporates many low level concept which I am interested in

tired shuttle
#

how long have u been programming?

#

and another question is that which framework is better for python?

#

and how long it will take to become a senior in this field?

unique shore
unique shore
tired shuttle
unique shore
#

but if you don't want everything given to you off the bat, and want to make stuff yourself, don't use it

#

it is batteries included

unique shore
#

idk it depends

ocean slate
tired shuttle
ocean slate
#

for back-end

#

it is beginner friendly

#

if in future u need help related to flask, the message me personally

#

I will try my best to help you.

tired shuttle
#

thanks for your guidance🙏

tired shuttle
ocean slate
#

:)*

tired shuttle
#

🙂

native tide
#

how do i stop anything other than output to stop showing in terminal?

ancient pumice
#

Hey there, I have a question about StreamingResponses in FastAPI. I'm passing a generator to a Streaming. The generator keeps getting data over a websocket. So does this work like a FIFO or does it poll for a limited duration to get the data from the generator? Cause I'm a bit confused on what happens if I don't send data over the websocket for a few minutes and then resume sending it.

agile ruin
#

Hello i need help with django,
i removed 2 models from the database and removed the migrations of them and now when i run migrations it shows like everything fine
but doesnt really add the models to the database and i cant access them in admin panel error: Relation..." " does not exist...

native tide
#
har = json.loads(driver.get_log('har')[0]['message']) # get the log
print('headers: ', har['log']['entries'][0]['request']['headers'])
Message: invalid argument: log type 'har' not found
#

ping me on reply pls

formal bronze
#

<ipython-input-9-7f7348bca851> in <module>
----> 1 f.objects.all()

~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py in get(self, instance, cls)
177 def get(self, instance, cls=None):
178 if instance is not None:
--> 179 raise AttributeError("Manager isn't accessible via %s instances" % cls.name)
180
181 if cls._meta.abstract:

AttributeError: Manager isn't accessible via Auctions instances
.......
.......
.......
I am trying to do f.objects.all() but getting this error

dark loom
indigo kettle
#

if so, you may need to also remove them from the migrations table that django creates...

#

normally, if you created a migration that you actually do not want, you would reverse the migrations and then delete them or just create new migrations which remove the tables

elfin tinsel
#

There's a discrepancy between the value I have stored in the db and the value I get from fastapi.
Stored DB Value: 9339981860999169
https://cdn.discordapp.com/attachments/776184661902491678/957348807438393404/unknown.png
https://i.imgur.com/XTmofAt.png
As far as I can see, I don't modify the ID manually, but it seems to change..

# services.py

async def create_club(session: AsyncSession, club: ClubCreate):
    new_club = Club(club.name, club.description)
    session.add(new_club)
    await session.flush()
    new_club = await get_club(session, new_club.id)  # HACK: Had to do this to fix the db issue.
    return new_club


async def list_clubs(session: AsyncSession):
    return (await session.execute(select(Club))).scalars().all()


async def delete_club(session: AsyncSession, club_id: int):
    new_club = await get_club(session, club_id)
    if new_club:
        await session.delete(new_club)
        await session.flush()


async def get_club(session: AsyncSession, club_id: int):
    return (
        await session.execute(
            select(Club).
            where(Club.id == club_id)
        )
    ).scalars().first()

async def update_club(session: AsyncSession, club_id: int, club_update_payload: ClubUpdate):
    await session.execute(
        update(Club).
        where(Club.id == club_id).
        values(**club_update_payload.dict(exclude_unset=True, exclude_none=True, exclude_defaults=True))
    )
    await session.flush()
    return await get_club(session, club_id)
#
# routes.py

@router.get("/", response_model=list[PartialClub])
async def list_clubs(session=Depends(get_session)):
    return await services.list_clubs(session)


@router.post("/", response_model=Club, status_code=HTTPStatus.CREATED)
async def create_club(club: ClubCreate, session=Depends(get_session)):
    club = await services.create_club(session, club)
    return club


@router.get("/{club_id}", response_model=Club)
async def get_club(club_id: int, session=Depends(get_session)):
    return await services.get_club(session, club_id)


@router.patch("/{club_id}/", response_model=Club)
async def modify_club(club_id: int, club_update_payload: ClubUpdate, session=Depends(get_session)):
    print(club_id)
    return await services.update_club(session, club_id, club_update_payload)


@router.delete("/{club_id}/", status_code=HTTPStatus.NO_CONTENT)
async def delete_club(club_id: int, session=Depends(get_session)):
    await services.delete_club(session, club_id)
    return Response(status_code=HTTPStatus.NO_CONTENT)
#
# models.py

class Club(Base):
    __tablename__ = "clubs"

    id = Column(BIGINT, nullable=False, primary_key=True, default=id_gen.create_id)
    name = Column(String, nullable=False)
    created_at = Column(DateTime, default=datetime.now)
    description = Column(String)
    money = Column(BIGINT, default=25000000)

    def __init__(self, name: str, description: str):
        self.name = name
        self.description = description

ocean slate
#

hello, I want to learn about api in python flask

#

suggest me any good tutorial where i can learn API with flask, I saw many videos but they were not so in deep

agile pier
#

hii, i m using base 64 encode for the image

unique shore
#

the basic flask program IS a REST API

agile pier
#

My image is in {{dd.image}}, I want to ask where do I give the value{{dd.iamge}} in

    AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
        9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />```
unique shore
#

app.get("/"), which is essentially used in all flask beginner tutorials is a GET request at the index route

vivid canopy
#

can u please tell me why we use def list or create in a rest framework if we have ListCreateView?

bronze palm
#

it allows us to be selective on which kinds of methods we allow, if we disallow methods we don't need faster we get better results

#

and with generics specifying can be useful like the listapiview is read-only and tis explicit

#

while the list create isn't

#

@vivid canopy hope that helps

vivid canopy
#

thx bro)

bronze palm
#

no worries

cinder whale
#

what is the average python web dev's tech stack look like

#

or feel free to share your own too

inland oak
cinder whale
#

thanks DW

#

oh good to know

#

ubuntu is what im most familiar with

inland oak
#

Feel free to get acquainted with Alpine for docker images purposes though

cinder whale
#

wait DW, you didnt mention any frontend frameworks

inland oak
cinder whale
inland oak
#

Anyway.. React or Vue.js

cinder whale
#

ok good

#

bc im learning react

#

do you use a css framework too or no

inland oak
#

React or Vue.js
Some sort of related state management system
SCSS

cinder whale
#

Sass ive played with before

#

my friend is super into tailwind

inland oak
cinder whale
#

yet

rare oar
#

Hey all, I got a weird question and the FastAPI discord is dead

inland oak
#

Alpine Linux is cool for docker. It is really small. 5mb base size

cinder whale
#

figma lets you export code too

cinder whale
#

i will note this down

rare oar
#

I'm having a issue with a background task that I created. Its a simple function that goes in an infinite loop with a sleep and is created by asyncio_create_task. When I run this FastAPI instance under uvicorn everything is working fine and does what it needs to do. However, when I use gunicorn and pass in the UvicornWorker, I can see the task being created, but the function never executes. Any ideas?

cinder whale
inland oak
# cinder whale do you think you will focus on web dev or move to another specialty in future or...

I will remain in web dev and concentrate on backend/DevOps

My future plans

  1. getting hands on fastapi and async related python ecosystem
  2. practicing golang
  3. learning tekton/argocd as kubernetes native gitlab CI alternative
  4. learning Kafka and building microservices architecture around it
  5. improving my code quality things to handle really big sized projects
  6. practicing with AWS
  7. learning secondary cloud infrastructure objects like Vault, Elastic search, mongodb and etc
  8. getting more exp with Postgresql, and wishing to try Flyway dB version control system
#

And I am certainly not going to improve my frontend or anything related to it.
Except may be a bit setting up testing stuff for that

#

I like infra more than front

#

I already tried Frontend with Vue.js, so I got the taste of it

#

It has some certain appeal in simplicity and relaxation, but it is not for me

cinder whale
#

i see

rare oar
#

Front end sucks.

cinder whale
#

there is always need for more backend than frontend i feel like kekHands

#

my background is in DS so it all is new to me DoggoKek

inland oak
cinder whale
#

yeah im trying to learn as much as i can for this website project for my software engineering class rn

#

since it seems the other team members are unreliable kekHands

#

like

#

they are all CS majors and im the only AI major

#

why am i the main developer kekHands

#

honestly i will probs end up having to make this entire website by myself. already calling it kekHands

#

but at least i will get to learn stuff

inland oak
cinder whale
#

but i guess it seems common in CS programs maybe

inland oak
#

During uni one of other students made a hack with js to pass our computer network exams.
And shared to all other students
Tbh what he did still looks like magic to me

cinder whale
#

i wanted to take a cybersecurity class this summer

#

but it filled up

#

🕯️

inland oak
#

Hell, I did not know I would be even programmer until I got taste of first job

cinder whale
#

this seems like its more in line with reality

inland oak
#

For the last one year and half I got certainty with my path and moving into one (two) directions

#

Backend+DevOps is a nice combo of my choice

#

Usually people just go backend, or just DevOps, or frontend, or full stack

#

My choice is just my personal quirck born out of need at the past job of handling everything alone

#

I started to work in a good company now... But I already got used to certain ownership of Backend and infra at a more intimate level

#

And it is just stacking well

cinder whale
#

interesting interesting

cinder whale
# inland oak And it is just stacking well

i like DS work and i will explore if i like dev work too, especially this summer (SWD internship), so i may try to follow your path and find a good combination if possible

inland oak
#

Your future company will value your DS/ML much more if u could code it in not a shitty way

cinder whale
inland oak
#

Out of all web devs, backend guys learn the most of code quality stuff

cinder whale
inland oak
#

Because it will give the basic instruments to operate during MlOps

#

DevOps stuff is meant to be started with person having already some background in other stuff? In Backend or in Ops?

cinder whale
inland oak
#

Bwhahaha

#

Reading article for differences between DevOps and MLops

#

Checked the author name and nickname...

#

... My brother.

marsh minnow
#

Anyone knows how can I interact with a source game server console with python in a website?

unique shore
#

some sort of API

cinder whale
inland oak
#

Conviniently he is experienced DevOps person which participated in all sort of public activity

cinder whale
#

what did he say the difference was btw

inland oak
# cinder whale what did he say the difference was btw

It is long article written in my native language.

If to summarize his all words.
MlOps = machine learning with DevOps with difference in

  1. pipeline for MLops requires not just code as data input, but also data and parameters, and results in model and then release
  2. requires more hardware
  3. monitoring of the system has some sort of dynamically changeable specifics to what is monitored

Main thing for MLOps to automatize building of model and its training tuning.
That alone will free more time for ML specialist to work more on model.

cinder whale
#

ah that tracks with what ive heard

#

they even specific tools for it but i wont get into it in this channel kekHands

#

since its OT

inland oak
#

It looks impossible to catch up with him

#

He is pure DevOps though, while I am a hybrid between backend and DevOps. So at least in backend knowledge and general code quality stuff I should be able in theory to surpass him. Not guaranteed though

cinder whale
inland oak
trail axle
#

can u gather input using the backend or would u need to take it using js and send to the python app?

obtuse robin
#

you can for sure gather input using backend