#web-development

2 messages ยท Page 126 of 1

native tide
#

But the thing is that the API only gives whole lines, so it has to get filtered first before it gets into the final data file but it all happens in real-time

pearl quiver
#

yes, but at some point, you converted stuff in memory to be saved to the big CSV, yes?

native tide
#

I actually wanted to read the csv file from the javascript. But the javascript refuses to find my csv file, whereas my python(flask) can find it and "send" it to my javascript

pearl quiver
#

that stuff in memory is still there right after you save to the big CSV. so filter that one down to the two columns you need and save again.

#

javascript in browser shouldn't be accessing local files

#

that's kinda dangerous, if i send you a malicious javascript file, i guess where the file is downloaded and make your browser open it

native tide
native tide
pearl quiver
#

oh, lol, we need to keep these things separate

#

we're going to get confused if we mash everything together

#

step 1: save all data into two CSVs every time we hit the API, one complete CSV and one smaller CSV with only the data the javascript needs.
step 2: separate CSVs that have already been loaded (I'm assuming that's what you mean by historic data) and CSVs that haven't been loaded (current data?) to send even less to the javascript

native tide
#

Yeah so the javascript receives the historic data at once and the loaded data immediately. That's what you are saying right?

#

So then you don't have the issue of sending the CSV file again and again

pearl quiver
#

i mean ... i think your first step is to try to load the full (two column) CSV every time first

#

let's get over that hump first ๐Ÿ˜„

#

there are many many ways to optimize it after that, but maybe that should be your first step

#

see what the performance is

#

imagine if your two column CSV goes from 50mb to 50k

#

you're not really going to worry about 50k

#

even 500k is like, well. not too bad.

native tide
pearl quiver
#

if i was doing it, i would probably get that working first

#

even if it's a proof of concept

#

plenty of time to optimize after it works

native tide
#

Yeah so that's what I'm stuck with for days hahaha

#

And strangly enough I cannot find a preceding project that uses something similar

#

Which is weird

#

Thank you so much for educating me on the databases

pearl quiver
#

no problem, that's what we're here for ๐Ÿ˜„

pearl quiver
#

Vuejs is usually regarded as one of the easier to learn libraries (of the three)

#

what it can do is reload (the entire CSV) on a timer, and if there's a change, they will update the chart

#

but ... it's going to be a bit of a rabbit hole, and i don't know how much time you have

native tide
#

That's a wicked idea and would love to learn it eventually but I unfortunately don't have much time anymore. My main goal is to get dots plotted on a chart at this point... hahaha

pearl quiver
#

yeah. no problem ๐Ÿ™‚ thought i'd throw it out there in case you're interested

snow estuary
#

what is the difference between odoo framework and django ?

hollow jay
#

@vernal furnace how are your templates setup?

#

You need to remove 'base/' from your template name.

vernal furnace
#

even tho im not rendering it

hollow jay
#

Replace "base/base.html" with "base.html".

vernal furnace
#

I don't have anything like that whatsoever

hollow jay
#

There is no directory called 'base'. You are telling Django that your template is in the 'base' directory.

#

This is why you are getting a "TemplateDoesNotExist" error.

vernal furnace
#

I'm not telling django anything tho

hollow jay
#

Refresh the web page.

vernal furnace
#

Yeah the same thing happens

hollow jay
#

Create the 'base' directory inside the 'templates' folder. Then move both .html files into the 'base' directory and return to the origin code: return render(request, 'base/home.html', {})

vernal furnace
#

Oh it worked

#

thank you so much :D@

hollow jay
#

No problem! I've only worked with project-level and not app-level templates so apologies for the initial confusion!

native tide
hybrid bobcat
#

what's the difference between Apache, Nginx, and Gunicorn?

dark heath
#

Not much but a friend of mine prefers Nginx over Apache due to functionality

native tide
#

@native tide Maybe D3 would help? It's a JS data-visualization library which can create all sorts of graphs.

#

and you can load .csv

#

Thanks @native tide I also just found something similar called Papaparse

#

Cannot get it to work either

#

Never heard of it tbh, but I do know that D3 is very popular and should have lots of writeups on stuff you are encountering.

#

thanks, will look into it

native tide
#

How can you remove html elements with react?

#

By manipulating the DOM

#

You can also do it in vanilla JS

#

I'm trying d3 now @native tide but I get the same problem again. My file is not found... error 404

#

Could it be because the file you're trying to access is relative to your .html file's location? It doesn't seem like your path is.

quick cargo
#

looks like your cwd is higher than userinterface

#

is projects the top level file

native tide
quick cargo
#

is python serving the file or r u just clicking the html

native tide
native tide
quick cargo
#

no but i mean how are you testing it

#

cuz pycharm a lil fucky with cwd

native tide
#

I basically run the website I made locally, then look at the console through inspect

quick cargo
#

but how are you running it

native tide
quick cargo
#

just with python or by using pycharm

#

to open the html

native tide
#

I'm using pycharm

#

So basically I run the app using flask which gives me a link to the local website

#

Does that answer your question? I'm sorry I'm a real noob

#

First time using flask

#

So by running a python file, I'm running a server locally that hosts my website. And then I just edit the scripts, refresh the browser, check the console

#

Do you think my file is badly positioned?

quick cargo
#

i think it's pycharm running it at the top level

