#web-development

2 messages Β· Page 145 of 1

inland stirrup
#

is there any while loop sort of thing for django templates

steep sage
#

Looking for JS/CSS frontend developers for a Flask project.

Pay may be included, depends on a few things

We have a team already, we're 90% done with the project, its almost ready for launch.
We just need some more people on our team to help.

DM if interested
You'll know the details after u DM

Thanks !!

stable ledge
#

Can I use Flask to create a chrome web extension, without the need of JS/HTML?

steep sage
#

any other channel i can use for recruitment?

opaque rivet
#

python discord doesn't allow for recruitment

opaque rivet
inland stirrup
heady iris
#

Do i need to create a database for a sign in page?

serene prawn
heady iris
#

what would be the difference?

serene prawn
#

You usually store them locally

#

It would be more convenient imo

heady iris
#

hmm ok thx

hallow yacht
#

anyone here use django trans ?

native tide
#

Anyone know how to send multiple html files in the response in NodeJS ?

glacial dew
#

my heroku app does not recognize my local timezone, it shows local timezone as UTC, how to configure my heroku app to recognize user's timezone??

#

i am using pytz library of python

serene prawn
serene prawn
native tide
serene prawn
#

I have a question about Json Web Tokens:
Is storing access token in memory and refresh token in http only secure cookie would be good solution for frontend authentication?

heady iris
serene prawn
#

Yep

wooden ruin
# heady iris im sorry backend?

backend libraries are things like django, flask, or express js which serve as an http server (and when configured correctly can also support non-http)

heady iris
#

ohhhhh

#

i see

#

im using flask then

serene prawn
serene prawn
serene prawn
#

Memory like memory πŸ˜‰

#

not in local storage or cookies

vestal hound
#

oh

#

you mean like

#

actual memory

heady iris
#

but thank you

serene prawn
#

Yep, just a variable @vestal hound

vestal hound
#

uh

heady iris
#

thx for help

vestal hound
#

then if you refresh the page?

serene prawn
#

You request new token...

vestal hound
#

I mean

#

I guess that's fine

#

if

#

it's a SPA

serene prawn
#

It is

vestal hound
#

yeah I guess that's fine

serene prawn
#

If you store it in local storage then it would be insecure, right?

vestal hound
#

it could be

#

to XSS and stuff

serene prawn
#

So you can't persist refresh or access token

vestal hound
#

anything that allows execution of untrusted JS

serene prawn
#

Only thing left is http only cookie, right?

#

Can't then attacker get access token though? πŸ€”

#

by just making request to an api

vestal hound
#

in which case?

serene prawn
#

in case of xss

vestal hound
#

like

#

as in

#

for your case (local variable)

#

with XSS?

serene prawn
#

@vestal hound I mean i would have to create a way to issue new token

#

With that cookie

#

But can't attacker make that request with xss?

#

To say api/auth/gettoken

#

or something

#

Because i have to get that access token in a first place

#

Because i though that having an endpoint that will issue a new access token based on your cookie with refresh token would be enough πŸ˜…

native tide
#

How can uninstall the dependencies that were installed when I installed python-dev-tools? I've done pip uninstall python-dev-tools, but I can still see A LOT of unwanted packages in requirements.txt πŸ˜’

serene prawn
#

use pipenv

native tide
#

Instead of pip uninstall <> do pipenv uninstall <>?

#

Have found a guide

limber laurel
#

How could I get data form my api/ send post requests to it locally, for example in my case I serve react through django staticfiles , but it triggers cors

#

how could I avoid using cors?

opaque rivet
#

how would I go about deploying my project? I'm using redis / celery / django channels, do I need multiple servers for this?

limber laurel
#

And when I requested from there it started working

opaque rivet
#

hmm, well as long as you are on the same origin, same port, and same http protocol you should bypass it just fine πŸ‘

wooden ruin
high parrot
#

hi everyone , i want to learn python for webpage with django , anyone know papers for i learn this

stable hemlock
opaque rivet
native tide
#

AWS is really not the hardest part

#

plus there is way more tutorials/free courses on AWS than there is on heroku

#

or gcloud

#

for that matter

#

so I would say go for AWS

past rover
#

hi!

#

anyone know how to take a nested list that was made using flask inputs, and use it in another file?

native tide
native tide
past rover
#

the variable, i want to use it in the paramter for the function in another python file i have

native tide
#

that other python file

#

do you want to run it separately

#

or are you importing the code in that file

#

to your flask's py file

#

with import

#

?

past rover
#

im just using os to run that file if it recieved some data

#

because it has it's own variables it needs to be run, not only the function

native tide
#

or flask application

past rover
#

wait

#

i think i might have just fixed it

#

one second

#

heeey, the data transfer things worked

native tide
#

literally no idea whether you were running 2 files as 2 separate processes at once

#

or were importing one file into the other

#

but

#

doesnt matter anymore i guess

little storm
#

does anyone have experience with django? I need some help regarding static files

reef tree
#

guys

#

anyone knows how to know the site of my flask app

#

im beginner

rare bay
#

hi

#

i have a question

#

do you have some good tutorials for python beginners?

native tide
#

for websites?

#

here is a tutorial if your interested in django web framework

#

Learn the Python Django framework with this free full course. Django is an extremely popular and fully featured server-side web framework, written in Python. Django allows you to quickly create web apps.

πŸ’»Code: https://github.com/codingforentrepreneurs/Try-Django

⭐️Course Contents ⭐️
⌨️ (0:00:00) 1 - Welcome
⌨️ (0:01:14) 2 - Installing to Get ...

β–Ά Play video
opaque rivet
#

@native tide alright - thanks! I'll slowly learn AWS :)

reef tree
#

@native tide can u help me?

#

i m beginner

native tide
#

in django?

reef tree
#

so i coded a website

#

flask

native tide
#

nope sorry I dont use flask

reef tree
#

no html file

reef tree
native tide
#

?

reef tree
#

pls

#

where is the website

#

i have the file

#

and im hosting it

#

rn

#

and dont know where is my website

#

(no html file) built in html code into flask project

native tide
#

dude I only use django sorry I cant help you

reef tree
#

can anyone help me then

native tide
#

just wait for a few hours people will reply or just search in stackoverflow

#

maybe this can help

reef tree
#

nah\

#

i dont have an html file

#

just py file

chilly falcon
#

ModelForm has no model class specified.

#

form.py

    email = forms.EmailField()
    class meta:
        # which model is affected
        model = User
        # this is fields that we want in order
    field_order = ['username', 'email']

class ProfileUpdateForm(forms.ModelForm):
    class meta:
        model = Profile
    field_order =['image']
#

views.py

def profile(request):
    u_form = UserUpdateForm()
    p_form = ProfileUpdateForm()
    context ={
        'u_form':u_form,
        'p_form':p_form
    }
    return render(request, 'user/profile.html',context=context)
#

traceback



Request Method: GET
Request URL: http://192.168.10.112:8000/profile/

Django Version: 3.1.7
Python Version: 3.8.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'blog.apps.BlogConfig',
 'users.apps.UsersConfig',
 'crispy_forms']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "E:\django\Django-blog\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "E:\django\Django-blog\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "E:\django\Django-blog\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "E:\django\Django-blog\django_project\users\views.py", line 26, in profile
    u_form = UserUpdateForm()
  File "E:\django\Django-blog\lib\site-packages\django\forms\models.py", line 287, in __init__
    raise ValueError('ModelForm has no model class specified.')

Exception Type: ValueError at /profile/
Exception Value: ModelForm has no model class specified.
#

can any one help

#

html

            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-button mb-4">Profile Info</legend>
                {{ form|crispy }}

            </fieldset>
            <div class="form-group">
                <button class="btn btn-outline-info" type="submit">Update</button>
            </div>
        </form>```
vivid canopy
#

guys may i ask for some docs or some video for displaying or filtering all own uploads of the user?

acoustic narwhal
#

Is there any way I can get details of the logged in user, like I am checking if the user's designation is xyz then only a particular task should happen (in django)

steady hatch
reef tree
steady hatch
#

domain is the name

#

like

reef tree
#

but how to find it

steady hatch
#

this can help u

#

and no it is not free

reef tree
#

man

steady hatch
#

u can use github it has a domain and it is for free

reef tree
#

i dont know this www.thisthingidontknow.com

steady hatch
#

wt is wrong with u

reef tree
#

its not showen in terminal when i run the code

steady hatch
#

wtf

reef tree
#

i swear

#

photo?

reef tree
steady hatch
#

ok

reef tree
#

just the bot

#

ive imported it(the webserver

steady hatch
#

k

#

is it for discord bot

reef tree
#

yes

steady hatch
#

send code

reef tree
#

a website

reef tree
steady hatch
#

webserver

reef tree
#
from flask import Flask
from threading import Thread


app = Flask('')
@app.route('/')

def hone():
  return "<h2>Web Server OK, Discord Bot OK</h2>"


def run():
  app.run(host="0.0.0.0", port=8080)

def keep_alive():
  t = Thread(target=run)
  t.start()```
reef tree
#

0.0.0.0 is an dns

native tide
#

0.0.0.0 means you want your website to be accessible by anyone in your local network and anyone outside your local network (aka internet)

elder jackal
#

i have a flask app and a bunch of methods like

@bp.route('/somestuff', methods = ['POST'])
def some():
    body = ({underscore(k): v for k,v in request.get_json().items()})

