#web-development

2 messages · Page 116 of 1

quick cargo
#

why do you need wsl2

#

hyper v should be enough for most people

hybrid bobcat
#

i tried to run commands from docker and it says "daemon is not running" which it is, and the "WSL2 install is incomplete" pops up everytime when i log in

hybrid bobcat
quick cargo
#

it should be pre installed with windows

#

you just need to tell docker to use it since now they added wsl2 docker defaults to it

hybrid bobcat
#

how do i tell it to use that?

#

sorry im completely new to docker and it got me confused

quick cargo
#

docker desktop

hybrid bobcat
#

ohhhh

#

thank you

#

do i need to restart after setting that?

#

oh wait, it won't let me deselect...

#

prolly need to sign in hold up

#

yea it wouldn't let me deselect the "set WSL2 to default " one

quick cargo
#

are you on win 10 pro?

#

or win 10 workstation

hybrid bobcat
#

home ;-;

#

and 2.5.0.1 is the only version i can install rip

#

prolly that's why

hybrid bobcat
quick cargo
#

its like 9$ or so i think for a key

hybrid bobcat
#

ok thanks

quick cargo
#

i say this with activate windows in my screen

#

lol

hybrid bobcat
#

dang docker is so much things to setup

#

but ill still do it

#

but does doing that break some things on my machine?

quick cargo
#

from what ive heard it can

hybrid bobcat
#

welp

quick cargo
#

joys of win 10 pro

hybrid bobcat
#

rip im home boy

quick cargo
#

vm installed by default not wsl2 though

hybrid bobcat
quick cargo
#

@cursive whale how is that relevant

cursive whale
#

yes

hybrid bobcat
#

wait it says i need a VM for WSL2

amber sail
#

this is with flask

hybrid bobcat
#

flask?

quick cargo
#

pretty sure thats not how sqlalchemy works

amber sail
#

idk I am following a tutorial

hybrid bobcat
#

bruh dude i got this problem on this step

#

when i run wsl --set-default-version 2

#

it says

quick cargo
#

you should have that though

#

unless its disabled in BIOS

hybrid bobcat
#

ok im really lost this stupid docker thing brainmon

quick cargo
#

dont blame docker for window's issues 😩

hybrid bobcat
#

docker desktop

quick cargo
#

probably cuz you dont have the hyper vm installed because you're not on win 10 pro or workstation

#

cuz windows class that stuff as 'prograde'

hybrid bobcat
#

dang, is there any way to do that?

#

like

#

just get the hyper v vm

#

without win pro

quick cargo
#

no idea

#

probably

hybrid bobcat
#

ok so on desktop, do i really need that linux kernel or whatever it's called to run it?

quick cargo
#

yeah

hybrid bobcat
quick cargo
#

saying that i dont think you get it with pro either

#

cuz powershell WSL 2 requires an update to its kernel component. For information please visit https://aka.ms/wsl2kernel For information on key differences with WSL 2 please visit https://aka.ms/wsl2 PS C:\WINDOWS\system32>

hybrid bobcat
#

yea that's the error i got for trying to set WSL2 to default

quick cargo
#

oh wait should of restarted

#

oops

hybrid bobcat
#

i do?

#

lemme try it

#

The way that guy named Fireship on YouTube does it, makes me thought docker was easy to set up ;-;

primal grove
#

I have to make a simple website for a non-webdev class; for flask, how do I pick which page a given function is handling post requests for?

quick cargo
hybrid bobcat
#

Ah I see

quick cargo
primal grove
quick cargo
#

So you know your standard endpoint function

primal grove
#

looks like it may have something to do with app.route?

quick cargo
#

Yeah

#

I would just do it as you would for a Get request put pass app. Route methods=["POST", "GET"]

native monolith
#

what should be returned at link /favicon.ico ? cause I got error 404 and wonder if anything has to be reutrned

quick cargo
#

And then you should be able to compare your request.method global var to the str

#

@native monolith that's the browsers default thumbnail icon bit

vestal hound
quick cargo
#

You can set a custom on in the meta tag in le html

#

Hard to really show on mobipe

vestal hound
#

so, yes, route

primal grove
#

Thanks @vestal hound @quick cargo

#

also @vestal hound do you just check every topical channel?

vestal hound
hybrid bobcat
#

yo @quick cargo for "Install your Linux distribution of choice" do i choose Ubuntu? i been hearing it a lot sooo

vestal hound
native monolith
#

i attach it with link

#
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
hybrid bobcat
#

@quick cargo yoo i got my problem resolved

#

sorry for the ping but im so glad i got the problem resolved

#

this tutorial actually does the trick

swift heron
#

Hello, currently to update my frontend in jquery I am running the following

function update_applications() {
    $.ajax({
        url: 'http://127.0.0.1:8000/computer/',
        type: 'POST',
        data: {update: true},
        dataType: 'json',
        success: function (app_data) {
            //Remove Old list of windows
            $('#application_list').empty();

            // Response Received updating list
            $.each(app_data, function (index, app) {
                $("#application_list").append(
                    'BUNCH OF HTML'
                )
            });
        },
    });
}


setInterval(update_applications, 5000);

So basically I run this function on a interval to tell my backend to update the database, is there a better way to do this? such as have this interval run in the backend and then on database change send the new data to the frontend? how would I go about creating an update loop in the backend?

#

feel free to @swift heron thanks

wispy ice
#

Hello, i have a simple http web with lighttpd server, working fine. How can i implement HTML with python?

#

Load a file in the html web, click send, get the file in python, modify it and serve it back, or a "success" message

#

Do i need a server for python?

#

I tried just with ajax, but it does not work...

#

i dont know if i call the function properly, and im sure i dont know how to return the return file/string of the function and put it in a html vae

#

If answer, please @ me

slim beacon
#

Can anyone point me in the right direction?

I wrote a text-based game that prompts for input on terminal and prints out strings to screen.

I want to put the game on my site so users can play it, but I'm having a hard time finding how to print to screen in a similar fashion to terminal and how this can be tied together with the game.

native monolith
#

but I am not sure if it would work, without state preserving

slim beacon
#

Oh I think I should be more specific. My site is running Django already pithink

coral raven
#

Use javaScript @slim beacon

slim beacon
#

@coral raven How would that work? Javascript could be set up to print out strings to screen and when the original code prompts the user for input, it would take this input and also print it to screen and ask the user for their input?

#

sorry not very familiar with JS. I am reading about it now.

nimble birch
#

what's good about django that you cant get from react vue or angular?

coral raven
#

Yes

#

You can get the value from the text input field and print it on the screen

#

@nimble birch React, Vue and Angular are front end frameworks, Django is a backend framework

gaunt marlin
#

@slim beacon if you just want for it to return the result from the game(which i believe that you wrote in python) you could write a RESTFUL api that handle input of user and return output in the html

wispy ice
#

Hello, i have a simple http web with lighttpd server, working fine. How can i implement HTML with python?
@wispy ice
Can you answer please

#

Load a file in the html web, click send, get the file in python, modify it and serve it back, or a "success" message
@wispy ice

#

Full msge 3 hours ago

whole sierra
#

im just trying to run a function (in a py file) with a html form in django

#

thats my path

#

here is the form, can anyone tell me why this isnt working?

#

I dont see where im passing an argument

rotund token
#

can anyone help me make a dropdown menu and style the menu?

twilit needle
#

so I have a rest api

#

and token auth

#

is it necessary that I need to store the user's token like from the client side?

#

I am using redux and so, can I store the token in redux?

#

pls ping me when help, thanks!

native tide
#

dont u have to use html to web develop?

slim beacon
#

@coral raven Okay so I looked into it and thought about it, but am getting stuck at one part. To understand that, I think I need to explain the text-based game I wrote.

The game is started, and the prints to terminal a string, then prompts for user input and the input is in stored in a variable. This variable is compared in a conditional, then runs the appropriate function. This new function prints something to terminal and then waits for user input before proceeding.

#

I think sending data to javascript (essentially sending the string I want to print) is easy enough, but sending the user input variable to the appropriate part in the code is more tricky.

#

I understand when writing the Javascript in the HTML, I would be declaring a function to be run with a button or something is clicked, and this function would then send user input written in a form or something to be sent to the corresponding function. The problem is, when the button is clicked, the data is being passed to the same function which is only sending this data to the same part in the python code.

