#web-development

2 messages · Page 165 of 1

gritty cloud
#

or another framework

royal cloak
#

woah, Thank you, is there also a tutorial that teaches about rest api using flask?

gritty cloud
#

ah man that was for django

west peak
#

Im using django

gritty cloud
#

when you save the form

#

you can do this

#

instead of form.save()

#

you can use instance_of_form = form.save(commit=False)

#

now instance_of_form is a model

#

that corresponds to the model in the modelform

#

then you can insert whatever you want

#

so like

#

instance_of_form.date = django.utils.timezone.now()

royal cloak
pseudo lark
#

Hello Dear Friends,I wanna say that I have spring boot ecommerce backend + advanced design + clean code + unit tests if you are interested in my app please contact me!

lavish prismBOT
#

9. Do not offer or ask for paid work of any kind.

west peak
gritty cloud
#

!rule 6

lavish prismBOT
#

6. Do not post unapproved advertising.

gritty cloud
#

other than that im not really sure

west peak
outer apex
#

Is there a value set for the checkbox input? If so it will be truthy since None is falsey.

if request.form.get('input_from_checkbox'):
    do_something_when_true()
else:
    do_something_when_false()
dapper solar
#

here's the html part

outer apex
#

is there a submit button for that form?

#

also are you POST-ing to that form?

dapper solar
#

yes

#

its a check box so no submit button

#
 <div class="form-check form-switch">
           <form method="post" action="">
               <label class="form-check-label" for="addToDb">add to your collection</label>
            <input class="form-check-input" type="checkbox" id="flexSwitchCheckDefault" name="toAdd", value ="True">
          
         </form>
outer apex
#

How are you submitting data then? Do you have some JS that's submitting on the checkbox click?

dapper solar
#

no this is it, do i need a submit button too?

outer apex
#

yes

#

You could also have the name and value attributes in a button too.

dapper solar
#

okay

#

i guess i will just replace checkbox with a button

rare lagoon
#

Should I first learn HTML, CSS and JS or should i learn html and css and use flask as backend?

#

I barely know about HTML, and I want to design a webpage for my project, nothing complex just the website showing features and dowload buttons, guess that's a static website right?

calm plume
foggy bramble
#

it gives me parse error, can someone tell why?

rare lagoon
#

Probably you have to fix the strings

foggy bramble
rare lagoon
#

Alright my bad

foggy bramble
stark axle
#

I have certain texts on site (flask) that may be edited from time to time (like description of site in /about). Because manually rewriting jinja templates just for these parts may be a bit far from optimal - I thought if there is some recommended way to insert markdown texts into these?

I've found flask-markdown package on pip, but its from 2010 and never updated since then

#

it just feels like such trivial and popular idea (everyone love blogs, right?) - I refuse to believe there is no package to solve it

thorn igloo
#

simple as that

restive kindle
#

Anyone know how to get the sec- headers to send from a browser? Ive checked on other sites and it does work but what ive read says it should just magically send.

stark axle
ivory bolt
#

Normally I'd go for any (edit) AWS service any day (cost-wise).
I've been happy with EC2

#

cuz money

#

just checkout wether scalability is an issue for you or not

calm plume
#

They were asking which AWS service to use

ivory bolt
#

Sorry not what I intended @calm plume

ivory bolt
#

thanks for pointing that out

graceful flax
#

I've used light sail, not elastic bean stalk

#

An ec2 instance gives many hurdles in automating

ivory bolt
graceful flax
#

And with the database, have used RDS small scale, never aurora or Redshift, this time it'll be a huge DB so needed some help figuring with scaling

ivory bolt
#

I'm having some issues of my own

#

with Heroku that too

#

literally NEVER had an issue with Heroku before

grave jungle
#

Why does django not work well with mssql

#

I wish it did

#

Or at least as easily as it does with oracle

ivory bolt
#

It works great with heroku

little merlin
#

goddamn my flask app is such a clusterfuck

ivory bolt
#

*postgres

ivory bolt
little merlin
#

ahhaa feel ya

#

is it working now?

ivory bolt
#

yep

#

except for the fact that all my static files are giving up on me

#

so that's just…so great

#

it's 4:22 AM here

echo hound
coarse heart
#

Thanks so much!! Thought I already found out what the issue was ... Another typo

#

(phone acc)

native tide
#

GCP mini and dedicated reservations are the cheapest on the market rn

#

IBM is much easier though that AWS or GCP, though GCP is all automated bots and no boys though

west peak
#

Hi

#

Im trying to get data from my db

#

but the .objetcs.filter() function return me <QuerySet []>

#

these are my models

#
class Purchase(models.Model):
    total = models.IntegerField()
    date = models.DateTimeField(auto_now=True)
    user_phone = models.CharField(max_length=50)
    id_user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )


class Purchase_detail(models.Model):
    id_product = models.ForeignKey(Product, on_delete=models.CASCADE)
    id_purchase = models.ForeignKey(Purchase, on_delete=models.CASCADE)
    quantity= models.IntegerField()
    price = models.IntegerField()
#

and this is how can i use the function

#
def see_purchase_detail(request, id):
    if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        purchase_detail = json.loads(serializers.serialize(
            'json',
            Purchase_detail.objects.filter(id_purchase=id)
        ))
        print(purchase_detail, Purchase_detail.objects.filter(id_purchase=id))
        return JsonResponse({'details': purchase_detail}, safe=False)
    else:
        return JsonResponse({None}, safe=False)
#

Im using django

native tide
#

hey how do I make a python script to detect if there is a new GET from a page?

primal thorn
#

i have return render(request, 'Pages/home.html', context) in my views function but it gives a 404 error that home.html does not exist, but i think i gave it the correct path

west peak
#

If you are using an app

primal thorn
west peak
primal thorn
#

ya that fixed it 😅

glad creek
#

where should one store the js file in a flask app?

primal thorn
#

is it possible to use a template from another app? i wanna make a navbar but i want them all to use the same layout

calm plume
#

A js folder inside static

glad creek
native tide
#

hey how do I make a python script to detect if there is a new GET from a page?

inland oak
inland oak
native tide
inland oak
native tide
inland oak
#

I think I don't know enough about your situation then

#

Are you web scrapper?

#

The web site is not belonging to you?

native tide
#

? I'm nothing, just a guy who wants to know when my browser do a GET method

inland oak
#

Oh that is what you are doing...

native tide
#

I have just a bit of experience with python

native tide
inland oak
#

...well.. the easiest would be making something like chrome extension, attaching javascript to internal browser APIs

#

With python it would be harder, but you can look for sniffig, how to make sniffing to intercept browser requests with python

native tide
#

wireshark

inland oak
#

Oh yes, it can help a lot

#

It will give answer, what you will be able to do in python

#

Since you would see in comfortable GUI what can be done for sniffing at all

native tide
inland oak
west peak
#

But i am searching in the docs

native tide
primal thorn
#

i have added 'DIRS': [os.path.join(BASE_DIR, 'layout')],# Add this line to my settings.py file to have layouts accessible to all apps, how do i set my {%extends "layout/layout.html"%} so that it points to the folder

west peak
inland oak
west peak
#

Other option is refactor the data from Purchase_detail.objects.all() with javascript

#

But is meh

native tide
inland oak
#

Just... use....

#

Purchase_detail.objects.filter(id_purchase__pk=id)
You can specify after __ any parameter of sub obj attached to foreign key

#

including user id, phone and etc

#

Or actually...

#

You could make a search for purchase, before trying to search purchase detail

west peak
#

It don't work :C

#

I tried with Purchase_detail.objects.filter(id_purchase__id=id)

#

But also don't works

inland oak
#

Perhaps this one then

west peak
#

i will try

inland oak
#

Request all your purchase objects, and check their pk

west peak
#

The Puschase.objects.filter(pk=id) works

#

A return the Purchase

#

But the second line no

primal thorn
#

how do i get the records from another table based on the id of a table and display them on the admin panel, for eg i want to get the name of a countries based on a 'continent' id

west peak
#