@bp.route('/somestuff', methods=['GET'])
def do_something():
    result = []
    body = ({underscore(k): v for k,
            v in request.args.items()})

how does a decorator look like to wrap this "body" var into locals by default so i dont copy-paste this generator over and over again

smoky skiff
#

meaning it runs on ur machine

#

and is only available in your local network

elder jackal
smoky skiff
#

if you want it reachable from WAN you either have to NAT it with ur wan ip

#

or get a hoster and domain

#

and host it from there

ocean dirge
#

would this port mapping automatically direct http requests to my pc?

smoky skiff
#

yeah it should redirect http (80) to 5002

#

if i understand the website correctly

ocean dirge
#

thanks, so if i set up a dns would it automatically direct to my port without a port at the end?

smoky skiff
#

no

#

dns is for domain names

#

oh i read it wrong yeah

#

if u have an ip and give it a A record you can reach the ip with ur domain

native tide
#
import time



username = "ddddddd"
password = "gddgdsf"

driver = webdriver.Chrome("C:\Program Files (x86)\chromedriver.exe")
driver.get("https://www.mysdpbc.org/sso/portal")

username_textbox = driver.find_element_by_id("Username")
username_textbox.send_keys(username)

password_textbox = driver.find_element_by_id("Password")
password_textbox.send_keys(password)

login_button = driver.find_element_by_id("login-button")
login_button.submit()

ok_button = driver.find_element_by_id("AUPAccept")
ok_button.submit()``` https://i.imgur.com/cMV3jxC.png and https://i.imgur.com/MjZtb2P.png
sterile sphinx
#

A record is just a simple name poiting towards a ip you need the computer or the router to perform DNS lookup witch in result uses a TCP conenction towards teh database and checks for ip with the domain

native tide
#

does anyone know why this would work

#

it works up until the ok_button code

cedar pasture
#
dicts = []
        curr_date = pd.to_datetime(list1[-1])
        for i in range(X_FUTURE):
            curr_date = curr_date +  relativedelta(months=+1)
            dicts.append({'Predictions': transform[i], "Month": curr_date})


        new_data = pd.DataFrame(dicts).set_index("Month")
        ##df_predict = pd.DataFrame(transform, columns=["predicted value"])

        labels = [d['Month'] for d in dicts]
        
        values = [d['Predictions'] for d in dicts]

        colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
                   "#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
                   "#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]

        line_labels=labels
        line_values=values
        return render_template('graph.html', title='Time Series Sales forecasting', max=17000, labels=line_labels, values=line_values)


    
        response = make_response(new_data.to_csv(index = True, encoding='utf8'))
        response.headers["Content-Disposition"] = "attachment; filename=result.csv"
        return response
     ```
#

Hi community, I m currently work on time series forecasting model on webpage, my problem is I would like to return my new CSV file with the predicted value and plot graph into the web under 1 function, I m wondering does any other ways can pass 2 different return value in one function in flask python, please share some tips with me! thanks in advance

opaque rivet
chilly falcon
reef tree
smoky skiff
#

buy a vps/dedicated server and deploy it there?

native tide
smoky skiff
#

think heroku also has free tiers for certain requirements

#

same with azure if im not mistaken

reef tree
native tide
#

to host a website as a production

#

you want to rent a web server

#

and web server is basically another computer but in a cloud

smoky skiff
#

isps give you dynamic ips

native tide
#

correct

smoky skiff
#

the moment you get a new one the setup doesnt work anymore

#

and udh ave to reconfigure it all the time

#

there are free tiers like aws, heroku and azure

#

worst case a small vps is super cheap

elder nest
#

I have a flask app and changeable text in html. How would I make it so there is an update button and it updates my mongodb database?

smoky skiff
#

with a form

#

and a post method?

elder nest
#

how would I do that?

#

I am brand new to html

smoky skiff
#

google jinja2 and database queries

elder nest
#

@smoky skiff the only thing I see is putting stuff from in my database into the html

elder nest
#

I am not trying to display database info in my website I already am doing that

#

I am trying to update my database from text boxes in my website

smoky skiff
#

oh

elder nest
#

any ideas on how to do that?

#

@smoky skiff

carmine swift
#

use post and make backend code to intercept any post keys

elder nest
opaque rivet
elder nest
opaque rivet
elder nest
#

@opaque rivet I can't figure it out and everything is giving me errors is there a good example that you know of?

opaque rivet
#

what's the error?

elder nest
#
RuntimeError: Working outside of application context.```
#

I deleted the code I had bc every time I fixed one error I got another so I need to work on it again

#

give me a little bit

royal tendon
#

@elder nest, welcome to PM me with some code and I’ll run through it with you quickly

royal cove
#

Flask and Django make me drool

#

πŸ˜›

royal tendon
#

Whatever you’re into, budddddy

#

πŸ™ˆ

royal cove
#

Well, before I didn't have Webhooks that I could farm that data...now I do. Django is a beast, but it's good if you take the time to learn it

#

I feel like Flask is easier to get up and running

royal tendon
#

yep I've enjoyed using Flask

#

tried Django when I first played with Python, didn't go great as I sucked

#

but put me off Django. Sure I'd be fine with it if I tried it again, but Flask has been everything I need so far

royal cove
#

Yeah, it's kind of a pain...getting all the middleware working etc

mortal pike
#

Django Question here:
I have been looking through the docs and haven't found anything about this, though I could just be looking in the wrong place. I am trying to make a form where several fields are repeated based upon the input to a PositiveIntegerField.
If you were to put in 4 in the PositiveIntegerField, 4 pairs of inputs would pop up. I am not sure how to make the fields variable based upon the input, could I just make 100(or some number) of fields and just hide the rest?

low rapids
#

hey

#

how do you make a web server ???

#

by node js

#

any help is appreciated

frigid egret
#

Anyone here ever tried beeware?

royal tendon
frigid egret
#

I don't see a category here for mobile dev so I thought web is the closest one.

mortal pike
#

if anyone has any experience with Django and wants to come help me out jump into Code/Help0

candid meteor
#

Can't vc rn

candid meteor
mortal pike
candid meteor
#

it's impractical to have user filling in 100 fields btw

mortal pike
mortal pike
candid meteor
#

Why not just take the list of inputs in a single input field in the form of a list

#

^^ More user-friendly

#

for example, if a user wants to order 4 items, he could just type in "mouse, keyboard, monitor, headphones"
instead of typing each in a diff field

#

ion acc know what you're trying to achieve, but this sounds much more practical

mortal pike
candid meteor
#

holupp

mortal pike
#

can you join a voice chat and I can stream a purely html mockup of what I am trying to do?

candid meteor
mortal pike
mortal pike
candid meteor
#

On it

opaque rivet
#

@mortal pike user submits number of fields they want, view parses that number and renders a new template which renders n fields (jinka2 template). What do ya think?

mortal pike
mortal pike
candid meteor
#

Ajax is simply best for submitting data

#

Via form, or without forms loll

serene prawn
#

So it would be easier to make a list of fields that you can expand

candid meteor
candid meteor
#

Just append input fields using a js 'for loop' oninput event

serene prawn
#

I mean i wouldn't do that without framework πŸ˜…

candid meteor
#

You can't just do it from the backend, it'd just make a mess

serene prawn
#

I didn't say backend

#

I said framework πŸ˜‰

#

So can be say Angular/React/Vue

candid meteor
#

He's using HTML for the front-end smh

serene prawn
#

If he's a beginner he can use do it however he thinks is ok

#

These frameworks can be overwhelming for beginners

#

Because you would have to learn html/css/js + Frontend Framework + Language you code backend in and backend framework

static wind
#

trying to deploy my flask app to my domain on cpanel using the application manager but i keep getting 503 errors

#

anyone know how to solve this

#

the basic code they give doesn't work either

candid meteor
serene prawn
#

πŸ˜…

serene prawn
#

But working with jquery is pain πŸ˜‰

candid meteor
#

it was an easy 6 line code sofar

serene prawn
#

It's not 6 lines

#

If we're talking about adding items into this form, deleting them and actually sending that to the backend

candid meteor
#

Was round 6 for the front-end stuff, the oninput, adding input fields and rest
form submission is diff

#

ive recommended him learning ajax form submission at earliest loll

serene prawn
#

Just on itself it isn't really useful though

candid meteor
#

tf, am using it almost everywhere on my site

#

It's acc perfect

serene prawn
#

I'm just saying that submitting form via ajax just on itself isn't doing much

candid meteor
#

It hits a view where you can do anything you want, anything

#

Ezpz

#

With the data ofc

mortal pike
#

I am really confused. About how to link the template with the json to the form rn

candid meteor
#

Just send the data via ajax to the url
That url hits a view
in which you get the post data and create entries in the Model using that data

#

Ez af

mortal pike
#

that doesn't simplify it though

candid meteor
#

It's just ajax, url and view

candid meteor
#

Put in the efforts, you'll do

native tide
#

Hi all, i am new to pyramid and i am trying to figure out Chameleon. Specifically (coming from jinja) i have something like this in my html file, i need to do this in my .pt template...

base.html

  <head>
      <title>MyApp - %{block title%} %{ endblock %}
  </head>
  <body>
    {% block content %}
    {% endblock %}
   </body>

homePage.html

%{ block title %}My Awesome Home Page {% endblock %}

{% block content %}
    <h1>Welcome to my Home Page</h1>
    <p>This is the home page content blahblahblah</p>
{% endblock %}

Any idea how i can do this in Chameleon?

quiet ridge
candid meteor
#

Make it much more quicker

#

Users don't prefer waiting to acc read what's next

opaque rivet
#

too much for me

#

way too much of the typewriter effect

ornate burrow
#

whats wrong with this datatable filter query?

      {
                'if': {
                    'filter_query': '{trains} contains OBIS'
                },
                'backgroundColor': 'tomato'
            },
            {
                'if':{
                    'filter_query': query
                },
                'backgroundColor': 'rgba(0, 116, 217)'
            }

DataTable filtering syntax is invalid for query: local_end_time datestartswith 2021-03-29
is all my console gives me and i cant figure it out. ive been trying for the past hour

filter_time = 'local_end_time'
        query = f'{filter_time} datestartswith {time}'
slim ginkgo
#

I've been having alot of trouble with a supposedly simple slider input in html/js

#

I have the element <input type="range" min="1" max="50" value="10" class="slider" id="thickness">
In my js I use var slider = document.getElementById("thickness");
howver the value I get seems to always be "" instead of a number

#

figured it out after I noticed it on my watch list

#

any ideas?

mortal pike
candid meteor
#

It'd be some real efforts also you'll have to submit the form twice

#

Neways, peaceout

mortal pike
#

Having to submit twice isn't really a problem so might as well use what I know

simple star
#

I new to web development , I am thinking of building websites using only html, CSS and JavaScript. Do one know how I can structure thiis challenge iin step

#

Any template or layout to follow for website design will be resourcesfull. Thanks

#

A mental model and a high level thinking- the way to think we one is task with building a website

opaque rivet
# mortal pike I think I am going to do this, it is much simpler. Any tips?

Have one form where the user specifies n items (the number of fields). Once submitted pass this to your view, and render a new template passing down the n variable. Create a for loop within the jinja2 template to render n inputs.

If it has gotten to this stage it's an anti-pattern and it's why python forms are terrible.

What you could do is use Jquery and have some hidden divs within a hidden form on the page.
Take the value from an input (for how many fields is required) and then use jquery to modify the innerHTML of them divs to then show new inputs.
https://api.jquery.com/jquery.map/

I don't use Jquery, but if you used something like React this would be easily overcome (and nice)!

opaque rivet
candid meteor
wooden ruin
#

then integrate it with something like vue.js which is a really good javascript/html/css website combo

haughty turtle
#

I have a Conversation Model which holds a ManyToMany field of the users in the convo

class Conversation(models.Model):
    users = models.ManyToManyField(User, blank=True)```I am filtering this to get all the Conversations in which a user belongs to```py
    u = User.objects.get(username=request.user.username)
    convo = Conversation.objects.filter(users=u)```My problem occurs when trying to obtain a list which contains all the users per convo in which the user belongs to `print(convo.values("users"))` My current solution is ```py
    for i in convo:
        print(i.users.all().values("username"))``` but is there a better solution in which would not make me loop through a QuerySet thus having to hit the DB an unknown amount of time?