#

How would I have the user input be sent to the appropriate function as the code progresses?

coral raven
#

You have the terminal program in your django part?

#

@slim beacon

slim beacon
#

@coral raven I don't. So in my text-based game program, I use print () for printing to terminal and input() for getting input from the user from terminal, but as well know, there isn't something related that connects the program to HTML. I would have to build something I think

#

But I'm trying to figure out how to go about it. This is my trouble.

coral raven
#

Have you thought of embedding a terminal inside yourwebpage

green snow
#

thats genius

coral raven
#

If it's a thing

#

It would work

green snow
#

idk

coral raven
#

One better idea would be to handle the input and print part with javaScript

crimson igloo
#

Any free hosting services out there? With which we can host as many websites we want ?

coral raven
#

Sadly no, they all have limits @crimson igloo

#

Netlify is good for static ones

green snow
#

wat would be best for dynamic ones?

#

(free)

crimson igloo
#

@coral raven I make websites in django

#

@green snow yep

green snow
#

ya same

coral raven
#

Herkoku has a free tier but it is limited to 1000hrs imo

#

Don't know the exact numbers

slim beacon
crimson igloo
#

Or any other way with which we can host our website ?

coral raven
#

Pythonxyz has 3 months free hosting

green snow
#

they require bank details?

coral raven
#

No

green snow
#

1000 hrs is fine

#

1 month

coral raven
#

@slim beacon how big is your program?

#

@green snow it renews every month

green snow
#

wait

slim beacon
#

1 main directory with about 10 files, and about 5 subdirectories with between 5-10 files in them

#

@coral raven

green snow
coral raven
#

@green snow there's a catch, the servers sleep if there is no activity and it takes some time to load for them to wake up

#

@slim beacon you can drop them in a replit link and point there in your website

green snow
#

i see

slim beacon
#

@coral raven i will look into that

#

looks promising

native tide
#

@twilit needle lol why use redux for tokens

#

store it as a cookie

vernal furnace
#

guysss

#

port

#

is not working

#

🥲

#
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = '110'
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.environ.get('HOST_EMAIL')
EMAIL_PASSWORD_USER = os.environ.get('HOST_PASSWORD')
#

I tried every number, I am trying to access a port for django reset email but its not working

coral raven
#

change '110' to 110

#

Also I don't think 110 is correct

#

587 for TSL port and 465 for SSL port

#

@vernal furnace

vernal furnace
#

it gives me this error

coral raven
#

Oh, have you enabled third party access

#

Something like that

#

In gmail settings?

vernal furnace
#

no

#

but heres what he says in the comment section

#

the tutor

#

Hey everyone. It seems like since this video was created, Linode has disabled the mail ports by default. So if you are using Linode then you just need to contact them to open the correct ports.

#

You can find more about that here:

#

I Checked it

#

but I couldn't understand anything

coral raven
#

Looks like linode blocked the known ports because of spam

#

What the comment says is to contact the support of linode to get access

vernal furnace
#

I tried to create an account but it asks me for my credit card and stuff

#

._.

coral raven
#

You plan to host it?

vernal furnace
#

no

coral raven
#

Linode is a hosting platform

vernal furnace
#

then how do I send an email to reset the password

#

Is there any other way?

coral raven
#

smtplib

vernal furnace
#

lemme look at the docs

#

I guess this should be done in the same way?

coral raven
#

Yes

#

Most stuff is the same

vernal furnace
#
No module named 'django.core.mail.backends.smtplib'
coral raven
inner drift
solar oracle
#

Hi channel, I am trying to improve the performance of a django webserver with memcached. Any good material to recommend me?

vocal berry
#

hi

native tide
#

hi

native monolith
sturdy pike
#

Hey does anyone know the steps after cloning a repository from github onto my desktop how to go about downloading all the project package requirements? Do I just create a virtual environment and then download each package one by one?

#

From the requirements.txt file? Thanks!

quick cargo
#

you can just do pip install -r requirements.txt

#

venv is recommended but not required

sturdy pike
#

@quick cargo Thank you brother. One more question if you don't mind. If the project is using slightly older versions of packages and django isn't it in my best interested to create a virtual enviroment then to download them all into there?

quick cargo
#

yeah

#

i personally use a seperate venv for each project

sturdy pike
#

True, okay cool thank you CF8 you're a god

native monolith
native tide
#

can someone help me with flask talisman security policies?

#

this is what i have right now in my app:

#
csp = {
    'default-src': [
        "*",
        "'unsafe-inline'"
    ]
}

talisman = Talisman(app, content_security_policy=csp)

#

but i have an image in b64 format that is not loaded on the website. i have this error:

#
Refused to load the image 'data:image/png;base64,iVBORw0KG....................AABJRU5ErkJggg==' because it violates the following Content Security Policy directive: "default-src * 'unsafe-inline'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.
#

what do i need to do to enable the image but also keep the website still as secure as possible?

verbal snow
#

I'm trying to connect to a db in django, and im getting this error django.db.utils.OperationalError: could not translate host name "('xxx.xxx.xxx.xxx'" to address: Unknown host could not translate host name ")" to address: Unknown host. Everything was working until I moved the ip to a config file

vale vault
#

does anyone know how to display a string as a markdown. I'm doing it for a blog.

#

flask

native tide
#

Yoo these react animations are hella crisp

quick cargo
#

if you spend the time to work on transitions properly you can make stuff look way more fluid

vale vault
#

does anyone have experience with the markdown library in python?

native tide
#

@quick cargo What should I improve for more fluidity?

#

I did just notice after starting a new animation there is a brief white background behind my component

#

So just changing that made an improvement

quick cargo
#

i wasnt knocking you

#

probably came of badly

native tide
#

I know you're not

quick cargo
#

the only blip i have

#

is when it reloads that side bar

#

it goes white then instantly dark again

#

which looks a lil messy

frozen python
#

Do you need to be good at styling to use python? I’m really running into.... I don’t like styling because of how vague it is. I like the concept of react hooks, but, it’s annoying with the run around you do to do one thing

native tide
#

Yeah, due to your comment I actually looked at things much more closer and noticed that.

quick cargo
#

would rather it stay dark and just slide the elements on it back in rather than the whole thing pop in and out

native tide
#

👍

#

I think I should change the way the blocks animate too.

#

Thanks for making me spot that 😉

native tide
#

And I should probably mix and match the animations, as I only have elements sliding in the sidebar, which probably gets repetitive when moving in/out screens

#

@frozen python No, it was aimed to CF8

#

You wouldn't need styling for python no, but for website making in general... it's good to have something solid

#

I also agree it's very vague

#

But I guess that's just due to how subjective it is

frozen python
native tide
#

I don't understand what you're asking me

frozen python
#

@native tide I meant “stays away” from styling the most

native tide
#

and... what do you mean by that

frozen python
#

@native tide , I don’t like styling, so what part of Django is more about functionality?

native tide
#

well styling is just on the frontend.

#

so you can focus on APIs

#

but you will always have to run into a html page or something similar

#

and "styling" your page doesn't mean it has to look spectacular, if it's functional its good.

quick cargo
#

if you're doing for a api type system FastAPI is probably the best for you

native tide
#

yeah I've heard good things about it

frozen python
solar oracle
#

you can try Vue too

native tide
#

you're always gonna run into frontend stuff anyway, there's no avoiding it

#

because how else will you consume your api endpoints?

digital hinge
#

hey all, prob something so simple but im trying to add another file to download on my website with flask, but i get the following error:

werkzeug.routing.BuildError: Could not build url for endpoint 'plot_csv'. Did you mean 'process' instead?\r

Here is the code:
https://bpa.st/T6JA

