#web-development

2 messages ยท Page 186 of 1

dusk portal
#

i feel noob

#

when i ask simple things

#

i work as a freelancer im good at django and done same thing in different use case

#

but when then too when i ask then i feel bad

ionic raft
#

Perseverance.
I'm a 50 year old business consultant with 25+ years experience, and 12+ years as a visual developer with SharePoint/Nintex Workflow. That experience has given me a headstart with many things.

dusk portal
#

i have done same thing but in

#

different model

#

then too im facing errors

#

thats disappointing

ionic raft
# dusk portal then too im facing errors

Well, I will say this. As frustrating as a pile of errors are, they're actually the greatest teachers. Persist, tackle each one at a time, and see a changing error message as progress.

#

You know, I spent two days on an error where I had a : but needed =
Seriously...2 days!

dusk portal
#

ohh

ionic raft
#

I was close to tearing my hair out. Brutal one. Even pro developers missed it. In the end, I actually spotted it where a pro missed it. Coding is demanding as a science.

dusk portal
#

im 16

#

and u're 50

#

u r older then my father

ionic raft
#

Yah. And I've 34 more years experience with analysis, and problem solving

dusk portal
#

ohh

#

u're gr8

ionic raft
# dusk portal ohh

Don't compare yourself to others. Compare yourself to yourself. If you solved a problem better this time, then you're growing.

#

I've also spent decades as a coach/mentor to other analysts. I happen to be a decent educator and communicator.

dusk portal
#

i took some mins this time

#

and case was different

ionic raft
#

Right. Whether the time is faster, or the solution is more elegant, or both, progress is progress. And then before you know it, you're helping others.

#

I am still learning that most errors can be understood with a trace for example. Nowadays I'm more likely to find the cause of the problem and research it before I ask a question here.

dusk portal
#

ohh

#

u leart rest framework

#

??

ionic raft
#

I learned how to query the DB. I purely use Object.objects.filter().condition and get the data I need with .includes/.excludes/.values_lists etc.
I don't know whether that's the REST Framework though

#

PyCharm taught me alot about what I can do for querying the DB through the ORM

#

OK. I really have to go. Take care bruh ๐Ÿ™‚

dusk portal
#

ohk

rotund perch
#

Hello, how to make a FK automatically connect to the table in another model. For example, making a blog with a FK of a user which is an author, but the problem is whenever I want to create a blog I have to asign the user, is there a way to make the user automatically asigned?

NOTE: I USE SERIALIZERS (REST FRAMEWORK)

rare lagoon
#

I'm really lost with web development, I will first learn HTML, CSS and Js, then what?

autumn hedge
#

@rare lagoon then learn about databases + servers

opaque rivet
rotund perch
#

can u show me an example bcuz am trying but cant get it

opaque rivet
#

I need to see your model

#

and your serializer

rotund perch
#

Okay

#

views.py

def ProductCreate(request):
  serializer = ProductSerializer(data=request.data) #request.data = request.POST | Sends JSON Object

  data={

  }
  print(request.user.id)
  if request.data['seller'] == request.user.id:

    if serializer.is_valid():
        product = serializer.save()
        # data['seller'] = request.user.id
        data['title'] = product.title
        data['price'] = product.price
        data['description'] = product.description

  return Response(data)

serializer.py of Product

from rest_framework import serializers
from .models import *
from Account.models import MyUser

class ProductSerializer(serializers.ModelSerializer):  
  class Meta:
    model = Product
    fields = '__all__'

models.py of Product

from django.db import models
from Account.models import MyUser


# Create your models here.

class Product(models.Model):
  title = models.CharField(max_length=200)
  description = models.TextField(max_length=500)
  price = models.DecimalField(max_digits=5, decimal_places=2)
  seller = models.ForeignKey(MyUser, on_delete=models.CASCADE)
opaque rivet
#

In request.data (the request data from your frontend), include data about the seller, e.g. {"seller": "pk_of_MyUser_object"}

rotund perch
#

so I can do it automatically in the front end?

opaque rivet
#

yep

ionic raft
# rare lagoon I'm really lost with web development, I will first learn HTML, CSS and Js, then ...

That's an important question. Web development has two main components: Front end, and back end. I have been told that the rarer snowflakes are those that develop both the back-end and front-end. They're called, Full-Stack Developers.

The front end concerns what the user sees. HTML gives a web page structure, css gives a page style (how it looks), and js allows you extend behaviour (what happens when you click things).