quiet ridge
#

Okay dude thanks for suggesting @opaque rivet @candid meteor

frigid spindle
#

im creating a new django project. i should use a virtual env right?

quiet ridge
#

Yes ofcourse you should @frigid spindle

frigid spindle
tardy star
#

you want to have that venv and that requirements.txt

frigid spindle
#

requirements.txt is similar to package.json right?

wooden ruin
#

@frigid spindle kind of. just like package.json contains the dependency requirements, thats all that requirements.txt should have

#

however package.json also contains where to find scripts and other config files

#

requirements.txt simply lists all the python packages your project will require

#

and since python projects have loads of depedencies, this file is essential for big projects like web apps

frigid spindle
#

im gonna start the polls app and then the blog app

#

then whats settings.py?

tardy star
#

okay yes, settings.py is where you store the configuration for the webapp

#

um i guess express doesn't have much of config or anything, but in django what you usually do is, instead of taking api keys and other values directly from environment, we read them all in the settings itself

#

advantages are that you get to modify those pythonically, and add other settings which env vars might not be able to hold

#

and, you get to raise errors if some variable is not present.

#

but not only that, it also contains setup information for middlewares, and initializers for apps.

#

basically configuration of the "Django" part of the app.

#

the "Python" details sit in pyproject.toml and/or requirements.txt, while django-specific details live in settings.py

limber laurel
#

has anybody here used the django rest's token authentication?

#

if yes, please ping me, I have some questions on how it works.

native tide
limber laurel
#

no

#

Token authentication when logging in in REST

limber laurel
#

I think that might be what you are saying

chilly falcon
#

do any one know hoe to use python shell??

#

how*

vivid canopy
opaque rivet
limber laurel
#

well I have retreived the otoken from my auth view in react

#

but I am not sure how tonow check if Iam logged in in a different view

opaque rivet
#

store the token within a cookie. When you make new requests to your views you need to include the Authorization header with value: Token <user_token>.

If your views have the TokenAuthentication decorator, DRF's middleware will check if the token is valid or not.

#

Thus checking if a user is authorized / logged in.

reef tree
#

guys, why are django are that hard?

opaque rivet
# haughty turtle I have a Conversation Model which holds a ManyToMany field of the users in the c...

