#web-development

2 messages Β· Page 127 of 1

glad patrol
#

in my html form

#

or anywhere else

supple bramble
glad patrol
#

se this

#

huh not this 1

#

i create 2 fields now

#

height and weight

#

i dont want that user enter bmi

supple bramble
#

okay

glad patrol
#

bmi auto set when user enter height and weight

#

how can i achive this

supple bramble
#

wait

glad patrol
#

ok

supple bramble
#

you have added the height and weight in views.py right?

glad patrol
#

right now

#
    if request.method == 'POST':

        pregnancies = float(request.POST['pregnancies'])
        glucose = float(request.POST['glucose'])
        bloodpressure = float(request.POST['bloodpressure'])
        skinthickness = float(request.POST['skinthickness'])
        bmi = float(request.POST['bmi'])
        insulin = float(request.POST['insulin'])
        pedigree = float(request.POST['pedigree'])
        age = float(request.POST['age'])
        name=str(request.POST['name'])
        date=str(request.POST['date'])
        gender=str(request.POST['gender'])
        mydb = mysql.connector.connect(
            host='localhost',
            user='root',
            password='',
            database='mdss',
            port='3306'
        )
        mycursor = mydb.cursor()
        sql = "INSERT INTO diab (name,gender,date,pregnancies,glucose,bloodpressure,skinthickness,bmi,insulin,pedigree,age) VALUES (%s,%s,%s,%s, %s,%s, %s,%s, %s,%s, %s)"
        val = (name,gender,date,pregnancies,glucose,bloodpressure,skinthickness,bmi,insulin,pedigree,age)
        mycursor.execute(sql, val)

        mydb.commit()```
supple bramble
#

okay so add height and weight like you added other fields, then add
bmi = height*weight

glad patrol
#

then how i set the bmi in html form automatically

supple bramble
#

hmm

#

placeholder?

glad patrol
#

i can calulate but i dont know how to set it on html page

supple bramble
#

placeholder = f'{bmi}'

#

where do you wanna show the bmi ?

glad patrol
#

this is bmi in html page

#
   <div class="col-md-4">
        <div class="form-group">
          <label for="bmi">BMI</label>
          <input
            type="number"
            step=".00001"
            class="form-control"
            id="bmi"
            value="0"
            name="bmi"
          />
        </div>```
#

right now

#

like the value set when height and weight multiply

supple bramble
#

hmm

glad patrol
#

like a user restirct he cant add bmi on its own

#

it auto calculate

supple bramble
#

do something like {bmi} in html

#

might work

#

im not sure

glad patrol
#

where i add this

#

value = {bmi}

supple bramble
#

not sure if it will work, add it in the html page where you want it to show

glad patrol
#

ok i try

#

can i ping you if i get any error

supple bramble
#

sure

vital rapids
#

someone can tell me what should be better?

quartz plinth
#

how do u get a hel pchannel

quartz hedge
vernal furnace
#

Guys can I run my django project from my pc and see it from the phone?

#

I guess no right?

stray spire
#

Yes

#

You can locally host

vernal furnace
#

How

stray spire
#

steps I don't know offhand, but you can google "locally host django project + your system / other details that are unique to you"

#

so add in Windows or Linux

#

or wahtever you're running on

#

and if you want it accessible outside your local network or not, I'd host locally first and check it out via local IPs

quartz hedge
#

You need to get your IP address, and run it over there instead of localhost. Then only people connected to your WiFi will be able to see it

stray spire
#

then worry about opening it up to the world

#

Yep, local network vs world wide

#

I'd recommend getting it up and running locally first, good dry run

#

might satisfy your current needs

vernal furnace
#

Lemme try mm

stray spire
#

then you can look into an rpi or something else with 24/7 capabilities, or use a free online service

vernal furnace
#

That damn page is not pulling up

#

Can you access it ?

#

Ok it opened

quartz hedge
vernal furnace
#

ohhh thank you

#

both

#

πŸ˜„

#

it says getaddrinfo failed

quartz hedge
#

You could try a different port I guess

#

maybe 3000 or 4200 or something

vernal furnace
#

I think the website gave me the wrong ip

#

mm

#

yeah it worked

#
ipconfig
#

Thanks so much guys :D!

velvet vale
native tide
stoic knot
#

how can i allow various fonts from discord in my html file

#

some names are written in a weird way and i get errors

native tide
velvet vale
#

@native tide so what do you advise me how to change? An example if you can see it

native tide
velvet vale
#

I want to automatically display as many such forms as there are questions and the question will be automatically selected. Do you understand?

#

@native tide understand?

swift sky
#

how are you supposed to handle migrations

#

i have a web app that's deployed

#

and im trying to avoid having to use the CLI on the server to make changes

native tide
#

i am currently trying to make a proxy scraper that scrapes proxies from multiple sources, can anyone help?

#

DM ME

topaz lily
#

In flask, if I want to access request data like params, query, headers, etc. do I have to use app.request_context(environment):? What do I pass in for environment, if so?

native tide
velvet vale
#

@native tide Can I write to you in pm if you have time

mortal mango
#

does anyone know why django is telling me disallowed host even though I added my domain to settings.py allowed hosts? ALLOWED_HOSTS = ['207.246.87.164', 'atomlink.tk/', 'www.atomlink.tk/']

indigo kettle
#

idk if this is why but you don't need the /

mortal mango
indigo kettle
#

it is not updating

#

either you're not pushing it properly, or it's being overwritten somewhere else

mortal mango
#

oh

#

how do I restart the nginx server?

swift sky
#

systemctl restart nginx

#

then

#

systemctl status nginx

#

@mortal mango

mortal mango
#

ok

#

how do I update it?

#

I did systemctl restart nginx but it's still saying disallowed host

swift sky
#

idk friend,

#

i have my own coding to do at the moment

#

but those are the commands to restart and check status of nginx server

mortal mango
#

oh ok

swift sky
#

its likely something is happening elsewhere that is restricting access

#

did you link allowed hosts with available sites

mortal mango
#

@swift sky I fixed it. I did sudo reboot and it worked. I guess the nginx server just needed to be shutdown and started again to update. Do you know a way to update it with a command?

swift sky
#

i usually use systemctl restart nginx

#

but it seems like you had some permissions and so it wasn't doing it

mortal mango
#

oh ok

wicked steppe
#

ok

mortal mango
#

I deleted db.sqlite3 from my vps but now when I upload it from my local machine, it automatically deletes. Does anyone know why?

glossy arrow
#

Hey guys, I'm having a problem with Flask and Jinja2, i'm passing a dictionary to the HTML, and looping over the keys with jinja, but the data is being displayed incorrectly inside a modal, and correctly outside a modal

native tide
glossy arrow
#

Well, I have something like the following ```jinja
<table>
<tbody>
{% for i in organizations.keys() %}
<tr>
<h1>{{i}}</h1>
<button class="btn btn-white btn-sm" data-toggle="modal" data-target="#modal">Open</button>
<div id="#modal" class="modal fade" role="dialog">
<div id="modal-content">
<h1>{{i}}</h1>
</div>
</div>
</tr>
{ % endfor %}
</tbody>
</table>

#

And i'm doing ```py
return render_template("organizations.html", organizations=organizations}

#

And lets say organizations is the following {"test1": 1, "test2": 0}

native tide
glossy arrow
#

Think so

#

But for each of the items added to the table, the first h1 outside of the modal is correct, but its wrong inside of the modal

#

wait

glossy arrow
#

But its correct inside my code

native tide
glossy arrow
#

But yeah, theres still the problem

native tide
glossy arrow
#

Uh, not really, its a closed source app

native tide
glossy arrow
#