id_purchase=id or id_purchase=purchase are returning a QuerySet with no lenght like always

inland oak
west peak
#

Ok

#

I'll do it tomorrow

#

Thanks for the help bro

shut rampart
#

should i use python for back-end web development?

calm plume
shut rampart
calm plume
#

Absolutely!

#

Frameworks like Django scale very well

west peak
calm plume
#

Yup, Instagram uses Django with a fork of CPython called Cinder

shut rampart
#

thanks

west peak
#

a check my db

inland oak
west peak
#

And i tryng with get Purchase_details kith id=1

#

but i don't have them

calm plume
#

But Postgres scales very well

#

So it should be able to go pretty far

inland oak
calm plume
#

I've never heard of it, but O'Reilly is pretty reputable, and it seems like it's quite interesting

inland oak
#

Yup. Definitely on my schedule to read

#

looks quite useful for any backend dev

calm plume
#

Looks like it'd be worth a read for me

west peak
calm plume
#

I haven't used MySQL, so I have no idea how it scales

whole spear
#

is there a way to select by aria-label in Selenium?

#

(except Xpath or CSS selector)

west peak
calm plume
coarse heart
grand oriole
#

I am currently working on a website project, would anybody like to collaborate with me on it?
It's to generate PDFs or PNGs from LaTeX.

fallen marsh
#

just finished learning python. anybody knows some good udemy courses so that i could start on web dev?...

ivory bolt
#

I normally wouldn't recommend udemy at all

#

I'll ask you a question or two, and I'll give you a tutorial series

#

do you want to start out by building a simple blog site, or a webapp?

tidal dock
#

ned help

#

which is best

#

flask + bootstrap or flask + react

#

and

#

why css not working

zinc notch
#

how do I use CSS to centre a circle (like smack bang in the middle of a webpage)
and I want resize compatibility, so like if the user resizes the window, it should still stay in the centre

#

nvm got it

native tide
#

to understand

lapis fable
#

Hi! How do I build a desktop application with python? Which IDE should i use?

lapis fable
#

oh if i use vs code, can i like code and launch a desktop application? sry... im rly new to programming

inland oak
#

surely

#

python is not requiring actually anything to run it

#

except having installed python

#

(and installed dependency into your virtualvenv)

#

you can launch project literally from console

#

the only small specific about desktop applications

#

that they are at a later stage, minimized with something like pyinstaller

#

to be not dependended on python,

#

making some .exe file

lapis fable
#

oh okay. thank you!

surreal portal
#

Is there a way to create custom types for a Django model like with SQLAlchemy?

surreal portal
#

Thanks. I think I know how SQLAlchemy's column types work but not Django ORM's

inland oak
#

I think I am having an opposite of the problem

vestal hound
#

you need to define a custom model field class

#

with the methods to serialise and deserialise etc.

#

but why do you want to do that?

surreal portal
#

Meanwhile there's another portion of code that creates data, that uses SQLAlchemy

opal agate
#

anyone knows why it didn't work?

#

the html file is empty

surreal portal
#

I think I'm stuck in a bottom pit

opal agate
#

any idea or way of rewrite those lines?

fallen marsh
ivory bolt
#

they do have a lot of courses

fallen marsh
#

ikr and i cant choose which one to go cause of my zero experience in web dev

ivory bolt
#

I'll help out

fallen marsh
ivory bolt
#

hmm

#

right off the bat, there's just too much to learn at once

#

If you're comfortable with javascript, then learn react only

#

or node js only

opal agate
#

😩 that's hurt

fallen marsh
#

im only comfortable with python at a moment

ivory bolt
#

don't learn two heavy frameworks at once

#

then I wouldn't recommend you take this course

#

get familiar with javascript first

fallen marsh
#

ohhh

ivory bolt
#

What do you wanna build with web-dev

fallen marsh
#

is javascript the best language for web dev?

ivory bolt
#

it's the most widely used

fallen marsh
inland oak
ivory bolt
#

Though I'm a django lover it's the harsh reality

fallen marsh
#

cool

#

thanks

inland oak
#

and even for frontend devs, javascript is augmented with typescript

fallen marsh
#

imma get my hands on javascript then

inland oak
#

backend devs like more wider range of languages

#

python is good one

ivory bolt
#

it is but not a lot of companies are using django

inland oak
fallen marsh
#

i cant learn too many things at a moment i have my school studies as of now too

ivory bolt
#

alright, let's start small

inland oak
#

as far as I know

#

django is good too ;b

#

but php is probably more wider used

ivory bolt
#

first, focus on getting familiar with javascript. Then, pick up node js

fallen marsh
#

imma be a dev at microsoft and will LeAk wiNdOwS 18

ivory bolt
#

If you want you can DM me if you want a learning path

ivory bolt
inland oak
#

yeah, node.js can work too

#

you can be completely full stack web dev

#

while knowing only javascript

ivory bolt
#

yep

fallen marsh
#

my brother's best friend just got an internship at google, he a web developer (idk front or back though) as an internship they paying a hella amount of money

solar epoch
#

You say not a lot of companies are using Django but I've never been out of work for even a few days in the last 5 years or so

#

pretty anecdotal I suppose and I don't know how the market is where you live

inland oak
#

I am not having a shortage of work in Django too

#

loving this framework.

#

Blazingly fast development

solar epoch
#

It's also worth noting it's not too bad to be in a niche. Sure, it might be easier to find a job with Node, but you probably can't demand as high of a salary, either, because there is just so much competition.

vestal hound
#

I really like Django for prototyping

#

maintainability can get problematix

#

but at @ small scale it’s just SO EZ to get something up and running quickly

solar epoch
#

I don't have much problem with bigger projects personally, Instagram is still running on Django last I checked. I dunno, I think it's a problem in any framework that things get a bit hard to find as the codebase gets bigger

#

I do contract work for a single company full time at the moment, but I have freelanced in the past.

native tide
#

is it absolutely necessary to set max length validators in wtforms?

#
class ContactForm(Form):
    name = StringField('name', render_kw={"placeholder": "Name"}, validators=[DataRequired("Provide your name.")])
#

or is it enough to just set a field?

#

Or what i am acutally trying to ask: If I do not set max length, could people cause overflow errors or something like that and would this make my app unsafe and prone to hackers?

#

so is setting max length mandatory?

solar epoch
#

Depends where it's going after your form handles it

#

The server will have some maximum request body size anyway so if it's truly large it's unlikely to get through to your form in the first place.

quick cargo
#

You probably want to set that

#

Nginx by default is 10MB If i remember

solar epoch
#

Yeah there is not really a reason not to, here.

quick cargo
#

Python webservers dont even limit the amount they read because idk

#

10MB is still enough to cause issues depending on your setup

#

if it's a small enough server it's running on then 1000 connections all sending 10MB will cause issues

vestal hound
#

“less maintainable” doesn’t mean “unmaintainable”

solar epoch
#

I'm sure there are some cases where that's true but whenever I looked into the research into this it didn't seem like statically typed languages have any overwhelming advantages in reducing bugs. Admittedly the research into this has not been super robust, or it wasn't when I last bothered to read about it, anywhere. In therms of "maintainability" I'm not so sure because it seems like quite a subjective term by it's nature. I would be interested in reading if there are objective measures though.

tepid parcel
#

Hello, I am currently migrating my strapi api (Very basic) to FastAPI, but i want to "secure" it so no other app than my own app / Frontend is allowed to get the REST API data. How would i do that, i already using JWT for user authentification via Login, BUT i dont want to authentificate a USER, i want to allow my frontend to communicate with the API, how would i do that?
I am thinking about API-Keys like other API's are using it, BUT i am not sure how someone would implement it any suggetions?

vestal hound
#

Python’s type hinting can more or less replace something like Java

#

but FP languages have more powerful type systems, IME, that really help

solar epoch
surreal portal
#

Btw I was wondering if it was possible for Django to read a database and "analyze" its contents to generate an object model. I know SQLAlchemy can do it with MetaData but I heard Django ORM wasn't as evolved.