This should give you something you can loop through an access the usernames of each object. The statement below is only 2 database queries, and the queryset it returns is cached so looping through it (and just accessing a field like username won't incur extra queries). Hopefully no syntax errors πŸ™‚

conversations = Conversation.objects.filter(users=u).prefetch_related(Prefetch(lookup='users', queryset=Users.objects.values("username"))

Might be useful to have a read of the prefetch_related methods, Prefetch objects and django database caching:
https://docs.djangoproject.com/en/3.1/ref/models/querysets/
https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.Prefetch
https://blog.etianen.com/blog/2013/06/08/django-querysets/

opaque rivet
reef tree
limber laurel
wary goblet
#

Hi, there.

#

Anyone here uses Mooshak?

native tide
#

I am really very stuck with this. Do I have to use psycopg2 if I am using a Flask-SQLAlchemy?

#

Will Flask-SQLAlchemy work without psycopg2?

opaque rivet
native tide
#

Thanks. That is the impression that I have too. Just need to use it to connect to the postgres db by using create_engine

#

Will try that once I have fixed the gunicorn.service file issue 😫 feels like one bug after another at the moment.

stable hemlock
#

Is there an efficient way to migrate files from one Django project to another? I started a Django project to learn it, and now I have built most of a website I want to put into production in that same project, and I want to move it to a fresh project.

stoic tulip
#

How make website page same as apple india in AirPods pro page???

foggy bramble
#

Hello everyone, when I update custom user model object, password is not getting hashed, I can see it as plain text via django shell, also this makes log in process impossible as it checks for hashed password... any suggestion

mortal pike
#

Simple Django Question:
I am trying to make it so that when a button is clicked and a specific choices is selected the choices will change. I can't figure out how to make it so that both of these work at the same time. any help would be great

#

@opaque rivet ?

native tide
#

hi, i have this webapp running at 0.0.0.0:8080.
in the webpanel of the router i set portfowarding to 192.168.68.104 which is my local ip but when i try to connect via the public ip it doesnt work

high parrot
#

hi

indigo kettle
sterile sphinx
#

ip 0.0.0.0 reffers to the loopback witch is 127.0.0.1 witch means localhost so using public ip (shouldnt happen here unless it's a shitty framework) wont work

barren moth
#

0.0.0.0 makes it run for everyone on the network

#

localhost or 127.0.0.1 means its not accesible on other machines

sterile sphinx
#

It's not set to a ip so the router dosn't know where to redirect the traffic, so using 0.0.0.0 will not make it available for tohers you have to set a static ip

#

just for the lan it's available

barren moth
#

yeah

#

but that means that a router can forward traffic to it

sterile sphinx
#

You can but shouldn't

frigid spindle
#

what is the django REST framework?

velvet vale
#

django model's inheritance is good idea? because when i save child model also save parent model

opaque rivet
opaque rivet
opaque rivet
velvet vale
#

@opaque rivet I want to have 2 types of registration. Teacher and student and different fields. How better to override user model and then create 2 registration model class teacher (User): extra field and class student (User): extra field. or If I have only a User model and have choosefield (is_teacher or is_studen) and when user register then show another model and save its info (there will be different fields)

opaque rivet
native tide
#

ah so how can i fix this?@sterile sphinx

velvet vale
#

@opaque rivet And another method? For example, after registration, I will display another model form (info model) and connect it with a foreign key and save it.

#

or inheritance case

sterile sphinx
native tide
#

already tried

#

doesn't work

sterile sphinx
#

just open cmd and write ipconfig adn get the ipv4 ip

native tide
#

k

#

i'm gonna try tomorrow pc is off

sterile sphinx
#

Alright

frigid spindle
#

what is best way for a beginner to build a chat bot? is there a library?

mortal pike
frigid spindle
#

does chat bot use ML?

opaque rivet
frigid spindle
opaque rivet
#

it's a job for JS

mortal pike
sterile sphinx
frigid spindle
sterile sphinx
sterile sphinx
opaque rivet
#

What are you struggling with specifically?
By the way, this isn't a good way to do things and is a limitation of Django forms. JS is always the best option here. But, if that isn't an option for you, here is how you would do it:

  • Setup 2 forms, one with the initial inputs you want, and another with the modified inputs.
def your_view(request):
  # different forms (with different options, whatever they may be)
  form_1 = Form1()
  form_2 = Form2()

  # if form_1 is submitted  
  if form_1.is_valid():
    # render a new template, passing form_2
    render_template('yourTemplate', form=form_2)

  # then handle form_2 being submitted

  else:
    render_template('yourTemplate', form=form_1)
frigid spindle
#

cant you build an api using just django?

sterile sphinx
frigid spindle
opaque rivet
#

if you want to automate a chat bot without restrictions to what the user can ask, then it will be using ML (NLP) to process a response

opaque rivet
frigid spindle
opaque rivet
#

it's a whole area of ML

opaque rivet
foggy bramble
frigid spindle
opaque rivet
foggy bramble
#

my problem solved already

opaque rivet
#

oh okay

frigid spindle
#

you can create an api in django with a few simple commands, no?

foggy bramble
#

Thanks a lot for your attention appriciated

opaque rivet
#

πŸ‘

frigid spindle
#

or is it within django?

opaque rivet
#

does it matter? It's used on top of django.

frigid spindle
#

is django mvc?

serene prawn
#

If you have some common fields in some models, like say you might have a Resource model

class Resource:
  pk
  created_at
  updated_at

You could mark it as abstract in it's Meta and inherit from it

serene prawn
frigid spindle
#

model view tempkte

serene prawn
#

Yep

#

They're similar

opaque rivet
#

could anyone help me with this? I'm trying to call a function which will wait 60 seconds without blocking my main thread and then perform a specified action.

    def get_token(self):
        for token, count in self.token_info.items():
            # usage count of a token is 0
            if count < 5:
                # returns token and updates its count +1
                self.increase_token_count(token=token)
                
                # < HERE > I want to call a function which will wait 60 seconds (non-blocking) and perform an action
                return token

so when I call Instance.get_token(), it will return token but also fire a side effect for 60 seconds.
there is probably a simple async solution, which I'm terrible at. any thoughts?

opaque rivet
#

also are there any advocates for FastAPI? what is the use-case? when you want a fast API and have no need for django features (e.g. ORM / models / etc.)?

vestal hound
#

also FastAPI natively supports async

#

Django REST Framework doesn't

frigid spindle
#

can i use fetch api with python?

opaque rivet
#

oh I see, I was interested in it but I don't like leaving all of django's features behind, thought I could just use it for a few data processing endpoints

crude badge
#

Can I learn vuex before vue?

native tide
#

How would i do port forwarding? I have heard of it but have no idea how to do it

serene prawn
crude badge
#

not familiar with either, saw a project with vuex that I wanted to use and wasn't sure if I can learn vuex before vue

#

@serene prawn

serene prawn
#

You would have to learn vue anyway if you want to use vuex

#

So learn vue first i guess πŸ˜‰

crude badge
#

ok cool. thanks

stable hemlock
#

How do I make my django longingly page redirect back to the previous page after login? (For example, when the user tries to access a page that requires login, they get redirected to the login page, and then back to the original page.)

marsh canyon
#

use the login_required decorator or the mixin

#

I believe they redirect the user to the login page and then to the prev page after logging in

minor horizon
#

Hello. I'm using fastapi for an api server. How can cancel processing a request if the client cancel it, close the browser or switch to another page etc.?

reef tree
#

guys how can i make host on my pc as a production server?

hallow perch
#

Hello their, i have a function name login in my home_views.py and i have a function dashboard in my dashboard_views.py when i'm login, it redirect me on my dashboard. But when i'm on my dashboard, how can i say to programm that my function dashboard inside my dashboard_views.py is the main function now for this page?

sterile sphinx
#

I don't use python but i think waht you are looking for is to make the function public so other functions from other files can reach it?

hallow perch
sterile sphinx
#

And right now it dosn't?

hallow perch
#

No look at my login function.

sterile sphinx
#

So you have 2 routes on the same host with diffrent functions is taht correct?

hallow perch
#

Yes ;)

sterile sphinx
#

So when you ar eon the dashboard you wish to perform what's on the left but first you wanna do waht's on the right?

hallow perch
#

Yes exactly

sterile sphinx
#

You got 2 options, either put everything inside the same file or remove the @app.route("/dashboard") over the left side and make the function callable in that file.py to the other file where you first called the code so all you do is execute a function on the right side

#

Hope i understood your question right.

quiet ridge
#

hey how can I store a list in flask sqlalchemy

hallow yacht
#

Need help 😦 i run my migrations with the extnd with AbstractUser...
elation "users_customuser" does not exist
settings.py is AUTH_USER_MODEL = 'users.CustomUser'

#

Solved! πŸ™‚ makemigrations 'appname' πŸ™‚

hallow perch
#

Hello again, i successfull call my function dashboard n my home_views.py but it doesn't change the route access.

native tide
#

Let us know what the issue is, and then maybe... @fair shale

limber laurel
#

How secure is otken authentication, as I am implementing it I feel like it is very insecure

#

could someone help me understand some details?

wary goblet
#

Anyone here that uses Mooshak can help me?! Please.

mortal mango
#
File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\__init__.py", line 80, in authenticate
    user.backend = backend_path
AttributeError: 'method' object has no attribute 'backend'```
I'm getting this error from Django. I don't know how to fix this because I don't have the word "backend" anywhere in my code.

this is my auth.py
```py
from django.contrib.auth.backends import BaseBackend
from .models import DiscordUser
from django.contrib.auth.models import User

class DiscordAuthenticationBackend(BaseBackend):
    def authenticate(self, request, user) -> DiscordUser:
        find_user = DiscordUser.objects.filter(id=user['id'])
        if len(find_user) == 0:
            print("User was not found. Saving...")
            new_user = DiscordUser.objects.create_new_discord_user
            (user)
            print(new_user)
            return new_user
        return find_user
#

Does anyone know how to fix this?

mortal mango
#
Traceback (most recent call last):
  File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Internet\Desktop\Programming\Discord\Ξ X 0 Website\Ξ X 0 Dashboard\dashboard\home\views.py", line 12, in home_view
    authenticate(request, user=user)
  File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\__init__.py", line 80, in authenticate
    user.backend = backend_path
AttributeError: 'method' object has no attribute 'backend'
#

this is the full traceback

#
from django.http import HttpResponse, HttpRequest
from django.shortcuts import render
from django.contrib.auth import authenticate, login
import requests

client_id = "707641033210593351"

# Create your views here.
def home_view(request: HttpRequest, *args, **kwargs):
    code = request.GET.get("code")
    user = exchange_code(code)
    authenticate(request, user=user)
    return render(request, "home.html", {})
``` This is my views.py
opaque rivet
mortal mango
#

yeah

#
AUTHENTICATION_BACKENDS = [
    'home.auth.DiscordAuthenticationBackend'
]
#

@opaque rivet

#

this is my file tree

opaque rivet
#

not entirely sure. can you check if users are being created within your database? could it be that authenticate() is returning return find_user which is an empty queryset and not a user instance / None?

opaque rivet
lament sapphire
#

I'm curious in yoru thoguhts about this Strapi and Django mix?

I found most use Strapi as the backend and stuff like Nextjs in the front0end. I'm thinking about incorporating Django as a middleman backend to manage both Starpi and Nextjs.

What are some of your thoguhts?
https://strapi.io/integrations/python-cms
https://strapi.io/integrations/django-cms

The #1 headless CMS to build powerful applications with Python. Strapi is a new generation API-first CMS, made by developers for developers. Get started in minutes with Strapi and Python.

The #1 headless CMS to build powerful applications with Django.
Strapi is a new generation API-first CMS, made by developers for developers. Get started in minutes with Strapi and Django.

quiet ridge
spare iris
#

πŸ₯΄

river raven
#

Hi, we don't allow advertising on this server, as per rule 6.

stable hemlock
#

is there way to make a button that looks like this in django? Or do I need to use CSS/JS on a checkbox?

mint folio
stable hemlock
candid meteor
#

W3schools is hot

ebon tulip
#

i agree

wooden ruin
#

^^

sleek sable
#

Was making a full stack app using django and react. And i encountered this problem. I have made the index file,its inside the directory. But it is still showing error

#

This is my index.html

#

I tried to re "runserver" and it gave me this error

#

I have added static file in Settings

opaque rivet
#

W3 schools can't get their facts straight, go to Mozilla instead πŸ™‚

opaque rivet
karmic flare
#

Does anyone know how to take the console output and put it to a webpage using flask?

#

I want this:

#

To show up in a webpage served by flask, I've got flask handling file uploads and being able to execute commands with subrocess.Popen

stable hemlock
#

So I switched to agsi and hypercorn in django and my static path broke so none of my website assets load. Anyone know why?

eternal blade
#

Hi, can you suggest a easy to configure http web server for my django web site, Thanks

last steeple
# eternal blade Hi, can you suggest a easy to configure http web server for my django web site, ...
#

Heroku or Pythonanywhere

eternal blade
#

Thanks

ruby summit
#

Hi
I've made a django app and deployed it on heroku
in the app the user logs in, i check the input password with the hashed password in db(using the bcrypt module)
this is ok in the local server
but on heroku
it shows this type error
could someone help me with this
(full code here - https://github.com/iameinstein/Djank/tree/deploy)

rustic pebble
#

How are you saving the hash in the db? @ruby summit

ruby summit
#

using bcrypt as a binary field

rustic pebble
#

And when you try to check the hash are you making sure that the variable that holds the binary hash is converted to hash?

#

Seems to me like u got a type error

#

@ruby summit

ruby summit
#

but

#

it's only on heroku

rustic pebble
#

Send your code

ruby summit
#

when i run the app locally

#

there's no error

rustic pebble
#

Local != production environment

ruby summit
rustic pebble
#

What file should I be looking for?

ruby summit
#

here

#

this one

rustic pebble
#

Line?

#

Help me out man haha

cedar pasture
#
@app.route('/database')
def database():
    # generate some file name
    # save the file in the `database_reports` folder used below
    return render_template('database.html', filename=stored_file_name)

@app.route('/database_download/<filename>')
def database_download(filename):
    return send_from_directory('database_reports', filename)
#

<a href="{{ url_for('database_download', filename=filename) }}">Download</a>

ruby summit
ruby summit
rustic pebble
#

Sned the user.authenticate() methid

#

Method

ruby summit
#

line 19

cedar pasture
#

Hi community, I m currently deploy machine learning model in web, I m referring the code resource, Does anyone know how to define the stored_file_name ?

rustic pebble
#

I think you are passing wrong values. You are converting the pwd to bytes and the self.password is of type binary

#

Bytes are not the same as binary

ruby summit
rustic pebble
#

I don’t know, just trying to understand whats going on from what I am seeing

ruby summit
rustic pebble
#

Yes obviously hahaha

#

They save variables differently

#

In postgres i think you can save a hash as is

#

It allows for a wider variety of types

#

You should probably stick with the same database

ruby summit
#

okay
but sqlite3 aint good for prod..

rustic pebble
#

What?

#

Hahahaha

#

Who told you that?

ruby summit
ruby summit
rustic pebble
#

Yea sqlite3 isnt good for production

#

Thats why you need to stock to postgres

#

Both locally and on prod

#

I am guessing you have the postgres server somewhere hosted

#

Just get the dsn and set it as an env variable

ruby summit
#

or do i need to change models

rustic pebble
#

I mean since the only thing that changes from localhost to server is the database then we can only assume that it is the root of the issue

cedar pasture
#
@app.route('/database')
def database():
    # generate some file name
    # save the file in the `database_reports` folder used below
    return render_template('database.html', filename=stored_file_name)

@app.route('/database_download/<filename>')
def database_download(filename):
    return send_from_directory('database_reports', filename)
#

<a href="{{ url_for('database_download', filename=filename) }}">Download</a>

#

Hi community, I m currently deploy machine learning model in web, I m referring the code resource that I shared to your guy, Does anyone know how's the stored_file_name will be defined like ?

#

cause I m getting this errorNameError: name 'stored_file_name' is not defined

drifting ore
cedar pasture
#

@drifting ore I got this error aganThe requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

#
            new_data = pd.DataFrame(dicts).set_index("Month")
            ##df_predict = pd.DataFrame(transform, columns=["predicted value"])
            response = make_response(new_data.to_csv(index = True, encoding='utf8'))
            response.headers["Content-Disposition"] = "attachment; filename=result.csv"

            labels = [d['Month'] for d in dicts]
            
            values = [d['Predictions'] for d in dicts]

            colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
                       "#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
                       "#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]

            line_labels=labels
            line_values=values
            return render_template('graph.html', title='Time Series Sales forecasting', max=17000, labels=line_labels, values=line_values , filename='stored_file_name')


        
            ##response = make_response(new_data.to_csv(index = True, encoding='utf8'))
            ##response.headers["Content-Disposition"] = "attachment; filename=result.csv"
            ##return response

    @app.route('/database_download/<filename>')
    def database_download(filename):
        return send_from_directory('database_reports', filename)     
#

@drifting ore This is my code

drifting ore
#

πŸ€”

cedar pasture
#

First, I was getting this error >> NameError: name 'stored_file_name' is not defined

drifting ore
#

Dunno actually man! I just know some basics of flask πŸ˜•

cedar pasture
#

I see, anyway thanks for your commend @drifting ore

native tide
#

like once i do the oauth2

#

it redirects to errors

storm roost
#

Hey guys, I was wondering that if I delete a row with a File Field, will the file also get deleted? (In Django)

carmine zenith
mellow geyser
carmine zenith
#

Thanks

#

Python 3.9.1

#

How do I install old versions of pillow.
Do I type pip install pillow8.1?

carmine zenith
mellow geyser
#

pip install Pillow==5.4.0

#

Unistall the already downloaded one, before doing this.

limber laurel
#

Is there any reason to bother with securing token authentication over just using sessions?

carmine zenith
worthy flicker
#

FastAPI issue.

{"detail":[{"loc":["body"],"msg":"field required","type":"value_error.missing"}]

Not sure what this message means, missing a field "body"? Working with Pydantic model with only one field, which I've included in the json body.

humble rain
#

Iam starting with flask websockets, can anyone recomend me some good tutorial? Iam trying to build chat app

cedar pasture
#
           new_data = pd.DataFrame(dicts).set_index("Month")
            ##df_predict = pd.DataFrame(transform, columns=["predicted value"])
            response = make_response(new_data.to_csv(index = True, encoding='utf8'))
            response.headers["Content-Disposition"] = "attachment; filename=result.csv"

            labels = [d['Month'] for d in dicts]
            
            values = [d['Predictions'] for d in dicts]

            colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
                       "#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
                       "#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]

            line_labels=labels
            line_values=values
            stored_file_name = filename
            return render_template('graph.html', title='Time Series Sales forecasting', max=17000, labels=line_labels, values=line_values , filename=stored_file_name)


        
            ##response = make_response(new_data.to_csv(index = True, encoding='utf8'))
            ##response.headers["Content-Disposition"] = "attachment; filename=result.csv"
            ##return response

@app.route('/graph/<filename>')
def database_download(filename):
    return send_from_directory('database_reports', filename) 
#

Hi community, I m currently deploy a machine learning model in web using flask python, Does anyone know how's the stored_file_name can be defined like? cause I m getting this error >> NameError: name 'stored_file_name' is not defined

#

cause I would like to store the new_csv_file into directory and retrive back from the download

#

<a href="{{ url_for('database_download', filename=filename) }}">Download</a>

#

Does anyone know how to solve, please help ~

sage bluff
#

guys i have one small doubt in jwt , after the successful authentication jwt is returned to the frontend , so imagine that jwt data contains the authenticated user's username ```
{
username : someone,
expires : 162834123
}

cedar pasture
#
new_data = pd.DataFrame(dicts).set_index("Month")
            ##df_predict = pd.DataFrame(transform, columns=["predicted value"])
            response = make_response(new_data.to_csv(index = True, encoding='utf8'))
            response.headers["Content-Disposition"] = "attachment; filename=result.csv"

            labels = [d['Month'] for d in dicts]
            
            values = [d['Predictions'] for d in dicts]

            colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
                       "#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
                       "#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]

            line_labels=labels
            line_values=values
            stored_file_name = filename
            return render_template('graph.html', title='Time Series Sales forecasting', max=17000,              labels=line_labels, values=line_values , filename=stored_file_name)


@app.route('/graph/<filename>')
def database_download(filename):
    return send_from_directory('database_reports', filename) 
#

<a href="{{ url_for('database_download', filename=filename) }}">Download</a>

#

Hi community, I m currently deploy a machine learning model in web using flask python, Does anyone know how's the stored_file_name can be defined like? cause I m getting this error >> NameError: name 'stored_file_name' is not defined
cause I would like to store thenew_csv_file into directory and retrive back from the download

sage bluff
cedar pasture
#

I have no idea how to define it actually

#

but it dint mention how to define the 'stored_file_name'

ruby summit
#

Hi guys
I am storing binary data in a Postgres database
But when I query it
I get a memoryview type object
Could anyone tell how do I convert this memoryveiw into bytes ?

cedar pasture
#

@sage bluff

#

like actually how to store my new CSV file to stored_file_name?

sage bluff
ruby summit
#

Ok

#

Thnx @sage bluff

sage bluff
#

np

cedar pasture
#
@app.route('/transform', methods=["POST"])
def transform_view():
 if request.method == 'POST':
        f = request.files['data_file']
        if not f:
            return "No file"

        
        stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None)
        csv_input = csv.reader(stream)
        stream.seek(0)
        result = stream.read()
        df = pd.read_csv(StringIO(result), usecols=[1])
        
        #extract month value
        df2 = pd.read_csv(StringIO(result))
        matrix2 = df2[df2.columns[0]].to_numpy()
        list1 = matrix2.tolist()
         
        # load the model from disk
        model = load_model('model.h5')
        dataset = df.values
        dataset = dataset.astype('float32')
        scaler = MinMaxScaler(feature_range=(0, 1))
        dataset = scaler.fit_transform(dataset)
        look_back = 1
        dataset_look = create_dataset(dataset, look_back)
        dataset_look = np.reshape(dataset_look, (dataset_look.shape[0], 1, dataset_look.shape[1]))
        predict = model.predict(dataset_look)
        transform = scaler.inverse_transform(predict)

        X_FUTURE = 12
        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]

        dicts = []
        curr_date = pd.to_datetime(list1[-1])
        for i in range(X_FUTURE):
            curr_date = curr_date +  relativedelta(months=+1)
            dicts.append({'Predictions': transform[i], "Month": curr_date})