So the first h1 is different both times, but the h1 inside the modal is test1 through both of the iterations

native tide
native tide
glossy arrow
#

I typed it out by hand

#

Not sure why its not working for me then

#

Say I have something like this then ```jinja
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"/>
</head>
<body>
<table>
<tbody>
{% for i in organizations.keys() %}
<tr>
<h1>Title: {{i}}</h1>
<button data-toggle="modal" data-target="#modal">Open</button>
<div id="#modal" class="modal modal-fade" role="dialog">
<div id="modal-content">
<h2>View Organization</h2>
<h2>Title: {{i}}</h2>
<h2>Address: {{data[i][1]}}</h2>
<!-- And so on for every piece of data, so address, city, state, zip -->
</div>
</div>
</tr>
{{% endfor %}}
</tbody>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>

indigo kettle
#

@glossy arrow It looks like you're creating a bunch of modals with the same id

#

you need to create them with unique ids and target the correct one in each iteration

#
data-target="#modal-{{i}}"
id="#modal-{{i}}"
#

or something

glossy arrow
#

Ohh ok

#

Wait, so a different modal for each organization?

#

Because users can add a new one any time

glad patrol
#

hi

#

how to set text field based on other 2 text field results

#

i need to set bmi = weight x height

#

i write javascript code but its not working

#
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<script type="text/javascript">
var elem = document.getElementById("height").value;
var elem2 = document.getElementById("weight").value;
var result = parseInt(elem) * parseInt(elem2);
document.getElementById("bmi").value = result.value;
</script>```
#

when i enter height and weight on html page the bmi value is not set

glad patrol
#

where i put this

#

after the script

gaunt marlin
#

first you need to import jquery

glad patrol
#

i am new to js and query can u pls show me

gaunt marlin
#

like the link i posted above

$("input").change(function(){
  alert("The text has been changed."); // you functions in this
});
#

@glad patrol javascript itself doesn't handle much on static website, to make static website interactable you need to learn jquery and ajax

glad patrol
#

shit

indigo kettle
#

you can make one modal, and alter its contents with javascript

glad patrol
#

how to set input field value on run time base on other two input fields?

glad patrol
#
var heightField = document.getElementById("height");
var weightField = document.getElementById("weight");
var bmiField = document.getElementById("bmi");

function handleHeightOnChange(event) {
  bmiField.value = event.currentTarget.value;
}
function handleWeightOnChange(event) {
  bmiField.value = event.currentTarget.value;
}
heightField.addEventListener('change', handleHeightOnChange);
weightField.addEventListener('change', handleWeightOnChange);```
#

how to add both height and weight event values ?

swift sky
#

does anyone know why in my test db i could add a column of varchar(10000) but when i try to flask migrate over on to the deployment server

#

it tells me that its too large

#

row size too large*

fervent oar
#

I am having a problem with building my Python discord bot on Heroku

#

this seemed to be the best fitting channel

#

nvm

wicked elbow
#

sounds dumb, but i know have node.js and django installed on AWS, can i just upload my code from my computer to the server and start the server and it work? or do i have redo all the installs for it to work?

gaunt marlin
wicked elbow
stable kite
native tide
native tide
wicked elbow
#

my server is fully up and running now. and yes, django is the server, im still using the developement server so im not gonna link anything to it. wanna run some tests

wicked elbow
#

if i close the ssh will the server continue running

gaunt marlin
#

@wicked elbow when you close the ssh it's also mean the terminal will be closed, look into screen for keeping the terminal up and running

#

if you using python manage.py runserver

wicked elbow
#

at least in aws

#

nah server is still up and running after closing my SSH link

gaunt marlin
#

oh ok

wicked elbow
#

i suppose i could share the public ip though eh? anyone could find it anyways

native tide
night hawk
#

how to change the font in HTML

#

???

vestal hound
night hawk
#

in CSS

#

YA IM RIGHT

vestal hound
night hawk
#

NOT html

vestal hound
#

which would be in the HTML...

#

...but nevertheless, I don't really see your point

night hawk
#

give me the example

#

pls

vestal hound
#

choice of font is not the province of HTML

night hawk
#

give me the font name

#

of HTML

#

name a font name

#

like verdana

wicked elbow
#

css is a child of html... css cant do anyting by itself, but html is plain and ugly without html

wicked elbow
#

man gotta wait up to 48 hours for dns to resolve my domain name lemon_eyes

night hawk
native tide
#

Hello Nut

#

I can't implement pagination and search function together

#

Hello. I need help with flask sessions.
Basically, I have my frontend with react and the backend is in flask. My frontend port is 3000 and my backend is 5000 in my localhost machine. when I log in, I want to save some credentials of user in their session like their key. It doesn't matter if they are able to see it or not but I don't want them to change it. I'm already successful in saving their session so basically when they click that button it saves that user session. But when I try to get that session using another api in flask, it is None and its like the data has never saved before. I thought it might be because browsers don't save sessions if they are in seperated ports. I wonder why is this happening and how to fix it? Is it same when I push it into production server with domain?

velvet vale
kindred osprey
#

Hello all, I actually want one of my image tag in web page to move down on scrolling.
I referred to many online sites but I am not able to fix that.
Can anyone please guide me here.
I want that bike to move down on scrolling

mortal mango
#

Is there a way to remove the title "Long URL" in this Django form?

    <form method="POST" action="/create" style="font-family: bebas neue; margin-top: 20%; font-size: 3em; animation: fadeInRight 3s;">
        {% csrf_token %} {{ form.as_p }}
        <center><button type="submit" class="btn link2" style="font-family: bungee; margin-top: 1%; font-size: 0.8em; background-color: white;">Shorten URL</button></center>
    </form>
native tide
native tide
#

I have an issue...

request.user tries to retrieve a user from the User model. However, I have a custom user model (AbstractUser), how can I change it so that request.user tries to reference it?

mortal mango
indigo kettle
#

@native tide I think you just need to specify AUTH_USER_MODEL = 'customauth.MyUser' in your settings.py

native tide
indigo kettle
#

request.user should return an instance of AUTH_USER_MODEL, so i'm not sure

#

if they aren't logged in, it will be an anonymous user

#

@native tide

dense slate
#

@native tide The custom model is in the DB?

#

That setting mentioned above should "reroute" which user model is used to the appropriate model.

#

AUTH_USER_MODEL = 'core.CustomUser'

native tide
haughty turtle
#

Print out request.user

#

See what you are getting

#

@native tide

#

I believe it returns an object.

#

Your User object.

#

So like request.user.email will return enail

#

request.user.username returns the username

#

request.user returns the User model for the user as an object, can't verify on mobile but I believe this is what it does.

#

So if your User model doesn't have a suite attribute you will get such error

#

@native tide

native tide
#

Working on it now

frosty current
#

Sup

native tide
#

Been having a CORS issue despite following all the correct steps (I think)

indigo kettle
#

you can just visit the api url directly in your browser

native tide
#

Yeah but I've got Token Authentication which requires an Auth header

rose field
native tide
rose field
#

<center><a class = "download-btn" href = "information.html/files.zip" download="files.zip">bruh</a><center>

#

it doesnt work

mortal mango
haughty turtle
#

@native tide that means no one is logged in, do a try-if statement to catch that error or make logging required for that page

#

@native tide also I do not think you are making a call by getting the object. It's stored in cache on every request.

native tide
haughty turtle
#

Are you passing in your CRSFtoken ?

native tide
#

No... do I need to?

haughty turtle
#

If sending a POST request yes

native tide
#

It's just a GET

haughty turtle
#

Then weird I have gotten such error when trying to login sending a POST requedt

#

When I got CORS error

#

What's the error exactly ?

native tide
#

Ok so I will lead you through what I have done this far

#
  1. pip installed djangocorsheaders
#
  1. added it to installed apps
#
  1. added it to middleware
#
  1. added this in settings.py:
ALLOWED_HOSTS = ['*']
CORS_ORIGIN_ALLOW_ALL = True
#

Then I try to make a GET request in postman

glossy arrow
#

Can I pass jinja2 data in an onclick?

#

Like ```jinja
<button onclick="myfunction({{whateverdata}})">Click</button>