#

At worst i'll just copypaste the fields

quick cargo
#

If the api is exposed, and is used by the fronted like React, Vue etc... Its easy enough to get around anything you can do to try and mask it

solar epoch
vestal hound
vestal hound
#

and that’s 100% something you need to take into account as a tech lead when choosing the stack

solar epoch
#

Currently the only people I know who like/understand FP are math nerds, and that for sure ain't me and probably ain't most programmers either.

vestal hound
#

whether your present/future team can actually work with the language

vestal hound
#

don’t you use comprehensions?

tepid parcel
#

@quick cargo@solar epoch Hmm ok i do understand, but how does other API's it? Where i need an API Key for my app to even use it? For example openweather api or Firebase? Hmm, i usually would not care but was wondering.

surreal portal
vestal hound
#

if you want something there a package for it

solar epoch
#

Sure, I use comprehensions, sometimes I even use map() :)

vestal hound
#

I tried to write a webapp in Rust and it was HELL

vestal hound
solar epoch
#

yeah I mean that's why I use Python, right, I can use the handy bits of FP and discard the stuff I can't read :P

quick cargo
surreal portal
# quick cargo Can you elaborate a bit more?

Suppose you have a polls table already created in a SQL DB, with a couple of rows inserted. Django must use this table to expose its results. Knowing that the schema is already prepared, is there a way to generate a Django model from it?

vestal hound
#

I’m not saying you have to use monad transformers and higher-rank polymorphism

#

(which I don’t really get tbh)

quick cargo
#

I dont believe so, and i think by the time you work out how to do that you might as well manually implement the model

vestal hound
#

but you DON’T need those super hardcore aspects

solar epoch
#

Indeed that's kinda my point, right? I can use functional bits of Python where it makes sense and is readable. But in say, Haskell, I'm kinda forced to understand monads and stuff, right?

vestal hound
#

I would not write a webapp in Haskell

#

I was thinking like Scala or Rust

#

or F#

solar epoch
#

I wouldn't say Rust is really that functional but I don't use it very often so I dunno

vestal hound
#

I don’t even know Haskell 🥴

surreal portal
#

Or Java

vestal hound
#

but its type system

#

well Rust is imperative @ its core I’d say

#

but it also has a lot of compile time benefits which was more what I was going for

#

and it uses functional ideas like ADTs and pattern matching

solar epoch
#

yeah this is kinda why I hate language ideology, like why use a "pure" functional language when you can just use the best bits?

vestal hound
#

the borrow checker is basically affine typing

primal thorn
#

i have added
def __str__(self): return self.title
to my model but my dropdown for the admin panel is still the same and when i attempt to migrate it says no changes were detected

vestal hound
vestal hound
#

so it won’t appear in a migration

quick cargo
#

I thought the admin panel used the __repr__ of the model

#

unless I forget

vestal hound
#

^

#

is my guess

primal thorn
#

lemme try that

solar epoch
#

Hmm I think it does use __str__() but only if you don't set the fields yourself.

primal thorn
#

nope, the dropdown still displays the object

tepid parcel
#

@quick cargo @solar epoch Well i guess i leave it then for now open accesable API :/ thx for the answers !

vestal hound
solar epoch
vestal hound
#

you should be able to configure it in the form

primal thorn
# solar epoch Showing the admin class might be useful

class SubjectsAdmin(admin.ModelAdmin): exclude = ('status','created_by','modified_by', 'branchid','pastpaper_visibility', 'visible_stat', 'uservisibility', 'solved_papers_visibility', 'untopical_visibilty', 'topical_visibilty', 'topical_books_visibility', 'qbyq_visibilty') list_filter = ('cat_id','title') list_display = ('id','code', 'title', 'cat_id',)

vestal hound
#

actually wait I didn’t read

#

never

#

mind

solar epoch
#

oh is this just for a regular dropdown, sorry, I misunderstood

vestal hound
#

wait

solar epoch
#

you put __str__() on the ExamCategory model, right?

vestal hound
#

it is?

solar epoch
#

I thought you were using autocomplete_fields originally

primal thorn
solar epoch
#

mm, __str__() on the right model should work

#

reload server / etc.? I'm not sure otherwise, would have to tinker with it

primal thorn
solar epoch
primal thorn
#

`
class ExamSubjects(models.Model):
class Meta:
verbose_name_plural = 'ExamSubjects'

cat_id = ForeignKey('ExamCategories', default=None, null=True, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
code = models.CharField(max_length=255,default=None, null=True)
description = models.CharField(max_length=255, default=None, null=True)
created_at = models.DateTimeField(auto_now_add=True, null=True)
modified_at = models.DateTimeField(auto_now=True, null=True)
created_by = models.IntegerField(default=None, null=True)
modified_by = models.IntegerField(default=None, null=True)

def __str__(self):
    return self.title

`

solar epoch
#

That's where you need the str

primal thorn
#

omg that was it

#

i thought i had to put it in the model where i used the foreign key

#

thank you so much

solar epoch
#

nah 'cause it's showing the name of the category in the dropdown

#

no worries

native tide
#

hi guys

#

can anybody explain me

#

how to create a plan for a website

solar epoch
primal thorn
#

another question i have is how do i set a custom name for my the name for my admin panel fields , for eg i have a field named body but i want it to be named description in the admin page

solar epoch
native tide
solar epoch
#

well it wouldn't be that much work, but it's probably still annoying to write a custom form if you don't have to

primal thorn
#

i manually deleted a table from my db and when i try to migrate it says the table does not exist, how do i fix this 😅

solar epoch
#

or you can manually create the table from sql

primal thorn
#

okay thanks

#

thankfully there’s nothing important on it

opaque rivet
#

That sometimes works for me, but most of the time I also just nuke my database

primal thorn
#

i nuked it and everything is working now

surreal portal
#

I don't really understand some methods from Django Field values

primal thorn
#

how do i make it so that for a foreign key it shows a specific field and not the id

surreal portal
#

Aren't get_db_prep_value() and get_prep_value() redundant? I just want to pass an array as a BYTEA field

#

So far it looks like this:

class NumpyField(models.Field):

    description = "A Numpy array from bytes"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def db_type(self, connection):
        if (
            connection.settings_dict["ENGINE"] == "django.db.backends.postgis"
            or connection.settings_dict["ENGINE"] == "django.db.backends.postgresql"
        ):
            return "bytea"
        else:
            return "varbinary"

    def from_db_value(self, value: Any, expression, connection):
        if not value:
            return value
        out = io.BytesIO(value)
        out.seek(0)
        return np.load(out)

    def to_python(self, value: Any) -> Any:
        if isinstance(value, np.ndarray):
            return value
        if value is None:
            return np.ndarray
        out = io.BytesIO(value)
        out.seek(0)
        return np.load(out)
solar epoch
#

it'll hit the datbase for each row though, so you might want o use select_related on the queryset

native tide
#

I want someone to help me Dm Me For help Pls

primal thorn
solar epoch
proud lintel
#

How can I create subdomain for each user in django?

#

Like as website opens in GitHub or wix and lot more

solar epoch
dusk aspen
#

Hey, so i have made a registration form and i would like to access the username that the user submitted as a variable. How would i do that?
This is my main.py: ```python
from flask import Flask, render_template, url_for, flash, redirect
from forms import RegistrationForm

app = Flask(name)
app.config['SECRET_KEY'] = 'fdc00fc2de7015cd9477a90b7de191a9'

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

@app.route('/about')
def about():
return "About"

@app.route('/register', methods=["GET", "POST"])
@app.route('/', methods=["GET", "POST"])
def register():
form = RegistrationForm()
if form.validate_on_submit():
flash(f"Account created for {form.username.data}!", "success")
return redirect(url_for("home"))
return render_template('register.html', title='Register', form=form)

if name == 'main':
app.run(debug=True)

my `register.html`: ```html
<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
    <title>Flask Forms</title>