swift heron
#
setInterval(update_applications, 1000);
``` Is this a smart way of grabbing updated data from the backend? or should I run the update in the backend and send the data to the frontend?

I dont like how my terminal is being spammed with POST requests constantly
#

but with the backend method I dont know how to send data from the backend to a function in the frontend

#

and Nut that looks great! I really wish I had something like that for taking notes in my classes

#

well if anyone has a opinion feel free to @swift heron thanks!

topaz widget
swift heron
#

yeah I have been hearing about websockets is that maybe what your thinking of or is it something different?

topaz widget
#

I think websockets can do that, yeah.

#

Websockets is what I was thinking of, but it may not be the only way to do that.

#

You definitely don't want to be making AJAX calls every second if you can avoid it.

native tide
#

@swift heron if you're making API requests based on user input you can check whether the user is interacting with your site and make API requests based on that

swift heron
#

yeah definetly I only want it to run when the database actually changes, so having a schedule loop running on the backend every 5 or so seconds and if there is an actual change that needs to be updated on the frontend then run a function

native tide
#

What's your app?

swift heron
#

my app?

native tide
#

Your project

swift heron
#

oh right

topaz widget
#

What are you trying to do? I think is what nut is asking.

native tide
#

mhm

swift heron
#

basically I am running win32 grabbing all the applications and displays on my pc and creating a stream via ffmpeg I just want to send that data on a website.

#

I have all the data being stored in the django db

#

I just changed my backend to be doing the update

#

so I have something like this in the backend

scheduler = BackgroundScheduler()
scheduler.add_job(scanApps, 'interval', seconds=1)
scheduler.start()

This will update the database accordingly and if there is a change I would like to create a function telling the frontend to make a request or better yet send that data to the frontend

#

This is what my view look like currently

@method_decorator(csrf_exempt, name='dispatch')
class ComputerView(View):
    def get(self, request, *args, **kwargs):
        if request.GET == {}:
            context = {'title': 'Computer Stream', 'applications': Application.objects.all()}
            return render(request, 'pages/computer_view.html', context)

    def post(self, request, *args, **kwargs):
        post_data = request.POST

        if post_data.get('hwnd') is not None:
            hwnd = request.POST.get('hwnd')
            return HttpResponse(hwnd)
        elif post_data.get('update') == 'true':
            apps = Application.objects.all()
            app_data = ApplicationSerializer(apps, many=True)

            return JsonResponse(app_data.data, safe=False)

CSRF is off just for testing and learning but all I am able to do is front-back but I cant do back-front

topaz widget
#

What's the purpose of turning CSRF off for testing?

swift heron
#

none of this works with it on XD

topaz widget
#

Are you making cross-domain requests?

#

Do you know how to send a cookie with JavaScript?

#

If not, let me give you some copypasta

swift heron
#

you will have to forgive me I am new to django and the web dev scene I do not know that that is

#

Im guessing CSRF is some sort of security feature where it checks the browser cookie token or something?

#

I dont know a whole lot about this stuff but I could be wrong

topaz widget
#

That's correct. And when you send AJAX calls, you have to send the token.

#
'use strict';
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');
#

That's the bulk of the JavaScript you will need to send with write in for the request.

swift heron
#

Okay intresting, ill work on this as soon as I get the main functionality in. but im still not sure how to send data from the backend to the frontend without refreshing the page

topaz widget
#

Oh, okay, so you aren't event to AJAX calls, huh?

#

If that's the case, what are you doing with setInterval?

swift heron
#

I made this function when I was doing updates on the frontend

function update_applications() {
    $.ajax({
        url: 'http://127.0.0.1:8000/computer/',
        type: 'POST',
        data: {update: true},
        dataType: 'json',
        success: function (app_data) {
            //Remove Old list of windows
            $('#application_list').empty();

            // Response Received updating list
            $.each(app_data, function (index, app) {
                $("#application_list").append(
                    'BUNCH OF HTML'
                )
            });
        },
    });
}

But now that I am running an update loop in the backend I dont know how to call this function from the backend

#

SetInterval is what I was using to update the database from the frontend

#

I am now using ```python
scheduler = BackgroundScheduler()
scheduler.add_job(scanApps, 'interval', seconds=1)
scheduler.start()

#

to update the db and make it more efficent in the backend

topaz widget
#

But do you have some view on the backend sending data in response to this AJAX call without refreshing the page?

swift heron
#

All I have been able to do so far regarding ajax is click a button on the frontend and have the server return values regarding that button push, I have not been able to tell the backend to run ajax in the frontend

topaz widget
#

The backend wouldn't run ajax, it would just return values.

swift heron
#

so how do I send data to the frontend from the backend? or do I have ajax making constant post request to keep grabbing that data?

#

Im confused as to tell my backend whent he db updates to say hey run this jscript function and here is the data

topaz widget
#

Well, websockets would be one way, though I'm not sure if it's the right one for your application.

#

Or, as Nut said, if some user action triggered the update, then you could just fake it with the AJAX method you already seem to know how to use.

swift heron
#

yeah it wouldnt be a user action sadly I will take a look at websockets then good to learn more 👍

topaz widget
#

So let me try to understand this: are you trying to do live streaming of a device's display?

swift heron
#

yeah pretty much

topaz widget
#

I think there's actually a different protocol if you want to do video streaming, which is what it sounds like you want to do.

#

Unless you're saying you want to remotely control some machine.

swift heron
#

what would that be? right now using ffmpeg it creates a video file that I am storing in my projects file structure, im guessing I would have to somehow store that in the db?

topaz widget
#

I don't remember what the protocol is, but it's not ffmpeg, and it's not websockets or http.

#

It's a different protocol. I'd just google "video streaming protocol" or something like that.

#

I think ffmpeg is a codec IIRC

swift heron
#

alright will do thanks for letting me know, that will be my next step once I actually get this done with optimized updates

topaz widget
#

By the way, I don't think you need that cookie stuff I just pasted. Maybe with JQuery, but I was going to check on that, as fetch doesn't seem to require it.

swift heron
#

okay intresting

topaz widget
#

Yeah, so, apparently it's not required when using fetch but is when using XMLHttpRequest (and you need to set the X-CSRFToken header field, too, (to the cookie obtained from that function) when using XMLHttpRequest).

#

fetch must get that automatically.

#

Perhaps JQuery uses XMLHttpRequest under the hood, which would explain why it doesn't work with a CSRF token unless you set the header field appropriately when sending the AJAX call.

#

~~~~~~~~~~~~~~~~~~~~~
Anyone here well-versed in JavasScript animations know why setTimeout works better on some devices, while requestAnimationFrame works better on others?
requestAnimationFrame seems to work better on an old iPad of mine, while my laptop (running both Ubuntu and Windows 10) and Android smartphone seem to work better with setTimeout.

frozen python
rustic pebble
#

React

#

React is a better framework imo

#

and it has way better business appeal

native tide
#

^^

topaz widget
topaz widget
# frozen python Between react and vue, which is better to focus on? I started with Vue, but swit...

React is more widely used from what I understand. Vue has been gaining popularity more quickly recently compared to React, though. I have used neither framework sufficiently to make a comprehensive first-hand evaluation of either, but I have used Vue for some things. I'm not sure what Kiwi thinks is better about React intrinsically, but I would be interested to know its strong points compared to Vue.

frozen python
#

@topaz widget @rustic pebble ok, but how about using Django or python with it? Is that a typical combination?

native monolith
topaz widget
#

Django REST Framework (Python) on the backend, Vue or React on the front end.

frozen python
#

@topaz widget I’ve started to use Django REST Framework, I like it. But when is it better over just Django? ... is pandas/Numpy, ect.... ever implemented for sales analysis?

topaz widget
#

Django REST is for when you have a front-end heavy (single-page) application I'm pretty sure and you're mostly just making API calls to the backend. There could be other use cases for it.

vestal hound
#

you just want to expose an API

topaz widget
#

^ @frozen python

solemn stream
#

Is it bad to have query sets as class methods within your models classes?

indigo kettle
#

I don't think it's bad, something you can do though is create a custom model manager with your own get_queryset method

#

if it's a very common queryset you want access to

gaunt marlin
#

it's not bad, it's useful because you can use it anywhere when you call an instance of that model

indigo kettle
#

here's a snippet

class PublishedManager(models.Manager):
    def get_queryset(self):
        return super(PublishedManager,  
                     self).get_queryset()\
                          .filter(status='published')

class Post(models.Model):
    # ...
    objects = models.Manager() # The default manager.
    published = PublishedManager() # Our custom manager.

#

now you can call Post.published.all() instead of Post.objects.all()

frozen python
#

@topaz widget @vestal hound I’ve looked up some stocks and plotted acouple, I can see allot of possibilities with that, but, how long does Numpy, pandas, matplot, Scipy, ect.... take to become “hirable”?

rustic pebble
#

I have made a custom boilerplate framework in Flask/Redis/Celery that works perfectly with React though

frozen python
#