native tide
#

I have had it setup in the past no problem

haughty turtle
#

@glossy arrow should be able to pass in whatever you want as a parameter

glossy arrow
haughty turtle
#

Because it's inside of a ""

#

@glossy arrow

glossy arrow
#

@haughty turtle No, its sort of working

#

So Im doing something like this ```jinja
{{% for i in organizations.keys() %}}
...
<button onclick="myfunction({{i}}, {{data}})">Click</button>
...
{{% endfor %}}

#

So im looping over a dictionaries keys

#

and lets say i is test

#

and data is a dict

#

Its saying that test is not defined

#

So its loading in the value for i

#

But saying its undefined

haughty turtle
#

@glossy arrow it's because your passing a var inside of a string as said. Take a look at the link

glossy arrow
#

Cool, i'll look at that, thanks :D

#

Hm, that doesn't seem to solve the problem

#

Wait

#

yeah it doesn't solve the problem

#

Its not showing anything about jinja values

native tide
# glossy arrow yeah it doesn't solve the problem

I did successfully include Jinja2 in JavaScript like below, so maybe safe helps / maybe there is a way to rewrite your code?
<script> {% if mytable %} var table_data = {{ mytable|safe }}; {% else %} var table_data = null; {% endif %} // table_data.data = table_data.data.slice(0,5); // DEV config sub array </script>

glossy arrow
#

Thanks :D I can't figure out why its not working, but I found somewhat of a workaround

glossy arrow
native tide
#

Does anyone know why DRF is giving me an AnonymousUser forrequest.user?

#

So anyways I don't think DRF catches on to my AUTH_USER_MODEL

#

Do I need to write some sort of custom middleware so that request.user references my custom usermodel, and not that of the default django user model?

dense slate
#

Shouldn't have to.

#

That is what I used to do it my first time and it shouldn't be a complicated process.

#

Last option is what you want.

uneven wren
#

Hello, i need to persist session after logout to load my cart on next login. Is it alright to overwrite logout function to do not flush session ? Thanks

native tide
#

Because from what I see request.user is set to return an instance of the User model...

#

I'm pretty sure custom authentication / middleware is needed here...

spiral needle
#

Why does no data get sent when I include POST data directly in the urllib.request.Request object, but rather I have to pass the kwarg when calling urllib.request.urlopen?

e.g. : urllib.request.urlopen(urllib.request.Request(url, data=DATA), method="POST") doesn't work, while urllib.request.urlopen(urllib.request.Request(url, ...), data=DATA, method="POST") does

Both the Request class's initializer and the urlopen function accept the data kwarg yet only the former appends data to the body

sorry if this isn't the right channel to ask

native tide
#

Can someone explain why this header:
Authorization: Token cb5837c90e8f8c352a370798e058e42d5913eeb4

returns None from this code:

    def authenticate(self, request):
        auth = get_authorization_header(request).split()

        if not auth or auth[0].lower() != self.keyword.lower().encode():
            return None
quick cargo
#

you sure its not asking for Bearer or smth

#

assuming that get_authorization_header(request).split() is doing anything extra

native tide
native tide
#

That's a no

#

But it's narrowed down

native tide
#

not too sure on what this does though

#

self.keyword.lower().encode():

vestal hound
#

verifying that the header starts with the given keyword

native tide
#

self.keyword.lower() is token

vestal hound
#

which, in this case, is expected to be Token

native tide
#

yeah, what's with the .encode() on the end?

vestal hound
#

presumably

#

since the header comes from a HTTP request

#

it's a bytestring

#

and self.keyword is a string

#

so to compare the two you need to either decode one or encode the other

native tide
#
    def authenticate(self, request):
        auth = get_authorization_header(request).split()

        if not auth:
            return None
#

This still returns None

#

Maybe I'm looking at the wrong thing...

quick cargo
#

print(auth)

native tide
#

empty list

#

[]

quick cargo
#

okay

#

what does get_authorization_header(request) return

#

can you print that?

vestal hound
#

p sure it's empty

#

are you sure your request contains the right header?

quick cargo
#

and maybe also print(request.headers)

#

i recon its gonna be a headers property or smth, i dont do much django but its pretty much the same across all systems

edgy isle
#

How do you get all the chosen options with select2?

native tide
# vestal hound are you sure your request contains the right header?

This is the right header according to the docs:
Authorization: Token cb5837c90e8f8c352a370798e058e42d5913eeb4

However I am using postman and they may be adding something which I don't see, I can try from my react frontend.

The issue I am originally having is that request.user is returning AnonymousUser instead of my AUTH_USER_MODEL specified in settings.py

native tide
# quick cargo and maybe also `print(request.headers)`
{'Content-Length': '', 'Content-Type': 'text/plain', 'Host': '127.0.0.1:8000', 'User-Agent': 'PostmanRuntime/7.26.10', 'Accept': '*/*', 'Accept-Language': 'en-GB,en;q=0.5', 'Accept-Encoding': 'gzip, deflate', 'Authorization': '', 'Origin': 'https://web.postman.co', 'Connection': 'keep-alive'}
#

Interesting

#

So the Authorization header is empty

quick cargo
#

finger_twirl would appear so

vestal hound
#

problem solved

native tide
#

I'm specifying a value for the header in postman πŸ€·β€β™‚οΈ

#

I'll try this from my frontend and see if it differs

#

OMG

#

Postman has 3 columns, "key", "value", and "description", I mistook the "description" column for "value" as it was hidden.

#

Thank you so much @quick cargo @vestal hound I was stuck on that all day

vestal hound
#

yw hf

edgy isle
#

How do you get all the chosen options with select2?

#

Ive tried getlist but it just does the first selected object

atomic sonnet
#

django api link?

shadow dirge
#

rest api?

atomic sonnet
#

what?

#

i just want a link to django where i can learn django web dev

shadow dirge
#

so docs?

atomic sonnet
#

yea basically

atomic sonnet
#

thank you

shadow dirge
#

wlc

jolly pilot
#
        db = sqlite3.connect("textPosts.db")
        c = db.cursor()

        sql = ("SELECT textContent FROM textPosts WHERE username=?")
        val = ([user])
        
        c.execute(sql, val)
        result = c.fetchall()

        for text in result:
            print(text)
            
        c.close()
        db.close()

        return render_template("view-text-uploads.html", result=text)```

```html
            {% for text in result %}
            <p>{{ text }}</p>
            {% endfor %}

only returns last item of list

#

ping if responding

indigo kettle
#

you wrote result=text

#

@jolly pilot

#

maybe you want result=result?

jolly pilot
#

for some reason there are 2 tuples

#

so i had to do that

#

this is with result

indigo kettle
#

I guess you're retrieving all the columns

#

but there is only one

#

what happens if you do result=result

jolly pilot
#

well the image

jolly pilot
indigo kettle
#

oh

#

then can you do {{text[0]}}

jolly pilot
#

i want all the items

#

to be shown

indigo kettle
#

it will

jolly pilot
#

nope

indigo kettle
#

wdym

#

if you do result=result and do your for loop but use {{text[0]}} I think that should work

jolly pilot
#

it doesnt

indigo kettle
#

ok so what's happening

jolly pilot
#

so you mean

#

return render_template("view-text-uploads.html", result=result)

#
            {% for text in result %}
            <p style="color: white;">{{ text }}</p>
            {% endfor %}```