#
    new_data = pd.DataFrame(dicts).set_index("Month")
            ##df_predict = pd.DataFrame(transform, columns=["predicted value"])
            response = make_response(new_data.to_csv(index = True, encoding='utf8'))
            response.headers["Content-Disposition"] = "attachment; filename=result.csv"

            labels = [d['Month'] for d in dicts]
            
            values = [d['Predictions'] for d in dicts]

            colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
                       "#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
                       "#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]

            line_labels=labels
            line_values=values
            stored_file_name = filename
            return render_template('graph.html', title='Time Series Sales forecasting', max=17000,              labels=line_labels, values=line_values , filename=stored_file_name)

@app.route('/graph/<filename>')
def database_download(filename):
    return send_from_directory('database_reports', filename)     
#

this is the whole code

sage bluff
#

and the error

cedar pasture
#

NameError: name 'stored_file_name' is not defined

#

@sage bluff do you have any ideas ? haha

sage bluff
#

but stored_file_name should have the filename right ?

#

then why dont you ```
stored_file_name = 'somename.format'

cedar pasture
#

hmm sorry, I dont get you, what should I write axactly?

sage bluff
#

nvm wawit for better help , i dont get your question either , sorry

#

but why do you even wawnt to move the data from one csv file to another ?

cedar pasture
#

oh it is okay, thanks for your reply

#

how to ?

#

the new csv file is use to store the predicted value one

chilly falcon
#

can we use authentication function of django in other models lalso??

#

also*

opaque rivet
lavish prismBOT
#

Hey @lusty cloud!

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

lusty cloud
#

after creating a secondary application and linking urls, i get this

#

when i try to run my server

opaque rivet
#

What you meant to do here was include('articles.urls') and be sure to register 'articles' in your INSTALLED_APPS

lusty cloud
#

still doesnt work

#

this is my articles url.py file also

opaque rivet
#

yeah... as I said, your code says include(articles.url). There is no articles.url. It should be include(articles.urls)

lusty cloud
#

gotta love one missing letter

#

thanks

mellow geyser
carmine zenith
#

Thanks. I’ll give this a try

wheat skiff
#

Hi, does anyone have website with django which is contain registration and chat? I have one i made by myself but i dont know how to connect between db and the site So if one of you can help me it will be very good too

mellow geyser
wheat skiff
#

no, i will chat with u in private

mortal mango
#
File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\__init__.py", line 80, in authenticate
    user.backend = backend_path
AttributeError: 'method' object has no attribute 'backend'```