</head>
<body class="bg-dark text-white">
    {% block content %}
        
    {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
          {% for category, message in messages %}
            <div class="alert alert-{{ category }} text-center">
              {{ message }}
            </div>
          {% endfor %}
        {% endif %}
    {% endwith %}

    {% endblock %}

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
</body>
</html>```
and my `index.html`: ```html
{% extends 'layout.html' %}

{% block content %}
    {{ form.hidden_tag()}}
    
{% endblock %}
coral pelican
#

We can access the input data on form with request.form.get("<name of input tag to get>")

#

You have to import request class from Flask module

#

To request data from the form

#

Hope this answer is correct........and fulfil your needs

solar epoch
#

Um, do you mean, like firefox's source code for example? Or something else?

#

I'm not sure what you're hoping to find from it :)

#

which is basically unbranded google chrome

cunning crane
#

hey guys! I am planning to start web development and I do not have any experience (in web development not in coding) why should I use python instead of html and css?

solar epoch
cunning crane
#

so what is python for?

solar epoch
#

for dynamic content

#

so reading something from a database, doing calculations, deciding which pieces of html to show, ...

cunning crane
#

and which library should I use?

#

django?

solar epoch
#

If you're new it's a good choice I think

unreal eagle
#

learn javascript

#

React

cunning crane
#

why?

solar epoch
#

that's very subjective

#

react is just a js framework for making stuff reactive

#

if you're a beginner to web stuff you should maybe not worry about it too much

high star
#

you can update text dynamically in javascript

#

must learn if you want to get into web dev

solar epoch
#

learning JS is probably necessary but you don't necessarily need to learn react

#

frontend frameworks are highly subjective in any case

#

you can create useful websites without needing any JS, it's mostly for making a nicer UX

cunning crane
#

then what I see here is I definitely should start with html and css, I need them anyways

solar epoch
#

yeah

cunning crane
#

OK

#

thanks

solar epoch
#

you don't even need to know a lot of CSS really, it's not a programming language, it's for declaring layout

#

and HTML is super simple, it's just markup

cerulean badge
solar epoch
#

I wouldn't say any is really better than the other, depends what you prefer I guess ¯_(ツ)_/¯

loud remnant
cerulean badge
solar epoch
#

As long as you can read it and it doesn't turn into a mess at some point I think it's fine

cunning crane
#

It seems nice 👍

loud remnant
#

It's all in one
Intro into programming then some web with python too

foggy summit
#

hi what do you recommend instead of spaced keys with commands/texts?
"great racing game": showText
js, objects
array with commands?
like tasks: ["great racing game", "second", "third"]
I'm making sth like this u type the text and result is given
currently I have like this:

const tasks = {
   "great racing game": showText,
   "show car": showCar,
   "update os": updateOs,
    "show popup": showPopup

}```
the keys are mapped to user input
native tide
#

how can i do web scraping? i want to take for example btc value

surreal portal
#

But for webscraping, you have requestsand bs4(stands for BeautifulSoup)

#

For more advanced webscraping there’s Selenium (for JS) and Scrapy. But the most appropriate section I think is #data-science-and-ml

#

I think. I’m not sure bc webscraping is more for gathering data

eternal glade
#
import requests
response = requests.get(TICKER_API_URL+'btc')
response_json = response.json()
return float(response_json[0]['price_usd'])
native tide
#

i just want to get some cryptocurrency values

surreal portal
#

Check if the status code is 200 for more safety

native tide
#

and dont know how to do it

eternal glade
#
import requests
TICKER_API_URL = 'https://api.coinmarketcap.com/v1/ticker/'
def get_latest_crypto_price(crypto):
    response = requests.get(TICKER_API_URL+crypto)
    response_json = response.json()
    return float(response_json[0]['price_usd'])
get_latest_crypto_price('bitcoin')
surreal portal
# native tide and dont know how to do it

These infos are available on APIs so you have to find one that you can use, then request an API token (to use the API). Once it’s done you can use the requestslibrary to extract the information you want

eternal glade
native tide
eternal glade
naive rock
#

So how can one bypass 403 response - Forbidden error. The server understood the request, but will not fulfill it.

#

I make the request to google that returns 200. But I am making request to another website that 403.

#

When I open the same url in incognito, that website still opens.

#

I have done the following, but neither worked

response = requests.get(url)
response = requests.get(url, auth=(username, password))
scarlet spoke
#

hello

#

i need help on basic css

solar epoch
#

I suggest you ask the question then

scarlet spoke
#

my bad

#
body {
    background-image: url("mai_sakurajima.jpg");
}
#

this is my css code

solar epoch
#

yep, looks ok

scarlet spoke
#

OHHH WAIT

#

IK WHY

#

dangg

solar epoch
#

glad I could help :)

scarlet spoke
#

i had my styles.css in my css folder

#

but my picture was in the project folder but right outside of it

#

dang

#

ty

mossy marlin
#

hey this isn't really a python question but hopefully someone has a quick answer: I have a web app running locally, on localhost:portnumber. I keep forgetting what the portnumber is. is there a way to make it so I can type localhost/my-app in my browser and have it go to that port instead

#

or my-app.localhost or something

#

just giving the port a name

#

im on ubuntu

mossy marlin
#

yeah bookmarking is probably simplest

glad creek
#

Hello folks how do I add /health as an endpoint which responds to GET requests with status-code 200?
I have no clue

glass badger
#

Does anyone have any good tips for a Django CMS when building a blog? Is the best way to post the blogs through the admin panel?

#

Or creating individual blog posts via static HTML files?

solar epoch
surreal portal
#

Does anybody have a good ressource for DRF especially for FastAPI/Flask-RESTful users? I must admit putting classes everywhere confuses me a little bit

#

Ie, how would an @app.get would work with these ApiViews?

zenith yacht
#

single backend endpoint that returns paginated data (needs to actually return paginated data) and a frontend to fetch that data (doesn't need to display response, just fetches the data)
May 20, 2021

surreal portal
foggy fiber
#

Could someone explain to me how I might get "oEmbed" working with Flask? I see there's a method using .json files, but that doesn't seem wise to do with Flask

sturdy rapids
#

I am using selenium to make a script it is also using a chrome driver

#

Now that script is running on my machine

#

Any way to host it on some server

#

To run

#

Because it closes as I close my PC

naive rock
#

When would this happen if requests.get and asyncio with aiohttp would take roughly about the same time?
If asyncio and aiohttp isnt set up properly?

#

Or could companies or developer who designed the api, limit the threshold/limit to how many requests can be made per second?

#

Made 55 requests, requests took 189 seconds
asyncio with aiohttp took 206 seconds

glass badger
solar epoch
solar epoch
solar epoch
surreal portal
#

Meaning the intermediate stuff gets done there

solar epoch
#

and from JSON to the ORM, yes.

sturdy rapids
solar epoch
#

though they don't strictly serialize to json, you can render that data as a csv, say.

small forge
#

Hi there. Anyone free to do a hobby python project with me?

solar epoch
surreal portal
#

Because I’d like to handle authentication and authorisation based on user roles

#

Like who sees what

sturdy rapids
leaden widget
#

does anyone know how get a variable from another file to my webpage ? or can you directly create variables in the web page itself (in Django)

surreal portal
#

I prefer using Selenium with Firefox bc Chrome is a pain to test with

solar epoch
surreal portal
#

The thing is: I have the data, I have an idea for an endpoint and who should see what, I just don’t know where to start lol.

#

For now the only endpoint is a list of prediction points you can see according to multiple filters

solar epoch
#

ok, you might want to look at APIListView and depending on how much filtering you need, you can do it manually, but probably better to use the django-filter package, it has a nice integration with DRF.

#

If what you want to list isn't as simple as a bunch of database rows from the same table, it might not work for you, but if it does, then it should work

#

for the permissions, you make a class and stick it in the view class as an attribute

surreal portal
solar epoch
#

if you're just listing stuff, the serializer is more or less just there to determine which fields you want to output

solar epoch
surreal portal
subtle otter
#

hello , i got a flask route that return this return jsonify({'webshellFiles' : webshellFiles, 'normalFiles' : normalFiles}) and those two are arrays , how can i them in response variable in fetch pls?

noble spoke
#

fetch you mean the fetch api in js?

#
async () => {
  const response = await fetch(...);
  const data = await response.json();
  // now access them as you would a regular object 
};
#

after you do the response .json() you can destructure

async () => {
  const response = await fetch(...);
  const data = await response.json();
  const { webshellFiles, normalFiles } = data;  
};
uncut spire
#

in FastAPI, if i create a cache singleton instance on startup, how to i access it from within a router?

primal thorn
#

is there a way i can make a dynamic dropdown menu based on a selection from another dropdown

#

for eg, when i select a continent, only countries from that continent will show in the country dropdown

wooden ruin
# primal thorn for eg, when i select a continent, only countries from that continent will show ...

you could use a frontend framework for this. let's say you have your continents and countries stored like this:

const data = {
  "north-america": ["USA", "CANADA", "MEXICO"],
  "europe": ["FRANCE", "SPAIN", "ITALY"],
}

then, you can use data binding to bind the country options based on the continent. here's a vuejs example

<select v-model="continent">
  <option v-for="country in data[continent]" v-model="_country">{{ country }} </option>
</select>
primal thorn
#

thanks, ill look into it

primal thorn
#

im trying to make a custom field in the admin panel, i used the format the docs gave which is ```python
change_form_template = 'admin/myapp/extras/openstreetmap_change_form.html'