#
import os
print(os.cwd())```
#

put that at the top of your file

native tide
#

of which file?

quick cargo
#

and send here what it prints

#

the main file

#

of python

#

hmm interesting

#

oh wait

#

in your file for the csv

#

remove the userinterface bit of your path to the csv

native tide
#

/ltc.csv?

native tide
# native tide Ehhhhh, so how do I do it relative to the index.html file?

Accessing it relative to the .html file, I don't know if it is though! https://realpython.com/absolute-vs-relative-python-imports/

If youโ€™ve worked on a Python project that has more than one file, chances are youโ€™ve had to use an import statement before. In this tutorial, youโ€™ll not only cover the pros and cons of absolute and relative imports but also learn about the best practices for writing import statements.

quick cargo
#

it's looking for C:/Users/alaed/Google Drive/Subjects/Minor CS/DT/project/userinterface/userinterface/ltc.csv

#

also it's trying to get flask to serve the file

#

in which case it needs to be in your static folder i believe by default

native tide
quick cargo
#

send a ss of the browser terminal

native tide
quick cargo
#

the csv

#

move csv to static

#

then you should be able todo

#

/static/ltc.csv

native tide
fading helm
#

When I run the code git init in my console to put it inside my workspace in VS code, it says 'git' is not recognized as an internal or external command, operable program or batch file. Do I need to download something? I'm on Windows 10.

native tide
#

it worked

quick cargo
#

thought it might

#

flask by default only serves static content from the static folder

native tide
#

Thank you so much @quick cargo and @native tide

native tide
fading helm
#

@quick cargo can u help me with my error?

fading helm
#

tysm

#

Where should I put it?

fading helm
#

doing so rn

quick cargo
#

just follow the install, if it asks if you want it in PATH say yes

#

it might do it by defualt though and not ask which is fine

fading helm
#

it worked, thanks!

quick cargo
#

then you should be able to a) use git bash which is a better cmd and then use git

native tide
#

@native tide sweeeeeeeeeeeeeeeeeeeet d3 csv is now finally working

#

OMFG

#

I've been working on this for over a week

#

You guys are saints

#

thank you so much

#

๐Ÿ™‚

proper hinge
#

How can I select the first child of an element only if that element is of a certain type in CSS?

#

This is not the same as :first-child or :first-of-type as far as I can tell

#

The element must strictly be the first child overall, not the first of a specific type.

#

I need to check the type after I select the first child

fading helm
#

./manage.py startapp tweets just doesn't create anything. Anybody got a solution?

proper hinge
#

Hmm wait I think it just just div:first-child lol. Need to play around with it more

wicked elbow
#

anyone know why this is my api response?

{
    "detail": "Not found."
}

not getting a 404 page, just that as a response

wicked elbow
#

i guess if you have 2 slashes in your router url it doesnt work, but only 1 slash works. makes zero sense

hollow torrent
#

on digitalocean droplet

rose junco
#

how does Django know which html template file to use for each class based view?

analog arch
#

checks template_name

wicked elbow
#

anyone know why im getting a method not allowed on an axios.post? i know it works from postman. thats how i got my first 2 messages into it. so i know its not a backend issue

gaunt marlin
#

i think you need to enable CORS on your backend

wicked elbow
#

cors is enabled

gaunt marlin
#

then check the so link i just posted

#

probably you have something else in header

wicked elbow
#

no, i have a prebuilt header script for all posts containing the token and the content-type to application/json. it just doesnt make sense. ive being looking at every other post request both front end and backend. everything matches. and i supplied the same headers to postman and used the exact same data for both. it just doesnt make any sense

#

what in the hell, maybe its just node.js being slow compiling again. reset it all back to what i had originally after trying a few things and it works now ๐Ÿ™„

queen tapir
#

hello guys, I want a Django projects to contribute to? any suggestions?

twilit needle
#

can someone please help me here?

#

thanks a lot!

#

please ping me when help or there

echo mesa
#

Can someone explain how can I populate a WTForms FieldList using Flask?

#

I tried the google answers but I have a strange thing happening

#

I make sure to delete the previous data of the form and then change the data to the new data but it just reverts back to the old data even though when I check after the "Delete" it is delete and nothing exists there

past cipher
echo mesa
#

Um not exactly what I meant

#

I have a fieldList of Selects

#

I saw how the .data is looking like

past cipher
#

maybe you want to use querySelectField to prepopulate the select fields

echo mesa
#

what is that

#

wait let me google

#

sec

past cipher
echo mesa
#

it's a schedule of school clases

#

I have buttons and selects to choose a grade and a class

#

that when GETing the site (I set it to default pull from the first class) it works great

#

but when I use the buttons to choose a class the functions get all the correct parameters and the correct data is recevied form the DB but it just doesn't update it

#

I'll try the queryySelectFioeld

#

I'm not sure I understand how to use this QuerySelectField

#

Let me give an example

past cipher
#

lets say you have a class for the classform, and you have a selectfield, queryselecy will query the database, and use the result as the selectfield options

#

i'll help in ten mins if you're still struggling, g2g

echo mesa
#

ty

#

I'll try that

#

my database is a remote Firebase database and I'm getting my values as a string

#

it says this is for django and I'm using Flask

wicked elbow
#

django seriously frustrates the crap out of me... lmao

echo mesa
#

same here with Flask and WTForms

past cipher
#

then use query field on the classform

echo mesa
#

{'TwoDTable': [{'Lesson': 'ืื ื’ืœื™ืช'}, {'Lesson': 'ืกืคื•ืจื˜'}, {'Lesson': 'ืžื’ืžื”_ืžืฉื ื™ืช'}, {'Lesson': 'ื—ื™ื ื•ืš'}, {'Lesson': 'ืื™ืŸ ืฉื™ืขื•ืจ'}, {'Lesson': 'ืชื›ื ื•ืช ืžื•ื ื—ื” ืขืฆืžื™ื'}], 'changed': None, 'submitToDB': False}

#

That's my pulled data

#

I tried to make it the same as the .data of the form

past cipher
#

add all the lesson values to a list

#

wrap it all in a function

echo mesa
#

This is it nah:?

past cipher
#

so you can call the function with required paramters, and get the result as a list

echo mesa
#

That is the pulled data

past cipher
#

brother, I've just told you what you need to do...

echo mesa
#

I didn't understand that sorry ๐Ÿ˜ฆ

past cipher
#

right, so this is the pulled data:

{'TwoDTable': [{'Lesson': 'ืื ื’ืœื™ืช'}, {'Lesson': 'ืกืคื•ืจื˜'}, {'Lesson': 'ืžื’ืžื”_ืžืฉื ื™ืช'}, {'Lesson': 'ื—ื™ื ื•ืš'}, {'Lesson': 'ืื™ืŸ ืฉื™ืขื•ืจ'}, {'Lesson': 'ืชื›ื ื•ืช ืžื•ื ื—ื” ืขืฆืžื™ื'}], 'changed': None, 'submitToDB': False}

And you only want the lesson name to appear in the select field, right? Like ืื ื’ืœื™ืช

echo mesa
#

I want it to be selected

#

but when you click the select it will have the other normal options

#

how do I provide the QuerySelectField is the dataset?

wicked elbow
#
IntegrityError at /api/comments/
NOT NULL constraint failed: web_comments.post_owner_id
Request Method:    POST
Request URL:    http://127.0.0.1:8000/api/comments/
Django Version:    3.1.4
Exception Type:    IntegrityError
Exception Value:    
NOT NULL constraint failed: web_comments.post_owner_id

why am i getting this? im supplying everything it needs... the post owner id matchs to something in the database its linked to. i dont understand. ive tried multiple different things and end up with different errors everytime

#
{
    "post_ref": "5",
    "user_comment": "2",
    "post_owner": "1",
    "comment": "Such a pretty place to visit!"
}
``` data submitted through postman
quick cargo
#

post_owner_id

#

missing

twilit needle
wicked elbow
#

its not post owner id. thats the foreign key. the model name is post_owner links to id in profile.

quick cargo
#

well your error is saying that table web_comments is missing a post_owner_id as part of the lookup and failing the constraint

wicked elbow
#

its saying that it doesnt exist in the Profile table i think, not that its actually missing. it has to do with ForeignKeys, not a simple post query

quick cargo
#

yeah, you're failing the constraint

#

that post_owner_id cannot be Null

wicked elbow
#
class Comments(models.Model):
    post_ref = models.ForeignKey(Posts, related_name="post_ref", on_delete=models.CASCADE)
    user_comment = models.ForeignKey(Profile, related_name="commenter", on_delete=models.CASCADE)
    post_owner = models.ForeignKey(Profile, related_name="poster", on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now_add=True)
    comment = models.TextField()
``` thats the model
#

it isnt null though, theres a profile row with an id of 1 and 2... i know for a fact

wicked elbow
#

why? i didnt change anything, just seperated it into its own app instead of being apart of the main app without changing anything else and works like a charm now...

tulip shoal
#

Having trouble with using comparison operators on a jsonfield, like json__count__gt=1000 - it returns nothing, I believe it may be evaluated as string somehow.

rose field
#
        .Packages > * .dark-mode {
            background-color: black;
            color: white;
        }
#

i cant seem to get the color switch working

rain bison
#

anyone here?

tender seal
#

how to place an element a a particular place?

near bison
#

you mean using css ?

tender seal
near bison
#

Take a look into the position propery.
if you want to place a element respective to the window., you can you position: fixed and change the left, right, top, bottom attribs

tender seal
#

ok

near bison
#

or use position: absolute if you want to change the position respective to a non - static positioned parent elelment.

tender seal
#

actually I need to place an image

#
.mic{
    color: white;
    width: auto;
    height: auto;
    top: 10vh;
    margin-left: 200px;
    margin-top: 50px;
    position: right;

}
```this is what I have
tender seal
near bison
#

try position: fixed;

tender seal
#
.mic{
    position: absolute;
    width: auto;
    height: auto;
    left: 300px;
    top: 270px;

}```this?
#

works but what if I resize the screen?

#

it stays there

near bison
#

does position: fixed; work for you ? it places elements with respect to the screen.

#

the element won't change position even when you scroll the page

tender seal
#

i did the % replaced for px

#

so now It sorta wroks

primal sonnet
#

Is there anything about Django here?

native tide
#

@primal sonnet Yeah, you have a question about it?

primal sonnet
#

Yes

native tide
#

Sure, go ahead and ask

primal sonnet
#

So the scenario is like this. Iโ€™m trying to build this website for the college club.

#

I wanna know how to structure it. Are โ€œAppsโ€ supposed to be pages?

native tide
#

@primal sonnet apps are essentially different parts of your entire application. Think of them as individual pieces of a puzzle. You can have one app deal with the dashboard, another for user accounts/logins, etc.

#

It's just a way of splitting up your project into different sections

primal sonnet
#

I see.

#

Just one more thing

#

Could you suggest any resource to help me dig into django further ?

native tide
#

The only way I learn new frameworks is making projects

#

I will read about the framework, watch some youtube videos about it to know what's possible

#

I'll say "I'm going to create such a project"

#

And I will just research, learn, and create

vernal furnace
#

Nut, Since when did u learn Django ๐Ÿ‘€

native tide
#

I'm still learning it I'm a noob tbh

#

I started a few months ago

#

Then learnt React because of it

mortal mango
#

how do you put a label inside a django widget?

indigo kettle
#

you need to set placeholder on the formfield

mortal mango
indigo kettle
#

I think it's the same thing basically?

#

you just need to use the correct widget

mortal mango
#

I got unexpected keyword argument 'label'

indigo kettle
#

can I see what you're writing?

#

I don't think you need the label argument

#

anyway

#

and use widget.Textarea

tulip beacon
#

guys I have a doubt in making of a zoom clone

#

My host camera is working, but when I'm connecting with another device for the same meeting, I can only see one

#

what should I do?

mortal mango
# indigo kettle can I see what you're writing?

This is my form```py
class CreateNewShortURL(forms.ModelForm):
class Meta:
model=ShortURL
fields = {'original_url'}

    widgets = {
        'original_url': forms.TextInput(attrs={'class': 'form-control'})
    }