AUTHENTICATION_BACKENDS = [
'home.auth.DiscordAuthenticationBackend'
]


I'm getting this error from Django. I tried searching for a solution but I can't find one.

https://gist.github.com/PRA7H1K/f7802dad07466e5fb9d08a6ded10fa68 this is my code
Gist

GitHub Gist: instantly share code, notes, and snippets.

swift nebula
#

Good day to all, me and my team on capstone are planning to make a website that accepts online meeting like zoom. Can someone recommend me what to use or what to embed to our website? (No, we didn't use wordpress so we can't embed zoom)

charred imp
#

Hey guys

#

Someone know how i can make a website without a framework?

#

to be more specific how develop a back end without framework

stable hemlock
charred imp
gloomy edge
#

what

#

is web devlopment

#

nd can we do

stable hemlock
gloomy edge
#

it by html

#

means

charred imp
stable hemlock
charred imp
prisma canopy
#

hi anyone here

#

i have a doubt about flask

stable hemlock
native tide
#

I need PyCharm Professional crack πŸ˜”

sterile sphinx
native tide
#

It's very very cool, but I don't have the money to subscribe

#

πŸ˜‚

sterile sphinx
#

there is a comunity edition witch is free.

mortal mango
#
File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\__init__.py", line 80, in authenticate
    user.backend = backend_path
AttributeError: 'method' object has no attribute 'backend'```

AUTHENTICATION_BACKENDS = [
'home.auth.DiscordAuthenticationBackend'
]


I'm getting this error from Django. I tried searching for a solution but I can't find one.

<https://gist.github.com/PRA7H1K/f7802dad07466e5fb9d08a6ded10fa68> this is my code
sterile sphinx
#

user.backend is not a thing, remove backend from user.

mortal mango
#
Traceback (most recent call last):
  File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Internet\Desktop\Programming\Discord\Ξ X 0 Website\Ξ X 0 Dashboard\dashboard\home\views.py", line 12, in home_view
    authenticate(request, user=user)
  File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\__init__.py", line 80, in authenticate
    user.backend = backend_path
AttributeError: 'method' object has no attribute 'backend'
#

this is the full traceback

mortal mango
#

it looks like it's in a init.py file

sterile sphinx
#

I highly doubt it's a django error most likely you caused the error on your end witch triggered an exception in django

mortal mango
#

oh ok

sterile sphinx
#

Looking at here i assume this is the file you are working on " File "C:\Users\Internet\Desktop\Programming\Discord\Ξ X 0 Website\Ξ X 0 Dashboard\dashboard\home\views.py", line 12, in home_view
authenticate(request, user=user)"

mortal mango
#

Yeah views.py is one of the files I'm working on

#

I think the error is at authenticate(request, user=user)

sterile sphinx
#

The code in:
def home_view(request: HttpRequest, *args, **kwargs):
code = request.GET.get("code")
user = exchange_code(code)
authenticate(request, user=user)
return render(request, "home.html", {})

Indicates a error in the traceback, i would look for errors there, set a breakpoint see where the error happens and come back if you still strugle with finding it, i normally never use python.

native tide
mortal mango
#

oh ok

#

thanks!

sterile sphinx
native tide
#

I don't know, it doesn't sound like a good idea

mortal mango
#
def home_view(request, *args, **kwargs):
    print("1")
    code = request.GET.get("code")
    print("2")
    user = exchange_code(code)
    print("3")
    authenticate(request, user=user)
    print("4")
    return render(request, "home.html", {})
    print("5")
``` @sterile sphinx print 4 and 5 didn't trigger
#

so I'm pretty sure its the authenticate

sterile sphinx
#

I don't know what authenticate function is but user=user is reffering to it's self but user is allredy null and user is equal to user means it's null unless user is a global variable?

mortal mango
sullen ridge
#

Hello πŸ‘‹

I am trying to do something in Flask and was wondering if someone could help me.

What do I want to do?
I am looking to make a basic messaging application that works without databases. I have made one with databases before but I am now looking to make one that is reliant on nothing other than itself. Don't get me wrong, I am not stupid. I know without storing it somewhere, it cannot be retrieved and shown to the user. But that's not what I want to do. I want to make it so upon the page being reloaded, the message is gone. So basically, User 1 inputs some text into an input field and presses the send button and then the other user (User 2) sees that text on their screen.

native tide
#

Can anyone here who knows selenium help me out with one really tiny thing thats frustrating me for the last few hours?

Using driver.execute_script("return localStorage.getItem('thing')") doesn't work, but when I do it in developer tools of the selenium firefox window, it works

cerulean vapor
sullen ridge
#

Hm. I saw some JS thing and it's called Broadcast Channel. Ever heard of it?

cerulean vapor
#

@sullen ridge Nope, I don't follow JS stuff

sullen ridge
#

Oh right.

#

I assumed this would require JS.

#

So you're suggesting websockets?

cerulean vapor
#

websockets is one way to do it, but it isn't always ideal. For instance, if you're using a shared hosting environment, it may not be possible to deploy it

#

another way is just to have each client use JS to periodically poll for new messages

#

but you don't need a database as such to hold the messages, a dict with lists would do fine

sterile sphinx
#

Well you can just use python, make a tcp listner and implement the websocket spec, it isn't hard at all.

swift wren
#

hey guys, for wtforms, how can i add the attrs value and link them to bootstrap's form-control

#

this is flask

grim tiger
#

@swift wren Is there a package for wtf-bootstrap?

swift wren
#

i figured it out

#

the jinja has params

#

pretty cool

grim tiger
#

Does anyone want to work on a project together? It's a birthday reminder service.

swift wren
#

dose it work with email? or sms

native tide
#

How can I serve react app with Django ?

swift wren
#

serializer

opaque rivet
# native tide How can I serve react app with Django ?

make a view which handles any visits to the base URI /

def index(request):
  return render_template('index.html')

You are going to have to go into settings.py and make the templates folder & static settings point to your static folder in your build directory once you have npm run build in your react app's root directory.

#

that way Django knows where to look for your React's index.html page πŸ™‚

native tide
#

@opaque rivet Thank you for help

opaque rivet
#

i wonder if I can do SSR for my next.js app / django πŸ€”

serene onyx
#

I am currently working on building a website using Flask for the server backend

#

I cannot figure out how to create a hyperlink back to the index.html file

#

nvm literally just got it lol

acoustic narwhal
#