but it still does not work
#

my path is ```python
change_form_template = 'admin/Papers/extras/Papers_change_form.html'

covert kernel
ionic raft
#

Flask help. Why doesn't adding /blog to the url work in the following snippet? what am I missing?

from flask import Flask, render_template

app = Flask(__name__)


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


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


if __name__ == "__main__":
    app.run(debug=True)```
#

^ is driving me bonkers!

#

/blog gives me a 404. The html file exists

#

In fact, if I reverse it and place it as the file for the / it works just fine

#

The index and blog file are in the same Templates dir

#

I've accomplished with other projects...and I can't see what I'm missing...

#

Are you sure you want quotes in that query?

#

And if you do, add one to the end

#

Are you querying an API? does the documentation list how it wants to receive that element?

#

While the YYYY-MM-DD is a string, typically, I use a dictionary to build the query and then tack it on to the end.

#

Well, that's good since you control the methods 🙂 Add a double quote to the end though

#

Be consistent. Quotes all around or none

#

As for using a dictionary....

#

Assuming requests imported...

parameters = {
    "key1": VALUE,
    "key2": VALUE2,
    "formatted": 0
}  # or whatever other key:value pairs you require for the method.
response = requests.get("https://api-endpoint-url.com", params=parameters)  # and whatever method required obviously
response.raise_for_status()
working_var = response.json()  # Now I have what I need in json format :)
#

I find loading a dict for parameters makes it INFINITELY easier to manage method calls

#

Python takes care of building the query for you

#

I'd start with the documentation. But scanning that I'd start with...

parameters = {
    "date_from": date_from_var,
    "date_to": date_to_var,
}```
#

once you load dictionaries for parameters in API calls you can never go back though 😉

#

Now, I don't have experience with Django yet and I'm only on day 56 of a Python boot camp...so don't take that as gospel

#

I'm just learning Flask. Django comes later 😉

#

Only day 56.

#

57 days ago I knew none of this...so noob

#

Well I'll be....turns out '/blog' must be reserved in Flask!

native tide
#

how can i make my own web framework

exotic viper
#

in Django request.POST returns a dictionary, but what dictionary though?

limpid pivot
#

where can i host the django app with celery and redis except heroku. My problem with heroku is it asks billing information for Heroku Redis which I do not have.

inland oak
#

hetzner is good

#

(requires knowing how to deploy in linux on your own)

#

they just provide server OS of your choice

#

there free tiers in some providers

prisma orbit
native tide
#

Anybody here who can help me out in html ,css who knows it well

covert kernel
#

I have a list of items which are put into a dropdown, how can I pass the selected value and filter the list accordingly? I am using starlette/fastpi

rugged charm
#

so u'll have to create an & query.....firstly you'll have to convert the date received from string to a date or datetime object depending on your model
then u can use in your query filters
model_name.objects.filter(created_at__gte=<range_start_point>) & model_name.objects.filter(created_at__lt=<range_end_point>)

whole spear
#

How to retrieve data from onChange (storage listener) with js in Selenium?

solar epoch
#

This doesn't seem like much to do with web development

topaz basin
#

oh no

#

sorry i didn't notice

surreal portal
#

Ok I'm confronted to a difficulty with DRF. I have a Numpy array stored as Bytes in the DB. With my models I can retrieve it just fine. My question is how should I serialize it

native tide
#

not really web development, but whats the standard for applications that hold data offsite? Should every query on my client request the server, or should i request for changes?

surreal portal
#

Like, should I create an image through a function from that np array, then return the URL serialized?

#

As a sort of cache

solar epoch
surreal portal
#

numpy arrays can have multiple dimensions. What I'm trying to do is reconstruct an image when I make an API call

#

Decided to store the np array as a BYTEA column because it was small enough

solar epoch
#

hmm, well, it's possible to have n dimensions in a DRF ListField but I think you need to know the number of dimensions in advance

#

e.g. for a 2d array you can do ListFielf(child=ListField(child=FloatField())) or so

surreal portal
#

During serialization

solar epoch
#

oh yeah you can do stuff like that

#

check out SerializerMethodField

surreal portal
#

I want to provide some sort of cache to avoid making too much

solar epoch
#

you can implement the cache however you like, with Django's cache framework or maybe something simpler.

#

(though django's cache framework is already quite simple)

native tide
solar epoch
#

yeah if they're stored you can just cache the url directly in the database

native tide
#

yep, and if they are supplied you can construct some sort of hash -> filename table

#

and maybe have something delete rows and files after X time not accessed?

surreal portal
native tide
#

if they are fixed then you should probably create the images at insertion

solar epoch
#

I would just do that translation on save

native tide
#

and delete them at delete

solar epoch
#

Assuming it's read more often than written anyway

native tide
#

yeah, if they are fixed

surreal portal
#

Yeah i planned to keep the data stored in bytes just in case I could exploit heatmaps on a JS frontend

#

or any JS structures illustrating SVG-like imgs

native tide
#

mm, disregard all i posted, i think i misunderstood what you were talking about

surreal portal
#

Btw I encountered a session_error when I started the API. What happens exactly when you make migrations when the table already exists?

#
ProgrammingError at /api/
relation "django_session" does not exist
#

My Docker entrypoint script looks like this btw:

#!/bin/bash

# Run Django server with DB init
python manage.py makemigrations

# Migrate
python manage.py migrate

# Runs the server
python manage.py runserver 0.0.0.0:8000
solar epoch
#

you probably shouldn't run makemigrations or migrate from a Dockerfile

#

migrate is maybe ok but you should run makemigrations manually

#

sometimes it can prompt for input, for example

#

also if you're not usually a volume the migrations won't necessarily end up in your local filesystem

surreal portal
surreal portal
# vestal hound hm

it was small enough so I thought I should keep it that way + it can be reusable for a frontend framework

chrome reef
#
class User(AbstractUser):
    
    """ User model """
    username = None
    first_name = None
    last_name = None

    email = models.EmailField(unique=True)
    is_active = models.BooleanField(default=False)
    is_employer = models.BooleanField(default=False)
    company_name = models.CharField(max_length=50, blank=True)


    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = []

    def clean(self):
        if (is_employer == True and company_name == ""):
            raise ValidationError("Employer must fill out company name")
#

Why isn't the clean function do anything in my model when I try to add something trough the REST API?

solar epoch
dapper solar
#
 <form method="post" action="{{url_for('delete',post_id=post.id)}}">
<label class="form-check-label" for="addToDb">Watched already?</label>
 <input type="submit" value="Drop"  class="btn btn-danger" name="dropIt">
</form> ```
#

i am getting an error that post_id is missing although i passed it in url_for