mortal mango
#

@indigo kettle โฌ†๏ธ

woeful atlas
#

Hello, I have an error in a module (quart_discord) that I did not have before. I am using python3.8. Here is the error:

>>> %Run test_app.py
 * Serving Quart app 'test_app'
 * Environment: production
 * Debug mode: True
[2021-01-08 21:08:54,303] Running on http://127.0.0.1:5000 (CTRL + C to quit)
[2021-01-08 21:08:57,498] ERROR in app: Exception on request GET /
Traceback (most recent call last):
  File "/home/pi/.local/lib/python3.8/site-packages/quart/app.py", line 1862, in handle_request
    return await self.full_dispatch_request(request_context)
  File "/home/pi/.local/lib/python3.8/site-packages/quart/app.py", line 1887, in full_dispatch_request
    result = await self.handle_user_exception(error)
  File "/home/pi/.local/lib/python3.8/site-packages/quart/app.py", line 1104, in handle_user_exception
    raise error
  File "/home/pi/.local/lib/python3.8/site-packages/quart/app.py", line 1885, in full_dispatch_request
    result = await self.dispatch_request(request_context)
  File "/home/pi/.local/lib/python3.8/site-packages/quart/app.py", line 1933, in dispatch_request
    return await handler(**request_.view_args)
  File "/usr/local/lib/python3.8/site-packages/tests/test_app.py", line 25, in index
    if not await discord.authorized:
  File "/usr/local/lib/python3.8/site-packages/quart_discord/client.py", line 184, in authorized
    async with await self._make_session() as discord_:
  File "/usr/local/lib/python3.8/site-packages/quart_discord/_http.py", line 93, in _make_session
    return OAuth2Session(
  File "/home/pi/.local/lib/python3.8/site-packages/async_oauthlib/oauth2_session.py", line 91, in __init__
    self.auth = lambda r: r
AttributeError: can't set attribute```
I know this is not an error of my code because even the given example with the correct information does not work. The error occurs when an interaction with discord occurs.There was no error before (operating system reset)
barren drum
#

Let's say you have a client (be it a person, artist, org or small shop) who is interested in having a website for him on the internet, something basic with html, css for example, maybe 2 or 3 pages maximum or a landing page Who wants nothing more than to have visibility, provide access to their social networks and direct contact, is it also good to follow all these practices, for example the creation of a userflow?

lavish ruin
#

does anyone know a way to load a chunk of html from another file using flask/jinja? i have all my files already made, but when i make a new one i have to update my navbar every time. i was wondering if i could insert the whole value of my navbar.html inside a certain location of another html document

<!-- navbar.html -->
<div class="topnav" id="myTopnav">
  <a href="#home" class="active">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
  <a href="#about">About</a>
  </a>
</div>
<!-- homepage.html -->
<html>
  <head>
    <title>homepage</title>
  </head>
  <body>
    <!-- navbar.html goes here -->
    <p>content of home page blah blah blah</p>
  </body>
</html>
native tide
#

{% extends "layout.html" %}

radiant canyon
#

can someone pls help me

#

?

native tide
#

So put navbar.html instead of layout in the files you wanna use your navbar in, at the top of the page

radiant canyon
elder girder
#

does building a website cost money?

vestal hound
#

does building a website cost money?
@elder girder you mean the code?

#

not unless you pay someone to do it for you

#

or do you mean hosting?

#

then it depends on how good a plan you want

#

certainly there are free hosting plans

twilit needle
#

can someone please please please help me

#

am stuck with this for 3 days now

#

please...

#

It would mean a lot for a solution...

crude ingot
#

how do i download folium in python?

twilit needle
pliant magnet
#

hiii

tawny tendon
#

Stop Pinging Me

echo mesa
#

I'm trying to use a | list filter to transform a generator to a list but for some reason I get a very weird error
jinja2.exceptions.TemplateRuntimeError: no test named 'ืื ื’ืœื™ืช'
that in the line {% set removedChoices = removedChoices | list %}
removed choices is define as a generator created using | reject 'ืื ื’ืœื™ืช' is what the value of the the generator is suppsoed to give

#

I'm really new to Flask, Jinja2 and WTForms overall but from what I seen it's not supposed to use tests?

vestal dove
oblique mulch
#

I'm in the process of making a youtube download-er which uses PyTube and want to host it on a web server. But the issue is that I have clue what would be the most cost effective way of downloading the videos from Youtube and then allowing the user to download the video on their end, all with not using a ton of storage and bandwidth as paying for hosting isn't quite an option at the moment.

#

Using Django as my framework

twilit needle
echo mesa
#

How do i use the | list filter in Jinja2

haughty turtle
#

In my JS file I am grabbing the cookie value but its null, in order to send a CSRF to Django

    getCookie = (name) => {
        let cookieValue = null;
        console.log(document.cookie)
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }``` of course its returning a null value to Django and in Django when using a POST request I get `Forbidden (CSRF cookie not set.): /filter/
[09/Jan/2021 07:45:24] "POST /filter/ HTTP/1.1" 403 2864` This worked fine for me exactly as code was before, but I transferred my Django files to a different PC and now its returning me with this problem
#

Ah upon further reading as I am using React+Django, React rendering my page thus my CSRF cookie is not initially provided on render as no contact with Django has been made. Have to set this initially on set up if none set...

echo mesa
#

I'm struggling with WTForms and jinja2

#
{% set removedChoices = template_choices|reject("eq", template_previousSchedule[6 * (hour - 1) + day]['Lesson']) %}
                                    {% set removedChoices = removedChoices | list %}
                                    {% set newList = [template_previousSchedule[6 * (hour - 1) + day]['Lesson']] %}
                                    {% set currentChoices = newList + removedChoices %}
                                    {{ template_previousSchedule[6 * (hour - 1) + day]['Lesson'] }}
                                    {{ template_form['schedule'].TwoDTable[6 * (hour - 1) + day](default=currentChoices)}}
#

I'm trying to place select fields from a field list and set each one's default to some kind of element but I don't understand how to do so

#

is there something like document.getElementById from JS in Python using Flask?

haughty turtle
echo mesa
haughty turtle
echo mesa
#

is there no way to do that in Python?

arctic thicket
#

Hi I need help in django models. In which user can add Ingredients of the Dish by three ways - by images(can be multiple), by blog link, and can add manually by text(it also can be multiple ).

User can add any one way of three.

tulip beacon
#

guys why is command error

const socket = io('/')

#
const myPeer = new Peer(undefined, {
    host: '/',
    port: '3001'
})

myPeer.on('open', id => {
    socket.emit('join-room', ROOM_ID, id)
})
 

socket.on('user-connected', userId => {
    console.log('User connected' + userId)
})```
#

this is the full code

quasi notch
#

does someone know how i can test my proxies with python?

#

and get the speed of them

lilac lintel
#

Hey guys! Not 100% sure where to put this, but basically this is what I need help with:
I am making a program that can tell me whether an item is in stock or not on the IKEA website by checking the color of a pixel on the screen. My question is; Is it possible to somehow only grab the pixel color of a window instead of the whole screen?

drowsy rune
#

hello everyone

native tide
#

@lilac lintel If the stock indicator is a html element such as a div you can access its background color

#

then you can determine whether it's in stock or out of stock

lilac lintel
#

Oh, didn't know that

#

Thanks for the help!

native tide
#

@lilac lintel You could probably use Selenium for this

#

and then access the DOM element, and find its background color

hollow jay
arctic thicket
hollow jay
# arctic thicket PostgresQL

After a quick google search, you could add a FileField() to the Dish model for images. You can use a CharField for the text and hyperlink.

#

It can't be stored in the same field as they're different data types.

arctic thicket
hollow jay
#

So you're only allowing 1 option and not all 3?

#

There's way of doing this... Iโ€™m unsure what is the most โ€˜perfectโ€™ way โ€“ which often leads to over-engineering and never solving the problem. But, for your scenario, you could have a CharField (in the Dish model) with CHOICES: Image, hyperlink, or text. You would then create three different models with the respective fields (CharField, FileField, and URLField), each has a ForeignKey to a Dish. The choice selected dictates which model you will use; this logic can be handle in the save() (or clean()) method.

native tide
#

Use imagefield

hollow jay
autumn fjord
#

yay my web is now fast! ๐Ÿ™‚

#

got some new internet XD

#

๐Ÿ™‚

glossy arrow
#

Hey guys

#

Can Flask-Socketio work when you do flask-run from the terminal?

glossy arrow
#

Nvm I got it

dawn heath
#

is possible to order the cveid per id number, and keep the newest at the first , but keeping the ordering?
class Vulnerabilities(models.Model):
cveid = models.CharField(max_length=255)
last_modified = date
class Meta:
ordering = ('-last_modified',) # the newest cve at the beginning

vestal hound
#

There's way of doing this... Iโ€™m unsure what is the most โ€˜perfectโ€™ way โ€“ which often leads to over-engineering and never solving the problem. But, for your scenario, you could have a CharField (in the Dish model) with CHOICES: Image, hyperlink, or text. You would then create three different models with the respective fields (CharField, FileField, and URLField), each has a ForeignKey to a Dish. The choice selected dictates which model you will use; this logic can be handle in the save() (or clean()) method.
@hollow jay I think this works

vestal hound
#

hm anyone know how to use a CSS animation to create the effect of something moving from a static position to a fixed position?

lime glade
native tide
#

Hey guys, I'm new at code at all, knowing only Python which is my entry language. I've thinking about getting into web development but haven't seen much about python in the front end. Is it really worth learning Flask/Django or should I just go back to the beginning and try JavaScript instead? I may be sounding stupid right now and if so I'm sorry

real rain
#

and if u want to build better websites, you'll eventually be forced to learn javascript (my current situation)

native tide
#

Hey guys, could you let me know if I'm doing this right? Any other ways of doing it, any decorators?

class Suite(models.Model):
    suite_id = models.CharField(max_length=5, primary_key=True)

    def __str__(self):
        return f"{self.suite_id}"


class Customer(AbstractUser):
    suite = models.OneToOneField(Suite, on_delete=models.CASCADE)

    def assign_suite(self):
        self.suite = Suite(suite_id = get_random_string(4, "AB123456789"))

I want to create a customer then assign them a suite.

a = Customer()
a.assign_suite()
lucid vine
#

Anyone uses selenium and pylance? This is the first module for which I get 0 autocompletion, for some reason it doesn't recognise it

lucid vine
native tide
#

@lucid vine is there any way to set Suite based on whenever I save a customer?

lucid vine
#

if you use @property and write a setter method it will set it during __init__

twilit needle
#

someone please help me here, thanks a lot!

cold portal
misty pecan
#

plz help

#

i wanna know basics

zinc hill
#

!ask

glossy girder
#

hey guys

#

so, i'm looking for a tutorial / doc where it is explained how to serve different type of media files(mainly mp4) to a web aplication

#

I don't really know the correct terminology, so i come here to ask how it is called.

#

Something like this

glass yew
#

@native tide you import Post already so i think you can just call objects.all()

#

lemme look over it again

void summit
#

@native tide it's django request right ?

#

you have to do

request.POST

to access all params within the request

#

is it what you want to do ?

#

to me it seems good

#

maybe it's just your editor that couldn't resolve the object reference

#

you can use PyCharm ๐Ÿ˜„

glass yew
#

i deactived the linting for my vscode

#

lol

void summit
#

nah don't worry, it has as much as vscode features at least

#

the only benefit of the pro version is the ability to access your databases from pycharm

glass yew
#

i access my database through vscode

#

the nice thing is theres a nice plugin for everything

void summit
#

what kind of plugin do you use ?

twilit needle
glass yew
lucid vine
#

Can heroku be used to deploy python web apps in any framework or only django / flask?

tulip beacon
#

hello guys, I cant view my image in html

#

what should I do?

tulip beacon
#

hello?

native tide
#

@native tide get the gitHub educational pack

silent owl
#

I have a m2m field in my Post model called votes, I'm trying to only return the vote fields that match the user making the request, as a sort of optional field. So excluding all the votes that don't match the user making the request. I'm not sure how I can achieve this in Django.

    post = Post.objects.filter(id=post_id, votes__user=self.request.user)
native tide
#

if you are a student

#

or have access to a school email

#

you can get PyCharm Pro for free etc, gives you boilerplates for Flask/Django applications and all sorts

#

You don't need an ID, just a school email

#

And if you really need one you can just buy .edu emails online for $1

native tide
#

check ur img link and see if u have lnked it right

native tide
#

When playing with your models within the shell python manage.py shell, will my signal functions still work?

#

like this one

@receiver(pre_save, sender=Suite)
def create_suite(sender, instance):
    instance.suite_id = get_random_string(5, "ABC123456789")
    instance.save()
#

Because when I try it's not, I'm not sure if it should be picking it up.

haughty turtle
#

Ok I got my projects done for my portfolio, its 3 websites, I want to display them in one, whats the way to go about this?

#

@native tide No reason why it should not o.o

native tide
#

Just as you typed that message, I found that if I put my signals in their own file, e.g. signals.py, it wouldn't work

#

But if I put the signals in the same file as my models, models.py, it does work

#

Oh

#

Probably because when I'm in the shell I forgot to import the signals

#

๐Ÿคฆโ€โ™‚๏ธ

silent owl
haughty turtle
silent owl
#

yeah, think I've figured it out though by using .set() maybe there is a better way though

                post = Post.objects.filter(
                    id=post_id)
                votes = post[0].votes.filter(user=self.request.user)
                post[0].votes.set(votes)
haughty turtle
#

to exclude the votes you do not want

silent owl
#

will do, thanks

haughty turtle
#

post[0] will only return the first object

silent owl
#

yeah thats all I want

#

its for a single post

haughty turtle
#

is there only ever one at a time? then use get instead of filter

#

post.objects.get().votes.exclude()

silent owl
#

hmm yeah I tried that but I'm getting errors using get

haughty turtle
#

Whats the error ?

silent owl
#
class GetPost(viewsets.ModelViewSet):
    serializer_class = GetPostSerializer
    http_method_names = ['get']

    def get_queryset(self):
        name = self.request.GET.get('subreddit', None)
        post_id = self.request.GET.get('post_id', None)

        # try:
        if name is not None and post_id is not None:
            if Subreddit.objects.filter(name__icontains=name).exists():
                post = Post.objects.get(
                    id=post_id)
                return post

'Post' object is not iterable

modest shale
#

hi everybody

#

i have question

#

can i write a game at web browser ?

#

if i can, how ?

silent owl
haughty turtle
#

One sec in a match ๐Ÿ˜…

silent owl
#

haha all good

haughty turtle
#

Ah your using REST framework havent touched that

edgy isle
#

Right so I am using Flask + Requests to send a POST request to a external server and its returning "TypeError: 'Request' object is not iterable" the traceback leads to this:

@main.route('/send/ban', methods=['POST'])
def send_ban():
    r = requests.post('http://localhost:5001/upload/ban', data=request, timeout=5) # This is the traceback line
    
    if r.status_code == 200:
        if not r.text.find('Uploaded'):
            flash('Successfully Banned User', 'primary')
            return redirect('/ban')
    elif r.status_code == 404:
        flash('Unable to ban user, server appears to be offline', 'danger')
        return redirect('/ban')
    elif r.status_code == 500:
        flash('Unable to ban user, server appears to be having issues', 'danger')
        return redirect('/ban')
haughty turtle
noble smelt
#

Guys

#

Is there anyway to serve media files for free? Cause heroku won't let me

haughty turtle
haughty turtle
noble smelt
#

It asks for credit card

edgy isle
#

You could use repl.it HTML server and just upload the images to there

haughty turtle
#

@noble smelt But it does not charge you

noble smelt
#

Thanks guys

silent owl
#

@haughty turtle that worked, thanks!! is there a way to upvote you? sorry I'm new here.

drifting furnace
#

Is there a way to design a website with Python (front end), or code the functionality of the website with Python (back end)?

edgy isle
#

And frontend just use normal stuff like HTML, CSS, JS

drifting furnace
#

ok thx

edgy isle
hollow jay
hollow jay
hollow jay
weary bough
#

plz help with this error

toxic flame
#
class CreateUserForm(UserCreationForm):
  class Meta:
    model = User
    fields = ['username', 'email', 'password1', 'password2']
#

so the email doesnt save

#

is there anyway to fix it?

native tide
#

@toxic flame where does the email not save? In the database? Have you checked that your view is receiving a value for email? You need to be more specific.

toxic flame
#

yea

#

it doesnt save in the database

haughty turtle
#

@toxic flame All you are showing is the model not how you are saving it in your view

#

Show more code

toxic flame
#
    form = UserCreationForm(request.POST)
    if form.is_valid():
      user = form.save()
      username = form.cleaned_data.get('username')

      Client.objects.create(
          user=user,
          first_name=username
      )   ```
#

dont have to mind the others, it's just a .save() like the default.

hollow jay
#

Does any other data get saved?

native tide
haughty turtle
#

@toxic flame Print out the email part of the form check what you are getting

hollow jay
#

Is the form even valid?

toxic flame
#

yes other data gets saved

#

and yes form is valid orelse it wont save

uneven wren
#

Hi, i am doing my Django project and now am dealing with creating cart. At this point i am creating by every click on "add to cart" button new OrderItem object and saving that to database. Is that ok ? or should i use session to store my cart ? Thanks for help

#

should i ask about this in help channel or is this ok here ?

toxic flame
#

You should use Javascript, localstorage for shopping carts

haughty turtle
uneven wren
toxic flame
#

im lookign up how ot print the email

haughty turtle
#

In debug it works out the box I believe

#

Prints to the cmd

toxic flame
#

damn

#
<tr><th><label for="id_username">Username:</label></th><td><input type="text" name="username" value="JohnDOe2" maxlength="150" autocapitalize="none" autocomplete="username" autofocus required id="id_username"><br><span class="helptext">Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</span></td></tr>
<tr><th><label for="id_password1">Password:</label></th><td><input type="password" name="password1" autocomplete="new-password" required id="id_password1"><br><span class="helptext"><ul><li>Your password canโ€™t be too similar to your other personal information.</li><li>Your password must contain at least 8 characters.</li><li>Your password canโ€™t be a commonly used password.</li><li>Your password canโ€™t be entirely numeric.</li></ul></span></td></tr>
<tr><th><label for="id_password2">Password confirmation:</label></th><td><input type="password" name="password2" autocomplete="new-password" required id="id_password2"><br><span class="helptext">Enter the same password as before, for verification.</span></td></tr>```
#

yep messy afk

haughty turtle
#

Dude your printing out the whole form.

toxic flame
#

ill just parse the email by its id and add it manualy

haughty turtle
#

Get the cleansed email version as you did for username

haughty turtle
toxic flame
#

alright

haughty turtle
#

Your forms does not have an email section.

toxic flame
#

yes it does

haughty turtle
#

Your email input is not in there.

toxic flame
#

i see i will have to debug my code further

uneven wren
#

I have one more question. I need to develop filters for my restaurants and i need to be able to filter by city and at the same time by category like vegetarian and stuff. Now i can select just by city or by category

haughty turtle
uneven wren
#

well my restaurant has city and category, but how i cant pass both of category and city to my ListView ?

#

on page there is an input field for city and buttons for category

haughty turtle
#

Input and Selections

#

Upon submitting the form you have the city entered and the category you then filter based on those results

#

Although city should be a selection element also, as you likely won't have a restaurant in every city and there are multiple ways to write a city. So you would need to control this through a selection element

zinc hill
#

I have a question about Django, Do people normally just use pure Django or do they use it with other "framework" like react or anyother stuff?

#

by people i mean like if a company was to use django

#

not like beginner

native tide
#

@zinc hill django is just a backend framework

#

so yes if you wanted to make a website you'd think about the frontend too, and if you want to do that well, you'd use a framework like React

#

React/Vue/Angular etc.

zinc hill
#

ok I just wanna make sure

native tide
#

@zinc hill If you're wondering if it's worth to learn frontend frameworks, I think it definitely is ๐Ÿ‘

hollow jay
#

If you want a job then a frontend framework is required.

#

If you just want to focus on Django (and Python lets say), use something like Bootstrap or Tailwind to make it pretty.

zinc hill
#

I have been learning but I dont know if people just use pure django where everything is in django like the templates, static

#

my current one is a front-end that just request stuff from djago

hollow jay
#

You can build a website many different ways. Depends on the situation.

#

People switched fron static to rich JS websites; then SPA; now some are converting back to static.

#

Again, depends on the product.

zinc hill
#

ok thanks glad that im not wasitng time

native tide
#

I'd say React + Typescript is pretty hype rn

#

So there's good opportunity with those technologies

zinc hill
#

yeah I saw that

hollow jay
#

If you want a job... then learn React.

#

If you want some fun... perhaps Dart

haughty turtle
#

@zinc hill if you are looking for a pure backend job no need to learn js

#

No need for fancy designs, etc. Just get what you need working on the page. If you want to be a full stack learn js sure.

zinc hill
#

yeah the reason why I ask that question is because from my research, alot of fullstack django+react tutorial was not decouple like react was sitting in the template instead of its own folder. So I not sure if that was the way to do it or decouple everything was the way.

#

my approach was create a django backend and have a separate project for a front-end and just request the data

#

instead of passing "parameter" to html or something idk

ashen sparrow
#

Hi guys, I am writing a little something on django vs flask vs FastAPI. would love to get what the community thinks is better for small, medium, and large proj.

vestal hound
#

on what kind of project?

#

and other requirements

#

but I would defo say check out FastAPI, it's p cool

#

the main thing about Django is convenience

#

it has more or less everything you need

#

but some of its patterns are a bit dated

#

Flask is better for smaller projects IMO

ashen sparrow
#

@gm thanks for your input. I have, infact, worked on fastapi in a few projects. I am trying to conclude my views and hence I'm gathering the community's perspective.

I want to know what you mean by 'kind of project' and other requirements? Can you give an example. Lets consider we need to make a REST api and obviously, be connected with a db

#

I also want to point out, that thought DRF is really powerful especially with the serializers, ORM, and generics. FastAPI seems really interesting too. It reminds me of the simplicity of Flask. Additionally, the native support of asgi pydantic and openai means better testing, validation, and response time. Do you think Django is a better choice when we need to aim for the moon and think of scaling the project in the future?
I agree its ORM is hands down the best, but I believe with a good crud.py and schema validation using pydantic in FastAPI, it is superior to django.

tulip beacon
vestal hound
#

being a newer framework and built with ASGI in mind

#

which also means you can use SQLAlchemy with it, which in its most recent release is (experimentally) supporting async

#

on the other hand, Django was always built for sync

#

and is now transitioning...but the ORM in particular isn't async-ready

ashen sparrow
#

Yes. Asgi > wsgi

vestal hound
#

also, DRF doesn't support async

#

and

#

SQLAlchemy > Django ORM

ashen sparrow
#

The community should be accepting FastAPI soon enough. But if Django is able to somehow bring in async natively, there's no stopping Django bois ๐Ÿ˜‹

vestal hound
#

in terms of power for sure

ashen sparrow
vestal hound
#

in terms of power

#

and expressiveness

ashen sparrow
#

Don't you need to write raw sql in alchemy?

vestal hound
#

nope

#

it's an ORM

#

in particular when you want to write queries involving joins and subqueries

#

SQLAlchemy starts to shine

#

the equivalent in Django can be messy at best

#

and impossible at worst (without raw SQL)

ashen sparrow
#

Yes agreed. I tried making joins in Django ORM and it wasn't fun.

vestal hound
#

basic joins are fine but

#

anything beyond that

#

starts to get icky

ashen sparrow
#

Good to learn more about SQLaclhemy

#

If that's the case, big scalable projects specially with async, will adopt FastAPI.

#

Thanks @vestal hound .

#

I'll include the stuffs i learned from our conversation in the article.

vestal hound
#

yw

sturdy pike
#

gm

#

You're awesome man

#

Keep being you

vestal hound
#

thank you ๐Ÿ™‚

modest shale
tulip beacon
#

guys I have a problem in importing image to my .js file

#

can anyone help me

tulip beacon
#

hello?

#

anyone?

wicked elbow
#

man why is django so overly complicated... why cant one class do both get and post with ForeignKeys

wicked elbow
#

hey so how can i check if a row already exists in the database? like the whole row not just fields....
for example table is this:

id: 1,
user1: A,
user2: B

i need to check if this combination exists already. so the next rows cant be:

id:2,
user1: B,
user2: A
or,
id:3,
user1: A,
user2: B

and i dont want repeats in the database of the same group

#

i mean i suppose i could simply run a validation field with unique set to true

gaunt marlin
wicked elbow
pallid laurel
#

!!!Help

#

Any body can help for cloudinary custom uploader for models in django? Thank you !!

wicked elbow
vestal hound
#

@wicked elbow what model is this

wicked elbow
vestal hound
#

show me your model definition

#

actually, you know what

#

what I would do is

#

when creating an instance

#

enforce user1.id < user2.id

#

with a check constraint

#

and then the abovementioned unique constraint

#

that said

#

it seems like you could just use a recursive ManyToManyField...?

#

if I understand you correctly

wicked elbow
#
class MessageGroups(models.Model):
    user1 = models.ForeignKey(Profile, related_name='user1', on_delete=models.CASCADE)
    user2 = models.ForeignKey(Profile, related_name='user2', on_delete=models.CASCADE)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['user1', 'user2'], name="UniqueGroup")
        ]