@rustic pebble so mainly use python and node?

rustic pebble
#

It really depends on the project I am working on

#

Most of my projects are really based on a different client and server

#

So that’s why I use flask

frozen python
rustic pebble
#

Django is too bloated imo

#

I just build everything myself

topaz widget
frozen python
#

@topaz widget I’m familiar with React, Vue, Django, Styled-Components. some Python. Then Vuetify, Bootstrap, Material-UI and SASS

#

@topaz widget then I’m getting the hang of Numpy and Pandas

rustic pebble
#

If you want to become hireable just learn a stack

#

MERN is really good atm

#

Mongo-Express-React-Node

frozen python
#

@rustic pebble ok, I’ve used Sqlite a bit

topaz widget
#

"familiar with" doesn't mean much. I'd have a portfolio that exemplifies your abilities with those technologies.

frozen python
#

@rustic pebble isnt Express for multiple JS files?

rustic pebble
#

Express is a NodeJS framework

#

Its basically flask for node

frozen python
#

@rustic pebble ok, I haven’t really focused on node. But javascript. It’s tough to get the hang of HS because everyone does a “example, console.log” but don’t truly implement using what there teaching

#

JS

rustic pebble
topaz widget
#

There's plenty of detailed JavaScript reading material out there, and videos.

rustic pebble
#

For like 15-20$/mo you can get really high quality content

topaz widget
#

You probably just haven't really learned much JavaScript yet if everything you're seeing is "console.log" examples.

frozen python
#

Ive been using SkillShare. I try and find true examples, but they don’t truly use what they make. I’ve been watching: Traversy Media, Dev Ed, Kalob Taullen, Net Ninja.

rustic pebble
#

Most frontend js frameworks heavily rely on objects and advanced javascript concepts so you should first get good with javascript in general and then start learning these

#

React has a really steep learning curve

#

If you are a rookie in js you won't be able to learn

frozen python
#

@rustic pebble I actually like react allot. I’ve been making objects, functions and using them right. I do catch onto Python and Django better tho

rustic pebble
#

Python backend frameworks are entirely different from js frontend frameworks

#

Django and flask are designed to give a multi-page experience whereas most frontend frameworks are SPA (Single-Page-Application) meaning that all you need is a restapi to make requests to and then control what the user sees in the frontend

#

Which is why express it rly good

frozen python
#

@rustic pebble python and Django are more strait forward. You maybe have 3-4 steps vs 5-7 with JavaScript

rustic pebble
#

Not really

#

Django especially

#

That shit is dead bloated

#

Flask mostly uses extensions that help you not require subclassing and editing

#

I have mostly created my own extensions for authentication, tokenization and more

#

For example Flask's JWT extension is not as secure as what authlib offers

frozen python
#

@rustic pebble like with CRUD with Django, its allot more simpler. React, it’s different syntax with code and what you include or render when and from different JS pages.

rustic pebble
#

React is frontend

#

It should not be able to directly edit anything

frozen python
#

@rustic pebble I know

rustic pebble
#

Everything that you do in react is visible by the client user

#

Thus being a huge security issue

frozen python
#

@rustic pebble but the steps to do one thing seem allot more then with Django

rustic pebble
#

I am not sure why you compare django which is a full stack framework meaning it can both frontend and backend with react

#

And as far as react is concerned it is faster, better and has bigger market application

#

All you need is a backend framework that can create a restapi

frozen python
#

@rustic pebble should I use Django with react? Or what would you prefer to use react with?

#

@rustic pebble I’m liking Django REST framework

rustic pebble
#

Best atm is the MERN stack which I also mentioned above: MongoDB for NoSQL database which is almost the same as json, ExpressJS for express backend building, React for a dynamic and modular frontend and NodeJS as the base

#

Throw that all in a docker container and boom

#

you got yourself a fully scalable web app

#

I am not sure why you would use Django for RestAPI

#

lel

#

for example this is a backend for a website I built

#

These are all the views

frozen python
#

@rustic pebble well, Django REST Framework is good for a API?

rustic pebble
#

Views are routes

#

Nah

#

Dude, look how easy everything is with in flask

#

i.e. this is a url shortener

#
from flask import Blueprint, redirect, request
from services import User, Product
import os, json

utilities = Blueprint('utilities', __name__)

@utilities.route('/<shortened_url>')
def url_shortener(shortened_url=None):
    if not shortened_url:
        return redirect('/')
    prod = Product.query.filter_by(shortened_url=f'{os.getenv("APP_URL")}/{shortened_url}').first()
    if prod:
        return redirect(prod.url)
    else:
        return redirect('/error')
#

This gets the shortened_url param from the request url

#

It makes a really simple database request with an ORM

frozen python
#

@rustic pebble how often is Flask used over Django?

rustic pebble
#

I have no idea

frozen python
#

@rustic pebble I’ve been using Django because it was said it’s asked for more

rustic pebble
#

It depends, I am aware of everything that needs to be done to build a secure and stable web app

#

You are not usually asked a specific framework

#

I mean

#

If a client has an idea and they prefer django but you use flask

#

You can just explain why you are going to use flask

#

for example

#

This is an authentication class

#

I use everytime

frozen python
#

@rustic pebble ok, I’ve been liking python/Django because the syntax seems better than JS. Again, I’ve had a tough time with JS, but react helped allot.

rustic pebble
#

This basically is a complete discord login handler, cookie handler

#

Python's syntax is different from javascript obviously

frozen python
#

@rustic pebble with Django, I got the hang of creating products, and showing them on the {%%} templates.

rustic pebble
#

That's called server-side rendering

#

when u use {}

frozen python
#

@rustic pebble vs react, it seems like you have allot more steps and it didn’t flow as easy as Django

rustic pebble
#

Again

#

React

#

is frontend

#

Django is full stack

#

That's entirely different

#

React has no server side rendering

#

it draws data from api endpoints and then renders views live

#

Thats why you never need to refresh

frozen python
#

@rustic pebble I know 👍 I’m referring the “flow”, it seems more straitforward with Django va the steps to do one thing with React or Vue

rustic pebble
#

React is hard don't ever think otherwise

#

It is not a beginner framework and requires high javascript knowledge

#

Django is not a beginner framework as well but it can be easily learnt

frozen python
#

@rustic pebble Vue seems harder, it has its own syntax that kinda “hides” and you don’t always realize that’s connected to what at times

rustic pebble
#

Vue is easier

#

lel

#

Vue is more straightforward

frozen python
#

@rustic pebble I can see that now, but, the custom syntax is annoying at times. A CRUD with Vue or React has allot more steps vs Django (I know what you mean by backend, I’m just talking about flow/steps)

rustic pebble
#

I don't know where you heard the term CRUD but it cannot be used with react or vue or anything in regards of frontend

#

You need to have corresponding backend routes that do that job

frozen python
#

@rustic pebble Creat Update Delete

#

@rustic pebble that’s what’s referrenced allot

rustic pebble
#

I am not sure why you want a user to have direct ability to edit your database through frontend

#

you need backend for that

#

a rest api

#

or graphql

frozen python
#

@rustic pebble a “to do app” is what that’s always used as a example...... it’s annoying

empty dagger
#

Ищу python разработчика писать в лс

frozen python
#

@rustic pebble what would you recommend for a project to learn what you’ve referred to learn?

rustic pebble
#

Not sure tbh

#

I have long past that point

frozen python
#

@rustic pebble I’m stuck right now because.... styling is so vague it makes me sick at times because of the different hindering classes that effect different things. I like how JS is, but it’s annoying with the wrap around a you define, re plug in, or use somewhere else with JS. Python seems more strait forward and Django, but, it seems like it’s mainly ML or DS, that need college

rustic pebble
#

Python is the second best language for everything you can think of

frozen python
#

@rustic pebble I’ve been focusing on python because of the better “direct” need for things that it’s good for. To move away from styling that’s so vague with front end

rustic pebble
#

Well you have a really long way to go with web dev

#

Building complex applications from 0 knowledge cannot be done within a month lel

frozen python
#

@rustic pebble I know react, just not as good with API

rustic pebble
#

there is no possible way that you know react

#

If you have no idea on how to build backend

frozen python
#

@rustic pebble better than Vue

rustic pebble
#

better than vue doesn't mean you know how to build anything lmao

frozen python
#

@rustic pebble I’ve been using Django for backend, I like it