surreal portal
#

Found this nice extension for geospatial data

swift sorrel
#

Hi ! I try to open my quart web server in my browser but it's not working... Here is my code :

app = quart.Quart(__name__)
ipc_client = ipc.Client(secret_key=TOKEN) 

@app.route("/")
async def index():
    member_count = await ipc_client.request(
        "get_member_count", guild_id=840333999003533432
    )  # get the member count of server with ID 12345678

    return str(member_count)  # display member count

if __name__ == "__main__":
    app.run(host="localhost", port=8000)
#

(you can ping me if you have any idea)

surreal portal
swift sorrel
swift sorrel
#

i fixed my issue, but i now have another error...

OSError: [Errno 10048] error while attempting to bind on address ('0.0.0.0', 20000)
gritty cloud
swift sorrel
#

found the solution

gritty cloud
#

try another port

swift sorrel
#

i just add

if __name__ == "__main__":
    client.ipc.start()
#

and it's working

wintry cape
#

need some help deploying a fastAPI dockerized backend (with docker-compose too) to heroku

fading gazelle
#

I was doing a tutorial on flask(https://www.youtube.com/watch?v=dam0GPOAvVI&t=5894s)
but I got an error but all is well don't know why

In this video, I'm going to be showing you how to make a website with Python, covering Flask, authentication, databases, and more. The goal of this video is to give you what you need to make a finished product that you can tweak, and turn into anything you like. We're going to also go over how you create a new user's account, how you store those...

▶ Play video
#

error:

#
PS C:\Users\admin\Documents\Flask> & C:/Users/admin/AppData/Local/Programs/Python/Python39/python.exe c:/Users/admin/Documents/Flask/main.py
C:\Users\admin\AppData\Local\Programs\Python\Python39\lib\site-packages\flask_sqlalchemy\__init__.py:872: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
  warnings.warn(FSADeprecationWarning(
Traceback (most recent call last):
  File "c:\Users\admin\Documents\Flask\main.py", line 3, in <module>
    app = create_app()
  File "c:\Users\admin\Documents\Flask\website\__init__.py", line 28, in create_app
    login_manager.init_app(app)
TypeError: init_app() missing 1 required positional argument: 'app'
PS C:\Users\admin\Documents\Flask> 
#

please help me I cant find it why is like this

#

Flask/main.py:

from website import create_app

app = create_app()

if __name__ == "__main__":
    app.run(debug=True)
naive rock
#

Does aiohttp and asyncio have built in try and except to make a request again upon failure?

modern verge
#

I'm not sure if this is web development but what ever.
I have a site that has a lot of pictures and I want to get those pictures but they have to load first. How can I make a request that waits a little bit until the website is loaded?

native tide
#

is there any way for me to remove the selection of this?

#

So people can't select the text?

calm plume
distant charm
#

hello people

#

need some help with widget

coral lotus
#

That's what we all want to know

sonic island
primal thorn
#

How do I make a dependant drop down list for the admin panel

#

For eg, when the continent drop down is selected, only countries from that continent show up

native tide
cold socket
#

I have a flask app that I want to use to access another server remotely. Is it best to SSH into that server or run another flask app on that server and just hit endpoints there?

outer dawn
#

Hey folks, I'm working on a Python tutorial titled "We developed a CMS web app from scratch in Python to host this Python tutorial on how to build this CMS web app"

This is trying to teach people how to build web apps in Python. To make it more fun, we developed a web app from scratch to host the tutorial, and the tutorial content is about how we build the tutorial web app. May I have some feedback on the tutorial title? I want to make it sounds like a tongue twister, but the current one might be too long... Thanks in advance!

outer apex
# primal thorn For eg, when the continent drop down is selected, only countries from that conti...

There's a couple of ways I can think of and both require some JS.

  1. On the continent select change, submit the form as is, and then reload the page with the given continent so that the countries dropdown is populated. Downside is the page reload - can be very heavy handed and UX is not great.

  2. On continent select change, submit a request to some URL that can provide you a list of countries for a given continent. With the countries returned, dynamically populate them to the countries select.

dull mango
#

Hello,
In my project I created an app that will only take care of updating the database in relation to the data received via socket. I have currently started writing code for this in views.py, although I would like to create a dedicated file for this purpose. Essentially the problem is that in the console I read the following strings:

(8180) wsgi starting up on http://0.0.0.0:5000
(8180) accepted ('127.0.0.1', 50224)

however the event handlers in views.py seem not to exist, as after connection I don't receive any message in the console.
I'm not actually able to figure out if I need to invoke something somewhere or add more in wsgi to get the event handlers in question to work.
I hope for some advice that can help me continue.

wsgi.py

import os
import eventlet
import socketio
import eventlet
import eventlet.wsgi
from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'discordwebsite.settings')

application = get_wsgi_application()
sio = socketio.Server()
application = socketio.WSGIApp(sio, application)

eventlet.wsgi.server(eventlet.listen(('', 5000)), application)

views.py

from django.shortcuts import render
import socketio
from .models import User

sio = socketio.Server()


@sio.event
def connect(sid, environ, auth):
    print('connect ', sid)


@sio.event
def disconnect(sid):
    print('disconnect ', sid)

balmy leaf
#

where or what do people use to create website/app mockups?

mint folio
karmic flare
#

Can I get a bit of help with flask-socketio?

I have an iframe that is feeding info from a text file to the client but am told using sockets would be better / more efficient.

I'm looking at the docs and I just can't translate what I've got right now to what I need.

distant trout
#

xss attacks are only possible through setting inner html? right?

#

so just avoiding all inner html is safe against xss?

wooden ruin
next oasis
#

I'm having trouble installing kivy on my mac os

#

any solututions I'm on the kivy website but i can't succesfully interpret it

primal thorn
dawn heath
tidal dock
#

How to soleve this problem

wet latch
#

what is this?

primal thorn
#

how do i link my layout to a file in my root directory for django

outer imp
#

it is Django admin panel

desert estuary
#

https://youtu.be/UIJKdCIEXUQ?t=1935
im following this guy here
and doing what he's doing and still the alert in the bootstrap doesn't pop up

In this Python Flask Tutorial, we will be learning how to create forms and accept user input. We will also learn how to validate that user input and notify the user if the input was invalid. Let's get started...

The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Python/Flask_Blog

✅ Support My ...

▶ Play video
primal thorn
#

setting a file field to "null=True" does not work

desert estuary
solar epoch
primal thorn
#

nope it dosent

#

i had to make it python blank=True
for it to work

solar epoch
#

well I don't know what you mean by doesn't work

#

blank is mostly used for forms, where null is more for the database

gritty cloud
#

If ur using js

#

Then you can call the document.ready event

#

document.ready = function whatever()

regal spruce
#

Hello
I'd like to know if u can add notifications alert in the django admin panel for it to show like unread requests etc

ember adder
#

Is there an equivalent in Django to Laravel Shift, where you pay a fee to have automatic version bumping to latest version

solar epoch
#

I can't imagine that's super reliable.

#

I'm not aware of anything, in any case

ember adder
#

Yes, it sends you a PR that you need to approve, it makes checks that everything works fine and bumps it.

solar epoch
solar epoch
#

But does it make code changes? e.g. if a function has been deprecated, will it update it to something that works? Or does it only bump the version?

#

If it's just the latter, dependabot does this for free.

ember adder
#

I just discovered that, I don't know. I was just wondering if such tool exists

solar epoch
#

I'm not aware of anything in any case - but if it's just sending a PR with the versions bumped, github can do it for you. I'm not sure if you're using something else.

mint folio
#

Actually looking at the package it does slightly more than just bump the version.

solar epoch
#

and there are also third party paid solutions, if you want something specific

#

Hmm yeah it does update code. There's nothing like that, no, and personally I wouldn't trust an automated upgrade even if the CI passes.

violet dock
#

anyone know what is causing this error? error: <class 'FileNotFoundError'>, [Errno 2] No such file or directory: file: /usr/lib/python3/dist-packages/supervisor/xmlrpc.py line: 560

ember adder
#

Forgot to activate a virtual environment?

high star
#

Should i learn javascript before react or is it fine just going to react straight away?

inland oak
#

I thought to learn css first)

#

then javascript

#

then react

#

it looks like fundamental approach, so I go with a longer, but hopefully with better in quality path

calm plume
#

But you don't need to learn too much JS, just the basics

west peak
#

Hi guys, i have a little doubt it's about the fetch function

calm plume
#

You should always be able to make a site with HTML and CSS before you venture into the JS world

west peak
inland oak
calm plume
#

Absolutely

#

And integrating Django's DB wonderfulness with React is also really nice

inland oak
#

I plan to go into CSS (and later into javascript) with Head First books

#

after finishing learning patterns with them, I can say they are awesome and really brain friendly)