class Messages(models.Model):
    msg_group = models.ForeignKey(MessageGroups, related_name='msg_group', on_delete=models.CASCADE, null=True)
    sender = models.ForeignKey(Profile, related_name="owner", on_delete=models.CASCADE, null=True)
    recipient = models.ForeignKey(Profile, related_name="recipient", on_delete=models.CASCADE, null=True)
    timestamp = models.DateTimeField(auto_now_add=True)
    message = models.TextField(null=False, blank=False)

those are the models. just trying to check both ways so a new group isnt created

vestal hound
#

hm.

#

yeah, I think you want a self M2M field

#

through an explicit model

#

if you want to use its PK as a FK

wicked elbow
#

i know, its the sender and reciever are repetive but it allows to id who sent the message

vestal hound
#

that is more or less what I did for my chat

#

except

#

well, some slight differences but nothing big

#

anyway yeah think about my suggestion

wicked elbow
#

this almost works, but its not truly unique_together because AB needs to be equal to BA. still trying to figure out how to do it.

#

and yea databases in django arent exactly easy. many ways to check, but how to do it in django is a different story.

sonic ferry
#

Why is it, when you urllib.parse.quote/encode strings before sending to a route, they look double quoted in address bar?
So for example:
<a href="{{ url_for('test', username='El Niรฑo'|urlencode) }}">testing</a>
shows: localhost:5000/test/El%2520Ni%25C3%25B1o in address bar,
but username is El%20Ni%C3%B1o inside the route function?