#

right?

indigo kettle
#

text[0]

#

then yes

jolly pilot
indigo kettle
#

mm, you might be consuming the data with your forloop inside the view

jolly pilot
#

what

indigo kettle
#

result = [x for x in c.fetchall()]
maybe try this instead of
result = c.fetchall()

jolly pilot
#

do i do result=text or result=result

indigo kettle
#

result = result

#

if you do result = text, it will only be the last one

jolly pilot
indigo kettle
#

are you doing text[0]?

edgy isle
#

How do you get all the chosen options with select2?
Ive tried getlist but it just does the first selected object

jolly pilot
#

no

#

YOOOO

#

thank you so much

#

omg

indigo kettle
#

wew

#

finally

edgy isle
indigo kettle
#

share what your form looks like too

tribal python
#

actually, nevermind, I just figured out my actual problem and the solution to it as I typed the question

glad patrol
#

hi

#

i am creating some basic app hospital system , i need some help

#

how to generate report in django , i have some variable's holding information like name , bmi , age etc i want to display in some report template .

ashen sparrow
#

@glad patrol write model_name.objects.all() to get all objects of your models.
Pass the resulting query set to your templates and then in your html you can simply iterate over it query set using jinja

glad patrol
#

@ashen sparrow i am using sql database direct not model

ashen sparrow
#

Are you using SQLaclhemy?

glad patrol
#

no sql database

#

phpmyadmin

gaunt marlin
#

phpmyadmin is a database GUI, not the database

glad patrol
#

sql database

gaunt marlin
#

he asking what ORM are you using

ashen sparrow
#

@glad patrol whatever you do, you need to perform a query on your database similar to
SELECT * FROM REPORT_TABLE

glad patrol
#

i done the query

#

i get the results

#

i just want to display it on page

ashen sparrow
#

Now populate result in a list

glad patrol
#

like prescription reeport

ashen sparrow
#

And pass the list to your templates

glad patrol
#

The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol.

#

i am getting this error even i import utf-8 in html page

ashen sparrow
#

Where did you import it and how are you using it?

glad patrol
#

i import in <head> tag

#

in first line

ashen sparrow
#

Before you pass your results to the template, try encoding it into utf8

glad patrol
#

nono

#

i am not doing reporting part right now

#

yesterday app working fine

gaunt marlin
#

set this in your html meta tag

<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
glad patrol
#

now its throwing this error

#

i set this

#
<!DOCTYPE html>
<html lang="en">
  <head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">

    <!-- Required meta tags -->
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />```
gaunt marlin
#

better to show the image of the error on the page

glad patrol
#

ok w8

gaunt marlin
#

this happen after you submit the form?

glad patrol
#

when i open https://172.17.85.70:8000 then i selete diabtese form then this appear

gaunt marlin
#

can you show your form template?

glad patrol
#

yes

gaunt marlin
#

maybe it's missing in some child template or parent template

glad patrol
#

i show u both base.html

#

and diabetes.html

gaunt marlin
#

even better, right click -> show page source

#

so we can know if it has

<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
glad patrol
#

from browser ?

gaunt marlin
#

yeah

glad patrol
gaunt marlin
#

ok then post the html of base.html?

glad patrol
#

ok

lavish prismBOT
#

Hey @glad patrol!

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

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

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

https://paste.pythondiscord.com

glad patrol
#

i guess its not using meta header

gaunt marlin
#

yeah that the problem

glad patrol
#

should i need to run migration ?

#

or reload project?

#

yesterday this happen i add meta and its work now its not working

gaunt marlin
#

ok now show me the diabetes.html?

glad patrol
#

ok

gaunt marlin
#

@glad patrol can you add space to these template tag?

{%extends 'base.html'%} {%block content%}
glad patrol
#

ok i add w8

gaunt marlin
#

like so

{% extends 'base.html' %} {% block content %}
glad patrol
#

w8

#

same error

#

if i reload the project

#

its works fine

#

if i add something then run it give me error

gaunt marlin
#

reload the project?

#

like restart the django server?

glad patrol
#

i have rar file backup

#

if i use that rar file backup its work

#

even the same meta tag are inserted

#

see now i unzip my backup and its working fine

#

if i add another html file in templates it start giving the errors

gaunt marlin
#

that pretty strange, what is your project structure like?

glad patrol
#

means?

zinc hill
#

what type of error?

gaunt marlin
#

you got a 500 server error @glad patrol try to print out what caused the error and put debug=True

#

i don't think the error related to the utf8

#

but the logic in the view itself

glad patrol
#

anyway i get ridoff later

#

can u pls tell 1 more thing

gaunt marlin
#

so the page can show the real error

glad patrol
#

ok

#
  pregnancies = float(request.POST['pregnancies'])
        glucose = float(request.POST['glucose'])
        bloodpressure = float(request.POST['bloodpressure'])
        skinthickness = float(request.POST['skinthickness'])
        bmi = float(request.POST['bmi'])
        insulin = float(request.POST['insulin'])
        pedigree = float(request.POST['pedigree'])
        age = float(request.POST['age'])
        name=str(request.POST['name'])
        date=str(request.POST['date'])
        gender=str(request.POST['gender'])
        bloodgroup=str(request.POST['bloodgroup'])
        mrn = int(request.POST['mrn'])```
#

i have this information which i send into database

#

how to generate report from this

gaunt marlin
#

yeah but can you reload that page with DEBUG=True?

glad patrol
#

1 mint

#

huh

#

i fix this

#

the error is i define index.html which is not even exsist

#

lol

#

i remove from diabetes.html

#

and its working

#

@gaunt marlin

#

i have report.html page

#

i add <a href="{% url 'report' %}">Home</a> in my diabetest.html page

#

when i click on home link it wont open the report page

#

thats why 500 erro occurs

#

`django.urls.exceptions.NoReverseMatch

django.urls.exceptions.NoReverseMatch: Reverse for 'report' not found. 'report' is not a valid view function or pattern name.
`

analog arch
#

Use {% url 'app_name:report' %} where app_name is the name of the app that contains your report view function

gaunt marlin
#

@glad patrol you can set the name of your url like so

from django.urls import include, path

urlpatterns = [
    path('index/', views.index, name='main-view'),
    path('bio/<username>/', views.bio, name='bio'),
    path('articles/<slug:title>/', views.article, name='article-detail'),
    path('articles/<slug:title>/<int:section>/', views.section, name='article-section'),
    path('weblog/', include('blog.urls')),
    ...
]

if 2 or more apps have urls with same name then you need to call app_name:url_name instead

glad patrol
#

i can import app with in app ?

#

and call 1 app url from another app?

glad patrol
#

so i need to run two manage.py for both app ?

#

or they both run at once with 1 manage.py?

gaunt marlin
#

manage.py runserver will run the entire project

#

project have many apps

#

so it will run all the apps

glad patrol
#

on the same ip and port ?

haughty turtle
#

yes

pallid fable
#

it's a long shot, but any chance I can get some help writing some REST API in YAML?

#

for a language that claims to be human readable, it sure reads like some fat nonsense

plain zealot
#

Hey so I keep on getting blocked by Cors policy when I make a fetch request

#

Anyone know what can I do to fix it?

vestal hound
#

Hey so I keep on getting blocked by Cors policy when I make a fetch request
@plain zealot your backend needs to serve the appropriate headers

#