The back end concerns coding (such as Python in a Framework such as Flask or Django) on the application layer to build web pages (to send to the front-end) and manipulating data in the Database (such as the user's profile).

I would start simple. In order to really play with html and css you're likely to benefit from learning a simple Framework such as Flask. When you learn Flask you'll see how it leads you to create the templates (html page) and serves them up. Flask is also a web server.

css will become important when you want to have a page that doesn't look like it was coded in 1996. ๐Ÿ˜„ JS is less important at first, where simple functionality where interaction with the user (or a consistent, dynamic UX) is not important. I'd worry about JS later.

I started python Apr 2021, and Flask in June and Django in July. I'm now about 25,000 lines of code into my first web project. I started with tutorials. But they're only suitable if you make sure to apply their concepts a few times to ground the knowledge. Reading from a book will take you deep into concepts, but the lack of videos walking you through and explaining concepts can be challenging. A boot camp (from a site such as Udemy) will be better than a tutorial because the good boot camps will come with projects for you to work on.

In the end, your learning style should determine how you learn. Whatever the case, best of luck. I find coding to be tons of fun!

opaque rivet
#

can anybody explain why my nginx service is not proxying my request to my backend service?

# ./nginx/default.conf
upstream backend {
    server backend:8000;
}

server {
    listen 80;
    location / {
        proxy_pass http://backend;
    }
}
# ./docker-compose.yml
nginx:
    image: nginx
    volumes:
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf
ionic raft
opaque rivet
#

thought I only need a default.conf and that's it. what's your default.conf looking like?

ionic raft
#

It is also setup for SSL as well...

opaque rivet
#

it would help. I don't know nginx well.

ionic raft
#

The first part that seems most aligned is ```upstream django {
server web:8000;
}

server {
listen 3999;

server_name _;
return 301 https://$host$request_uri;

}```

opaque rivet
#

that proxies the request?

ionic raft
opaque rivet
#

hmmm... a bit confusing from that snippet

ionic raft
#

There's also a listen dict on 4000 ssl. That has the location of media and static too.

opaque rivet
#

Ok interesting:

upstream backend {
    server backend:8000;
}

server {
    listen 80;
    location / {
        proxy_pass http://backend;
    }
}```

If I visit `127.0.0.1`, the request is proxied to `backend`. However, if I visit `0.0.0.0`, it is not. Any ideas why?
quick cargo
#

0.0.0.0 isnt actually a valid ip

#

its used by your pc to essentially say "bind to all external addresses"

opaque rivet
quick cargo
#

Typically its onky one

#

Like 192.168.0.1 etc...

#

That exposes the server to the open network (normally your LAN unless you port forward on your router)

native tide
#

whether its cable (ethernet), wifi or localhost meaning your own machine

opaque rivet
#

hmm, yeah, I know it in the context of docker containers, running django on 127.0.0.1:8000, other containers cannot send http requests to it. However if I run it on 0.0.0.0:8000, they can.

#

makes sense in that way I guess.

native tide
#

unsure about that

#

if you bind your server to 127.0.0.1:8000 then any process on your machine

#

will be able to access that

#

host:port pair

quick cargo
#

Nah docker network has each container in its own 'local machine'

native tide
#

yeah must be it

quick cargo
#

So each container network is essentially contained in itself

opaque rivet
#

It's like different virtual machines talking to eachother

native tide
#

yeah but virtual machines are different than processes (or simply running programs on your machine)

#

in that they are way more restricted

wicked tide
#

Where would I ask some questions about the Django Rest Framework? I'm kinda having issues understanding how to structure my code for different parts of my frontend.

#

Like I have Location models but I'd like to get different fields at different times. I find delivering all the information at one time for any request (even if it's not needed) is inefficient. But I can't find any information about selective fields. Unsure if this means I just make more Serializers for it or...?

vestal hound
#

there are 3 simple ways to do this

#
  1. just send everything
  2. make many serializers
  3. create a serializer that lets you choose which fields you want to send @ runtime
vestal hound
#

have you verified that it actually matters?

wicked tide
#

I don't know really. This is my first time I've built a REST framework in Django properly and unsure.

#

It's a photo serving site with a Location page with a Race model under that, a Gallery model under that, and a Photo model under that.

vestal hound
wicked tide
#

Location > Race > Gallery > Photo
Location would show all recent races which just needs a name, id and thumbnail ordered by date.
Also Gallerys too, same thing.

vestal hound
#

premature optimisation is the root of all evil

#

hold up

#

what is race

wicked tide
#

not like ethnicity. like a Motocross race

#

Vehicular

#

I do photography lol

vestal hound
#

huh.

#

then what if

vestal hound
#

for that matter, can there be photos not in galleries?

#

or in multiple galleries?

wicked tide
#

Photos will always be in Galleries.

#

Galleries will usually be in Races, but not always (I will support people uploading pictures from Practices)

#

Galleries will ALWAYS be under a location though, at minimum, either through gallery.location or gallery.race.location

vestal hound
wicked tide
#

They will be listed and viewed directly. Also I guess each photo, race and gallery will need the name and ID from the location it's attributed to.

vestal hound
#

for the same model

wicked tide
#

Two. One for viewing directly and one for a Gallery Thumbnail version.

#

Maybe three, at worst?

#

Only one of them needs to write anyways, the rest can be read_only ofc.

#
['uuid', 'name', ...(all other fields)]
['uuid', 'name', 'base64_thumb'] # <--- if I decide to use base64 thumbs, then the third one would be needed just so I'm not sending a bunch of data unnessecarily.
['uuid', 'name', 'hyperlink'] # <--- This one might not need the hyperlink anyways, I think Vue Router just needs the ID based on how I think it functions.
```maybe?
vestal hound
#

are there a lot of fields

wicked tide
#

currently*

astral pagoda
#

hey can someone help me in help in #help-orange its a flask question

native tide
#

Hello, I have question

#

I am new with http response and request

#

I wonder how to access data from the GET method and how to reach the Host

inland oak
# native tide I am new with http response and request

pip install requests

import requests

def make_request():
  resp = requests.get("http://your_target.com/url_to_request")

  if resp.status_code >= 400:
    print(f"Huston, we have a problem # {resp.status_code}")
    return

  print(resp.body) # accessing unformated data
  print(resp.json()) # accessing JSON formated data.
native tide
#

I am very tired right now so I sleep but Iโ€™ll use this tommorow

#

May you be blessed for taking your time to assist me

ionic raft
#

Well, converted a Django Inline Formset into an htmx dynamic form. WOW...is it ever better that way.
Bit of a trek to get there. ..but can update and delete child records to the parent inline! ๐Ÿ™‚

#

The default Inline Formset basically requires you to go into the child form, renders the child records you have, allows you to have preset extras...and if you need more, you need to save out and come back in again.
This for me is the holy grail of forms. Repeating forms...with very little JS! ๐Ÿ˜„
HTMX is...powerful.

lapis stratus
#

Hello any Django devleoper in here?

#

I've been stuck for 3 days in the 400 error whenever I send a post request

inland oak
lapis stratus
inland oak
#

not enough details then

#

from where to where request

ionic raft
lapis stratus
#

Here's what I've got @ionic raft I already check the network tab, setup django and add the cors policy as well but still getting that erro these couple of days I tested a post request at postman it worked but in the axios.post it didn't

ionic raft
#

The :1 looks off...\

#

Can you trace back to how that url is built? That auth/users/:1 looks off

lapis stratus
#

http://127.0.0.1:8000/auth/users/

ionic raft
#

That's good...it's the :1 at the end

#

That seems off to me...unless I'm missing something

#

The 400 error is saying the page isn't there...which aligns with :1 in the URL at the end,

#

I would expect to see auth/users/1

inland oak
inland oak
#

and test on it

lapis stratus
inland oak
ionic raft
inland oak
#

400 is generic error

lapis stratus
ionic raft
#

So the :1 at the end of the url makes sense to you?

lapis stratus
ionic raft
#

Darkwind is da mang for Django

lapis stratus
#

Thank you for the help guys @ionic raft and @inland oak you're both good ๐Ÿ˜„

inland oak
#

u a welcome

ionic raft
#

I just fed false information this time

#

Didn't mean to...noob tho

lapis stratus
#

tbh I'm not really a django dev haha I just need to setup it so I can wire up the front-end to the backend. I'm more of a front-end dev guy

lapis stratus
ionic raft
#

That ^ is like 100,000% improved over Django's Inline Formset...and next to no JS

#

OMG...I've wanted repeating forms since before I started coding with Django.

lapis stratus
#

Oh this is cool. is this an open source project?

ionic raft
#

It's called, LanesFlow.

lapis stratus
ionic raft
lapis stratus
ionic raft
#

And done...

#

Ok...htmx...very cool

lapis stratus
ionic raft
toxic hemlock
#

hey everyone so i just got back into python after a long break and i decided to start a little project just for fun. it involves using python to grab query info to generate and display html in a web browser based on the stuff in the query. i did this on separate machine a while back and it worked, but now that i'm doing it on my current machine it's not working and i'm not sure why. i have a feeling it might be because of the shebang line considering the python and the html i've written so far are all fine (yes, i've checked multiple times) but i'm not very tech savvy when it comes to python so i don't know lol. that said, i'm currently on windows 10 whereas the old machine was unix. does windows support shebang or does it use a different format for it, and if it's the latter, how do i write it? thanks in advance

#

also to elaborate, whenever i submit the form that fills out all the queries that need to be grabbed, it works fine but the python is not executed and thus the html is not generated. instead, the actual python program shows up in the browser. hope that might give a hint or two

prisma jackal
#

I have a question. Iโ€™m thinking about dropping out of university and going into web development but idk how to get started or if Iโ€™d be able to find a job. Iโ€™m reading up on it and some say u can get hired if ur self taught and others say u need an associates. Help?

inland oak
#

and how much years left?

prisma jackal
#

going into my thrid

inland oak
#

which specialization-direction-program of education / which country ?

prisma jackal
#

ecology and idk what i wanna do w that lol, in us

inland oak
prisma jackal
#

i have

inland oak
#

did you have math, or something

prisma jackal
#

no. all bio, but ive taken a lot of calculus and a intro to coding course

fathom fjord
#

hello

inland oak
fathom fjord
#

i am making a website, i wanna add a navigation bar to all of my pages, is there any way that i make a file named nav.html and add the content of it to all the other files

inland oak
#

entering programming without higher education is possible, but you know... that's much harder path.

fathom fjord
#

can u pls tell me

#

i am making a website, i wanna add a navigation bar to all of my pages, is there any way that i make a file named nav.html and add the content of it to all the other files

prisma jackal
#

@inland oak much harder how?

inland oak
#

when you would get few years of working experience, it will matter little though

prisma jackal
#

@inland oak would experience be enough to land a job? and where do u get experience to begin with?

fathom fjord
#

i am making a website, i wanna add a navigation bar to all of my pages, is there any way that i make a file named nav.html and add the content of it to all the other files

#

i am making a website, i wanna add a navigation bar to all of my pages, is there any way that i make a file named nav.html and add the content of it to all the other files

prisma jackal
#

also @fathom fjord brain empty when it comes to coding

#

idk anything :/

inland oak
# prisma jackal <@!370435997974134785> much harder how?

plus, without all CS program knowledge, it will heavily depend on your self-drive to learn all concepts from zero
CS program gives you a solid fundement(a kick in the ass) and teaches you how to learn, it all just makes easier

prisma jackal
#

@inland oak what about bootcamps? or online courses?

#

i read some websites and they give you a CCL but idk what that does

inland oak
#

not familiar with bootcamp concept enough to evaluate it

prisma jackal
#

@inland oak the situation grows bleaker

inland oak
#

if I remember right, some people said that udemy perhaps? offers a bit of more honesty
because you could check author reviews from other students

prisma jackal
#

@inland oak are u in the us?

#

and mkay, ill check it out

inland oak
#

we are all on hype with IT here at the moment

prisma jackal
#

how so?

inland oak
#

high demand, big salaries because IT is opened to foreign markets
(in comparison to any other profession, IT has much higher salary in Russia, economy is quite poor here)

#

so local online courses schools started to grow quickly to rip money from people on this hype

#

people go to them, pay a lot of money, but they are teached quite low there, and really limited knowledge

#

nobody in the end needs in our country people from online courses

#

it just does not make sense for companies to invest into online-course-graduates

#

because junior programmer is still... not a real programmer

#

at least a year or more is needed to be invested, getting him a real industry programming experience

#

in order for him to become a real programmer

#

that is rarely happening with online-cources-graduates. It takes much more than one year (years) for them to become good

#

that's why companies firstly target university-graduates. they have much higher chance to grow into real programmers

inland oak
# prisma jackal how so?

self education is still an option of course, but check statistics in your country just to be sure
how many people managed to land an IT job after having only self education

inland oak
#

university knowledge is not enough

#

I learn with practice, applying at the job or my pet projects, reading documentation to tools
and getting theory from books, O'Reilly is often chosen company of books. Material is always condensed and of high quality (I check reviews in amazon)

prisma jackal
#

hmm, i see

#

damn

#

electrician it is i guess

atomic wing
#

does anyone have any suggestions on what to use and how to make a discord bot dashboard?

inland oak
atomic wing
#

a discord bot dashboard is where you can change settings and such for your discord bot, e.g dyno's dashboard at dyno.gg .

#

here is a screenshot

inland oak
#

u make frontend

#

u make backend

#

u attach discord bot functionality to your backend

atomic wing
#

yes

#

but i don't know how to make a website for it

inland oak
#

use django for example

#

any python framework capable to be good at REST API role, would serve well to do the trick of having backend

#

frontend could be made in django OR in separate frontend framework like React/Vue/Angular

atomic wing
#

by frontend, do you mean the actual code

#

thats what i interpret, but probably not
what i interpret: frontend=code backend=website

#

probably no where near what it is

#

i have never made a website, just so you know

inland oak
#

web site = backend (interactions with database usually or other services) + frontend (collection of html/css/js files served to user)

vestal hound
#

it dynamically changes what you see based on your input

#

it talks to the backend, which is code that executes on the server

atomic wing
#

oh ok so i was pretty much right

vestal hound
#

that may also interact with other external parties, the database, etc.

vestal hound
#

๐Ÿฅด

atomic wing
#

dum <Me

inland oak
#

my description is not informative I guess

atomic wing
#

so, um, what should i use and how would i do it, and your description was, just hard for me to understand

inland oak
#

probably better other people answer it

vestal hound
#

Django would work

#

if you want a significant level of interactivity, you'd need a frontend too

#

Angular/React/Vue are the top 3, AFAIK

inland oak
#

if you don't need significant level of interactivity, django will still work as frontend too

atomic wing
inland oak
#

some people use heroku for that

#

user enters ip address (or domain) of your web server, he gets frontend

#

your discord bot makes requests to django application to interfact with it

vestal hound
vestal hound
#

you use it to write a program

#

when run, this program will handle requests.

#

then you host it on a web server

#

which will basically put it behind a URI

#

so you can access it, like, with your browser

vestal hound
#

which is p easy to use

atomic wing
#

i've made an account but it doesn't make sense, does the website go on it or the actual code?...

vestal hound
#

it's a user thing.

#

and by that I mean

#

your browser knows how to talk to the web server in certain ways

#

and when talked to in those certain ways, the web server sends back HTML

#

which your browser renders as what you see.

inland oak
vestal hound
inland oak
vestal hound
#

probably appropriate to mention

#

man I suddenly can't remember the name

#

that thing

#

...

#

what is it called

#

OMG I CAN'T REMEMBER

#

JQUERY

#

right

inland oak
#

right, and Ajax

atomic wing
#

um

vestal hound
#

okay I guess from my PoV

#

hm.

#

maybe you can say that Django is the frontend too? just not how I thought of it ๐Ÿฅด maybey ou're right

atomic wing
inland oak
#

but it does not have to

atomic wing
#

ok um i'm confused, so i install the django python library and... i have no idea how to use it or code with it but i can just search that up.

vestal hound
#

do you know how the web works (at a very high level)?

atomic wing
vestal hound
#

the request-response cycle, HTTP methods, cookies, the role of HTML and CSS, etc.

vestal hound
inland oak
vestal hound
inland oak
#

or if you know perhaps any other language better than python

#

web frameworks aren't limited to python

atomic wing
inland oak
#

good. u know some python then

atomic wing
atomic wing
inland oak
atomic wing
#

that ppl can't read my mind

#

it was a joke

inland oak
#

some people say that flask is more beginner friendly to learn stuff

#

but at the same time I would say that django is much better for real work

atomic wing
#

well i probably will cut straight to django, i am a quick learner most of the time

inland oak
#

probably for the best

#

less time wasted

manic frost
#

How can I distinguish between an optional and a nullable field in Pydantic?

#

Optional meaning "the field is not required to be present" , nullable meaning "the field is required but can be null"

#

Optional[str] = ... just shows up as a required string in the OpenAPI spec (with FastAPI)

inland oak
manic frost
#

pydantic just uses built-in type hints, yes

inland oak
manic frost
#

I know what Union is and I know what Optional is.

#

Pydantic treats Optional as "non-required", so I'm asking whether there is a way to express "required but can be null" (I'm modeling a third-party API)

junior cloak
#

pydantic works its own way

junior cloak
manic frost
#

Is there a way to mark it as required but nullable in the resulting OpenAPI spec?

junior cloak
#

there was talk of a Nullable[Optional[]] and DisallowNone[] and stuff but I don't believe it came to fruition

#

that i do not know

junior cloak
junior cloak
#

you want it to be required but allow None

manic frost
#

Yes

junior cloak
#

try using Optional[str] = ...

manic frost
#

class User(BaseModel):
    id: Snowflake
    username: str
    discriminator: str
    avatar: Optional[str] = ...

I get this ```js
"User": {
"title": "User",
"required": ["id", "username", "discriminator", "avatar"],
"type": "object",
"properties": {
"id": {
"title": "Id",
"type": "string",
"description": "https://github.com/twitter-archive/snowflake/tree/snowflake-2010"
},
"username": { "title": "Username", "type": "string" },
"discriminator": { "title": "Discriminator", "type": "string" },
"avatar": { "title": "Avatar", "type": "string" }
}
}

#

wait, is there even a null type in OpenAPI?

junior cloak
#

it has nullable: true

#

it does not have a null type

manic frost
#

weird

junior cloak
#

i wouldve sworn that type: null is in fact wrong and to not use it

#

at least for v3

manic frost
#

oh, I can do this

    avatar: Optional[str] = Field(nullable=True)
junior cloak
#

oh that is even better. haha

random sand
#

Can anyone help in jinja2

junior cloak
hybrid quartz
#

Hello is there someone who can help me with a scrapy question ? ๐Ÿ™‚ im a pyhton beginner

prisma jackal
#

would an associates degree be enough to get a job in web development?

native tide
#

even

#

and you arent talking about some prodigies or

#

anything

#

just someone who dedicates time to learning

prisma jackal
#

ive heard of it happening but idk, i get the sense that its unlikely? ive talked to some ppl and they said it would def help getting a job

#

and some reddit threads said employers just want to know u know what ur doing @native tide im just getting a lot of different answers

native tide
#

Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
PS E:\Coding\Python\Django framwork>

native tide
#

that just finds companies for you that require you to do some quick tasks

#

and they really don't require that much in terms of skillset

#

i am overdoing pretty much every task i get

#

i am EU though so unsure

#

about US

prisma jackal
#

damn

#

thanks @native tide ill keep looking into it ig

native tide
#

i will send you the name of a company

#

they take a cut of course

#

but i dont mind

random sand
#

can anyone help with flask ?

native tide
#

@random sand

#

just ask away

dusk portal
#

@ionic raftyo

native tide
#

hey, im trying to implement reddit oauth in my flask webapp but i need to create a state,

state โ€“ A string that will be reflected in the callback to redirect_uri. This value should be temporarily unique to the client for whom the URL was generated for.

does someone have an idea how i could create this and check if the state is the same for the client in the callback?

dense slate
#

Sounds like wherever you are sending them back to on your app (after Reddit authorizing them) requires some additional unique variable. So after they authorize via Reddit they are returned to something like https://yourwebsite.com/oauth_completed/<unique_variable>

#

That's my interpretation. @native tide

surreal portal
#

sup

#

Anybody knows how big societies handle their deployments on cloud services ?

#

On clssic VMs or on special services?

#

Suppose I want to publish my fullstack project on GCP. Does that mean i have to purchase a VM or is there something more convenient like stuff I can do CI/CD on?

woeful trellis
#

hi, i'd like to use a blockchain system in my django project.
i've checked internet about libraries but have n't gone anywhere.
do you know any libraries!?

native tide
bronze marlin
#

Hello. I'm a newbie to web development but have some experience with python. I want to make a small web game that has minimal graphics and is almost completely text-based. I want players of the game to be able to collaborate and play together in real time. I was wondering what the best way to go around this would be. Tutorials would also be nice.

inland oak
#

python can provide collaborating part though

dense slate
#

@bronze marlin That's going to be a pretty significant undertaking. You need to learn to server the website itself with a framework like Flask or Django, and then incorporate websockets for multiplayer (let alone graphics if you want them). It's all doable, just be ready for a significant project!

#

I've created MUDs (text-based multiplayer games) if you want to chat more about that, but I haven't dealt with graphics.

bronze marlin
#

it is primarily text based

inland oak
#

I guess you could go fully python then

bronze marlin
#

ok

#

so flask or django

#

or something else like tornado

#

?

inland oak
bronze marlin
#

i would probably start with a singleplayer version first

#

so what could i use

#

its a pretty simple website so speed isnt a huge factor

#

however i want something that isnt to complex to learn

#

because im aiming to finish it fast

dense slate
#

You know about the concept of game loops?

bronze marlin
#

yes

#

a bit

dense slate
#

If you're going single-player just to learn, I would build it in python first to learn the basics.

#

Then add the web layer once you've got that down.

bronze marlin
#

ok

dense slate
#

The underlying engine could be adapted to it.

bronze marlin
#

wdym?

dense slate
#

I mean that you can create the python engine in just python, get it running in your terminal, and then implement the part that connects it to a webapp.

#

The main engine would probably have to be adapted to it, but all your game classes and other assets could just carry over.

#

I basically created a game loop inside of a websocket library and then served it with Django.

bronze marlin
#

so should i use django

#

or flask?

#

also could you recommend some resources

#

@dense slate

native tide
#

Why aren't my staticfiles being served?

#

wsgi: ```py

import os

from django.core.wsgi import get_wsgi_application
from whitenoise import WhiteNoise

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')

application = get_wsgi_application()
application = WhiteNoise(application, root='./staticfiles')

#

settings ```py

STATIC_URL = '/staticfiles/'

STATICFILES_DIRS =[os.path.join(BASE_DIR, 'build/static')]
STATIC_ROOT = BASE_DIR / 'staticfiles'

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

#

I see styling and all but No media

#

I also set middleWare

dense slate
# bronze marlin so should i use django

It depends. Django is a steeper learning curve and has more bells and whistles out of the box - Flask could be an option here since it's more lightweight, but it depends what you need out of it.

#

I don't really know of any resource for what you're doing. Maybe I should have written one. ๐Ÿ˜„

#

I would learn how to create a basic MUD text game in python, and then how to use websockets with a python framework like Flask or Django - then tinker with it to combine them.

bronze marlin
#

so how would i go about learning that

native tide
#

wauw moving my question up

dense slate
#

@bronze marlin Which part?

dense slate
#

Can you directly access anything in media? Like one of the pictures/videos or whatever is in there?

native tide
#

yes

dense slate
#

Ok, so then it sounds like maybe you're not accessing correctly in your template? I don't really have much to go off of there.

native tide
#

yes I am cuz Im logging the src on the console in React

dense slate
#

ok so it loads it into state but doesn't show it...

#

This is in vanilla React?

native tide
#

yes

dense slate
#

shouldn't
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
be
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')?

native tide
#

doesn't seem to make a difference

dense slate
#

You could just be loading the src link, but not connecting to the actual image. My guess is something is wrong in your path to the media folder.

#

Can you print your BASE_DIR to make sure it's correct?

native tide
#

it is

dense slate
#

Welp, not sure then! I don't have any more info to go off of.

native tide
#

check the console

dense slate
#

Does collectstatic do anything for media? I forget.

opaque rivet
#

in docker-compose can I build from docker-hub without a Dockerfile?

#

e.g.

nginx:
    build: nginx # from Docker-hub
    image: ... # image tag
dense slate
#

I don't see anything in the console related to media. Which part?

native tide
#

when you create a post and go to "/" it should be there and the image you used is console logged

#

after you create an account ofcourse but you can use DummyUser 12345foo

#

to log in

#

password=12345foo and username=DummyUser

dense slate
#

on the post page I get a blank screen with an error:
react-dom.production.min.js:216 TypeError: Cannot read property 'toString' of undefined

native tide
#

This is off-putting

#

errors everywhere

#

can u send a screen shot?

#

why am I getting that error

mystic vortex
#

Someone suggest me a good tutorial to learn about flask

opaque vale
#

man im having serious issues understanding destructured functions, do people actively use them? I just cant wrap my head around how to read them and use them

dense slate
native tide
#

I see those errors yes

#

it says that rating is undefined

#

but it isn't!!

#

rating.toString() is giving an error

#

rating === 0 so I don't know why it says it's undefined

dense slate
#

You sure it's not setting state as undefined initially?

#

try rating && rating === 0

#

so that it has to be defined to do whatever it wants to do

#

or if rating... etc.

normal pebble
#

Please do not use ableist language

native tide
#

ableist? didn't know, I aplogize

native tide
#

It works well in dev tho

rare lagoon
mystic vortex
#

I have a question that to transfer some data from one location I need api but do I need flask or only request lib is enough

ionic raft
mystic vortex
#

Can somebody help me?

native tide
#

Why am I getting error??

import requests


r = requests.get("https://eaassets-a.akamaihd.net/fifa/u/f/fm21/prod/s/static/players/players_21/p200145_TOTS_PVRTC.pvr")
json = r.json()
print(json)```

Error:
```Extra data: line 1 column 2 (char 1)
fast hollow
#

Hi!
I would like create a thread with the discord API, but i have an error.
My code:

header = {
        "Content-type": "application/json",
        "Authorization": f"Bot {token}",
        "User-Agent": "Bot"
    }

request = requests.post(f"%s/channels/{channel.id}/threads" % API_ENDPOINT,
                                    data={"name": f"{under_category}", "auto_archive_duration": 1440, "type": 11, "invitable": False},
                                    headers=auth_api)

I have this error:

400: Bad Request

The data has no errors, unlike the header which has a problem.
Can you help me?
Thanks!

rotund perch
#

Hello, Can anyone explains for me simply what is cookies & sessions? What is the difference between it. I saw django needs (CSRF Cookie) to make requests, but also I am confused why most websites takes permission to use cookies on u?

opaque rivet
#

@mystic vortex a request library just sends a http request. You need an API with Flask. Start a WSGI server which will transform that http request into a python datatype which your backend can understand. Then you can do whatever you want with that data.

mystic vortex
opaque rivet
#

Frontend sends http request to backend API endpoint. Backend API endpoint returns a response to your frontend.

#

Look at a guide to making APIs with flask

opaque rivet
#

@fast hollow what is the error message of the request?

fast hollow
dense slate
ionic raft
#

Function views in Django: I am using the @login_required decorator. However, I want to only allow the user of the request to access the view. How can this be done? I've taken a look around and have not found the way as yet.

I would use a Class Based view and UserPassesTestMixin, however, I'm building this view with htmx and partial form updates. A CBV doesn't appear to allow the method to add a new child. So, I'm back to function views.

rotund perch
ionic raft
#

That's something to go on. Will research how to create a decorator

rotund perch
#

I think so. Good Luck!

ionic raft
#

Hmmm...apparently, user_passes_test is already included in Django...

dense slate
#

If so, you can get the author of the object/instance and then if the request.user is the author, allow access (within the view).

ionic raft
ionic raft
dense slate
#

That would be in a functional view.

#

def View(request):
if request.user == view.author:
allow
else:
redirect or whatever.

ionic raft
dense slate
#

It's just a standard view.

#

You only using CBVs?

ionic raft
#

Ok. I'm still not following...

#

No.

#

I can't use a CBV for this

dense slate
#

So you render a page with a view right?

ionic raft
#

Let me explain...

#

I'm replacing an Inline Formset....with htmx and functional views.
I've tried to build a CBV for this but the method to create isn't allowed. So I set that down. That would have allowed for UserPassesTestMixin.

So, I returned to the original functional view and while I can add the login decorator, I need to only allow access to that functional view if request.user == object.attribute.

dense slate
#

Yea, right. So the original functional view, what's it look like?

ionic raft
#

That ^ works perfectly. I just need to restrict access if the user isn't the owner of the object for the view

dense slate
#

Should the non-owner user be able to see the form at all?

ionic raft
#

If request.user == fmea.primary_team_user_owner then should be able to see the form

#

Otherwise, I want permission denied

dense slate
#

Ok so make that the first line, and it will run all of that.
Your else statement will just be a redirect to another page, for example.

ionic raft
#

right...

#

Good idea...

dense slate
#
def create_failure(request, pk):
    if request.user == thing.author:
        fmea = FMEA.objects.get(id=pk)
        failures = Failure.objects.filter(fmea_fk=fmea)
        form = FailureDetailsForm(request.POST or None)
    ...
        return render(request, 'pips/pips-fmea-create-failure.html', context)
    else:
        redirect(whatever)
#

right?

#

er one sec

ionic raft
#

I'll give it a try face palm

#

I'm already tweaking...

dense slate
#

and you can still use the login-decorator to make sure the user is logged in.

ionic raft
#

It's very testable...just working it out

#

Oh yes...I'll need login decorator or search would fail

#

well that's good...the positive test worked...now to try with another user ๐Ÿ˜„

ionic raft
dense slate
#

Good stuff.

ionic raft
#

So much simpler!

dense slate
#

Yea I'm not a fan of CBVs.

#

Same reason I gravitate to hooks in React. It's just so much simpler and cleaner to manage.

ionic raft
#

I am good with either type of view. However, in this case, functional views were really the way to go for replacing Inline Formsets with embedded update/delete/create logic for the child item

dense slate
#

I would be surprised if you can't use a CBV as it's just another way to approach it, but either way I'm glad it helps.

ionic raft
#

Actually...this is cleaner...

#

Solving the problem of build dynamic repeating forms without a JS Framework makes me happy. It's much lighter than JS, and the processing is all backend. htmx is very useful

#

I'll be learning React shortly, however, I want to use it to build a diagramming app. Having the ability to manage the UI consistently without a JS Framework is making for a very fast website. It's working very well for my needs so far.

#

At any rate, thanks very much again. Solved a big problem that was on my mind

dense slate
#

Sure thing.

mystic vortex
#

Guys suggest me a js framework

quartz forge
#

With a django model's fields, can I have the default of a field be dependent on a value of an another field in the model?

ionic raft
# quartz forge With a django model's fields, can I have the default of a field be dependent on ...

I don't know at the DB level. However, I would look to the application layer, and typically do so when dancing the Django Tango. ๐Ÿ™‚
I would ask when the 'other' field is determined and use that event to update the value of the associated field. This approach therefore does not look at rely on a default value at the model level. Rather, it uses the application layer to drive an adaptive default. I hope that makes sense.

#

When I think about the approach I've suggested above I am good with that. After all, the conditional determination of a default value for a field is not a pure data-layer event, it is an applicational one.

ionic raft
opaque rivet
#

so I'm running nginx and django on seperate containers. I have this in my nginx config:

upstream backend {
    server backend:8000;
}

If nginx container starts before my backend server is up, the container will exit. Any way to orchestrate them?

tame crater
#

Why are those a problems

opaque rivet
#

I have a disgusting view that keeps giving me problems:

class Top3Accommodations(ListAPIView):
    serializer_class = Top3AccommodationSerializer
    queryset = set(Accommodations.objects.all().annotate(Count("reviews")).order_by("-overall_rating", "-reviews__count")[0:3])

For some reason, if I have no migrations this one view always raises a variety of errors even though no requests were sent to it. (this is when setting up my django container). Anyone had similar issues or know what to do in this case?

#

Whenever resetting my db, I have to remove this view and URLconf, makemigrations and migrate, then paste it back in.

opaque rivet
#

@dense slate just got off to bed. But essentially, it's looking for the Accommodations model (but since there are no migrations, it doesn't exist, a slurry of related errors are raised).

But the strange thing is that no requests were made to that API endpoint and other API endpoints that use the same model don't raise anything.

#

I think I'll just rewrite the API endpoint

dense slate
#

if you print something inside the class, and it prints when you start the server, that's probably the case.

opaque rivet
#

I have other class based views which don't raise errors, that use the same model. You're probably right but I don't know why it's trying to create an instance. It shouldn't be.

dense slate
#

Does the Top3AccommodationSerializer call it?

opaque rivet
#

Yes, I believe its just a ModelSerializer which takes all of the models fields. But still, on import it shouldn't be making an instance. But what you said makes sense, I didn't think about that.

I'll try later today. Need to go to sleep after frying myself with AWS deployment

dense slate
#

I mean the traceback would really help to figure this out.

opaque rivet
#

I'll try fix it when I'm back working and will post the traceback if it continues. Think you've led me in the right direction though, thanks.

#

(On mobile, so I can't do it atm)

ionic raft
#

How's it going @opaque rivet ? Did you get the SSL certs installed?

carmine cipher
#

What best language for making mobile application?

wispy niche
#

Hi Web dev friends! Im new to web dev and wanted to see if anyone could help with some advice on which framework to use for a project of mine. I know that the two big guys are django and flask but im not entirely sure which one i should use.

#

I am working on a website that categorizes different softwares and contains reviews of said software platforms. At the moment, the website does seem like its going to be mostly displaying content but im hoping that it will grow from there. My understanding is that Flask is for smaller projects and Django is used for more enterprise level, but if i were to scale something up, would Flask be able to handle something like this?

vestal hound
#

people say Flask is for smaller projects

#

is that it doesn't do as much on its own

#

for contrast, Django has a templating engine, an ORM, a built-in admin panel, and all sorts of other nonsense

#

in terms of actually handling web requests they are more or less equal

#

so the question really is

#

do you want to use, for example, SQLAlchemy or Django ORM?

#

that said, I don't really like Flask's design tbh

#

but

#

YMMV

eternal blade
#

Hello, I am making an login api using drf (im using django-rest-knox for the authentication)

class LoginAPI(generics.GenericAPIView):
  serializer_class = LoginSerializer

  def post(self, request, *args, **kwargs):
    serializer = self.get_serializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    user = serializer.validated_data
    token = AuthToken.objects.create(user)[1]
    return Response({
      "user": UserSerializer(user, context=self.get_serializer_context()).data,
      "token": token
    })```
The LoginSerializer ```py
class LoginSerializer(serializers.Serializer):
  username = serializers.CharField()
  password = serializers.CharField()

  def validate(self, data):
    user = authenticate(**data)
    if user and user.is_active:
      return user
    raise serializers.ValidationError("Incorrect Credentials")
``` When I send a request to the api using postman with the correct credentials I get a 401 error, I assume this is because I have not set the authorization header with the token in my request. how can remove the requirement for the authorization header?
native tide
#
<a href="https://en.wikipedia.org/wiki/The_Mouse_and_the_Mask"><img src="ExpandaPics/MOUSEANDTHEMASK.png" alt="MFDOOM"class = imgz></a>

this wont display the image as a hyperlink

wispy niche
# vestal hound the reason

Thanks for getting back to me. Yeah I have heard that Django has all these features built in to them but I read its a steeper learning curve to get everything going.

vestal hound
#

but

#

you'd need to learn those things anyway

wispy niche
#

For sure, I can see if i were to get more into web dev with python. Django would most likely be the framework companies would use, right?

inland oak
wispy niche
#

Yeah i just saw a vid on fastapi it looks cool.

#

Does anyone here use node.js ?

ionic raft
inland oak
#

i am playing too.
making deployment of application made out of 11 different types of servers at the moment.

#

fun.

ionic raft
# wispy niche Thanks for getting back to me. Yeah I have heard that Django has all these feat...

I started with Django Jul 9, 2021 (and didn't know a line of Python before Apr 16, 2021). I spent June in Flask. I can tell you that I really like Flask. I also found that spending that first month+ was very helpful to give me a grounding in some web dev concepts. However, I have a complex web application project on the go and knew I'd need something more robust. There were two core things that swung it for me at first, and a third that convinced me.
Admin/built in user auth model. Those cannot be underestimated. I didn't know I was missing them with Flask. Now that I'm used to them in Django I'm not sure I'd want to do without them.
Housing multiple apps. I've already got 8 apps in this web application. There will be more. With only 2/3 apps in Flask I felt it's default horizontal structure started to make it feel cluttered. I made an effort at re-organizing, but I quickly realized that I needed to try Django. Dj is better for lots of apps.
The third point was one I realized after learning it. I call it, Doing the Database Django Tango. That Django ORM that @vestal hound referred to earlier CANNOT be underestimated. I really get a kick out of dancing around the DB. And trust me when I say, for a first web project, I'm already doing some incredible things (across 20 tables). Only today I converted an Inline Formset (parent and child objects on the same form, such as order and products) to dynamic forms using htmx. The Dj ORM is amazing. Oh, and using PyCharm to get suggestions on query terms...outstanding chef's kiss

My advice? If you've already got some familiarity with web dev frameworks and have a complex web app in the making, Django. If you're new to web dev, start with Flask and port over after 1-2 months like I did.

Next steps: Build an automated CI/CD pipeline and then learn React to build application #9 ๐Ÿ™‚

wispy niche
#

@ionic raft this was the response I was hoping to get. Thank you for waking me through your journey with both Flask and Django. I know you didnโ€™t have to.

ionic raft
#

One thing that is grossly under-represented about PyCharm is it's intelligent suggestions when working with the Django ORM. I can't tell you the number of times PyCharm has made a suggestion that literally solved a huge CRUD problem

ionic raft
#

A few days ago I spent 27 hours straight coding. Django and a great idea can do that to you ๐Ÿ˜„

#

Doing the Django Tango... <- there's a t-shirt in this ๐Ÿ˜‰

wispy niche
#

Iโ€™m excited that I joined this group. Iโ€™ve been looking for fellow python devs to talk with. The pandemic has made it hard to meet many people lately.

#

Iโ€™ve got a couple questions for you while youโ€™re still hereโ€ฆ

ionic raft
ionic raft
wispy niche
#
  1. I use vscode for most of my development. I know of pycharm, but never have used it. Would you recommend switching?

  2. Any recommendations on websites or something to learn the ins and out about django? Or should I just start with the docs?

ionic raft
# wispy niche 1. I use vscode for most of my development. I know of pycharm, but never have us...
  1. Tough question. I started with PyCharm and got used to it. Then I tried VSC code. I liked the idea, but there are things that VSCode simply does not do as well for Python.

Switch? Well, if you're primarily a Python coder, it's worth a try. If code with many apps, it may hamper your workflow.

  1. I started with Corey Schafer's YT tutorial on Django. But, I also extended on the 1 app I built with the tutorial into 8 apps. Combined with a good book (I can recommend two scoops of django) Corey will set you straight.
wispy niche
ionic raft
#

I sprung for PyCharm professional. It's $80/year, but I've discovered it's clearly worth it.

wispy niche
#

I might try it out. I got a free subscription for being in college

inland oak
# rotund perch Hello, Can anyone explains for me simply what is cookies & sessions? What is the...

most websides ask permissions because of some GPDR or something like EU regulation
the reason: because cookies can be used for evil, to track you across different sites, feeding you with different advertisements anywhere where you go. You could think of cookies being as your browser history, which goes to every web site during your surfing.

Cookie is basically sticky header, that gets attached to you, when you make request some url.
When you make new request, the attached cookie will be send back with every request. Cookie is basically sticking to your browser client.

CSRF thing is one of protections against CSRF attacks. For example you visit hacking web site, or press click in some fishy email. It makes automatic request with your data in other web site on your behalf. Like transfering all your moneys in bank account, or sending gmail email from your mail.

https://www.javatpoint.com/session-vs-cookies
apperently session is stateful server side login, when user login and related information about his movements is inserted into temporal file at server or database for example.

native tide
#

do u know krunker? i wonder how can i make website like that? what technology they use?

rotund perch
wooden ruin
jaunty birch
#

good day over here.. I am new to web development.. I need a someone I can jointly work with to learn more on real life code... I can do 4 hours a week

dusk mango
#

Hello. I'm looking for opinions on BlackSheep, Muffin, and Falcon as they are relatively unknown. I'm looking to replace Quart, since it is currently a bottleneck.
I don't need a feature-rich environment, since I use it only as a gateway, I need speed.
Currently considering Blacksheep, Starlette, or FastAPI, but looking for more opinions.

This is a benchmark from klen (Muffin's creator), that shows the difference in request per second:
http://klen.github.io/py-frameworks-bench/

inland oak
#

or actually consider Django

#

depending what you are doing

dusk mango
#

Django..?

#

Speed..?

inland oak
#

describe what you are doing

dusk mango
#

These two words don't go together.

inland oak
#

forget about speed
it can be achieved at the level out of frameworks

#

just put nginx at the front, with enabled caching

dusk mango
#

This is an application server, I'm not serving static files, I have nginx as a reverse proxy to Quart already.
I'm using Quart basically as an IPC gateway to a Discord bot (async).
From the metrics I monitor I can see that nginx has no problem serving the connections and the Discord bot has no problem with code speed (as the functionality is relatively simple), however Quart's speed just falls down by an insane margin after 200+ requests per second.

#

And I'm writing in this channel because web frameworks are considered part of web development, although I just use them as a form of gateway with less than 3 basic API methods.

inland oak
#

perfect to cache GET requests with query params

#

nginx goes beyond handling static files

dusk mango
#

the usage of the application is such that json caching will not help

#

each request gets an individual, unique response

dusk mango
#

I asked a question.. I've spent three days gathering information and metrics so I know what exactly I need currently. I don't need now people to start telling me "do this or do that" without actually answering my question

inland oak
#

we tell django or fastapi for the speed of development and culture of clean code they bring with themselves

#

fastapi goes fully async as far as i know, and u can choose your own ORM library, which would be async friendly

#

django is async friendly too, but its ORM is not

inland oak
#

if to remain in python, I would give a fastapi a go

dusk mango
#

I don't need speed of development, as I mentioned that I don't use Quart that way, I have less than 100 lines of code there. Same goes for cleanliness.
FastAPI is fully async, but is still way slower than the likes of Blacksheep or Starlette. I don't need an ORM-friendly library. I use it only as a gateway without any deeper logic.
Django is the slowest framework out there.
Python is a requirement, anything else is not an option.

dusk mango
#

I am considering FastAPI. But I am also considering Blacksheep or Starlette. That's why I want opinions.

vestal hound
#

yeah, if you don't need what it does

#

then Starlette could work too

dusk mango
#

Yeah, that's my point

#

Starlette also has grown a bit and has an active community

#

And it's one of the fastest, so it seems like the best choice.

rotund perch
#

Hello, is there a way to hide data(auth tokens for users) in ** tokens table **? [django]

rotund perch
#

when u access the database data should not show up

vestal hound
vestal hound
#

that's kind of a specialised usecase though

#

tbh

dusk mango
#

it should show up.. that's why it's a database, you shouldn't give access to the db to anyone

vestal hound
#

so I'm not sure how much help you'll get here?

#

this is the kind of thing you would ask a specialist

rotund perch
vestal hound
rotund perch
inland oak
vestal hound
#

so

#

let's say hypothetically there's a way to hide the tokens.

#

how would you unhide them?

#

you need some sort of credentials too, right?

#

which this attacker would have

#

if they can already access your database.

rotund perch
#

lol yes

vestal hound
#

so.

inland oak
#

lets check existing database users and their rights

rotund perch
#

but the pass is hashed tho

vestal hound
#

that's the point of salting + hashing

rotund perch
#

he cant get full credentials

#

he needs to decrypt

vestal hound
#

minimising the impact of data leakage

#

it's not called decryption

#

well, it could be, but it's inappropriate IMO

inland oak
vestal hound
#

anyway, the point is

rotund perch
inland oak
#

it is not django directly related, it is encryption related

rotund perch
vestal hound
rotund perch
#

okay, thats good then. Thank you for explaining !

rotund perch
vestal hound
glacial yoke
#

How can I request a function in django views.py from my frontend in react?
For example, I wanted to have a platform where people would have to sign in, and then are able to chat in the onsite messenger, so I have a function in views.py which checks if the user exists (is signed in), and if he is, the message is created in the db. But now, how do I request it from frontend, because of course, I would have to create the message in the db with the text that person input in the frontend

#

I was gonna use axios for it, but I'm not really sure how to, I guess I could just axios get() the function, but then how could I add the message text to the database?

lime mist
#

Python socket.io client's connect method not firing on connect
Here's my code for the client side

class SIOClient(Thread):
    def __init__(self, worker_state: WorkerState) -> None:
        super().__init__()
        self.sio_client = socketio.Client()
        self.worker_state = worker_state

    def run(self):
        self.sio_client.connect(server_url)

        @self.sio_client.event
        def connect():
            log(INFO, f"Connected -> {server_url}")

        @self.sio_client.event
        def disconnect():
            log(INFO, f"Disconnected -X {server_url}")

        @self.sio_client.event
        def sid(sid):
            log(INFO, f"SID: {sid}")
            self.sio_client.emit("set_local_key", this_worker_unique_key)

        @self.sio_client.event
        def set_worker_state(state_data):
            new_state_data = json.loads(state_data)

            if self.worker_state.proxy != new_state_data["proxy"]:
                self.worker_state.proxy = new_state_data["proxy"]
                log(INFO, "Proxy Updated!")

            if self.worker_state.jobs != new_state_data["jobs"]:
                self.worker_state.jobs = new_state_data["jobs"]
                log(INFO, "Jobs Updated!")

The connect is only fired when I close the server and re-run is which causes client to disconnect and then connect again automatically. Server is an ASGI Python SIO server served using Uvicorn

glacial yoke
#

and how would I check if the user is signed in?

vestal hound
#

so you send the message in the request body

#

that said...for this kinda realtime stuff you might wanna look @ WebSockets

rotund perch
#

Whats the point of using templates in django? Since Rest Framework API does all and are more flexible and can be used in Webs & Mobile Apps / Any Frontend Framework. Why most developers use templates instead of rest framework?

glacial yoke
# vestal hound so you send the message in the request body

btw, if I don't want to use websockets, could I just request a function which would check if the user is signed in, and send a callback, and then have a separate function which would POST the info to the rest api if the user is signed in

vestal hound
#

I don't really get this part?

#

why is there a callback

glacial yoke
vestal hound
rotund perch
glacial yoke
# vestal hound why is there a callback

well, whenever you request a function from react to django, it would have to give you a callback, because that's how it works in rest framework api, otherwise it would be pointless

vestal hound
glacial yoke
#

through axios

rotund perch
#

maybe he means HTTP METHODS

vestal hound
#

sending HTTP requests?

glacial yoke
#

yeah, pretty much

vestal hound
#

okay

#

so what you're talking about is really

#

on the React side

#

which means

#

no, not really.

#

okay

#

do you know how auth is normally done?

glacial yoke
#

no, not really

vestal hound
#

okay

#

so there are different ways

#

(and authentication and authorisation are different, but that's not relevant now)

#

take a simple case

#

do you know what HTTP headers are?

glacial yoke
#

yea

vestal hound
#

okay

#

so one common way to authenticate

#

is to send a header

#

with a token in it

#

the backend

#

will verify that the token identifies a user

vestal hound
#

there are different abstractions

#

but if you're using basic Django

#

then

glacial yoke
#

yeah, but how would I send this header from react to django?

vestal hound
#

that basically wraps your view and returns early if the user doesn't have the appropriate credentials.

glacial yoke
#

can you give me a small exmaple

vestal hound
#

When using Axios, in order to pass custom headers, supply an object containing the headers as the last argument

#

so this is something quite easy to Google

#

you should get used to it

#

okay, so

#

you would also send

#

your message or whatever in the body

#

and now on the Django side

#

your view would extract that

glacial yoke
#

i would write it to db?

vestal hound
#

and do whatever with it

#

yes

glacial yoke
#

ok

vestal hound
#

then you return a response

glacial yoke
#

makes sense

vestal hound
#

now, on the React side

#

your callback

#

gets the response

#

(or you can use async/await)

#

and you can check the status code from there

glacial yoke
#

and shows the message on website?

vestal hound
#

and handle it appropriately in your frontend

vestal hound
#

depends.

#

on what you wanna do

glacial yoke
#

ok

vestal hound
#

got it?

rotund perch
#

btw he should handle JS function for CSRF Cookie

glacial yoke
#

yeah

#

thanks

rotund perch
glacial yoke
#

btw, another question, if I wanted to make a logging in system through a social media, like facebook

#

Because in that case, I wouldn't need users info on the account, I just would like to receive a callback of his username

#

so in that case, headers wouldn't really work

#

how could I do it? @vestal hound

vestal hound
glacial yoke
#

ok

glacial yoke
thick hull
#

how do i change the embed title, icon and description? i got the title and description but idk bout icon

#
#

the icon here

eternal blade
#

Hello, I am making an login api using drf (im using django-rest-knox for the authentication)

class LoginAPI(generics.GenericAPIView):
  serializer_class = LoginSerializer

  def post(self, request, *args, **kwargs):
    serializer = self.get_serializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    user = serializer.validated_data
    token = AuthToken.objects.create(user)[1]
    return Response({
      "user": UserSerializer(user, context=self.get_serializer_context()).data,
      "token": token
    })``` The LoginSerializer ```py
class LoginSerializer(serializers.Serializer):
  username = serializers.CharField()
  password = serializers.CharField()

  def validate(self, data):
    user = authenticate(**data)
    if user and user.is_active:
      return user
    raise serializers.ValidationError("Incorrect Credentials")
``` When I send a request to the api using postman with the correct credentials I get a 401 error, I assume this is because I have not set the authorization header with the token in my request. how can remove the requirement for the authorization header?
rotund perch
#

What is the error?

opaque rivet
#

holy... AWS is a pain to learn, but it's so bloody useful. I love it.

grave raft
#

how can I deploy django drmatiq in production on ec2 ubuntu, nginx is reverse proxy and gunicorn server

grave raft
#

one more question how can I design a model in which I can store some pandas rows and then return them in serialized form

polar nova
#

does anyone know pdf to image converting tool except pdf2img

opaque rivet
#

Has anybody used certbot with nginx when it's dockerized?

mystic wyvern
amber beacon
#

hey all, I have a timestamp stored in my db with the following format:

strftime("%Y-%m-%d %H:%M:%S")

Now, I am getting the rows and wanted to calculate the elapsed time till now (time now - timestamp saved in the db).
I've tried the following:

time_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
elapsed_time = time_now - each_doc['creation_time']
print("Elapsed time: "+elapsed_time)

but got the error below:

elapsed_time = time_now - each_doc['creation_time']
TypeError: unsupported operand type(s) for -: 'str' and 'str'

Any ideas on how I can do this simple calculation?

mystic wyvern
#

Try to convert time_now and each_code to integers

amber beacon
#

@mystic wyvern I converted both variables to int but getting another error now:

ValueError: invalid literal for int() with base 10:
#

oh I got it, it worked. Thanks!

def datetime_to_int(dt):
    return int(dt.strftime("%Y%m%d%H%M%S"))
mystic wyvern
fossil loom
oak oak
#

Can anyone tell me how to make a simple web browser using python, without PyQt5

#

?

eternal blade
# rotund perch What is the error?

Sorry for the delay, This is the script I am using to send the request ```py
import requests

res = requests.post("http://127.0.0.1:8000/api/auth/login/",
data={"email": "test@gmail.com", "password": "1234"})

print(res.status_code)It prints `401` and when I check the terminal where the django server is running it shows thispy
Unauthorized: /api/auth/login/
[31/Aug/2021 18:54:59] "POST /api/auth/login/ HTTP/1.1" 401 58```

#

I double checked the credentials

rotund perch
stark tartan
#

(django ,python django Channels)Tell me if it is possible or not??

I am building a social media website like I Instagram I want to send real-time notifications to user like when other user like you post etc ..

Can a use Django channels and send a web push notifications to user

But how can I integrate django channels for whole I have implemented it for chating (for chating route ONLY /chats)
can I use same for whole website for all routes

eternal blade
#

The api will return the token

opaque rivet
dusk portal
#

i want to give user feature to follow and following button can i do that by IntegerField i only want it to show no. of following and followers and when someone clicks it increases rather then that nothing , i even dont want user to see who have followed

#

@opaque rivet @eternal blade

opaque rivet
#

yep

dusk portal
#

ohk cool

dense slate
dusk portal
#

and why would i use web sockets im not making chat app xD

stark tartan
dusk portal
#

i have any projects like rest api projects , ecommerce

#

and some tricky stuff like

#

how to get order history of only the user who's logged in not other

#

profile only of that who's logged in

opaque rivet
#

where do you guys get SSL certificates from?

stark tartan
dusk portal
dense slate
dense slate
dense slate
lucid vine
opaque rivet
dusk portal
#

and?

opaque rivet
#

certbot makes a request to my backend on a URL like: <my_domain>/.well-known/acme-challenge/4nHueVuk610z_NmFpaCNyP9xoSTWcfLVpALgw4DQQuo - how am I meant to know the token here?

lucid vine
dusk portal
#

yes

#

in which

#

we want output

#

instantly

#

where we use non-http protocols

#

right?

lucid vine
dusk portal
#
class Profile(models.Model):
    user=models.ForeignKey(User,on_delete=models.CASCADE,default='unknownuser')
    about=models.CharField(max_length=200)
    image=models.ImageField(default='default.jpeg',upload_to='Profile_Pics')
    follower=models.IntegerField(default=0)
    following=models.IntegerField(default=0)
```how can i ensure that 1 user can follow another user for only 1 time
#

;-;

#

ummm

lucid vine
#

set unique constraint on foreign key?

dusk portal
lucid vine
#

I think so, but you should change default to NULL then

#

also update old records

dusk portal
#

yes

stark tartan
dusk portal
#

btw im using OneToOneField

lucid vine
#

I am not familiar with the ORM you are using

dusk portal
#
class Profile(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)
    about=models.CharField(max_length=200)
    image=models.ImageField(default='default.jpeg',upload_to='Profile_Pics')
    follower=models.IntegerField(default=0)
    following=models.IntegerField(default=0)```
stark tartan
opaque rivet
dusk portal
lucid vine
#

You can do everything you can do with nginx in it. Static files, reverse proxy...

#

Setup is done with a simple file similar to nginx-conf

#

I personally run it with docker and reverse proxy all requests to frontend/backend containers to ensure they all have https

bitter vessel
#

can I use Django to create windows based applications?

opaque rivet
#

interesting... I'm thinking whether to use it.
I have containerized nginx and my backend services on an EC2 instance. But I'm having major troubles using certbot to get SSL certificates to use in my nginx conf.

All I need from nginx is SSL and reverse proxy. Staticfiles are catered for from a cdn. Would caddy be an easy replacement?

lucid vine
opaque rivet
#

and it handles SSL certificates auto-renew?

lucid vine
#

yes, everything is automatic

#

you never have to think about it, just run and forget

#

It shouldn't take you more then a couple hours to setup

opaque rivet
#

damn, I am sold. I'm going to try one last thing and if it doesn't work I'll move to it. Thanks ๐Ÿ™‚ ๐Ÿ‘

lucid vine
bitter vessel
# lucid vine nope

can you suggest any framework (python based) to create windows based application

lucid vine
#

there is also pysimplegui

#

which is good for beginners

bitter vessel
#

thx

fast lava
#

Hello

eternal blade
#

Hello

fast lava
#

If anybody knows

#

Django

#

please help me

fast lava
#

can u help me

lapis basalt
opaque rivet
#

think I'm just going to buy a SSL certificate and get certs that way.

#

such an unbelievable headache

native tide
native tide
native tide
manic frost
#

What error?

dense slate
#

so what's the error

native tide
#

i fixed im dumb

native tide
#

okay now there is the real problem

opaque rivet
eternal blade
dense slate
#

ยฏ_(ใƒ„)_/ยฏ

native tide
opaque rivet
native tide
#

๐Ÿคจ

#

why?? ? ? ?

dense slate
#

You don't offer us any information about errors or what else you have tried.

#

It is impossible to help.

native tide
#

!code

#
 * Serving Flask app 'main' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 944-197-235



dense slate
#

What is the url in your browser?

rotund perch
#

Anyone did a website using django and got a lot of users using it, is there a way to make database quiries optimized and faster, since making some unoptimized queries leads to much costs & bad performance.

dense slate
#

Sometimes for me, on my laptop, it doesn't connect when i launch it in vs code and i have to restart vs code is my computer.

#

What are you running Flask in?

native tide
#

i get same thing in vsc

raven harbor
#

guys i have some issue posted in #help-mango can someone help?

tawny pollen
#

I have a django question

ionic raft
tawny pollen
eternal blade
ionic raft
eternal blade
ionic raft
tawny pollen
#

ok thanks

ionic raft
#

Others may have deeper insight. Definitely a bit of speculation on my part. Feel free to research

#

I've seen so much Django the past 1.5 months that it's a bit of a blur still

dense slate
tawny pollen
#

form = RenewBookForm(initial={'renewal_date': proposed_renewal_date})
why is initial a dictionary type ?

dense slate
#

pk, uuid, an integer, a slug, etc.

ionic raft
dense slate
#

Yea, you usually want unique keys for auth.

#

I usually have a standard db-generated pk integer and a uuid for every object in my db that would need to be referenced in the future.

rotund perch
#

If the error is still there, u may be using a decorator or a default setting that makes anyone wants to access any view/url must be logged in since its written in the error unauthorized.

nova sonnet
#

my createview isnt saving to a database, there are no errors that are popping up, can someone help me?

nova sonnet
#

ive added it

#

in the form_valid method

rotund perch
#

U are saving users?

nova sonnet
#

just an object

rotund perch
#

Can u send code i will try to help if i can

#

and view?

nova sonnet
#

that is the view

#

you mean template?

rotund perch
#

sorry the form

nova sonnet
#

any idea?

rotund perch
#

did u try to create it using django admin?

#

yes I mean try tologin to the admin dashboard and create

nova sonnet
#

yep it works in admin

rotund perch
#

ok so the problem may be in the url?

nova sonnet
#

can you explain further?

dense slate
#

your action is ""

#

it needs to be the url to the view

cerulean badge
#

i want to make an app for the admin side of an ecommerce site can i name it admin? or will it clash with django's admin? if yes what should i name it?

dense slate
#

If you put a print statement in your view, first line, does it print it upon submitting? That way we know if it's even calling it fro the form (which I bet it's not) @nova sonnet

dense slate
#

what?

nova sonnet
#

where should i put the print?

dense slate
#

first line of the function/method where the post code is

nova sonnet
#

yep it aint, so should i just fill in the action?

dense slate
#

with the url/path yes

rotund perch