wicked elbow
# vestal hound that is more or less what I did for my chat

when i do the create, i could force the smaller user id to always be first right? so therefore if user id of one is 1 and user id of the other is 2, and the query sent 2 and 1 as the ids it would force id number 1 into user1 and id number 2 into user2 correct?

#

so for instance:

def create(self, validated_data):
    if validated_data['user1'] < validated_data['user2']:
        user1 = validated_data['user1']
        user2 = validated_data['user2']
    else:
        user1 = validated_data['user2']
        user2 = validated_data['user1']

    group_create = MessageGroups.objects.create(
        user1=user1,
        user2=user2
    )
    return group_create
vestal hound
#

because

#

of the additional constraint

vestal hound
wicked elbow
# vestal hound yes

alright, had to do some modifications because its a Foreign key, but this works

class MessageGroupPostSerializer(serializers.ModelSerializer):
  class Meta:
    model = MessageGroups
    fields = ['id', 'user1', 'user2']

  def create(self, validated_data):
    if validated_data['user1'].id < validated_data['user2'].id:
      user1 = validated_data['user1']
      user2 = validated_data['user2']
    else:
      user1 = validated_data['user2']
      user2 = validated_data['user1']

    group_create = MessageGroups.objects.create(
    user1=user1,
    user2=user2
    )
    return group_create