it's a long shot, but any chance I can get some help writing some REST API in YAML?
@pallid fable you mean parsing YAML in your API?

#

or rendering and returning a YAML response?

pallid fable
#

I literally have to send a REST request using YAML

vestal hound
#

okay so like sending YAML in the request body?

pallid fable
#

I wish

#

I know this sounds like something YAML doesn’t do

vestal hound
#

...I don’t really understand

pallid fable
#

But I actually have to format and send a GET request to an IPAM server, with the intention of receiving the next free IP address in a subnet

#

The code that sends the GET request is supposed to be written in YAML

plain zealot
#

But thanks

pallid fable
vestal hound
#

The code that sends the GET request is supposed to be written in YAML
@pallid fable ...wtf?

pallid fable
#

Yup

vestal hound
#

Found another way to fix
@plain zealot okay, hope it’s secure

pallid fable
#

To be fair, I’ve figured out how to do something sorta similar using the URI module

#

If it helps, this is being hosted by Ansible

#

Well, the code is being run from Ansible

vestal hound
#

...YAML can’t even be run...?

pallid fable
#

I think Ansible makes it work somehow

#

I got introduced to YAML and Ansible like a week ago. I’m a newish hire, and we’re in the process of moving our service onto Ansible. I’m translating workflows into Ansible/YAML

vestal hound
#

...it’s not an executable language

pallid fable
#

The old code that did this task was written in JavaScript which makes so much more sense

pallid fable
vestal hound
#

I have no idea either

#

πŸ₯΄

#

sorry

pallid fable
#

best I can explain it is that Ansible interprets YAML as an executable language

#

here's an example from the URI module documentation page

- name: Login to a form based webpage, then use the returned cookie to access the app in later tasks
  uri:
    url: https://your.form.based.auth.example.com/index.php
    method: POST
    body_format: form-urlencoded
    body:
      name: your_username
      password: your_password
      enter: Sign in
    status_code: 302
  register: login```
#

I mean, this is definitely written in YAML. But it also looks a lot like it's meant to be executed

gaunt marlin
#

Is there a reason your boss chose YAML to do request of all the things that existed out there?

pallid fable
#

I think they like that Ansible Tower (service running the workflows) has a much more modern interface than the old service we used for workflows

#

so the fact that all this shit now needs to be done in YAML is more of a side-effect

#

but I also arrived after this transition began so idk

#

I'm just a sad new college grad I wasn't ready for the level of bullshit that makes up YAML

#

"human friendly" my ass

gaunt marlin
#

the only thing i feels comfortable for YAML to run is writing test flow 🀣

#

but everyone going for that automation flow i guess

#

Β―_(ツ)_/Β―

pallid fable
#

just looked into it a bit more closely. Ansible uses an 'easy and descriptive language based on YAML and Jinja templates"

pallid fable
pallid fable
#

so it looks like YAML but it runs

#

because someone made the conscious decision that YAML would totally be a good executable language, somehow

gaunt marlin
#

i think they just like syntax of YAML without all the curly brackets

pallid fable
#

bahahaha they don't use the curly brackets? All my coworkers have been using them, can't wait to tell them why their code isn't running for shit

honest dock
#
<div class="quantity">
  <input type="number" class="qty-text" id="qty" step="1" min="1" max="12" name="quantity" value="1">
</div>
<a href="{% url 'add_to_cart' slug=quantity.value %}" type="submit" name="addtocart" value="5" class="cart-submit">Add to cart</a>

Django question to you guys, how do I pass to the slug the input value?

native tide
honest dock
#

I will give it a try but I doubt since it's not a variable? Give me a sec

native tide
#

Oh, my bad

#

I thought you were passing it in context

honest dock
#

Uh uh 😦

native tide
#

That being said, is there a possibility you can pass the slug through context to your template, then access it within the value?

honest dock
#

I don't understand ^^

#

I'm just trying to add a product to the cart, and i need the quantity to be passed in the url as well (having 2 slugs/parameters is another problem i'll be checking later on)

native tide
#

So in your view you will set the slug

def view(request):
  slug = "something"
  render_template(request, template, {"slug": slug})
honest dock
#

Okay and so the slug will be changed in the input?

native tide
#

I guess so, so you will pass your slug through the context and within your template you can access it with:
{{slug}}

honest dock
#

yup yup

#

and the url 'add_to_cart' can have multiple slugs right?

native tide
#

The URL itself yes

#

That example was for django

#

For flask it's basically identical

honest dock
#

I see

#

so it's something like:

#
path('addToCart/<slug:slug>/<amount:amount>', .....
native tide
#

Yes

#

And I believe you can access those parameters as so:

def view(request, slug, amount):
  ...
honest dock
#

Alright thank you man!

native tide
gaunt marlin
# native tide what is he doing here?

turn list of dictionaries that contains keys and values into json data for example it converted into this:

[{'field_1': value_1, 'field_2': value_2}, {'field_1': value_1, 'field_2': value_2}]
native tide
#

but when I follow that I get this error:

TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Decimal is not JSON serializable
#

@gaunt marlin

native tide
#

@native tide json.dumps(Info.objects.values()) does not work?

native tide
#

I am trying to achieve by other ways

inland stirrup
sonic ferry
#

Why doesn't Flask accept ../ as a path:variable in route decorator? e.g. @app.route("/test/<path:var>")

native tide
#

when I try to pass list as context and set that list as an array var in template and console log that, it shows some unusual characters like this:

#

[&#x27;University of Oxford&#x27;, &#x27;Stanford University&#x27;, &#x27;Harvard University&#x27;]

#

how can I solve?

sonic ferry
#

Looks like the single quote is being converted into the hex value 27

haughty turtle
#

that has to do with safe

#

enable safe

#

on the list call

native tide
#

how?

haughty turtle
#

safeΒΆ
Marks a string as not requiring further HTML escaping prior to output. When autoescaping is off, this filter has no effect.

Note

If you are chaining filters, a filter applied after safe can make the contents unsafe again. For example, the following code prints the variable as is, unescaped:

{{ var|safe|escape }}

native tide
#

thank you so much mate

velvet vale
native tide
#

How can I serialize a queryset into JSON without it being a list?

haughty turtle
#

this is what I use

native tide
haughty turtle
#

I mean I think what I am doing is mapping

haughty turtle
mortal mango
#

Does anyone know how to do a 301/302 redirect in python?

limber laurel
#
Server: WSGIServer/0.2 CPython/3.6.9
Content-Type: application/json
Vary: Accept, Cookie
Allow: OPTIONS, GET
X-Frame-Options: DENY
Content-Length: 109
X-Content-Type-Options: nosniff
Set-Cookie: β€Š

#

I am trying to get json data from my api view

#

That I made with rest

#

But the obly thibg I get is this

#

Is there a way I could change that?

tight totem
#

So I got this message from a friend today together with a django pdf: "I got this book from Jesus and I will start my Django journey soon. I will follow this book."

#

I was a bit disappointed to find out that her new coworker's name is Jesus. We could use a new bible

worldly current
#

Nice πŸ˜†

slow bear
#

Hey! I'm trying to implement a kanban board for my task management project, using this library http://www.riccardotartaglia.it/jkanban/ . I'm having trouble trying to understand how to implement the backend logic, especially how to keep track of the order the items are placed in a board. I tried searching on google but I didn't find any relevant results. Does anyone have any ideas? Or search terms to help me find something?

limber laurel
#

@haughty turtle the api view?

mortal mango
#

Error:
raise ImproperlyConfigured("URL route '%s' cannot contain whitespace." % route) django.core.exceptions.ImproperlyConfigured: URL route 'http://localhost:8000/{{ chars }}' cannot contain whitespace.

Urls.py
path('http://localhost:8000/{{ chars }}', redirect_view),

Views.py

def redirect_view(request):
    response = redirect('{{ obj.long_url }}')
    return response
```Does anyone know how to properly do this type of redirect? I'm creating a url shortener and I'm using django redirects to do the redirect
native tide
mortal mango
#