in the views.py file , when we write let's say a function home

  return render(request,'something')```

> where is request coming from? and what are we exactly returning?
#

Doubt : Django tech , level:beginner

pearl birch
#

anyone want to teamup for a hack

#

in django

obtuse kite
#

I cannot link my css file with html...is there anybody who can help me..if someone has some time I can either provide detailed info here or in the dms

#

I am using django framework btw

obtuse kite
#

I just tried to debug it nothing happening i did everything checked all the selectors and my main.html file again and again

#

also I tried to find help on websites and It won't help

smoky skiff
#

post code otherwise people cant help

opaque rivet
obtuse kite
opaque rivet
#

well I'd look into your console and see what response it's giving you when you're trying to fetch your stylesheet. If it's a 404, you know that it's a settings error. Otherwise you have a stale cache.

opaque rivet
#

I have a function which I want to run once when my server starts. I don't think I can use celery for this because it's not a periodic task. To do this, can I just call it in manage.py?

distant trout
#

im making an api request with react

#

but its calling the endpoint twice for some reason

#

i have a seperate function that fetches the api, and i call the function inside of my component, and its calling it twice

opaque rivet
distant trout
#

const ClipContainer = ({ title }) => {

    const access_token = getAccessToken()
    console.log(access_token)

    return (
        <>
            <h2 className="clip-container-header">{title}</h2>
            <div className="clip-container">
                <Clip />

            </div>
        </>
    )
}
#

im just testing it right now, so its console logging the api call twice

#

its a post request for refreshing access token, so its changing the access token every call

chrome shuttle
#

I'm trying to start into 'Django for beginners' and am not sure about starting my virtual environments. If I use PyCharm and create new with pipenv, I start with the pipenv active. Then I install django etc and am instructed to startproject. So, I get two sets of parens. Is this right?
(helloworld-JYK3ZMAd) (helloworld) C:\Users\XLT\PycharmProjects\helloworld>

opaque rivet
opaque rivet
chrome shuttle
#

yeah, that's what I was afraid of

distant trout
#

im rendering it once on my app.js file and i am passing in a title prop, it is only being rendered once, pretty sure.

I am gonna try out using useEffect hook, havent tried that yet. Thanks

chrome shuttle
#

@opaque rivet so do I want to stop running the top level pipenv that was created when I started the project and only run the one that starts when i start the project?

opaque rivet
#

I don't really know anything about virtual environments, but opening a new project w/ PyCharm and letting it setup the venv for you always works.

chrome shuttle
opaque rivet
#

maybe the book is focusing on setting up the venv yourself (without letting PyCharm set it up for you). You could do that, just setup a new project without a venv then do it yourself as the book is stating.

chrome shuttle
distant trout
#

using useEffect worked btw thank you @opaque rivet

native tide
#

hey

#

anyone able to quickly help me with a footer ?

austere acorn
#
e = e || window.event;
#

what does this line mean ? i see it a lot in javascript

#

e here refers to javascript event

mental bay
#

looks like its catching both js and window events?(would need a correction, likely wrong)

dull wigeon
#

is django or flask faster?

lusty cloud
#

when i go to try and retrieve my values from the models in unicode, its still staying as article object(1)

from django.db import models

# Create your models here.

class Book(models.Model):
    name = models.CharField(max_length=200)
    pages = models.IntegerField()

    def __unicode__(self):
        return self.name
#

fixed

opaque rivet
opaque rivet
#

to represent each object as a string

#

i just spent a few hours coding and got barely anything done 🀦

cedar pasture
#
 new_data = pd.DataFrame(dicts).set_index("Month")
            ##df_predict = pd.DataFrame(transform, columns=["predicted value"])
            response = make_response(new_data.to_csv(index = True, encoding='utf8'))
            response.headers["Content-Disposition"] = "attachment; filename=result.csv"

            labels = [d['Month'] for d in dicts]
            
            values = [d['Predictions'] for d in dicts]

            colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
                       "#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
                       "#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]

            line_labels=labels
            line_values=values
            return render_template('graph.html', title='Time Series Sales forecasting', max=17000, labels=line_labels, values=line_values , filename=stored_file_name)


        
  
@app.route('/database_download/<filename>')
def database_download(filename):
    return send_from_directory('database_reports', filename)
#

Hi community, I m currently deploy a machine learning model in web using flask python, Does anyone know how's the stored_file_name be define like and how to pass the New CSV file into stored_file_name? cause I m getting this error >> NameError: name 'stored_file_name' is not defined

cedar pasture
#

<a href="{{ url_for('database_download', filename=filename) }}">Download</a>

#

Does anyone know how to solve? Please help ~

glacial orchid
cedar pasture
#
 new_data = pd.DataFrame(dicts).set_index("Month")
            ##df_predict = pd.DataFrame(transform, columns=["predicted value"])
            response = make_response(new_data.to_csv(index = True, encoding='utf8'))
            response.headers["Content-Disposition"] = "attachment; filename=result.csv"

            labels = [d['Month'] for d in dicts]
            
            values = [d['Predictions'] for d in dicts]

            colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
                       "#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
                       "#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]

            line_labels=labels
            line_values=values
            return render_template('graph.html', title='Time Series Sales forecasting', max=17000, labels=line_labels, values=line_values , filename=stored_file_name)
#

Hi community, response.headers["Content-Disposition"] = "attachment; filename=result.csv" << My new file is being generated from here, so how do I pass my new CSV file into directory, so I can retrieve back from download button?

#

<a href="{{ url_for('database_download', filename=filename) }}">Download</a> Tag in HTML

cedar pasture
cedar pasture
#
new_data = pd.DataFrame(dicts).set_index("Month")
        ##df_predict = pd.DataFrame(transform, columns=["predicted value"])
        response = make_response(new_data.to_csv(index = True, encoding='utf8'))
        response.headers["Content-Disposition"] = "attachment; filename=result.csv"

        labels = [d['Month'] for d in dicts]
            
        values = [d['Predictions'] for d in dicts]

        colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
                       "#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
                       "#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]

        line_labels=labels
        line_values=values
        return render_template('graph.html', title='Time Series Sales forecasting', max=17000, 
        labels=line_labels, values=line_values)

@app.route('/database_download/<filename>')
def database_download(filename):
    return send_from_directory('database_reports', filename) 
#

I m currently deploy a machine learning model in web using flask python, Does anyone know how to pass my response.headers["Content-Disposition"] = "attachment; filename=result.csv" into next @app.route('/database_download/<filename>'), so I could retrieve back from download button?
<a href="{{ url_for('database_download', filename=filename) }}">Download</a> <<< this is my download button in HTML

obtuse kite
#

bro is it enough and what's the problem

opaque rivet
#

Where's the static root?

#

What's the response code in the console, 404?

#

And show us the code where you're trying to link the stylesheet

stoic tulip
#

How to make snake & leaders game??

cedar pasture
#
  new_data = pd.DataFrame(dicts).set_index("Month")
        ##df_predict = pd.DataFrame(transform, columns=["predicted value"])
        response = make_response(new_data.to_csv(index = True, encoding='utf8'))
        response.headers["Content-Disposition"] = "attachment; filename=result.csv"

        labels = [d['Month'] for d in dicts]
            
        values = [d['Predictions'] for d in dicts]

        colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
                       "#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
                       "#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]

        line_labels=labels
        line_values=values
        return render_template('graph.html', title='Time Series Sales forecasting', max=17000, labels=line_labels, values=line_values)


        
        ##response = make_response(new_data.to_csv(index = True, encoding='utf8'))
        ##response.headers["Content-Disposition"] = "attachment; filename=result.csv"
        ##return response

@app.route('/database_download/<filename>')
def database_download(filename):
    return send_from_directory('database_reports', filename)
#

<a href="{{ url_for('database_download', filename=filename) }}">Download</a>

#

Hi community, I m currently deploy a machine learning model in web using flask python, Does anyone know how to pass my response.headers["Content-Disposition"] = "attachment; filename=result.csv" into next @app.route('/database_download/<filename>'), so I could retrieve and download back the result.csvfrom download button?

compact crane
#

Hello, by doing the following can I grab returning data from my-route view?```python
@app.route('/my-route', methods=['POST'])
def login():
return jsonify({'data': data})