#

So I have big hopes for their other books

#

the only doubt I have

#

thinking with reading them in online

#

or getting them as real books

stoic lark
inland oak
#

real books are nice, can be read in a park, while relaxing from pc

stoic lark
#

anyone can help for add queue system b?

wary lake
#

Hi, does anyone know that how to add reCAPTCHA to flask project which is working in pythonanywhere ?

autumn hedge
#

what issue are you having? @wary lake

#

reCaptcha is JS powered not Flask

spiral gate
#

Adding to the list of people who need help, can somebody please help me installing psycopg2 on windows?

#

I'm not getting any progress since most solutions are for linux systems

autumn hedge
#

@spiral gate try using WSL

spiral gate
#

whats that

#

oh i see

#

to get linux

#

but you gotta register for that thin

dawn heath
#

how to build a orm query where says if the model doesnt exist (object) add , but if exist then change the modified fields?

from demo.models import Person
update_values = {"name": "Alice", "age": 12, "is_manager":False}
new_values = {"name": "Bob", "age": 25, "is_manager":True}
obj, created = Person.objects.update_or_create(identifier='id',
                                               defaults=update_values)
if created:
    print(f"created {obj}")
else:
    print(f"updated {obj}")
hexed scaffold
#

anyone here know how to web3 into the blockchain?

#

using python

#

i need help for a project im doing

ember adder
#

In Django, I have a model for a JobOffer and it can have a 1 or more positions available for the offer. I have a table, WorkerJobOffer that link a Worker object and a JobOffer object. I need to limit the number of WorkerJobOffer objects to the number of positions available for its JobOffer object.

Should I implement that behaviour in the model, the view or the form?

dawn heath
#

how do I perfrom a upsert in django?

eternal adder
#

dddd

twin hamlet
#

Hello I am working with django
the messages are not showing up after the condition is satisfied

jade lark
ember adder
#

I don't know what's that. Could you give me some pointers?

After thinking about it, since we always create new objects in the view after checking the form cleaned_data, I should just prevent the creation in the view and inject a ValidationError in the form saying you can't add more objects.

rugged charm
jade lark
ember adder
ember adder
jade lark
twin hamlet
#

is anyone here knows about django ?

ember adder
jade lark
#

Ahh I understand now. Ignore me on the crud file as that wouldn't work very well. Do not do this on a view as you might need to replicate it across multiple different views.

#

You'll want to add this functionality/check on the model itself. That way you're not repeating logic throughout your code base (or forgetting to check)

ember adder
#

That's a very good consideration I didn't take into account. I could override internal object creation function and make it return the newly created object of None. If None is returned, it indicates me there's a problem so that I can properly handle that in the view and the form.

jade lark
ember adder
#

so that in my view I would try/catch the object creation and handle it?

jade lark
ember adder
#

IIRC the save() method of Model is where the stuff happens before it is included in the DB. I need to figure out what kind of error I shoudl raise

jade lark
ember adder
#

Good. I'm a bit rusty on raising custom exceptions, I'll dig back into that. Thank you for your help @jade lark it helped me a lot!

jade lark
ember adder
#

Gotcha!!

jade lark
#

@ember adder
You would then raise it like if a conditional check fails or passes.

if total_positions < current_jobs:
  raise InvalidJobPositionsException("The provided positions is invalid")
ember adder
#

Thanks for the refresh. I'll give this a try.

runic sparrow
#

I've got a basic Flask "Hello World" setup, but apparently for production it's best to use something called "WSGI". According to the guide I'm following, I make a file called wsgi.py in my project root directory. However, I have Git in there, and that dirties things up. Should I:

  1. Add it to Git (maybe bad because this file could change across deployments?)
  2. Gitignore it
  3. Make the file somewhere else?

Thanks in advance!

ember adder
jade lark
desert estuary
#
class form_call(FlaskForm):
   username=StringField('Username',validators=[DataRequired(),Length(min=5,max=25)])
   email=StringField('Email',validators=[DataRequired(),Email()])
   password=PasswordField('password',validators=[DataRequired(),Length(min=8)])
   Password_confirmation=PasswordField('Confirmation_password',validators=[DataRequired(),EqualTo('password')])
   submit=SubmitField('sign-up')

class log_in_call(form_call):
   submit=SubmitField('log in')
   remember=BooleanField('remember me')
   logger=StringField('Username or Email',validators=[DataRequired(),EqualTo(form_call.username or form_call.email)])

the error displayed is kinda ugly for the username or email section also idk if the username or email will validate in that section idk if it's working the logic is there
check on the code idk if that might be the problem or something no ? i think that might be the thing even tho the logic is there cuz i want the logger thing to be equql to either the form_call.username or form_call.email
he might be able to either enter the email or the username so he can log in

native tide
#

Is the style tag part of html or css?

calm plume
late stone
#

i am facing a NoReverseMatch at /app/ issue for the last 4 hours

#

already check my url patterns or any argument or keyword arg in urls.py

#

i just cant see whats wrong with the code. is there any way someone can hop on my Teletype address and take a look at the code since i have a bunch of files

#

thank you in advance

dusk portal
inland oak
#

can read something in addition of a more beginner friendly nature

hybrid dome
#
from flask import Flask, render_template
app = Flask(__name__)

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

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

it says template not found BUT IT IS THERE

#

help me

grand harbor
#

what is the structure of your directory

hybrid dome
#

um lemme show

#

@grand harbor

dusk portal
#

ik good at flask how can i help @hybrid dome

grand harbor
#

instead of template.html make a templates folder and put that template,html in it

hybrid dome
#

ohh alright

dusk portal
inland oak
#

and well, do everything for it

hybrid dome
#

alright it is working now ig

#

I'm not really good in html

dusk portal
#

ok

hybrid dome
#

can i get help related to html

dusk portal
hybrid dome
#
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello World</title>
</head>
<body>

</body>
</html>```
#

dont u think the output should be hello world

#

it doesnt shows anything in website

inland oak
hybrid dome
#

oh got it

inland oak
#
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello World</title>
</head>
<body>
Hello World
</body>
</html>
hybrid dome
#

it works

#

is python easier than html?

inland oak
#

python is python.
using python would be similar to javascript a bit

hybrid dome
#

oo

inland oak
#

html is not really a real programming language
hardly can be compared

hybrid dome
#

yes

inland oak
#

it usually goes with
html+css+javascript

hybrid dome
#

front end

#

will pycharm show if there is any error in my html

ivory bolt
#

I HIGHLY recommend using heroku -- deployment is GREAT with git and for python files.

inland oak
#

xD, I saw people who said exactly the same, but with one extra word
"I HIGHLY don't recommend using heroku"

glossy scroll
#

hey guys

#

can someone help me out here?

grand harbor
#

well if you are not developing a software on multinational level company then of course its safe

glossy scroll
#

i have two models Player & Team

#

and i want to invite the player to the team

#

i can do the logic behind invitation but i have no idea how to create a unique , validate able hash/ token

#

<@&267628507062992896> is this allowed?

grand harbor
#

!rule 5

lavish prismBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

glossy scroll
#

I was talking about this guy, telling me to download cheats or smting

glossy scroll
grand harbor
#

uuid

grand harbor
glossy scroll
#

can you elaborate a bit?

#

I've only used the default django passwordauthtokengenerator

#

so im a bit new to tokens and stuff

chilly falcon
#

can any guide me learning about class base view in django?

#

tutuorial or any thing

glossy scroll
chilly falcon
#

thanks

glossy scroll
#

it gives you the details of all the parent classes with methods and such

#

just grab one method like get():

#

and do your logic between the super() function

chilly falcon
#

ok if we use super() it help us to modify that methods ?? isn't it?

primal thorn
#

how do i make my email unique in my forms , ```python
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(help_text='required', label='E-Mail')