oh

#

so do you know how I would do this?

#

I'm new to django

mortal mango
#

oh ok

#

@native tide is {{ obj.long_url }} jinja2?

paper rune
#

does anyone know how to put a limit to request.get() ? would requests.get("url", limit=1) work?

native tide
mortal mango
#

ok

topaz finch
#

Hello, I keep getting psutil.AccessDenied: psutil.AccessDenied when my flask app tries to open files to get things like cwd and all of that. How can I make it so that the flask/apache app user has access to all process files? @ me when responding please.

haughty turtle
mortal mango
#

path('<str:url>', redirect, name='redirect'),

def redirect(request):
    current_obj = ShortURL.objects.filter(short_url=url)
    if len(current_obj) == 0:
        return render(request, '404.html')
    context = {'obj':current_obj[0]}
    response = redirect(f"{long_url}", permanent=False)
    return response

@native tide I'm getting redirect() unexpected keyword argument 'url'. Do you know why this is happening?

#

actually nvm

#

I forgot to pass url

indigo kettle
#

that function is also recursive, I think unintentionally? You may want to rename it

native tide
#

Can we convert JS array back to python list in django template?

mortal mango
#

def page_redirect(request, url):
    if request.method == 'POST':
        form = CreateNewShortURL(request.POST)
        if form.is_valid():
            original_website = form.cleaned_data['long_url']
            return HttpResponseRedirect(original_website)
````ValueError: The view urlshort.views.page_redirect didn't return an HttpResponse object. It returned None instead.` Does anyone know why this is happening?
indigo kettle
#

if request.method is not 'POST' then you will return None

#

if form is invalid, you will return None

mortal mango
#

so how do I make it return a post?

indigo kettle
#

make it return a post?

#

I'm not sure what you mean

mortal mango
#

I mean like how do I make it not return None

#

sorry

indigo kettle
#

how do you make a function not return None

#

you have to return something right

#

there are two places where your function can exit without returning

#

you can have a catchall return at the end

#

with some sort of error

#

like a Http400 response

#

return HttpResponseBadRequest('invalid request')

#

or something

mortal mango
#

oh ok

#

same error

#
def page_redirect(request, url):
    if request.method == 'POST':

        form = CreateNewShortURL(request.POST)

        if form.is_valid():

            original_website = form.cleaned_data['long_url']

            return HttpResponseBadRequest('invalid request')
indigo kettle
#

the return you had before was fine

#

but look

#

you have two if statements right

mortal mango
#

yeah

indigo kettle
#

if either of those are false, then your function will return None

#

because there is no return after those if statements

mortal mango
#

oh ok

indigo kettle
#

does that make sense?

mortal mango
#

yeah

#

I put a couple print statements

#

it's if request.method == 'POST': that's returning False

#
class CreateNewShortURL(forms.ModelForm):
    class Meta:
        model=ShortURL
        fields = {'long_url'}

        widgets = {
            'long_url': forms.URLInput(attrs={'class': 'form-control'})
        }
``` @indigo kettle this is my form. I want to get `long_url` and put it in my `HttpResponseRedirect()`. How would I do that?
indigo kettle
#

form.cleaned_data['long_url'] did that not work

mortal mango
#

I did

def page_redirect(request, url):
    if request.method == 'GET':
        return HttpResponseRedirect(f'/')
```And it worked
#

but when i did

def page_redirect(request, url):
    if request.method == 'GET':
        form = CreateNewShortURL(request.GET)
        if form.is_valid():
            original_website = form.cleaned_data['long_url']
            return HttpResponseRedirect(f'{original_website}')
