#web-development
2 messages ยท Page 186 of 1
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
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.
i have done same thing but in
different model
then too im facing errors
thats disappointing
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!
ohh
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.
Yah. And I've 34 more years experience with analysis, and problem solving
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.
umm that time i took 2-3 days
i took some mins this time
and case was different
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.
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 ๐
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)
I'm really lost with web development, I will first learn HTML, CSS and Js, then what?
@rare lagoon then learn about databases + servers
can't you include the user in the request and have the serializer accept it as a field?
can u show me an example bcuz am trying but cant get it
Okay
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)
In request.data (the request data from your frontend), include data about the seller, e.g. {"seller": "pk_of_MyUser_object"}
so I can do it automatically in the front end?
yep
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!
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
Do you have an nginx dockerfile?
I'm no pro at this, but I've got one for the nginx build.
no, using official nginx image
thought I only need a default.conf and that's it. what's your default.conf looking like?
I'm just scanning. My config has an app and DB server...trying to work out the best way to share...
It is also setup for SSL as well...
it would help. I don't know nginx well.
The first part that seems most aligned is ```upstream django {
server web:8000;
}
server {
listen 3999;
server_name _;
return 301 https://$host$request_uri;
}```
that proxies the request?
I believe so. Just looking at other files. I got a lot of help building this...so like I said, I'm not the best pro.
hmmm... a bit confusing from that snippet
There's also a listen dict on 4000 ssl. That has the location of media and static too.
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?
0.0.0.0 isnt actually a valid ip
its used by your pc to essentially say "bind to all external addresses"
hmm, could you explain what "bind to all external addresses" means, please?
Tldr any addresses assigned to your machine
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)
by "assign to all" you can think of it as allowing "all" computers to send requests to yours via any interface you have
whether its cable (ethernet), wifi or localhost meaning your own machine
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.
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
Nah docker network has each container in its own 'local machine'
yeah must be it
So each container network is essentially contained in itself
It's like different virtual machines talking to eachother
yeah but virtual machines are different than processes (or simply running programs on your machine)
in that they are way more restricted
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...?
here
depends on your abstraction
there are 3 simple ways to do this
- just send everything
- make many serializers
- create a serializer that lets you choose which fields you want to send @ runtime
how inefficient is inefficient?
have you verified that it actually matters?
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.
until, and unless, you verify that it's a problem, don't worry about it
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.
you want to have galleries from multiple races?
for that matter, can there be photos not in galleries?
or in multiple galleries?
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
how many different ways of displaying locations do you think you will have
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.
no, more like...
how many serializers do you think you'd need to create
for the same model
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?
yeah, that's fine, but
are there a lot of fields
hey can someone help me in help in #help-orange its a flask question
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
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.
Thank you thank you thank you thank you my friend
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
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.
Hello any Django devleoper in here?
I've been stuck for 3 days in the 400 error whenever I send a post request
Debug=True in order to see more detailed error
It's already in true
Feel for you...let's see what you've got ๐
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
The :1 looks off...\
Can you trace back to how that url is built? That auth/users/:1 looks off
http://127.0.0.1:8000/auth/users/
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
postman requests are less picky than with other methods.
You need for sure having cors problem solved
pip install django-cors-headers
ALLOWED_HOSTS = [
"*"
]
CORS_ORIGIN_ALLOW_ALL = True
# add this
INSTALLED_APPS = [
"corsheaders",
# ...
]
# comment out this thing
MIDDLEWARE = [
# "django.middleware.csrf.CsrfViewMiddleware",
]
already did this man
make a simple endpoint with {"ping": True} exposed then
and test on it
does it mean that it throwing me an error because of :1 in the endpoint
have django server opened in terminal
and just read the error when you make request
That is possible. I'm nowhere as experienced as Darkwind. But the 400 error is page not found. The :1 doesn't fit as a url format. I'd expect auth/users/1
I assume the 1 is the PK
404 is page not found
400 is generic error
Okay sure man will do this.
right...
Ok. nvm then
So the :1 at the end of the url makes sense to you?
Yeah,really make sense to me.
Alright then. Don't mind me ๐
Darkwind is da mang for Django
Thank you for the help guys @ionic raft and @inland oak you're both good ๐
u a welcome
Did you get it working? If so, Darkwind was the real helper ๐
I just fed false information this time
Didn't mean to...noob tho
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
no, you're not
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.
Oh this is cool. is this an open source project?
Nah. It's an idea I'm working on. I'm building a Process Improvement Project Management system. Just deployed v0.1.1. Have open alpha testing on. Got much more to build yet
It's called, LanesFlow.
Woah can't wait to see the finished build of the LanesFlow.
https://lanesflow.io is the current deploy
Any chance you're into business? Collaborate with teams?
I'm not into business. I'm working with another backend dev just using existing tools like Google tech for collaboration
Sounds interesting. Getting some momentum going on doing dev professionally?
And done...
Ok...htmx...very cool
Yeah, there's a momentum.
Exciting...if you're solving problems that have value...always potential
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
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?
in which year you are?
and how much years left?
going into my thrid
which specialization-direction-program of education / which country ?
ecology and idk what i wanna do w that lol, in us
try to ask the same in #career-advice
i have
what do you have as subjects/disciplines in ecology
did you have math, or something
no. all bio, but ive taken a lot of calculus and a intro to coding course
hello
try to consider transfering for CS program
or if not, if it would be possible for you to enter CS program with at least year a bit lower, from second year of education or something
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
entering programming without higher education is possible, but you know... that's much harder path.
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
@inland oak much harder how?
the major problem would be to find first job and experience.
recruiters will prefer to take CS graduate than self educated one
when you would get few years of working experience, it will matter little though
@inland oak would experience be enough to land a job? and where do u get experience to begin with?
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
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
@inland oak what about bootcamps? or online courses?
i read some websites and they give you a CCL but idk what that does
a lot of scam in online courses at the moment.
most of them are just robbery of money while providing really low quality
I heard there can be found some good ones at some web site, not remembering which one
not familiar with bootcamp concept enough to evaluate it
@inland oak the situation grows bleaker
or at least full mode scammery goes in my country with online cources
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
nah, i am in russia
we are all on hype with IT here at the moment
how so?
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
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
I could say that after finishing university, I am in the constant self education now
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)
does anyone have any suggestions on what to use and how to make a discord bot dashboard?
what's discord bot dashboard, which functionality u wish to see there
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
see above
if I see it right, it is a full featured web site.
u make frontend
u make backend
u attach discord bot functionality to your backend
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
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
web site = backend (interactions with database usually or other services) + frontend (collection of html/css/js files served to user)
the frontend is code that executes on your computer.
it dynamically changes what you see based on your input
it talks to the backend, which is code that executes on the server
oh ok so i was pretty much right
that may also interact with other external parties, the database, etc.
<Me
my description is not informative I guess
so, um, what should i use and how would i do it, and your description was, just hard for me to understand
probably better other people answer it
minimally, you need a backend.
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
if you don't need significant level of interactivity, django will still work as frontend too
ok, so it seems Django is the best one for what i need. do i install it or is it a web browser thing cuz i have no idea
u will need to host it on server (usually linux)
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
it would be generally more appropriate to say that there's no frontend IMO? shrugs
it's a Python library.
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
i have no idea how to use it
i've made an account but it doesn't make sense, does the website go on it or the actual code?...
the "website" doesn't exist
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.
https://github.com/kamranahmedse/developer-roadmap/blob/master/img/frontend.png?year-2021-2
frontend is not just framework.
html, css and its libraries (bootstrap?) with all its concepts like flexbox/css grid and e.t.c, js and its libraries (can be tested with jest without any framework)
it is the code that generates HTML
yes, of course
I know that
I know that you know ๐ I make a point of how frontend is big without framework
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
right, and Ajax
um
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