tacit canopy
#

Hey anyone available to help for socket programming?

rustic pebble
#

Then go ahead an use it

#

@tacit canopy you can probably ask in #networks

tacit canopy
#

ive already asked just trying out here as I havent received a repsonse there

#

thanks 🙂

rustic pebble
#

ah alr

#

Then whats ur question? @tacit canopy

tacit canopy
#

running cgi scripts

#

''' python3

rustic pebble
#

cgi or cli

tacit canopy
#

cgi

rustic pebble
#

Ah yes

#

CGI

#

I got stuck for a sec lmao

tacit canopy
#

haha all good

#
if os.path.exists(file_path):
                        read_end, write_end = os.pipe()
                        pid = os.fork()
                        print("yes")
                        if pid != 0:
                            os.close(write_end)
                            os.wait()
                            read_opened = os.fdopen(read_end)
                            inp = read_opened.read()
                            # os.close(r)
                            print(inp)
                            x = file_open()
                            if "Content-Type" not in inp:
                                x+= "Content-Type:" + os.environ["HTTP_ACCEPT"] + "\n\n"
                            else:
                                x+= inp

                            clientsocket.send(x.encode())
                            clientsocket.close()
                            print("yes1")
                        else:
                            print("yes2")

                            os.close(read_end)
                            os.dup2(write_end, 1)
                            os.execv("/bin/python3", ["/bin/python3", "." + request[1]])
                            write_opened = os.fdopen(write_end, 'w')
#

thats my code for running cgi scripts if found in the http request

#

but it isnt working for some reason and cant figure out why

rustic pebble
#

I am not sure I can help you, my knowledge in sockets is not rly good

#

What have you tried so far?

tacit canopy
#

its printing yes for os.path.exists that means the file exists but isnt running it

#

ive tried the above so far

rustic pebble
#

So I am guessing that if never runs?

tacit canopy
#

yup

rustic pebble
#

Have you tried print the pid

#

?

tacit canopy
#

ill try that

rustic pebble
#

try it and come back to me

tacit canopy
#

7761
0

#

these are the pid's it is printing right after os.fork()

rustic pebble
#

I am not sure why you are using os.fork()

#

7761 is the PID of the child process spawned by fork() and 0 is the pid of the forked process

tacit canopy
#

it is required to run cgi processes

rustic pebble
#

Hmm

#

Give me a second to think

#

Can you run this:

if os.path.exists(file_path):
                        read_end, write_end = os.pipe()
                        pid = os.fork()
                        print("yes")
                        if pid is not 0:
                            os.close(write_end)
                            os.wait()
                            read_opened = os.fdopen(read_end)
                            inp = read_opened.read()
                            # os.close(r)
                            print(inp)
                            x = file_open()
                            if "Content-Type" not in inp:
                                x+= "Content-Type:" + os.environ["HTTP_ACCEPT"] + "\n\n"
                            else:
                                x+= inp

                            clientsocket.send(x.encode())
                            clientsocket.close()
                            print("yes1")
                        else:
                            print("yes2")

                            os.close(read_end)
                            os.dup2(write_end, 1)
                            os.execv("/bin/python3", ["/bin/python3", "." + request[1]])
                            write_opened = os.fdopen(write_end, 'w')
#

@tacit canopy

tacit canopy
#

ok

#

not working yet

digital hinge
#

4:09 PM <IronHEDGE> hi all, im unable to get both of these sites working at once, any tips: https://bpa.st/E5HQ running WSGI with Apache on Windows

#

The site that is commented out is the site I wish to use at the same time. Any ideas?

twilit needle
#

it also looks like a genius idea because I dont know where I would be needing these state variables

torpid pecan
#

What is the best way to view a sqlite3 file?

gaunt marlin
native tide
#

@twilit needle why not store it as a cookie? That's standard practice

left wadi
#

Hi, can anyone suggest which course to take on udemy for learning django from scratch.???? I've good knowledge of python as of now.

marsh canyon
#

I'm not sure about udemy, but youtube has pretty good ones
There is also a django tutorial on their official website which is good enough to start with.
I mostly learnt django by doing a lot of projects, learning when I need to

gaunt marlin
mystic wyvern
#

guys way css doesn't loaded in django

gaunt marlin
#

did you set up the static settings correctly?

mystic wyvern
#

yep

#

it was working but suddenly everything gone

warm ridge
#

hi, can i predefine django models with predefined content as foreign keys? like a choices.
i.e: in Table User
role = models.ForeignKey(CHOICES='OTHER TABLE with roles'
....
Table Role
| id | User_role|
| 1 | Admin |

mystic wyvern
native root
#

use limit_choices_to

warm ridge
gaunt marlin
#

@mystic wyvern it's STATICFILES_DIRS , not STATICFILES_DIRE

twilit needle
#

can somebody please help me here? thanks!

#

pls ping me when help, thanks!

#

the question is too long to post here with the code included, thats why

digital hinge
#

hi all, i need some help i have a flask app, that runs with Apache _the wsgi module. However, when i try use

 
import cv2 
#

the website hangs

#

import cv2 works fine in python tho, its only when it loads with wsgi and apache

#

i cannot find any errors that can povide me with what is going on and why it will not load, if i remote import cv2 i get my hello world test... :S

#

okay runs fine on my machine with python 3.9

#

im guessing cv2 errors out with python 3.7?

native monolith
#

which is better? 😄

digital hinge
#

11:39 PM <IronHEDGE> Hi all, I’m a little stumped. I have a web app I’m launching using Apache with the mod_wsgi however, this is running on Server 2016 with python 3.7 when I use ‘import cv’ the website hangs, there are no errors and I don’t know what the cause would be? It’s using opencv version 4.4.0 with my other machine python 3.9 it works fine with Apache and wsgi

#

App works fine outside of wsgi tho

cosmic aspen
#

Hello , I'm working with django rn , but i have this weird problem "NoReverseMatch at /new_post/" , my get_absolute_url() works perfectly with old posts but for new posts when i use the shell it gives me this Exception value :
"Reverse for 'article_detail' with arguments '('2', '3')' not found. 1 pattern(s) tried: ['article/(?P<pk>[0-9]+)/$']"

#

the weird thing is arguments '('2','3')' is for a post with post.id = 23

fading crag
#

Hey so I have a question and I'm not sure if it's Python related but it's related to web development for sure. In your opinions what's the best way to approach the launch of a product for example graphics cards or computer processors. Do you refresh at the minute, or what's the best way to go about it strategically through the website

#

Please @ me with responses, sorry if it's not Python related

native monolith
#

@fading crag you could checkout django :d

#

im not an expert, but it is good framework

fading crag
#

Alrighty, trying to figure out how exactly I should go about the launch of something i.e. refreshing at the minute of release but then the website crashing or is it simply just down to luck

native tide
#

@cosmic aspen Could you post some of your code?

cosmic aspen
#

`from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse,reverse_lazy
from datetime import datetime,timezone
from ckeditor.fields import RichTextField

class Post(models.Model):
title = models.CharField(max_length=200)
title_tag = models.CharField(max_length=200, default='myblog')
body = RichTextField(blank=True,null=True)
header_image = models.ImageField(blank=True, null=True, upload_to='images/')
author = models.ForeignKey(User, on_delete=models.CASCADE)
pub_date = models.DateTimeField(auto_now_add=True)
category = models.CharField(max_length=200)
likes = models.ManyToManyField(User,related_name='blog_posts')
snippet = models.TextField()

def likes_count(self):
    return self.likes.count()
def __str__(self):
    return self.title + ' | ' + str(self.author)
def get_absolute_url(self):
    return reverse_lazy('article_detail',args=(str(self.id)))
`

that is the models.py

this is urls.py:

urlpatterns = [ path('', HomeView.as_view(), name = 'home'), path('article/<int:pk>/', ArticleView.as_view(), name= 'article_detail'), path('new_post/',AddPostView.as_view(), name = 'new_post'), path('article/<int:pk>/edit/',UpdatePostView.as_view(), name='update_post'), ]

#

the weird part is really args = (str(self.id))
for exemple : it returns ('2','3') for a post with id = 23 🤨

granite pasture
#

where to start web development from

  • which module is used in it
#

ok django

cosmic aspen
granite pasture
#

umm ok

#

interested

#

in python

cosmic aspen
#

yeah Django or Flask , either are good

granite pasture
#

html for an insight?

#

or is it used?

cosmic aspen
#

it is the language of web so yeah Basic

granite pasture
#

umm ok

#

django, flask which is easier?

cosmic aspen
#

same difficulty i guess , depends on the person really , i personally find Django way more fun , but Flask is really solid too

granite pasture
#

umm ok first i need to learn html

cosmic aspen
#

yeah

granite pasture
#

Is CSS related to C?

cosmic aspen
#

no

granite pasture
#

ok

cosmic aspen
#

related to html and fairly easy

granite pasture
#

i thought they were upgradation lol
c
c++
css

#

😅

cosmic aspen
#

nah

granite pasture
#

thx

cosmic aspen
#

there is another way with html->CSS->Javascript then back-end with node.js but it really depends on your love for Javascript

#

i personally love Python but Node.js with Express is really fun

granite pasture
#

i didn't use js yet

#

i only used python for bot

cosmic aspen
#

fair enough

#

yeah if i'm in your shoes i will choose Python (django , Flask)

granite pasture
#

ok

#

i only made a 400 line code for my bot atm lol

cosmic aspen
#

all python modules have the same patern really so either you wrote bots or anything else , Python is Python

granite pasture
#

pithink with sqlite pithink

#

umm

#

ok

#

do u know module for security as well?

#

i know this is not the channel but

#

...

cosmic aspen
#

what security ??

granite pasture
#

umm all i know atm is the term security

#

like network

cosmic aspen
#

ah network securityyou mean ??

granite pasture
#

||opposite of hacking one||

cosmic aspen
#

Security and Hacking are in a way the same thing

granite pasture
#

o

#

lol

#

if u can help ig tell me in dn

#

dm*

#

oof so long answer lemon_eyes

cosmic aspen
#

i really don't know , sorry

granite pasture
#

Np pithink
it tooks u so long to type that thinkmon

cosmic aspen
#

i don't want to give any wrong info really

granite pasture
#

umm ok

whole sierra
#

does anyone know of a way to update a django models without restarted the server?

granite pasture
#

tysm

cosmic aspen
#

no problem

#

the thing is IT and networking are really something else , and programming is a very advanced topic in IT , so ... simply it's hard to recommend any modules i didn't use personally

native tide
#

@cosmic aspen how'd you compare django vs express? I'm thinking about learning express just due to learning react and I've heard that's the go-to for react applications

cosmic aspen
native tide
#

Great, I'll pick it up for a future project 🙂

cosmic aspen
#

if i'm to compare it with django i will say it's more basic than Django , like you may know django is really strict about the way you need to handle things , which makes Express for me more free but a bit more work so Big Projects are not the best for Express

native tide
#

Yeah, I used to use Flask and I disliked the "free-ness" of it compared to django where there's already prebuilt models etc which take out a lot of development time.

#

But the more you know the better 🤷‍♂️

cosmic aspen
#

yeah , you need to be very careful it's annoying

#

and Django is really straight forward , even errors are super clear

native tide
#

yeah, plus the docs are all in one

#

while the docs for flask libraries are scattered all over

cosmic aspen
#

yeah , weird to have a Web framework with a weird looking website xD

digital hinge
#

Okay, solved 1 part of my problem, import cv2 will only work if WSGIApplicationGroup is set to %{GLOBAL} my question is, how do you setup 2 vhosts to use their own environments (and the location) with Apache wsgi on windows? It doesn’t recondnise the daemon for Windows :/ here is my attempt, second site is commented out cause they don’t play nicely together. https://bpa.st/E5HQ

slim beacon
#

I asked this before, and I got some advice which I studied on, but I am still stuck at one place.

Essentially what I am trying to do is run a python script text-based game, which at points prints to screen and request user input, on a HTML page using JavaScript.

I understand I can use RPC or AJAX for having the JS do a remote call to the python file and run it, and when the python file is printing to screen or requesting input, this can be sent back through the response, but how would the python file wait at that point in the code waiting for further input from the JS side? This isn't possible right? Since any new requests sent from the JS side will not be able to go back to the point where the program is waiting for input.

#

Essentially, how would I get this continuous back and forth between the JS side and the python file using either RPC, AJAX, or something else?

native tide
#

hey guys, i'm learning Flask from corey schafer yt

#

I heard him say "environment variables" many times but I feel like I've probably missed the part where he explains it
I tried googling it but didn't understand anything

#

can someone explain to me what are environment variables?

#

@slim beacon You could setup an API and return responses to the frontend which could specify whether your process is "ongoing" or complete, and on every API request you could get this status by having a model for whatever your doing, which I don't really understand.

shrewd sage
#

Hi, I'm creating a site with a use of Python. I'd like to know how to connect HTML and Python. I need to add some conditions to my page, but can't do it. I simply don't know how...
May anyone help me?

noble star
#

You want to display html on a screen?

snow sierra
shrewd sage
native tide
#

@shrewd sage yeah best to watch a tutorial for that

gusty hedge
hybrid bobcat
#

if someone gets my ip address, can they hack my system when I run docker containers on localhost?

gusty hedge
hybrid bobcat
#

Oh ok thx for the reply, I thought this way because I remember reading a post someone said that localhost is not necessarily running locally and can be accessed if someone have access to my local ip

#

And read about another post saying docker has security issues and stuff

#

So as long as someone don’t have acccess to my network, then no?

gusty hedge
#

it's hard to find systems without security issues 😅

hybrid bobcat
#

Ah I see

#

Btw is there a way to spot vulnerability of my application? Like any software?

gusty hedge
#

if your container doesn't need network you can disable networking for it

hybrid bobcat
gusty hedge
hybrid bobcat
#

Ok thank you

gusty hedge
hybrid bobcat
#

Thx!

noble star
#

@shrewd sage sure

sterile oxide
#

i'm new to webscraping, and i'm working with socketio.
i tried using my browser's devtools to copy the sent packet, but i can't understand it. what's that leading 42?

upper heart
#

Is it ok to have a foreign key in custom user model in Django?

native monolith
#

~~

{% if rate_error is defined %}
    {% block header %}
        <style>
            .navbar {
            display: none;
            }

        </style>
        True: '{{ rate_error }}'
    {% endblock %}
{% endif %}

this drives me mad, it is always true ffs 😕~~

#

~~

    if er:
        print(er)
        return render_template("clocks.html", rate_error=er)
    print("No error")
    return render_template("clocks.html")

~~

#

output string on webpage True: ''

#

how is possible

#

I tried many things, checking legnth, size, if its defines if its none

native monolith
#

Solved

hybrid bobcat
#

ok so I'm using docker with django, gunicorn and nginx. I have created a Dockerfile and a docker-compose.yml file for production. Now everything worked fine on the last second, and now everything doesnt now.
When I ran ```bash
docker-compose -f docker-compose.prod.yml exec web python manage.py migrate --noinput

which executes the docker-compose prod file and executes migrate, it logs and error of the syntax error in one of my django urls.py file, I went fix it, it still logs the same error, I even tried deleting the whole file and it still logs the same syntax error for the same file. Which I assume is because Django is not detecting any of my changes anymore and I have no idea why. 
Does anyone have a hint?
#

I can show my Dockerfile, docker-compose.prod.yml file, or my nginx configs if anyone wanna help.

#

The traceback is from the urls.py file in the main app of the project. It does not have a migrations folder and I'm not quite sure whether that's how it was before or it got deleted somehow and causes the problem.

#

OK NEVER PROBLEM SOLVED

#

It just magically works now and I have no idea how

native tide
#

Hey guys, is there anyone who has used APIFY before? Do they have a google API by any chance? I don't want to sign up yet, I need to save my free trial for when I have to turn in my project for uni ..

#

nvm, I just found they do

hybrid bobcat
native tide
unique dawn
#

I have a Flask App with an route in which I print the value of a global variable, which also gets modified in a seperate thread during runtime, but flask seems to use an old value of the variable. Do the variables in a route only get set when starting the script?

native tide
naive oar
#

Hi, I'm having trouble filtering the regroup template tag on Django, I was able to get it to group by image but now I want to display all the names associated with the image, here's my template tag and model.

twilit needle
#

I am using the rest framework

#

in django

#

so I am making a post request from a reactjs cmponent like this

function LoginForm () {
    const dispatch = useDispatch();
    const { register, handleSubmit, setError, errors } = useForm();
    const onSubmit = data => {
    axios.post('/api/login/', data)
        .then(response =>{
            dispatch({type: "REFRESH_AUTH", payload: {user: response.data.user, token: response.data.token}});
            <Redirect to='/app/' />
        })
#

this is my api view

#
@api_view(["POST"])
@permission_classes((AllowAny,))
def login(request):
    data = request.data
    login_form = LoginForm(data)
    if login_form.is_valid():
        user = authenticate(password=data['password'], username=data['email'])
        if user:
            login(request, user)
            token, _ = Token.objects.get_or_create(user=user)
            return Response({'token': token.key, 'user': UserSerializer(user).data}, status=HTTP_200_OK)
        login_form.add_error('password', "Password doesn't match email")
    return Response({'error': login_form.errors}, status=HTTP_400_BAD_REQUEST)```
#

however, after the post request, I get this error:

AssertionError: The `request` argument must be an instance of `django.http.HttpRequest`, not `rest_framework.request.Request`.
#

How can I resolve this error? pls ping me when help, thanks!

vestal hound
gaunt marlin
vestal hound
gaunt marlin
#

i'm not sure as the latest version of drf i can use request.data normally. We don't know which version of django and DRF he using

vestal hound
#

because that's not where the problem is

#

that SO question is specifically about messages.

#

the problem is with one specific line

#

but I would prefer @twilit needle find it for themselves

#

with a bit of help

gaunt marlin
#

you mean the self right?

#

yeah i google that error and it just results in not related error i see why now

vestal hound
#

what self do you mean

gaunt marlin
#

he just using the wrong request of the DRF, should be login(self, request) instead

vestal hound
#

it's a function-based view

gaunt marlin
#

oh right function-based view doesn't need an instance, i forgot

twilit needle
#

okay

#

Any way I can make something like a parent function for these two react functions and make them inherit from it?

#

I am using react-hook-form for the forms

twilit needle
vestal hound
#

don't mix Django views/forms with DRF views/serializers

twilit needle
#

why not

#

its easier

vestal hound
old yew
#

hello

#

I just got started porting over a very simple Tkinter app into Flask, and I can definitely see why it's getting so popular

#

but I do have a question that I feel is kinda dumb; is there a way to turn it into a completely localhost app?

twilit needle
#

I have a doubt pls help me

old yew
#

Since my application deals with sensitive data, I need the application to run either completely local or only for the computers connected to their vpn/proxy

#

but I have very little experience with python webdev v.v

#

any help is appreciated

twilit needle
#
const UserReducer = (state=JSON.parse(localStorage.getItem('user')), action) => {
    switch(action.type){
        default:
            return state;
        case "REFRESH_AUTH":
            return state = action.payload.user;
        case "CLEAR_AUTH":
            return state = null;

    }
}```
this is my react-redux reducer
So, there is an item in localStorage which is json.stringified

to return the state of the reducer I JSON.parse the item.
The state is subscribed to that localStorage item

Now, when case "REFRESH_AUTH" comes, I want to update the state and thereby the localStorage item.

I have to do it by doing 
```py
 case "REFRESH_AUTH":
            return state = JSON.stringify(action.payload.user);

to store the user object. But, I always want the localStorage to store stringified value and the reducer should always return a parsed value

#

how can I do this? Pls ping me when help

#
const UserReducer = (state=JSON.parse(localStorage.getItem('user')), action) => {
    switch(action.type){
        default:
            return state;
        case "REFRESH_AUTH":
            state = JSON.stringify(action.payload.user);
            return JSON.parse(state);
        case "CLEAR_AUTH":
            return state = null;

    }
}```
#

I tried doing this

#

but got this error

#
Uncaught SyntaxError: Unexpected token c in JSON at position 1
    at JSON.parse (<anonymous>)
    at token (authReducers.js:15)
    at redux.js:367
    at Array.forEach (<anonymous>)
    at redux.js:365
    at s (redux.js:430)
    at Module.78 (index.js:5)
    at a ((index):1)
    at t ((index):1)
    at Array.r [as push] ((index):1)
stable kite
twilit needle
#

okay

#

one sec

#
const UserReducer = (state=localStorage.getItem('user'), action) => {
    switch(action.type){
        default:
            return state;
        case "REFRESH_AUTH":
            return state = JSON.stringify(action.payload.user);
        case "CLEAR_AUTH":
            return state = null;

    }
}
#

I think I messed it

#

can u pls help me from scratch

#

to store a user and retrieve it with redux

stable kite
#

@twilit needle Sure i am at class i can help you in an hour

twilit needle
#

is django rest framework token authentication related to JWT?

stable kite
twilit needle
#

pls help me, thanks!

neat hearth
#

hi all i am new in here, have some one eve created project with django channels?

elder sand
#

hey,
how can i make an annimation in my website using html&css

green snow
#

this is a really good documentation @elder sand

elder sand
#

ok thx

tiny warren
#

по русски говорит кто-то?

#

аууу

green snow
#

нет

stable kite
#

@twilit needle what's the problem?

vivid canopy
native tide
#

how can I change the content in the body part without needing to rerender the sidebar because that always remains constant?

native tide
#

yeah but how?

#
{% extends "main/base.html" %}

{% block content %}
<h1>This is Universities Section</h1>

<script>
  const linkColor = document.querySelector(".nav__link-dashboard");
  linkColor.classList.add("active");
</script>

{% endblock content %}

``` Is it good way to pass javascript into base template? it's causing some error.
#

makes some conflicts with existing JS script on base.html

twilit needle
#

I want to store objects and retrieve it with redux

#
const UserReducer = (state, action) => {
    switch(action.type){
        default:
            return state;
        case "REFRESH_AUTH":
            return state = action.payload.user;
        case "CLEAR_AUTH":
            return state = null;

    }
}
#

in this reducer

#

so I want to store the stringified version of the object in localStorage

#

and access it using reducer to return the parsed value

#

the object is action.payload.user

#

@stable kite

stable kite
#

@twilit needle have you defined action creater

twilit needle
#

whats that

#

oh yeah I did

#

@stable kite

stable kite
#

can you show the code of action creater

twilit needle
#
const refresh_auth = (payload) => {
    return {
        type: 'REFRESH_AUTH',
        payload: payload
    };
}

const clear_auth = () => {
    return {type: 'CLEAR_AUTH'};
}```
stable kite
#

@twilit needle the state is immutable so you cant directly change it

twilit needle
#

what

#

then how can I do it?

#


const UserReducer = (state=localStorage.getItem('user'), action) => {
    console.log(state);
    switch(action.type){
        default:
            return state;
        case "REFRESH_AUTH":
            state = JSON.stringify(action.payload.user);
        case "CLEAR_AUTH":
            return state = null;

    }
}

const tokenReducer = (state=JSON.parse(localStorage.getItem('token')), action) => {
    switch(action.type){
        default:
            return state;
        case "REFRESH_AUTH":
            /* Set token if not exists or update the existing token */
            return state = action.payload.token;
        case "CLEAR_AUTH":
            return state = null;
    }
}

export {UserReducer, tokenReducer};
#

my whole reducers

stable kite
twilit needle
#

thats okay

stable kite
twilit needle
#

still I can update the values of state variable

stable kite
#

but that should be done

twilit needle
#

?

stable kite
#

than whats the problem with your code?

twilit needle
#

well

#

I want to store the user as stringify in localStorage

#

but.. when I return the value as a parsed value in one of the cases..

#

the localStorage value changes to a parsed value

#

because the reducer is subscribed to it

#
const pixStore = createStore(
combinedReducers, /* preloadedState, */
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

pixStore.subscribe(() => {
  localStorage.setItem('token', pixStore.getState().token);
  localStorage.setItem('user', pixStore.getState().user);
});```
#

@stable kite

#

got it? how can this be solved?

#

pls help

stable kite
#

@twilit needle do you want your store to store your user in localstorage or you would manually do it?

twilit needle
#

I want to store it in localstorage

#

@stable kite

stable kite
#

why are you creating new Store?

twilit needle
#

am not

#

its my only store

stable kite
#

ok

#

are you able to store data in localstorage?

twilit needle
#

yeah

stable kite
#

and you are not able to get it?

twilit needle
#

nonono

stable kite
#

then?

twilit needle
#

its like I can get the data only if its stringified

#

or else I cant

#
const UserReducer = (state=JSON.parse(localStorage.getItem('user')), action) => {
    console.log(state);
    switch(action.type){
        default:
            return state;
        case "REFRESH_AUTH":
            state = JSON.stringify(action.payload.user);
        case "CLEAR_AUTH":
            return state = null;

    }
}
#

because of this

stable kite
#

yes because localstorage can only store strings

#

not objects

#

@twilit needle

twilit needle
#

okay

stable kite
#

what?

twilit needle
#

so the state's default is local storage object

#

I am parsing it because it will be stringified

stable kite
#

then?

twilit needle
#
case "CLEAR_AUTH":
            return state = null;```
#

I return null that is clear it when CLEAR auth is dispatched

#

now, I need to set the user when REFRESH AUTH is dispatched

#

how can I do this?

stable kite
#

you can just add code to do so in sepecificthings in local storage with specific reducers of specific actions

twilit needle
#

No

#

thats where am stuck

#

pls help me there

#
const UserReducer = (state=JSON.parse(localStorage.getItem('user'))```
when I do this
#
redux.js:441 Uncaught SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at user (authReducers.js:3)
    at redux.js:367
    at Array.forEach (<anonymous>)
    at redux.js:365
    at s (redux.js:430)
    at Module.79 (index.js:5)
    at a ((index):1)
    at t ((index):1)
    at Array.r [as push] ((index):1)```
#

error

#

I think its because the item is already passed

stable kite
#

the error is JSON error what the JSON?

twilit needle
#

what

#

didnt get you

#

what the json?

native tide
#

need a lil help in django.

stable kite
#

@twilit needle can you console.log your localstorage so i can see it?

stable kite
native tide
twilit needle
#
Storage {token: "5c4849da29adfe5cf89e5f0f4c88f9fa8611f4d5", user: "[object Object]", length: 2}
length: 2
token: "5c4849da29adfe5cf89e5f0f4c88f9fa8611f4d5"
user: "[object Object]"
__proto__: Storage```
stable kite
#

first jsonify it than read it

twilit needle
#

no

#

notice the string before the curly brakcets?

#

its a stringified object

stable kite
twin tapir
#

hi, i recently uninstalled python 3.8 and upgraded to 3.9 and also reinstalled django in 3.9

#

but now

#

when i try to start a django project with django-admin

#

it looks in the old python38 folder

#

which no longer exists

#

i want it to look in the python39 folder instead

twilit needle
#

how can I center my material ui icon

#
.dataSheetsContainer > * {margin: 5px 0px;}

.dataSheetsContainer button{
    background: var(--darkerSecondaryColor);
    color: var(--primaryColor);
    font-size: 25px;
    height: 40px;
    width: 40px;
    border-radius: 50%;
    box-shadow: 1px 0px 10px var(--darkerPrimaryColor);

    transition: 0.25s;
}```
#

this doesnt work

#

making it centered

twilit needle
#

even added this

#
vertical-align: middle !important;```
#

doesnt work

#

why? pls help

tall quarry
#

why doesn't node need something like uwsgi and can talk to nginx directly

twilit needle
#

pls ping me when help, thanks!

mystic wyvern
#

<div style="background-image: url("shattered.jpg");"> why doesn't works yert

proper owl
#

@mystic wyvern do you use web framework or just html document?

mystic wyvern
proper owl
#

have you set your static files or media folder? something that make your images available from the browser

#

Or you just have img in your root folder and hope it will work?

mystic wyvern
#

and i try to set it in static/css file but i got nothing

proper owl
#

what I do is

#

in settings.py python STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/")

mystic wyvern
#

i must upload the image in browser

proper owl
#

ok

#

do you want to do it in admin view or simple html <input>?

mystic wyvern
rotund token
#

yo can anyone help me style and add a dropdown menu to my navigation bar?

#

will give more info. just TAG ME and ask questions n i'll answer

hushed barn
#

Hey i need help im really new and just starting off with my first mini project i cant open my http://127.0.0.1:8000/products/ window it just says connection refused and this site cant be reached

native tide
#

@hushed barn what error code is it

native monolith
hushed barn
#

@native monolith Which file is the route in?

native monolith
#

show code

#

route = web url

#

/products or /products/

hushed barn
#
from . import views

#
# /products/1/detail
# /products/new

urlpatterns = [
     path("", views.index),
     path("new", views.new)```
#
from django.urls import path, include

#
# /products/1/detail
# /products/new
urlpatterns = [
    path('admin/', admin.site.urls),
    path("products/", include("products.urls"))
]```
#

@native monolith here

native tide
#

can you name your files

#

is the first snippet of code the urls.py for the products?

hushed barn
#

Yea!

native tide
#

I assume products is the name of your separate app

hushed barn
#

Yes

#

its products and pyshop are the folders

native tide
#

and you put them in the INSTALLED_APPS of your settings.py?

hushed barn
#

yea

#

btw thanks for trying to help if you cant figure it out!

#
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "products.apps.ProductsConfig",
    "products"
]```
native tide
#

hmm that's strange I can't see an error yet

hushed barn
#

yea i watched errors tab and it shows everything right!

#

A few greens with scribble under but thats it

native tide
#

could you show views.index?

#

btw the code you sent here

#
urlpatterns = [
     path("", views.index),
     path("new", views.new)
#

There is a closing bracket ] at the end, right?

toxic flame
#

Can i see your views?

hushed barn
#

yea

toxic flame
#

@hushed barn

hushed barn
#

it cut out at end

#

sure

#
from django.shortcuts import render


def index(request):
        return HttpResponse("Hello world")


def new(request):
        return HttpResponse("New Products")```
toxic flame
#
from django.contrib import admin
from django.urls import path, include

#
# /products/1/detail
# /products/new
urlpatterns = [
    path('admin/', admin.site.urls),
    path("products/", include("products.urls"))
]
#

And this is your urls file?

#

@hushed barn

hushed barn
#

yep

toxic flame
#

you should first import the functions first

hushed barn
#

so switch them around?

toxic flame
#
from products.views import *
native tide
#

@toxic flame that's his urls.py of the root app... there's another urls.py of his app where he imports the views

toxic flame
#

Wait first can we see your file structure

twilit needle
#

Also how can I include token as default header in axios

toxic flame
#

no

native tide
#

@twilit needle axios.post(url, payload, config)

const config = {
  headers: 
    {header: value}
}
hushed barn
twilit needle
#

No like make it default for every post

#

@native tide

native tide
#

what

toxic flame
#

The include ("") doesn't specify which function it's using though

#

Or does it

twilit needle
#

Make it a default so that everytime I post I dont have to specify the header

hushed barn
#

Yea well i have no clue why it aint working should i just make anotha 1

native tide
#

axios.defaults.headers.common[header-name] = 'value';

toxic flame
#

do u check console?

#

Console always display error

native tide
#

yea

twilit needle
#

Nike are you coming straight from Josh's tutorial on python?

#

Mosh

hushed barn
#

Im using moshs tutorial for this

twilit needle
#

New to python?

hushed barn
#

yea 6hours of video

#

and now this

#

is my next pwoject

twilit needle
#

Cool but would suggest more time to start something like a django project

steady maple
#

im watching the 6 hours tutorial too

toxic flame
#

From who

steady maple
#

tech with tim

twilit needle
#

Mosh

steady maple
#

for me

toxic flame
#

oof

#

I read documentations

hushed barn
#

yea but i want to just you know get this done im trying my best

twilit needle
#

Tech with Tim writes bad code imo

#

Its unstructured

toxic flame
#

He's still a college student

digital hinge
#

Hi all, does anyone know how to create a dropdown list with a flask app based on values in a csv file?

twilit needle
#

Am still in school and I can figure out his mistakes

hushed barn
#

This site can’t be reached127.0.0.1 refused to connect.
Try:

Checking the connection
Checking the proxy and the firewall
ERR_CONNECTION_REFUSED

twilit needle
#

Its immature code

toxic flame
#

Don't worry everyone has mistakes

twilit needle
#

Okay

#

Me too but am trying to be my best

native tide
#

@twilit needle where u from?

hushed barn
#

Well the reason i started coding was to work on skills im only 10 though so i was thinking at somepoint i can make a algotrading bot

#

and sell it by using a website'