```it didn't and gave me the same error as last time
#

@indigo kettle

indigo kettle
#

?

#

you're checking if the request is a GET but then putting request.post into your form

#

the post. will be empty

#

your form will probably be invalid

#

and then your function will return None

mortal mango
#

oh, I meant request.GET

#

but even if I do that, it still gives the same error

#

@indigo kettle

native tide
cold portal
#

The form works fine though... mystery to me

vestal hound
#

like based on logs

cold portal
#

I see both when I hit the submit button, but the get is what actually hits with regard to console output

vestal hound
#

that's not right

#

also that could lead to production bugs

#

because GET can be cached

cold portal
#

I am using an UpdateView. The form is an edit profile screen that displays the user’s details and lets them edit the fields

#

I hope that’s not going to be a problem when it’s in production

vestal hound
#

do you know the difference between GET and POST?

cold portal
#

Yeah

#

And he’s

#

Yes*

vestal hound
#

like from a spec perspective

vestal hound
cold portal
#

I guess from a behind the scenes caching I don’t know where there would be a problem. Not sure even where the caching would occur

#

Nothing as far as I can tell. I was commenting on someone else having an issue with form submission not hitting an if block checking if the request if a post

vestal hound
#

like the actual webserver

#

but browsers can also cache responses to GET requests

cold portal
#

So looking at potential memory problem

vestal hound
#

okay example

#

a static image is retrieved with a GET

cold portal
#

Yeah

vestal hound
#

and the next time you browse the page (if the site is set up a certain way), you won't need to retrieve it again

#

because your browser has cached it

#

if the update request is submitted with a GET

#

the browser could cache that too

#

so your request never gets sent to the server

#

but you get back a "success" response

#

also, separately, GET requests should be idempotent, but updating is also an idempotent operation so that's not a problem here

cold portal
#

Thanks for that info. I have a lot more reading to do. There is a post recorded in the console it would seem it is posting. On form submission the user is sent back to the same page so I expect a get. Hopefully there’s nothing to worry about, but it’s something to read up on to be sure.

edgy isle
#

Why is my stylesheets being replaced by the error page template?

#

oh nvm

#

That was wierd

#

uhm wtf

#

That was so wierd

#

I forgot to add the {{ url_for('static', filename='

native tide
#

I have a field named suite within my model:

class Customer(AbstractUser):
    suite = models.OneToOneField(Suite, on_delete=models.CASCADE, null=True)
    premium = models.BooleanField(null=False, default=False)

Why is it being named suite_id within my DB? Can I rename it?

mortal mango
#

@indigo kettle the first if statement is working now but the second one isn't. For some reason, the form is not valid. Do you know why this is happening?

indigo kettle
#

I don't

#

I would write some print statements to see what is wrong

#

you can print form.errors or something

#

and also print request.GET and see if you're getting the correct params

mortal mango
#

<ul class="errorlist"><li>long_url<ul class="errorlist"><li>This field is required.</li></ul></li></ul> this is what form.errors returns

native tide
#

try use redirect()

mortal mango
#

oh ok

mortal mango
native tide
#

I guess so, it may help (but it looks like the issue lies with the form)

heady stream
#

hey guys, idk if someone can help me with this but I am really struggling with flask progress bars!
I have searched everywhere for this, found a some examples online but they were only for file uploads which is not what I want.
I am failing to understand how to bind the python to the js and html!
I am working with someone on a neuron tracing project and they need some help with frontend.
The web portal is pretty simple and it just includes inputting your file tracing path (*.txt) and image path (**.tif) and then wait until another tab opens up which reveals a neurologlancer with a 3d view of your neuron (pretty nice!)
Now, my issue with this is the following:
the function that basically takes the whole time to load is in a different file than app.py and it includes the following code:

def func_that_takes_the_whole_time():
  # code here 
  with mp.Pool(mp.cpu_count() * 2) as p:
          # p.map(p_matting, range(0, len(gs_dict)))
          with tqdm(total=len(gs_dict)) as pbar:
              for i, _ in enumerate(p.imap_unordered(p_matting, range(0, len(gs_dict)))):
                  pbar.update()
  # more code here
  return something here

this is a progress bar that shows in the terminal
how can i get this to output in the frontend for the user to see, because the neuroglancer tab takes a bit of time to launch!
I am still a beginner to flask and am not even studying to become a developer, so it would mean a lot if somebody can help, been struggling with this for days!

#

Sorry for throwing this at you, but the result of tqdm only showing in terminal, want to find a way to output to user so they don't think they entered wrong input after clicking run!
Thanks a ton to whomever helps with this!

proper hinge
#

I don't think tqdm is appropriate for use with the web

#

I think it's relatively simple to render the progress bar on the web page

#

The tricky part is how to update the bar with the current progress

#

Since the server has to somehow relay that info to the client

#

I don't have an exact picture of how to architecture this, but I imagine you could accomplish this with a websocket

#

There's also eventsource, but that may be trickier since it's uni-directional.

#

I'd say to look into using a websocket

night hawk
#

import turtle t = turtle.Pen() turtle.bgcolor("black") colors = ["blue","pink","yellow", "red"] for x in range(1000): t.pencolor(colors[x%4]) t.forward(x) t.left(90)

vestal hound
#

@heady stream you need some JS for that

cloud path
#

guys how can i remove effects made from jinja2?

#

the outcome should be this:

#

but with jinja2, it adds more css effects and the outcome is this:

#

this is the code of what should it be:

#

code of what i did with jinja2:

nimble epoch
#

Hello everyone. im deploying a django project as a test on heroku wanted to know if i can use my local static file on heroku?

quick cargo
#

As much as that seems like a pretty good offer, it is against the Rules here to have the ads sorry

quick cargo
nimble epoch
cloud path
#

mmm

#

other styles are the ones of css i think

gaunt marlin
cloud path
#

i don't think it is escaping them probably it's just adding new ones too

#

now imma try m-1 thanks guys

nimble epoch
gaunt marlin
#

yeah

#

better to look over it because it's official heroku documents

nimble epoch
#

ok thanks i am

#

and of course im looking.... do you yourself have any idea about it?

gaunt marlin
#

i never deploy static on heroku before, i usually use nginx on VPS to serve my staticfile folder

nimble epoch
#

soo can i use my local folder in nginx

#

?

gaunt marlin
#

like you hosting the staticfile folder?

nimble epoch
#

yeap

gaunt marlin
#

don't know if that a good choice, why not use an amazon s3 server instead?

nimble epoch
#

i dont want to pay money lol

gaunt marlin
#

i mean heroku staticfile deploy is free

nimble epoch
#

or any free web services?

gaunt marlin
#

you can deploy django on heroku without costing money

nimble epoch
#

@gaunt marlin just read this => ''Your application will now serve static assets directly from Gunicorn in production''. should i use something in Procfile to access static file or just like dev, i gotta add something like {% static ..... %}?

#

or im wrong?

#

oh ok i got it.thanks

gaunt marlin
#

@nimble epoch do you want to run django on heroku with production or development environment?

nimble epoch
#

production

#

how?

gaunt marlin
#

oh i'm just asking, because you don't have to handle staticfile on heroku if django is in development environment

nimble epoch
#

yeah

#

its production that its got so complicated lol

tulip beacon
#

guy who here is good at react?

nimble epoch
#

i have some experiences

#

just reactjs not react router or anything elses

tulip beacon
#

oh

ornate scroll
#

Hi, can anyone give me a good link that talks regarding what languages are needed to develop a website both back and front end? (Including Python)

spare flare
#
from flask_wtf import FlaskForm
from wtforms import BooleanField

class MyForm(FlaskForm):
    if settings[0] == 1:
      my_default = True
    else:
      my_default = False

    name = BooleanField('name', default=my_default)

@app.route('/dashboard/<int:guild_id>/commands', methods=["GET", "POST"])
@requires_authorization
def dashboard_commands(guild_id):
    cursor = mysql.connection.cursor()
    cursor.execute(f"SELECT * FROM commands WHERE guild_id = {guild_id}")
    settings = cursor.fetchone()

    form = MyForm(settings)

how to i fix it to work? I know about _init_ and make another function but how to i return form then?

grizzled sand
#

Hey everyone. Have questions about Django.

For example if I have article model and want to steam it into my template i usually do it with {{ article.content }}
but if i want stream one content into few separate <div> first half of text from article.content </div> and <div> second part of text from article.content</div>

How can i do that?

native tide
dense osprey
#

how can i pass input from html form to python (flask) i am new to flask and html so forgive me if im being silly somewhere

real mirage
#

Can anyone here help me out with web designing, I just got a theme and I wanted to change the background video every time someone changes the slide, I can only get one video to play in the background and it wont change to another video if I change the slide

#

I am in Code/Help 0

#

wait

#

wth I cant talk in code help :/

#

Ping me if you can help me, I can screen share my issue

nimble epoch
#

I want to use my local dajngo media folder what should i set DEFAULT_FILE_STORAGE to?

raven shoal
#

Hey, is it possible to have html page running with form where user can type something and send it to python script running on other device? I want to call functions with arguments (from html) remotly from website and run scripts on raspberry.
I can make a simple html page with CSS and js but I don't know where to start. Searching on internet did not give me anything useful. Maybe you guys would help me?

native tide
lethal cedar
#

where's django's default login.html located?

native tide
iron cliff
heady stream
#

hey guys,
so I am following the following code to create a progress bar (loading bar): https://github.com/deshraj/flask-SocketIO-Progressbar
In my web portal as I click Run button to perform my web's functionality, my web starts loading forever and nothing new happens as I am supposed to enter a new tab!
As I enter: http://127.0.0.1:5001/socket.io/ I get the following message:
"The client is using an unsupported version of the Socket.IO or Engine.IO protocols"
I am running:
python-engineio 4.0.0
python-socketio 5.0.4
Flask-SocketIO 5.0.1
and I have changed the javascript socket.io version in the github from 0.9.16 to 3.13.2
According to flask documentation, these should be compatible!

waxen mirage
#

Hey Guys,

I need to use classes in my app.py from another .py in my directory in my flask app.

my structure looks like this:
app.py
forms.py
config.py
init.py

in my app.py file, i need to use a class from forms.py.
I've tried to do so like this:

from forms import loginforms
@app.route('/login')
def login(formsetUp):
    form = formsetUp.get(formsetUp()
    return render_template('login.html', title='sign in', form=form)

however, im getting TypeError: login() missing 1 required positional argument: 'loginforms'

true scroll
wintry dome
#

Does anyone have a link for the django discord channel

#

or is there django help in here?

vestal hound
#

or is there django help in here?
@wintry dome here

wintry dome
#

I want to to enable password reset/forgot password with django rest-auth but its a little sparse for help in the rest-auth docs. What's the flow for building a password reset? It seems like a POST req (/rest-auth/password/reset/) should be made with the email address. And then some how and an email needs to be sent to the user. And then from there another POST req (/rest-auth/password/reset/confirm/) should be made but there's supposed to be a UID and token that goes with the POST req but I have no idea where this comes from or how to send emails out with it

#

and I've been searching around and can't find any tutorials either

twilit needle
#

I need some help with django-rest-framework
so I've got views like this

class CategoryPositionsPatchView(MultipleObjectMixin, generics.UpdateAPIView):
    serializer_class = api_serializers.CategoryPositionSerializer
    permission_classes = [IsAuthenticated, ManageCluster]

    def update(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        ref_cluster = get_object_or_404(api_models.Cluster, id=self.kwargs['cluster_id'])
        api_models.Category.positions.update_object_positions(serializer.data, ref_cluster.categories)
        return Response(status=204)


class FieldPositionsPatchView(MultipleObjectMixin, generics.UpdateAPIView):
    serializer_class = api_serializers.FieldPositionSerializer
    permission_classes = [IsAuthenticated, ManageFields]

    def update(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        ref_datasheet = get_object_or_404(api_models.DataSheet, id=self.kwargs['parent_id'])
        api_models.Field.positions.update_object_positions(serializer.data, ref_datasheet.fields)
        return Response(status=204)

abc.py

class MultipleObjectMixin(object):
    # A mixin that ensures that the view at hand can
    # only take in an array of objects.

    def get_serializer(self, **kwargs):
        kwargs.pop('many', None)
        return super(MultipleObjectMixin, self).get_serializer(many=True, **kwargs)

I would like to make an abstract base class so that the PositionsPatchView suffixed classes can inherit from it
can someone please help me with it?

finite brook
#

Which is better to use? Django rest framework or django as full stack

native tide
#

Hi

#

Anyone familiar with any decent shared hosting for python web apps?

#

Heroku, pythonAnywhere and linode are expensive for me

buoyant shuttle
#

heroku has a free option

#

you can use that

#

I use a web hosting service, called alawaysdata.net. its a french web hosting service they have a free plan

buoyant shuttle
finite brook
#

it depends, if you want to deal with other APIS and stuff, maybe django rest framework
@buoyant shuttle Actually I am looking to build a cryptic hunt platform.

native tide
royal gust
#

Resources to Master Full Stack Development | Beginner to Advanced (https://youtu.be/WQPkYvGsWo8)
Please watch full video. This can give you so many resources that you might want.

Many of the people have contacted me of asking for resources and which learning path is the best and most efficient for full stack development.

The problem with most of the people is that there are tons of courses and materials available for free on internet but they are confused with which one to use and which one not to use.

So in this vide...

β–Ά Play video
native tide
#

hello can i get help in flask?

#

which line

native tide
#

im assuming Links is a class for the table?

#

you need to import that

native tide
#

you are trying to query the database

native tide
#

what is the class for the table you are trying to access

#

it should be {Class}.query.filter_by() something along those lines

#

from yourapplication import User User.query.filter_by()

quiet granite
#

Anybody using MongoDB with Django?

I am using Mongo Atlas (free tier) on a Django website. Everything's running fine from my local, but on server all my queries are running slow. For instance an update_one() query that takes around 0.5 seconds on local is taking 4 seconds on server. Shouldn't it take the same time since the query execution is taking place on Atlas server? Or do I need to tweak some server settings?

honest dock
#

Anyone is really good with css and js in Django? If yes, please let me know

#

I'm trying to fix a problem that I have been postponing for weeks

ornate scroll
native tide
#

how to redirect wherever the current url is in django?

buoyant shuttle
buoyant shuttle
#

you could use the redirect function, inside of your function abased views

#

if you mean in html, a href. instead of placing hardcore links like you would normally do in html you can do this in django. ```py
<a href="{% url <whatever the name is designated to your view in urls.py > %}">logout</a>