glossy scroll
glossy scroll
spiral gate
#

I'll try it here as my last resort, I'm running into a problem with my django project and psycopg2 as it doesn't seem to connect properly. Psycopg2 is installed on my OS and in my django project.

    self.connect()
  File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\backends\base\base.py", line 194, in connect
    self.connection = self.get_new_connection(conn_params)
  File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\backends\postgresql\base.py", line 178, in get_new_connection
    connection = Database.connect(**conn_params)
  File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\psycopg2\__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError

in my settings.py i have it connected via

primal thorn
vestal hound
glossy scroll
#

yes this

primal thorn
vestal hound
primal thorn
vestal hound
#

hm

glossy scroll
#

Are you using the base django User model ?

vestal hound
#

I believe (but am not sure) that email should be unique already

primal thorn
glossy scroll
#

or did you extend the base model?

vestal hound
#

if you're using it

primal thorn
#

its the default, i havent changed anything in it since creating the project

glossy scroll
#

You need to extend the base model and make the email unique

#

because by default only the username is unqiue

vestal hound
#

oh hm by default email can be blank right

#

I guess that means it doesn't have to be unique

primal thorn
#

thanks ill look into it

spiral gate
vestal hound
#

are you sure Postgres is running?

spiral gate
#

yeah it is

#

wait a sec

#

i mean postgres pretty sure is running everytime i did it

#

but now I've been thinking about using an external python script where psycopg2 may work and connect that to the django project afterwards

#

i mean when i tried starting my server with the shown settings it showed this ```System check identified no issues (0 silenced).
Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x04975148>
Traceback (most recent call last):
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run
self.check_migrations()
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\core\management\base.py", line 442, in check_migrations
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\migrations\executor.py", line 18, in init
self.loader = MigrationLoader(self.connection)
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\migrations\loader.py", line 49, in init
self.build_graph()
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\migrations\loader.py", line 212, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\migrations\recorder.py", line 61, in applied_migrations
if self.has_table():
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\migrations\recorder.py", line 44, in has_table
return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor())
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\backends\base\base.py", line 255, in cursor
return self._cursor()
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\backends\base\base.py", line 232, in cursor
self.ensure_connection()
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection
self.connect()
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\utils.py", line 89, in exit
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection
self.connect()
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\backends\base\base.py", line 194, in connect
self.connection = self.get_new_connection(conn_params)
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\backends\postgresql\base.py", line 178, in get_new_connection
connection = Database.connect(**conn_params)
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\psycopg2_init
.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError:

hybrid dome
#
<a href="https://www.google.com"><img src="https://www.imagefu.com/86849983-f222-4f81-8bc3-566acefcdb56.png"/></a>```
#

why this doesnt shows image

zealous wagon
#

HI, I have a simple problem.
I wrote this code to redirect a url to another url already provided by view. For test i used a random word like "hola/" . It successfully redirected but after changing it to "people/ " it still redirects to "hola/". I cant figure out the problem 😦

urlpatterns = [
    path('', lambda request: redirect('people/', permanent=True)),
    path('people/',include('people.urls')),
    path('admin/', admin.site.urls),
]

here what show in browser

Page not found (404)
Request Method:    GET
Request URL:    http://127.0.0.1:8000/hola/
Using the URLconf defined in peopletrack.urls, Django tried these URL patterns, in this order:

people/
admin/
The current path, hola/, didn’t match any of these.

You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
inland oak
hybrid dome
#
<a href="https://www.google.com"><img src="https://www.imagefu.com/86849983-f222-4f81-8bc3-566acefcdb56.png"/></a>```
#

WHY DOESNT IT WORKS

zealous wagon
inland oak
#

if we will replace to cat picture

<a href="https://www.google.com"><img src="https://icatcare.org/app/uploads/2018/07/Thinking-of-getting-a-cat.png"/></a>

everything is fine

#

because cats are cool

forest knoll
#

I get a deployment error in heroku

#

how can I solve it

ivory bolt
#

to be fair tho

#

heroku + git --> soulmates

hybrid dome
#

why doesnt mine does

inland oak
hybrid dome
#
<a href="https://www.google.com"><img src="https://www.imagefu.com/86849983-f222-4f81-8bc3-566acefcdb56.png"/></a>```
#

UHHH DOESNT WORKS

forest knoll
#

can anyone help me with my heroku deployment problem...

#

I'm using django

forest knoll
ivory bolt
#

can I know:

  1. What stack are you using
  2. What your working directory looks like
  3. How your Procfile and requirements.txt files are configured
#

@forest knoll ?

#

are you using django/flask to build your app?

fluid dawn
#

Hi, I need some help,, I've hosted django website on windows server 2016,, the website is accessable with the server ip now,,,
How can I add my .com domain to this website?

ivory bolt
#

is it a home server or have you deployed it on Azure or something

fluid dawn
#

Amazon ec2 windows server 2016

ivory bolt
#

Well first, buy a domain.
Then, add it to a list of hosts in your 'ALLOWED_HOSTS'

ivory bolt
#

can you show them to me

fluid dawn
#

Yes I can

ivory bolt
#

great

#

please don't show any credentials of course, protect your privacy as much as you can

fluid dawn
#

This is my iis manager

#

Website accessable with ip

#

Server manager

native tide
#

hello

ivory bolt
#

I'm sorry can you do screenshots

#

this isn't super readable

fluid dawn
#

Thanks 😊

#

I've found the solution

#

I actually have to setup DNS inside AWS

#

Not in the server instance

ivory bolt
#

oh great

#

Well, I have a problem

#

I'm trying to pop up a small flash message every time a new user is created, and i'm having some sort of template error while rendering it.

views.py

class UserCreateView(SuccessMessageMixin ,CreateView):
  template_name = 'users/registration.html'
  form_class = SignUpForm
  success_message = "%(username) was created"

  def get_success_url(self):
    return '../../'

Here's my template (it's a bootrstap sample for now don't laugh cuz there's no dynamic content yet)

home.html

{% if messages %}
<ul class="messages">
    {% for message in messages %}
      <div class="alert alert-{{ message.tags }}">
      {{ message }}
      </div>
    {% endfor %}
</ul>
{% endif %}

Just showed the logic part here

It's giving me a 500 error, any idea what I should do?

tight plover
#

reported

quick cargo
#

<@&831776746206265384> ^^

grand harbor
#

why not use js for alert

ivory bolt
calm plume
#

If you add a script tag, you can call that

grand harbor
#

like there is a sign up button use on click on that button and use the alert function...

ivory bolt
#

so how do I tell my frontend about the signed-up user?

#

will it be 'if request.user.username != "anonymous": `?

#

Plus I want to try the messages feature

#

plus I don't want a dialogue box

slow gazelle
#

any idea why the terminal shows this error? I already installed flask in the virtual enviroment and selected it as the interpreter

#

here is the pipfile

autumn hedge
#

@slow gazelle open terminal and type pip freeze and verify your python environement has that package

slow gazelle
#

should i input that in the pipenv or normal terminal

autumn hedge
#

use the vscode terminal. vscode has assigned your pyenv as 3.8.5 from what i see in your screenshot

slow gazelle
#

yes its there

#

in the windows terminal its not there

#

but it should't be an issue since i'm using virtualenv right?

autumn hedge
#

no, pipenv is your python virtual env and separate from your machines default python environment

dusk portal
#

i dont found anything new in djang0 which i can't do in flask

#

;-;