#

thats way to overly complicated for a simple solution lmao but here we are lmao

#

@vestal hound do you know where to put the try: except to catch the integrity error thrown when it fails? so i dont get the error

#

not really helpful in the front end if it already exists and i get the django help page back

vestal hound
wicked elbow
#

ah ok, i did it on the raise_exception haha. one line higher and it didnt work lmao thanks

fallen mango
#

Can anyone tell me what all things to take care of before building a project in Django that will be hosted on domain.

Like makin sure that web server support python...
Anything else?

boreal galleon
#

Here what does class Person(models.Model) mean?

Model is a class, but what is "model" and in the official django repository i am not able to find Charset method in Model class

hollow jay
#

Django adheres to the MVC patterns and bases its db scheme behind models. So when you create a Person class which inherits Model, you are telling Django to create a scheme for a Person.

#

The equivalent to charset is charfield.

haughty turtle
modest shale
hollow jay
#

Start easy.

haughty turtle
modest shale
#

flask

haughty turtle
#

Each change you make with Django for it to take effect you have to reload the page

modest shale
#

i will do with flask

haughty turtle
#

Same with flask .

modest shale
#

oh okok

#

but i cant understand

#

chess interface

#

how can i create it

#

with js

#

or flask ?

haughty turtle
#

Both.

modest shale
#

o_0

haughty turtle
#

If you are creating an online game.

modest shale
#

incrediblle

#

just tictactoe

#

maybe multip

#

maybe p vs al

haughty turtle
#

As you need to store the data in your server(flask, django)

modest shale
#

thank you guyd

#

guys

twilit needle
#

thanks a lot guys

native tide
#

@modest shale For a simple online game like tictactoe, you can just do it with JS.

If you need to store backend information like account information, etc. then that is where a backend framework comes in (django/flask/express.js)

fickle fox
#
app = Flask(__name__)


@app.route('/')
def hello():
    return render_template("index.html", name="Jerry")

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

why i cant load index.html file

#

???

tacit anvil
#

the error is too long to paste

native tide
#

@tacit anvil show your ModelSerializer

tacit anvil
#
from rest_framework import serializers
from .models import Room

class RoomSerializer(serializers.ModelSerializer):
    class Meta:
        model = Room
        feilds = ('id', 'code')
tacit anvil
#

oh

#

lol\

#

thanks

fickle fox
native tide
#

guys I've been getting this error and I don't really understand what to do, I've been trying to search it up and I can't understand/know what is happening here:

django.db.utils.OperationalError: foreign key mismatch - "api_customer" referencing "api_suite"

This only occurred when I tried to set suite_number of my Packages table to be my primary_key, is there any reason why this is not allowed?

Suite:

class Suite(models.Model):
    suite_number = models.CharField(max_length=5, primary_key=True)

    @property
    def suite(self):
        return f"{self.suite_number}"

Customer:

class Customer(AbstractUser):
    suite = models.OneToOneField(to=Suite, on_delete=models.CASCADE, null=True)
    premium = models.BooleanField(null=False, default=False)
native tide
tacit anvil
#

it was working legit a second ago now it isnt

#

and i get this

native tide
#

Exception Value: UNIQUE constraint failed: api_room.admin

#

It's working, it's just that the data you inputted already exists and is not unique in your table

tacit anvil
#

oh ok thanks

fickle fox
#

@native tide

native tide
# fickle fox

You need a templates folder, flask serves templates from there

fickle fox
#

oh that makes sense

#

thanks

native tide
#

Oh, and the previous issue was a naming issue. I was trying to setup a foreign key with the name suite within Packages and it was hard to spot because I had suite already as a class property...

#
class Suite(models.Model):
    suite_number = models.CharField(max_length=5, primary_key=True)