```html
<form action="/my-route" method="POST" id="form"></form>
const form = document.getElementById("form");
        form.addEventListener('submit', function(event) {
            event.preventDefault();
        })
         .then((response) => response.json())
         .then(function(responseJson) {
          var data = responseJson.data;
        });
magic kernel
#

File "C:\Users\asus\PycharmProjects\djangoProject\taskmate\todolist_app\urls.py", line 2, in <module>
from taskmate.todolist_app import views
ModuleNotFoundError: No module named 'taskmate.todolist_app'

magic kernel
native tide
#

try this from views import <view_name>, <another_view_name>

native tide
hardy cosmos
#

hi all, im developing a website using flask for the backend and i was wondering if anyone knows how i can let users add events created by the web application to their google calendar using a button on the site? the google calendar api docs basically just say copy paste this code to make calendar do stuff so its really not helping πŸ˜‚.

swift talon
#

Hi guys
I'm starting to learn Django
I have problem with it
why my server don't run?
I tried to use "python manage.py runserver " and "py manage.py runserver "
what can u advice me

obtuse kite
nimble epoch
#

Stupid question: if i setup google AdSense for my website do i earn money from only viewing website or viewers gotta click on ads?

opaque rivet
#

go to browser > developer console > network

obtuse kite
#

let me render the site

opaque rivet
obtuse kite
obtuse kite
opaque rivet
#

no, I didn't ask that, what is the response code when you are trying to fetch the stylesheet

#

go to inspect element

#

go to network

#

refresh

native tide
#

Does anyone has any experience with web scraping? I'm trying to get the twitter username of the people who liked a post, but keep getting this as a response if I fetch this url: https://twitter.com/mcnabbd/status/1378352586458206212

The HTML response contains this block:

<p>We've detected that JavaScript is disabled in this browser. Please enable javascript or switch to a supporter browser to continue using twitter.com</p>

So it doesn't return the html of the actual page but a page showing an error message.

@lexfridman β€œHanging on in quiet desperation is the English way”
Pink Floyd

Likes

470

opaque rivet
# obtuse kite what does these errors mean?
obtuse kite
#

@opaque rivet bro aplogise me I made a very basic mistake I made my static folder within the project instead of my app -_-

#

sorry for bothering

#

I really appreciate the help

opaque rivet
#

if you read through the link it will explain further

obtuse kite
#

tysm once again

limber dew
#

is there anybody who implement django with vue js before?

candid meteor
#

Not Me

limber dew
#

for sure there is somebody xD

mystic wyvern
#

Hi,I always wonder what is the use of class Meta in django??

sly canyon
#

Hi!! I'm trying to many a One-To-Many relationship using SQLAlchemy but I can't link two objects directly. In pure SQL I'd have to do this:

-- Finding the parent of a child
SELECT p.* 
FROM child c
INNER JOIN parent_children pc ON pc.child_id = c.id
INNER JOIN parent p ON pc.parent_id = p.id
WHERE c.id = 2323 -- example

-- Finding parent childrens
SELECT c.* 
FROM parent p
INNER JOIN parent_children pc ON pc.parent_id = p.id
INNER JOIN child c ON pc.child_id = c.id
WHERE p.id = 32323 -- example****

Here's the model:

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    children = # TODO: HOW TO?    

class ParentChild(Base):
   __tablename__ = 'parent_children'
   child_id = Column(Integer, ForeignKey('child.id'))
   parent_id = Column(Integer, ForeignKey('parent.id'))

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    parent = # TODO: HOW TO ?

Can anybody with some experience give a tip on how to code that?

obtuse kite
#

Rn My css file is linked with my main.html

#

but it doesn't render changes

opaque rivet
mint valley
#

hello, idk if its ok to ask this here but, any advice for start web dev with python?

stable hemlock
#

Do a flask tutorial to start.

#

Or django if you want something more complicated but powerful.

mint valley
#

flask, got it

#

ty

sly canyon
surreal horizon
#

i know in flask you can get parameters from the url like this py @app.route('/something/<para>') def something(para): return para But is there some way, I can redirect the user to a url by passing a parameter to the function and not the url. Something like this```py
@app.route('/something_else')
def something_else(para): # Redirect here and send paramenter in function, not url
return para + ' redirect.'

real hare
#

So you want to redirect?

#

You could do a return redirect(url_for('something_else')) perhaps?

#

Oh wait, I've not fully answered

surreal horizon
#

but i also want to send a parameter. the thing is i dont want the user to see the parameter in the url

real hare
#

return redirect(url_for('function_name', value=some_variable))

surreal horizon
#

ah ok that you mate!

torpid knoll
#

you can just call the related method if you want to continue on the same url

#

this will change url

real hare
#

I've got two functions, a POST, and it redirects to anther function which is a GET, and I wanna pass a file over, but I want to keep the session alive, how does one make it "persist"?

torpid knoll
#

I guess you can get same file from tmp

#

just pass tmp path

real hare
#

Can you give an example?

torpid knoll
#

I guess you will be getting file from a form post right ? like user will upload file ?

real hare
#

Yeah, I got the logic all drawn up

#

But this one part is missing

#

I get an error thrown to say the file does not exist when passing the file over to the function that is solely for a GET

torpid knoll
#

upload = request.FILES['ufile']
path = upload.temporary_file_path

#

so I guess you should be able to use this url, you can pass while redirecting etc

real hare
#

Thanks, I'll give it a shot

sacred prism
#

guys

#

i did this

#

<img class="logo" src="images/logo.png" alt="sorry image not found" /
width="150">

#

and this

#

div.logo {
float: left;
}

#

but it doesnt work

#

i defined it

#

i did this too

#

logo {
float: left;
}

#

it dont work

whole crow
#

@sacred prism "it dont work" doesn't tell us much. Can you put what you have in a jsfiddle so we can see it?

sacred prism
#

jsfiddle?

#

what is that

#

sorry i am new

whole crow
sacred prism
#

here

#

its a test site btw

#

how do i fix this?

surreal horizon
sacred prism
#

i need help

#

how do i class an image?

#

I AM SO STUPID

#

NVM NO HELP THX

surreal horizon
#

wdym class an image

slender whale
#

Can someone explain to me what python library I would use if I need to full stack development?

#

Or libraries*

real hare
#

<img src="...." class="blah" />

#

you mean like this?

vestal hound
#

so like

#

assume you just want to serve static pages

#

that’ll be sufficient

#

often you want to persist some data

#

that means you’ll need a database layer, hence a database driver

#

you might want some dynamic behaviour on those pages

#

so you’ll need to know JS

#

that can go all the way to learning a full library/framework like React/Vue/Angular

#

if you’re doing that your backend is probably just a HTTP API

#

you can also consider FastAPI/Django

stable hemlock
#

Does anyone have recommendations for JS tutorials/videos, particularly ones that involve interacting with django forms?

ashen sparrow
#

I am working on making a template for serverless framework for django, and would love contributions/opinions on several improvements such as asgi support, wsgi workaround for running app on each invoking etc. Anyone here who has worked with serverless framework before or wants to play around with it?

cedar pasture
#
new_data = pd.DataFrame(dicts).set_index("Month")
    response = make_response(new_data.to_csv(index = True, encoding='utf8'))
    response.headers["Content-Disposition"] = "attachment; filename=result.csv" #Want to return this response to auto download a new CSV file also

    labels = [d['Month'] for d in dicts]
        
    values = [d['Predictions'] for d in dicts]

    colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
               "#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
               "#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]

    line_labels=labels
    line_values=values
    return render_template('graph.html', title='Time Series Sales forecasting', max=17000, 
    labels=line_labels, values=line_values)
#

Hi community, I m currently deploy a machine learning model in web using flask python, Does anyone know how to return my response.headers["Content-Disposition"] = "attachment; filename=result.csv" and plot graph together, currently I m able to return the plot graph but no idea how to get or return the download with new CSV? Please share me some tips ~ thanks in advance

dull wigeon
#

do i need a user in a model for django

cedar pasture
native tide
#

I found something interesting while webscrapping in amazon

icy drift
#

is it possible to have a different background for every page using Django?

slender whale
cedar pasture
#
new_data = pd.DataFrame(dicts).set_index("Month")
            ##df_predict = pd.DataFrame(transform, columns=["predicted value"])
            response = make_response(new_data.to_csv(index = True, encoding='utf8'))
            response.headers["Content-Disposition"] = "attachment; filename=result.csv"
    
            labels = [d['Month'] for d in dicts]
                
            values = [d['Predictions'] for d in dicts]
    
            colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
                           "#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
                           "#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]
    
            line_labels=labels
            line_values=values
            return render_template('graph.html', title='Time Series Sales forecasting', 
max=17000, labels=line_labels, values=line_values, filename = response)
    
    
    @app.route('/download/<filename>')
    def download(filename):
        filename = filename
        return send_from_directory(filename=filename, as_attachment = True)
#

Hi community, I m currently deploy a machine learning model in web using flask python, Does anyone excel in send_from directory, please share me how to return my send_from directory correctly? cause I want to pass my response to serve a download route, currently I only can return my plot graph

#

Error I got >> TypeError: send_from_directory() missing 1 required positional argument: 'directory'

opaque rivet
cedar pasture
#

oh, so what should I change ?

#

btw It is possible to pass the to_csv to next app.route and return back one ?

cedar pasture
#

@opaque rivet

opaque rivet
#

@cedar pasture I dont know what you mean either. Plus I dont know your send_from_directory function. It needs a positional arguement, check the docs or your code if it's your own function.

#

I think what you're trying to do is make an API

long kestrel
#

Hi I work with flask restful with a database many to many
many sources have many categories and reverse
class Sources(db.Model,UserMixin):
tablename = "sources"

id = db.Column(db.Integer, primary_key=True, autoincrement=True)
source = db.Column(db.String(200), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
#catgeorie_id =  db.Column(db.Integer, db.ForeignKey('categories.id'))
date_created = db.Column(db.DateTime, default=datetime.utcnow)
categories = db.relationship('Categories', secondary=categories_sources, lazy='subquery',
    backref=db.backref('pages', lazy=True))
def serialize(self):
    return {'id': self.id,
            'source': self.source,
            'user_id': self.user_id,
            'date_created': self.date_created,
   }

class Categories(db.Model,UserMixin):
tablename = "categories"
table_args = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True)
category = db.Column(db.String(200), nullable=False)
#source_id = db.Column(db.Integer, db.ForeignKey('sources.id'))
date_created = db.Column(db.DateTime, default=datetime.utcnow)
keyword = db.relationship('Keywords', backref='categorie', lazy='dynamic')

def serialize(self):
    return {'id': self.id,
            'categorie': self.category,
            'date_created': self.date_created,
             }

s = Sources()
c = Categories()
c.categories.append(s)
db.session.add(c)
db.session.commit()

#

when for a ressource I had to add a categorie for a given source
I used for the post

#

def post(self, id_source):
category = request.json['category']

    categorie = Categories(category=category)
    db.session.add(categorie)

but how to make the relation with the id_source that i sent in the url
with the source table

#

please help or give me a link for a flask community

opaque rivet
#

!code

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

acoustic narwhal
#

can we not directly use request object inside models.py?

karmic flare
#

Anyone know why flask wont serve background image from css even though I'm sure the css is correct?