honest dock
native tide
#

like whenever the user do some stuff the views.py shouldn't change the route

buoyant shuttle
#

coool πŸ‘

native tide
#

instead stay wherever it is before the user does that task

buoyant shuttle
#

so you mean when your user clicks on anything, the views should not change route?

#

in that case, you can use the redirect() function

native tide
buoyant shuttle
#

wait i just finally understood what your question meant @native tide

#

If you want your user to do multple stuff on your website without changing webpages, or redirecting urls. Use Javascript

#

Thats basically what the langauge is meant for, it does the logic in a website.

#

Django only handles backend, with databases. Retrieve information, and collect. You will need to use the DOM effect of javascript to accomplish that

native tide
#

there should be a way

buoyant shuttle
#

let be give you an example of what i actually mean

native tide
#

i can understand but idk how can I do it

#

is there any way I can do some django view funtion on clicking a html element?

#

even by using js

buoyant shuttle
#

yeah it can be acheived using JS thats what is called fullstack development

tribal tapir
#

i like how im trying to do something but i have no ideas to create an app

native tide
buoyant shuttle
#

exaclty

native tide
#

now I have progressed a lot already

buoyant shuttle
#

lol

#

Ive been there

#

I was making a project for 5 months, almost half way there, then something happened to my hard drive

native tide
buoyant shuttle
#

lost all my work and rage quitted.

native tide
#

damn

native tide
#

it really is a life saver

native tide
#

almost 50% of the project

buoyant shuttle
native tide
#

I push to github after every feature changes

native tide
#

With a django/react project most of the time spent imo is on the frontend anyway

#

by a large margin

#

Because all you have to do on the backend is just setup a few API views and your models, some serializers, that's really it tbh

buoyant shuttle
#

tbh learning react shouldnt take you long

#

you can do it in a week,

native tide
#

yeah but I will have to reorganize the whole project 😦

quiet granite
short vector
#

When using jinja, if i have a stylesheet in /static, and i want to use it with another static html file in /static, can i do the usual {{ 'static', filename="foo" }} to link it, or do i have to hardcode it in?

vernal furnace
#

bruv

#

I made a todo app

#

and when I open it from my phone I see the tasks that I typed from the computer

#

how to fix that? I am using django

native tide
#

@vernal furnace do you have authentication in the app

vernal furnace
#

nope

granite pasture
#

can someone help me with how to setup django on idle

austere cloud
#

@granite pasture any errors you are facing?

native tide
granite pasture
#

i was earlier now i got it solved from youtube πŸ˜…

#

it was saying pip not recognised

austere cloud
#

Ok

granite pasture
#

umm its showing u should consider upgrading the pip version

#

how to do that?

vernal furnace
#

@granite pasture pip install --upgrade pip

granite pasture
#

ok done

#

thx

vernal furnace
#

nvm too late

#

πŸ˜„

native tide
#

HOW DO I REDIRECT TO SAME PAGE IN DJANGO?

granite pasture
#

i am just starting django
so do i need something besides udle too?

#

idle*

vernal furnace
#

@native tide
in your views.py

from django.shortcuts import redirect

 return redirect('/')
austere cloud
#

@granite pasture nope

granite pasture
#

okie thx

#

pog i m watching one piece as well

#

88 episode tho pithink

austere cloud
#

I am waiting for my hero academia

granite pasture
#

:O

granite pasture
#

ok before i start django i need to google about what is web development lemon_sweat

vernal furnace
#

Instead put the page url before the slash

#

Not the whole url

#

One min lemme get on my pc

#

@native tide Redirect works in a lot of ways, but since u only want to return it to the same page add your path before the slash

#

for example I have this in my urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('todo', views.index, name='list'),
]
native tide
#

dude I have applied the pagination

vernal furnace
#

oh

plain zealot
#

Anyone what can I do in css to keep the page from showing the edges in white

austere cloud
#

Have you tried width: 100%@plain zealot

versed lotus
#

it might be body and/or html where you need to set padding/margin to 0

#

body, html { margin:0; padding: 0 }

native tide
#

@native tide why would you want to redirect to the same page?

native tide
sullen forum
#

Im happy

#

πŸ‘

plain zealot
#

But when I stretch the page it still shows the white page

#

And in smaller sizes it still shows the white space

austere cloud
#

@plain zealot can i see your css?

raven shoal