class Packages(models.Model):
    suite = models.ForeignKey(Suite, on_delete=models.CASCADE, null=True)```

How can I access Packages from Suite?
hollow jay
#

Packages.objects.filter(suite=...).

native tide
hollow jay
#

You cant (as far as I'm aware) because there's no connection from Suite to Package; only Package to Suit.

native tide
#

Would there be any way to create that relationship?

#

Am I understanding this right? The foreignkey provides a ManyToOne relationship, with the "One" being the Suite and the "Many" being the Packages?

#

I found a way to access the reverse relationship, using TableName_set followed by .filter(), .all(), etc.

lavish prismBOT
#

Hey @fickle fox!

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

fickle fox
#

can somneone hgelp me with this

#

i cant create db

tacit anvil
#

hey, so im makign a website with django and react and when i try to run the website i get no errors but nothing shows up. i have the urls correct but nothing shows up

#

This django and react tutorial covers how to integrate react with django and perform all of the necessary setup steps. We will be using webpack and babel to bundle our react app and have the django backend render a template that react will control.

๐Ÿ’ป AlgoExpert is the coding interview prep platform that I used to ace my Microsoft and Shopify i...

โ–ถ Play video
haughty jetty
#

Is it possible to show matplotlib graph and customise them with html css ?

vernal furnace
#

It should print

complete the app
#

oh so stupid, I figured it out

boreal galleon
#

Hey
I was looking into the django repository
https://github.com/django/django/tree/master/django/db/models -- Into the models package
And there is a init.py file present in the models package
Is is possble instead of downloading the entire django framework, i can just use the models package and work with it?
Will it work?

native tide
#

@fickle fox you need to follow some sort of guide

maiden tulip
#

Hi, I have a Django Project and thought about renaming my root folder to mysite.tld - which unfortunately confuses Python -
I tried to refer to it as from mysite.tld.somepackage import something - which Python understands as a folder named tld that exists inside mysite. I saw that there are some modules that allow imports from dotted paths. Question is: Should I use 1 of these packages or instead either
A: cut that idea of naming the root folder like it was a URL

root
--somepackage

B: change the folding to java style ->

www
--mysite
----tld
------somepackage
toxic flame
#

why not just remove the .tld or just replace it with _tld

haughty turtle
#

@boreal galleon what would the reasoning be?

native tide
#

When using DRF,

request.user```
refers to a User instance. However, what if I have a different model as my `AUTH_USER_MODEL`? What can I do to change request.user to reflect my `AUTH_USER_MODEL` instead of User by default?
nova crest
#

I have a webapp with Flask, SQLalchemy and celery.

Some information is put in a database, with db.session.add(info) & db.session.commit(). Then, a long task is send to Celery. This task would use the information from the database, but the Celery worker says the database is empty.
When I query the database from Flask, it says the information is in there.

#

It seems as though the changes don't get saved to the database correctly. Does anyone have a clue what the problem could be?

modest scaffold
#

For django what actually is a primary key field and what is its purpose e.g. model.pk

opaque ice
#

Hey guys! I'm running a flask-app where I have some custom JS-files in my static folder. I also import some JS files from modules installed with node. The installed JS modules in turn import other JS components.

The problem I'm facing is that the imports in the javascript files are required to have .js file endings. But the imports in the installed node modules don't use file endings. One can ofcourse manually append the file endings but that's obviously hacky and not feasible in long term. What I wonder is why this happens? Why is the file ending required? Is there any way to allow imports without the .js extension?

Example:

myCustomJS.js

import { SomeComponent} from 'node_modules/some_module/SomeComponent.js'; // Works so far```
SomeComponent.js
```js
import { SomeOtherComponent } from 'some_other_module/SomeOtherComponent'; // Does not work```
Everything then works if i append `.js` to `'some_other_module/SomeOtherComponent'`, but that's not feasible to do with every node module I install. Please @ me if you know why this happens, where I can read more, if you straight up know a solution! Thanks
civic kiln
#

does anybody know how to have your foreign keys updated automatically, when data is inserted in the parent table in oracle ??

sonic atlas
#

hi everyone is there someone who can help me with flask jwt. i am building a webshop with python and flask-restful. as far as i know you need a def authenticate and def identify. the def authenticate gives me a token. so that one works. but the def identity should give me the current logged in user how can I get the identity function to work?

#
    print("User successfully authenticated")
    user = UserModel.login(email, password)
    if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')):
        return user
    print("Something went wrong. Authentication doesn't work")```
#
    con = sqlite3.connect("db/webshop.db")
    cur = con.cursor()
    cur.execute("SELECT * FROM users")
    user_row = cur.fetchone()
    user_id = payload['identity']
    print(user_id)
    return userid_table.get(user_id, None)``` these are my current def's. the authenticate function works because i get a token from it but the identity doesn't work at all. I tried putting a simple print in it but nothing shows up
fickle fox
#

@native tide i used to code in flask but after some time i forgot some things xD

short vector
#

Hi, sorry if this is the wrong place to ask, but when using js in my flask templates, i need to use { and }. are there any things i should do to escape them out?

ebon phoenix
#

How do i set env variables for Python? I need to hide a secret key for a django project

strange glen
ebon phoenix
strange glen
#

yes absolutely, if the env var is defined in the environment where the python process lives

#

if you use: os.environ['SECRET_KEY'], the difference is that it will crash in the case where the var is NOT defined, which might be desirable in your context

#

also, os.getenv('SECRET_KEY', 'bla') will default to bla in the case where it's not found

ebon phoenix
snow crest
#

Is there anyway to check for web update faster except downloading its html and scan (if any update) every minute

scarlet latch
#

Anyone know how to use sessions with Heroku? Mine get cleared after a redirect. I heard that Heroku Redis might help, but I don't know what that is.

#

Thanks!

inland stirrup
cold portal
inland stirrup
#

Got it

inland stirrup
#

if i wanted connect the search form i've built in layout.html to the form class in view.py how would i do that .... a general idea would suffice

knotty cradle
#

yo, how do I get form data in quart?

supple bramble
#
def transferred(sender, instance, **kwargs):
    transfer = instance
    to = transfer.to_user
    fromu = transfer.from_user
    amount = transfer.amount
    transfernow = Transfer(
        amount=amount, to_user = to, from_user = fromu)
    balance = to.profile.balance
    balance = 

post_save.connect(transferred, sender=Transfer)```
what should i add in the balance part so that that the existing balance of the user gets updated with the amount we sent
inland stirrup
#

balance =(fromu.profile.balance - amount)

supple bramble
#

idk what i am doing wrong but the profile isn't updating with the balance, here is my models.py:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=400, default='Hi! I am new :D')
    image = models.ImageField(
        default='default.png', upload_to='profile_pics')
    balance = models.IntegerField(User, default=10)

class Transfer(models.Model):
    amount = models.IntegerField(default=0)
    to_user = models.ForeignKey(User, related_name='rec', on_delete=models.CASCADE)
    from_user = models.ForeignKey(User, related_name='sen', on_delete=models.CASCADE)

def transferred(sender, instance, **kwargs):
    transfer = instance
    to = transfer.to_user
    fromu = transfer.from_user
    amount = transfer.amount
    transfernow = Transfer(
        amount=amount, to_user = to, from_user = fromu)
    balance = to.profile.balance
    balance =(fromu.profile.balance - amount)
post_save.connect(transferred, sender=Transfer)```
#

view.py:

def transferpage(request):
    if request.method == 'POST':
        t_form = TransferForm(request.POST, instance=request.user.profile)
        if t_form.is_valid():
            t_form.save()
    else:
        t_form = TransferForm(instance=request.user.profile)
    context = locals()
    return render(request, 'transfer.html', context)```
#

i think there is some problem with views.py (or maybe the signal), can anyone eksplane?

near bison
#

will js fetch() requests contain cookie data ? so that authentication status can be checked ?

honest dock
#

Template:

<p>{{ today_date|timeuntil:product.added }}</p>

In view:

today_date = datetime.now()
context['today_date'] = today_date

Model:

added = models.DateTimeField(auto_now_add=True)

Can anyone explain why the paragraph ain't showing anything?

zinc hill
#

what would happened if you do
context['today_date'] = "something"

#

would <p></p> show up

honest dock
#

yes each date show up but when i use |timeuntil it does not work

summer egret
#

Hi guys!

#

Do you guys know repositories which have a good example of a big django project

#

Ive done a couple of courses for Django but still I feel I lack the expertise in Django

hollow jay
#

Django!

native tide
native tide
#

Hi, I need best tutorial for Django and Flask.

#

anyone can help?

tulip beacon
#

how many of you know react?

native tide
#

I'm trying to reread a csv file everytime I refresh the page, however, somehow the data is being cached. This does not allow me to enter new data into the csv file in order to show it on a chart. How do I prevent caching? I already tried generating unique URLs based on a time stamp. That works once but not every time I refresh the webpage. I'm using Flask

native tide
#

Thanks ๐Ÿ™‚

glad patrol
#

hi

#

i am new to django , how to redirect to other page when button is pressed from html page in django

supple bramble
#

no wait

supple bramble
glad patrol
supple bramble
#

show it

glad patrol
#

<button type="submit" class="btn-lg btn-block btn btn-primary mb-5"> Predict </button>

#

this is how i create a button in html file

supple bramble
glad patrol
#

this is

supple bramble
#

?

#

isn't that button in html page

glad patrol
#

yes

supple bramble
#

show it

glad patrol
#

how to upload file in discord

supple bramble
#

just copypaste the code lmao

glad patrol
#

it say 2000 character

#

w8 i do something

supple bramble
#

ohk

lavish prismBOT
glad patrol
#

this is my diabteses.html

#

i want to add another button in diabteses.html to redirect to my home page

supple bramble
#

return redirect('/yoururl)

#

above the return render function

#

green area

glad patrol
#

but it return as soon as it predict the result

#

this is the html file i enter all the fields then i press predict button then it predict result and show the result on same paeg

#

i need to add new button when i press then it redirect

supple bramble
#

i don't understand :/

glad patrol
#

see

supple bramble
#

like when you click the button, what should happen exactly

glad patrol
#

i have predict button

supple bramble
#

okay

glad patrol
#

when i press i need to go my home page

supple bramble
#

so return redirect(request, 'home.html')
isn't working?

glad patrol
#

i dont know but i need to achive this when i press button

#

i need to add new button name home under predict

#

when i click home it redirect to home.html

#

i have home.html file

supple bramble
#

have you added return redirect thing in your views.py?

glad patrol
#

i think let me check

#

this `

supple bramble
#
return redirect(request, 'home.html')```
glad patrol
#

this 1

#

`def home(request):

return render(request,
              'home.html')

`

#

i have this

supple bramble
#

remove the def home request part

#

wait

#

no

#

@glad patrol

glad patrol
#

this is a function

#

ok

supple bramble
#

you need to add python return redirect(request, 'home.html') in your views.py diabetes function

#

oh wait

glad patrol
#

there is already return

supple bramble
#

what happens

#

when you click the button

#

after this python return redirect(request, 'home.html') function

glad patrol
#

i dontt have button

#

thats what i am trying to achive

#

i have function which redirect to home.html

#

but i dont have button on html pae

#

page

supple bramble
#

hmm

glad patrol
#

i show you get better idea

#

1 mint

supple bramble
#

okay

glad patrol
#

see i add red color which is basically home button i need to add in diabetes.html

#

when i press red button it redirect me to my home page

supple bramble
#

so you need both predict and home button?

glad patrol
#

yes

#

yes

#

predict which give me result

#

home which move me to home page

supple bramble
#

oh why don't you use navbar for homepage button tho?

glad patrol
#

its complex to add navbar

#

i am new

#

so doing a normal way

supple bramble
#

ohk, for the home button, make it a link, that would be easier, just use <a> tag, and edit it with css and add some padding then background colour to make it look like a button and set the href of the link to be {% url 'home' %}

glad patrol
#

should i create the button the same i create predict 1

#

like this

#

<button type="submit" class="btn-lg btn-block btn btn-primary mb-5"> Predict </button>

supple bramble
#

nono, use <a> tag and style it with css a little bit and it will look like a button

#

wait

glad patrol
#

ok 1 mint

#

urlpatterns = [ path('admin/', admin.site.urls), path('heart', views.heart, name="heart"), path('diabetes', views.diabetes, name="diabetes"), path('breast', views.breast, name="breast"), path('', views.home, name="home"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

supple bramble
#
<a href="{% url 'home' %}">Home</a>```
#

add this

#

to the page

#

and then use css to make it look like button

glad patrol
#

ok 1 mint

#

i add this line after the predict button code?

supple bramble
#

yes

glad patrol
#

ok 1mint

#

its worked

supple bramble
#

nicee

#

now use css to make it look like a button

glad patrol
#

can u help in 1 more problem pls

#

a little bit

supple bramble
#

yeah, what is it

glad patrol
#

ok i elaboreate what i am doing so you get better idea

#

see i enter my data in fields then i predict it which give me result

supple bramble
#

okay

glad patrol
#

as soon as i do this in parallel i get all the fields data

#

and send it to database

#

to store the result

#

this is the part

#
if request.method == 'POST':

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

i get all the fields and add them into sql database

supple bramble
#

oh i don't know how to add them to the database like this, i usually use a different method (using Models)

glad patrol
#

i add them into database

#

but here i need to add 1 more field which is gender male and female dropdown list

#

i add it previsouly but when i select gender it dont get selected value from drop down list

#

@supple bramble

supple bramble
#

oh

#

are you using any model for this?

#

are you using it?

glad patrol
#

no

supple bramble
#

oh :/

glad patrol
#

i put all the fields direclty into database

#

now when i select gender it input all the data into database except geneder

#

it is not get the secleted value

supple bramble
#

lemme find something

glad patrol
#

bmi = float(request.POST['bmi']) like this give me bmi

#

how to get the selected gender

#

ok

supple bramble
#

you have to make a forms.py file where you will put the options

glad patrol
supple bramble
#

see the answer

glad patrol
#

tough

vernal furnace
#

guys

#

I created a form in django

#

and when I click on submit it should redirect me to the same page right?

supple bramble
#

@vernal furnace the url should have forward slash at the end, not in the beginning

#

todo/

#

not /todo

#

neither /todo/

glad patrol
#

@supple bramble it get all the value from dropdown

#

not a seleted 1

supple bramble
#

how many values do you get?

#

i mean what values do you get

glad patrol
#

it displat male female both

#

i select male

vernal furnace
supple bramble
glad patrol
#

it has both

glad patrol
#

but i need 1 what i select

vernal furnace
#

it still doesn't work

#

it appends another todo/ to my todo/

supple bramble
#

@vernal furnace show me your urls.py

glad patrol
#

i only need to get 1

#

let me try 1 more time

#

i let u know

vernal furnace
#
urlpatterns = [
    path('', index)
]
supple bramble
vernal furnace
#

yeah that was it

supple bramble
vernal furnace
#
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('todo/', include('tasks.urls')),
]
#

forgot to copy the imports in the first one so no worries

supple bramble
#

@vernal furnace add backslash to the return redirect

#

wait

#

@vernal furnace oh wait actually just leave it with slash

#

don't add /todo

#

just /

vernal furnace
#

it redirects me to the home page

supple bramble
#

it's weird :/

#

/todo should work but idk why it isn't

vernal furnace
#

in the tutorial

#

he does the same

#

he only adds a back lash

supple bramble
#

try different patterns, using slashes and notice what happens, it shouldn't be hard to figure it out

#

url patterns are easy

#

just play with them a bit

glad patrol
#

@supple bramble i did it

supple bramble
vernal furnace
#

thing is there is no difference between my code and his code

glad patrol
vernal furnace
#

like I didnt change anything yet lolo

supple bramble
#

check desc if there is a source code

#

and see if copypaste works

glad patrol
#

@supple bramble can we set field value by multiplying two fields value

supple bramble
#

what type of field is it

glad patrol
#

like bmi = height x weight

#

i enter bmi directly

#

i want when i enter height and weight the value of bmi auto set

supple bramble
#

what is the value of height?

glad patrol
#

let say

#

50

supple bramble
#

what determines it?

#

do you enter it yourself?

glad patrol
#

yes

#

i enter height and weihgt by myself

supple bramble
#

are they different fields?

glad patrol
#

right now i enter bmi manually

#

yes

supple bramble
#

so you have a function which calculates bmi by multiplying height and weight you entered and when you enter bmi it shows the result because bmi was the variable right?

#

correct me if im wrong

glad patrol
#

right now i dont have any fucntion which calulate bmi

#

see this

#

i have bmi on form

#

i create 2 more fields height and weight

#

right now i enter bmi manuall

#

iwant bmi is set as soon as user enter weight and height

supple bramble
#

so you will replace bmi with height and weight right?

glad patrol
#

yes

#

bmi = height x weiht

supple bramble
#

bmi = height*weight

#

do something like this

glad patrol
#

yes

#

where should i do this