it can work as frontend ;b
but it does not have to
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.
https://docs.djangoproject.com/en/3.2/ the official docs are good
if they arent enough for you, get a book about django
how good are you with Python
do you know how the web works (at a very high level)?
no not at a high level
the request-response cycle, HTTP methods, cookies, the role of HTML and CSS, etc.
"high level" as in "big picture view"
ummm no idea
what all that is
what do you know about python?
you should learn then
or if you know perhaps any other language better than python
web frameworks aren't limited to python
well i know how to make an interactive discord bot, interactive games to play in the shell
good. u know some python then
i only really have python, the only other one i've attempted but stopped learning was HTML5
of course i do, if i didn't i probably wouldn't be extending to other libraries
you know that you know, but we don't know what you know ;b
true... sometimes i just forget
that ppl can't read my mind
it was a joke
I made enter into python web frameworks from here
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
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
well i probably will cut straight to django, i am a quick learner most of the time
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)
is pydantic having same syntax as type hints?
pydantic just uses built-in type hints, yes
https://docs.python.org/3/library/typing.html#typing.Union
Optional[X] is equivalent to Union[X, None].
Union type; Union[X, Y] means either X or Y.
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)
pydantic works its own way
this has been an ongoing debate for like a year, afaik the current recommended way to deal with it is still by using a validator
Is there a way to mark it as required but nullable in the resulting OpenAPI spec?
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
oh wait i think i thought you wanted the opposite of what you are asking
https://github.com/samuelcolvin/pydantic/issues/1223
found the topic all about it
you want it to be required but allow None
Yes
try using Optional[str] = ...
Data validation and settings management using python 3.6 type hinting
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?
that seems correct to me
it has nullable: true
it does not have a null type
hm, when I set it to None, I get this in the openapi:
"avatar": { "title": "Avatar", "type": "null" }
weird
i wouldve sworn that type: null is in fact wrong and to not use it
at least for v3
oh, I can do this
avatar: Optional[str] = Field(nullable=True)
oh that is even better. haha
Can anyone help in jinja2
i dont see that anywhere in the docs but havent looked at the function signature lately ๐ good find
it hides in the **kwargs...
Hello is there someone who can help me with a scrapy question ? ๐ im a pyhton beginner
would an associates degree be enough to get a job in web development?
people get jobs in web development without a degree
even
and you arent talking about some prodigies or
anything
just someone who dedicates time to learning
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
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>
one of the sources of income i have now doesnt require a degree, its a contract work via a middle company
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
can anyone help with flask ?
@ionic raftyo
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?
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
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?
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!?
thanks!
Big socieites?
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.
I think it would be more of javascript thing to do
https://developer.mozilla.org/en-US/docs/Games/Tutorials/2D_Breakout_game_pure_JavaScript
python can provide collaborating part though
@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.
it is primarily text based
uh, then canvas is not needed
I guess you could go fully python then
or fastapi
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
You know about the concept of game loops?
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.
ok
The underlying engine could be adapted to it.
wdym?
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.
so should i use django
or flask?
also could you recommend some resources
@dense slate
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
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.
so how would i go about learning that
wauw moving my question up
@bronze marlin Which part?
looks like your media and static roots are different
Can you directly access anything in media? Like one of the pictures/videos or whatever is in there?
yes
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.
yes I am cuz Im logging the src on the console in React
yes
shouldn't
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
be
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')?
doesn't seem to make a difference
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?
it is
Welp, not sure then! I don't have any more info to go off of.
check it my website is on heroku https://blog-youpost.herokuapp.com/
Web site created using create-react-app
check the console
Does collectstatic do anything for media? I forget.
nothing
in docker-compose can I build from docker-hub without a Dockerfile?
e.g.
nginx:
build: nginx # from Docker-hub
image: ... # image tag
I don't see anything in the console related to media. Which part?
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
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
This is off-putting
errors everywhere
can u send a screen shot?
why am I getting that error
Someone suggest me a good tutorial to learn about flask
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
You don't see it?
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
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.
Please do not use ableist language
ableist? didn't know, I aplogize
ok
It works well in dev tho
Oh about that, I would like to learn more in the backend area, since I like to make things to work and not in creating visuals, but i believe I need to learn frontend at least a little bit
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
Yes, for web development you definitely need to learn html. There's no way around it. You can get away with no css, but the sites you build won't look pretty. Depending on what you're building JS is much more optional. My recommendation would be to pick a simple project and tackle it with Flask. Best of luck.
Can somebody help me?
^
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)
Thanks
Help
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!
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?
@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.
Me nub in flask, api and all related to web dev need some assistance or maybe a sample code can help me to understand what u mean
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
Nobody?
@fast hollow what is the error message of the request?
The error message of the request:
{
"message": "400: Bad Request",
"code": 0
}
I think that looks like an error attempting to convert something to JSON that isn't serializable.
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.
maybe try to create your own decorator?
That's a good idea. I've not done that before. But now that i think about it, that would be the way wouldn't it
That's something to go on. Will research how to create a decorator
I think so. Good Luck!
Hmmm...apparently, user_passes_test is already included in Django...
@ionic raft Will the user be the owner of it, like a post or something?
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).
Yes. There is a field for the record being called
I'm used to UserPassesTextMixin so get that from the CBV perspective. Not sure for functional view
That would be in a functional view.
def View(request):
if request.user == view.author:
allow
else:
redirect or whatever.
Just trying to piece that together...
That is a sub-function?
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.
Yea, right. So the original functional view, what's it look like?
That ^ works perfectly. I just need to restrict access if the user isn't the owner of the object for the view
Should the non-owner user be able to see the form at all?
If request.user == fmea.primary_team_user_owner then should be able to see the form
Otherwise, I want permission denied
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.
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
and you can still use the login-decorator to make sure the user is logged in.
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 ๐
Excellent suggestion! Worked a treat. Very simple and effective.
Good stuff.
So much simpler!
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.
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
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.
I tried, but was getting a Method Not Allowed in the console. I'm not sure why. So I figured rather than go down that rabbit hole I would work with the func view I had that works brilliantly
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
Sure thing.
Guys suggest me a js framework
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?
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.
I would come at this question differently. What do you want to accomplish with the web application? Let that drive the search for the optimal approach and framework.
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?
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.
Want to share the errors?
@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
It's a class, so maybe it's trying to create an instance at runtime and since that model doesn't exist, you get errors.
if you print something inside the class, and it prints when you start the server, that's probably the case.
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.
Does the Top3AccommodationSerializer call it?
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
I mean the traceback would really help to figure this out.
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)
How's it going @opaque rivet ? Did you get the SSL certs installed?
What best language for making mobile application?
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?
the reason
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
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?
<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
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.
kind of?
but
you'd need to learn those things anyway
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?
Django, plus I see fastapi often around
v0.2.0 released! Now to learn/build a CI/CD pipeline. It looks gitlab and jenkins will be the secret sauce ๐
i am playing too.
making deployment of application made out of 11 different types of servers at the moment.
fun.
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 ๐
@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.
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
Delighted to help. This community has been INSTRUMENTAL in my getting my web app built and deployed. The least I can do is to take the time to pay it forward
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 ๐
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โฆ
This is an amazing community with very talented and experienced Python devs.
Sure. I'm just taking a breather after deploying my first Stripe webhooks! Yeah. ๐
-
I use vscode for most of my development. I know of pycharm, but never have used it. Would you recommend switching?
-
Any recommendations on websites or something to learn the ins and out about django? Or should I just start with the docs?
- 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.
- 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.
Ok dope. Iโll check those out.
I sprung for PyCharm professional. It's $80/year, but I've discovered it's clearly worth it.
I might try it out. I got a free subscription for being in college
Anyone?
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.
Session vs. Cookies| Difference between Session and Cookies with list of top differences and real time examples including images, dog, cat, gross, net, java, database, science, general, english etc.
do u know krunker? i wonder how can i make website like that? what technology they use?
Thanks ! Simple & Straightforward.
are you talking about the online game? it probably uses some sort of javascript engine to render graphics/animations and a backend real-time server such as through websockets
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
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/
Python frameworks benchmarks
FastAPI
or actually consider Django
depending what you are doing
describe what you are doing
These two words don't go together.
forget about speed
it can be achieved at the level out of frameworks
just put nginx at the front, with enabled caching
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.
nginx can be used to cache JSON requests too
you can write specifically there to cache all requests coming to /yoururl
it will make separate cache for request with any different query paramters
perfect to cache GET requests with query params
nginx goes beyond handling static files
the usage of the application is such that json caching will not help
each request gets an individual, unique response
discord bot, urgh.
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
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
if u want to have super big application speed.... u probably could consider golang.
its 40 times faster than python %
if to remain in python, I would give a fastapi a go
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.
why not FastAPI?
Python frameworks benchmarks
I am considering FastAPI. But I am also considering Blacksheep or Starlette. That's why I want opinions.
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.
Hello, is there a way to hide data(auth tokens for users) in ** tokens table **? [django]
what do you mean by "hide"
when u access the database data should not show up
why do you want to do that?
sounds like it
that's kind of a specialised usecase though
tbh
it should show up.. that's why it's a database, you shouldn't give access to the db to anyone
so I'm not sure how much help you'll get here?
this is the kind of thing you would ask a specialist
trying to make more security, since anyone can have access to the database can use users tokens
you shouldn't let anyone have access to the database in the first place
Yes I know but I mean if someone granted the access illegally?
in theory there is.
I heard there is database projection technique, which can make view of only the things you wish to show
but you should not give access to db to anyone indeed
lets them have access through your api
okay
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.
lol yes
so.
lets check existing database users and their rights
but the pass is hashed tho
then what's the problem?
that's the point of salting + hashing
minimising the impact of data leakage
it's not called decryption
well, it could be, but it's inappropriate IMO
better to not have password in md5
they aren't safe any longer ;b rainbow attacks or something like that
anyway, the point is
what is md5? sorry I am not a django expert
one of hashing algorithms
it is not django directly related, it is encryption related
nothing useful from hiding it?
yes
okay, thats good then. Thank you for explaining !
Thank you mate gotta learn more about these
yw ๐
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?
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
POST is appropriate here
yeah, but then isn't the function in views.py pointless?
and how would I check if the user is signed in?
the point of a view is to take a HTTP request, do stuff with it, and return a response
so you send the message in the request body
that said...for this kinda realtime stuff you might wanna look @ WebSockets
ok, thanks
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?
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
hold up
I don't really get this part?
why is there a callback
because they don't wanna use a framework
because you might want a static website
I think if uve put a decorator in your django like @permission_classes((IsAuthenticated,)) it will handle it for u
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
what do you mean "request a function"
because that's the only way to do it, right?
through axios
maybe he means HTTP METHODS
are you talking about
sending HTTP requests?
yeah, pretty much
well, there are other abstractions, but the point is sending a request
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?
no, not really
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?
yea
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
this is what you need to do in Django
there are different abstractions
but if you're using basic Django
then
there is a decorator for it
yeah, but how would I send this header from react to django?
that basically wraps your view and returns early if the user doesn't have the appropriate credentials.
can you give me a small exmaple
I don't remember, but there's defo functionality for it
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
i would write it to db?
ok
then you return a response
makes sense
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
and shows the message on website?
and handle it appropriately in your frontend
maybe, or not
depends.
on what you wanna do
ok
got it?
btw he should handle JS function for CSRF Cookie
if it gave you 401 Forbidden, I think thats the solution ^^
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
look up oauth2
ok
sheiat, auth0 and oauth2 makes it so much easier to do this stuff, thanks
how do i change the embed title, icon and description? i got the title and description but idk bout icon
like https://pypi.org
the icon here
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?
What is the error?
holy... AWS is a pain to learn, but it's so bloody useful. I love it.
how can I deploy django drmatiq in production on ec2 ubuntu, nginx is reverse proxy and gunicorn server
one more question how can I design a model in which I can store some pandas rows and then return them in serialized form
does anyone know pdf to image converting tool except pdf2img
Has anybody used certbot with nginx when it's dockerized?
I don't ensure you can remove the token from header you should every time you use post send the token with it
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?
Try to convert time_now and each_code to integers
@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"))
โค๏ธ ๐
Hi im learning django but i was wondering if there is a good database to use with django or i can use any db listed here : https://docs.djangoproject.com/en/3.2/topics/install/#database-installation
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
oh
Yes I think u need to send the token with the request
(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
But that is the login api, the frontend will send a request to it (with credentials) and get the token
The api will return the token
"Can a use Django channels and send a web push notifications to user" - yep
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
yep
ohk cool
You can also do that with some simple ajax rather than getting websockets all setup.
ohh how
and why would i use web sockets im not making chat app xD
did you have any project i want to see how to do that
what? that's what im asking here
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
where do you guys get SSL certificates from?
can you help me in my project
ohk what r u making
Sorry I thought you wanted to include websockets or something last week.
But websockets is not just for chat, it's for any real-time data setup.
certbot
websockets have more usecases beside just chatting
I've tried. I don't understand how to complete the ACME challenge.
mobile push notifications
and?
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?
multiplayer games for example
yes
in which
we want output
instantly
where we use non-http protocols
right?
I suggest https://github.com/caddyserver/caddy. It takes very short time to learn and provides automatic HTTPS, no setup required at all
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
set unique constraint on foreign key?
user=models.ForeignKey(User,on_delete=models.CASCADE,default='unknownuser')
in this i should use unique=True?
yes
he can you help me on a vc
btw im using OneToOneField
I am not familiar with the ORM you are using
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)```
sir replay me
Read through the page a bit, I'm not sure on what it does. Is it a replacement for nginx?
umm ohkay w8 coming
yes
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
@opaque rivet https://caddyserver.com/docs/getting-started
can I use Django to create windows based applications?
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?
I started using it because it was easy to setup and it's unbeliveable but yeah 100% no setup required for HTTPS and as I said you can reverse proxy
and it handles SSL certificates auto-renew?
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
damn, I am sold. I'm going to try one last thing and if it doesn't work I'll move to it. Thanks ๐ ๐
also if you have any questions there is a great community https://caddy.community/
can you suggest any framework (python based) to create windows based application
tkinter, qt for python come to mind
there is also pysimplegui
which is good for beginners
thx
Hello
Hello
It's basically all automatic.
can u help me
Please @all any help
https://stackoverflow.com/questions/69000946/perform-tests-on-a-route-calling-another
I have no clue why it's not working, but for me it fails when using certbot --nginx -d <my_domain>. It's making a request to http://uni-halls.com/.well-known/acme-challenge/vup6XOCpiLOZb90LfDu5vINiH0LQ-DPUL68gsqPIImg and I don't have access to that ACME token.
think I'm just going to buy a SSL certificate and get certs that way.
such an unbelievable headache
return render_template('index.html',discord_url = 'https://github.com') why?
why what?
why that
i got error for render_template
What error?
so what's the error
Using sudo?
okay now there is the real problem
yep
maybe you didnt start the server
ยฏ_(ใ)_/ยฏ
i did.
indeed
Thanks
You don't offer us any information about errors or what else you have tried.
It is impossible to help.
there is no errors
!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
just this
What is the url in your browser?
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.
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?
guys i have some issue posted in #help-mango can someone help?
I have a django question
Ask away
You cant access it on your pc then
uuid is more rare, and I believe (I may not be completely accurate here) that it would be used in token creation.
127.0.0.1 is local
In general, I've used int:pk LOTS...and uuid once IIRC
ok thanks
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
Uuid is just a method of assigning unique identifiers to an object. You can use anything you want to identify an object.
form = RenewBookForm(initial={'renewal_date': proposed_renewal_date})
why is initial a dictionary type ?
pk, uuid, an integer, a slug, etc.
That makes sense, and why I've seen it once for password resetting IIRC
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.
Try allowed hosts and Cors headers, If u are using external frontend for making api requests
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.
Anyone?
my createview isnt saving to a database, there are no errors that are popping up, can someone help me?
Myb u forgot
.save()
U are saving users?
just an object
sorry the form
any idea?
did u try to create it using django admin?
yes I mean try tologin to the admin dashboard and create
yep it works in admin
ok so the problem may be in the url?
can you explain further?
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?
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
on the valid method?
what?
where should i put the print?
first line of the function/method where the post code is
yep it aint, so should i just fill in the action?
with the url/path yes
can u show the urls.py