#web-development
2 messages · Page 162 of 1
import cgi, os
import cgitb; cgitb.enable(display=0, logdir="/log")
try: # Windows needs stdio set for binary mode.
import msvcrt
msvcrt.setmode (0, os.O_BINARY) # stdin = 0
msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
pass
form = cgi.FieldStorage()
# Get filename here.
fileitem = form['filename']
# Test if the file was uploaded
if fileitem.filename:
fn = os.path.basename(fileitem.filename)
open('upload/' + fn, 'wb').write(fileitem.file.read())
message = 'The file "' + fn + '" was uploaded successfully'
else:
message = 'No file was uploaded'
print("""
Content-Type: text/html
<p>%s</p>
""" % (message,))
I store the file send by form in upload folder and I can use the file but for the audio file I don't have the full audio send
Why you dont close the file after opening?
I can try to close it to see if something change
Okey
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/')
def home():
return "Hello"
if __name__ == '__main__':
app.run(debug=True)
```What's wrong with cors here, it isn't working.
Whats your browser wrote to you?
Access to fetch at '<url>' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I try this but nothing change : ```py
file_data = open('upload/' + fn, 'wb')
file_data.write(fileitem.file.read())
file_data.close()
Why you dont use Django, Flask?
Why you use cgi?
I use Flask for making the word generator
I think the problem with cgi
And my file also uploading from html form
Ok ok I will try flask
Nvm got it, the problem I was using Chromes driver and using edge to check stuff out. Thanks btw
Hi! Does anyone can recommend a good Django 3 course?
oh lol no problem
How much experience do you have with django
and what specifically do you want to learn
check out Corey Schafer on YT. He has got an awesome django basic tutorial .. ❤️
I have no experience with Django but I am a Python junior
I have some experience with modular systems such as Odoo
also i've some experience with PyTorch
Yes but he use Django's older version
😦
I'm searching for Django3 tutorial
Not much of a difference .. If you are looking to start somewhere that's the right place. You can further go through change documentation later.
Hi I am having an issue with new url patterns. for some reason Django cant find my new url patterns and is displaying my old home page http response instead of my new one. here are some code snippets. any help greatly appreciated!
Hello all. I've a question about Django's ORM.
Say, I have an object named UpgradeRequest. Whenever a product's higher version is requested, this UpgradeRequest object is being created automatically. Currently, it has 3 statuses. 1-) Approved, 2-) Rejected, 3-) Cancelled.
without_upgrade_request = UpgradeRequest.objects.filter(
user_profile=OuterRef("user_profile__pk"),
status__in=[2, 3], # Rejected and canceled won't be shown.
)
Product.objects.filter(user_profile__user=self.request.user)
.annotate(without_upgrade_request=Exists(without_upgrade_request))
.filter(without_upgrade_request=False)
I'm currently checking if a user has requested to upgrade a product or not. But since one product can have more than one statuses in past, if that object has an UpgradeRequest object with status cancelled or rejected won't be shown even if it has an UpgradeObject with approved status currently.
How can I exclude the past statuses (rejected and canceled) if that object has a UpgradeRequest object with approved status?
the products and customer urls return a 404 😦
interesting 
this is what the httpresponse for the landing page
idk why it is that though as my httpresponse is just set to 'home'
how to do smth like this ```js
(function () {
const second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24;
let birthday = "Jun 8, 2021 16:54:00",
countDown = new Date(birthday).getTime(),
x = setInterval(function() {
let now = new Date().getTime(),
distance = countDown - now;
document.getElementById("days").innerText = Math.floor(distance / (day)),
document.getElementById("hours").innerText = Math.floor((distance % (day)) / (hour)),
document.getElementById("minutes").innerText = Math.floor((distance % (hour)) / (minute)),
document.getElementById("seconds").innerText = Math.floor((distance % (minute)) / second);
//do something later when date is reached
if (distance < 0) {
let headline = document.getElementById("headline"),
countdown = document.getElementById("countdown"),
content = document.getElementById("content");
headline.innerText = "Ended!";
countdown.style.display = "none";
content.style.display = "block";
clearInterval(x);
}
//seconds
}, 0)
}());
Try force reloading. Ctrl shift r on chrome.
it's really mostly the same
really a few things here and there with authentication
corey shafer is good but you can also check out coding entrepreneurs
I believe coding entrepreneurs has a structured course
and then when you want to get into specifics, you can check out corey shafer, Denis Ivy
I also feel that the django documentation is supremely good! After a certain level, you'll find yourself relying less and less on tutorials
I myself use django 3.2
check out your httpresponse parameter first and SAVE everything
happens a lot
also probably try namespacing?
so change it to
from django.urls import path, include
no it didn't work bro
Hey! I'm working in an API for manage an OLT (Optical Line Terminal) for my company.
It uses telnet protocol to send/receive commands and data. Could someone give a feedback about
my code, Django Rest structure, etc?
https://github.com/giacomoquinalia/olt-management
Thanks!
Hello , so i got a website where i'm trying to use a python script in , the script takes the uploaded files and removes duplicates and sorts them into new folders depending on their extension . how i want this to happen is first of all the user uploads the file then chooses the type after that he clicks on . than he gets the interface that i'm gonna send in screenshot next where he runs the python script (this interface is in the same page just done some js to hide the other one and display this one).
What i want to do is the post request doesn't refresh that page so the js code works
this is the new interface
ok so I git cloned a project, did flask run than closed the terminal
now am doing a different flask project and when I do flask run it displays the previous flask project? how do I fix it, I have no clue
Can anyone tell me is fastapi can be used for heavy load application?
hey guys, what is the data attribute of "Visit W3Schools.com!" in -
<a href="https://www.w3schools.com">Visit W3Schools.com!</a>
thanks
@opaque rivet did it work?
can you show me your views.py logic
assuming you're using django
lemme upload it to code pen one sec
alright
checking it out rn
so @subtle otter you are returning users to an index.html template after a successful upload with the valid file validations correct?
yea but i don't want that to happen
i want it to upload the file and don't refresh the page
wait, you don't want it to refresh the page?
yea
so you want it to happen asynchronously?
uploads the files and after the upload is done the js code where it hides the first interface and brings this one happens
I'm not a 100% sure here but the way to do that must be via some sort of use of websockets
ohh
so is it one form after the other?
Basically
i read that ajax could be used but limited knowledge with that too
I get that
yea the first one for the upload the second one it calls a python script to start working
wait a minute -- is the python script in any way dependent on the file upload?
cuz otherwise you just first validate the form and then move onto the second form before processing the post request
which means that
write the same POST logic for both
yea it takes the uploaded file and do some work on them
yea how could i do that pls?
well…I'd need to check out the docs
can you tell me what exactly the script is doing and where it's running?
https://codepen.io/ya-hia/pen/vYxagMq this is the full python script with flask too
what it does is take a folder with webshell files sorted by their extensions then hash them using md5 then checks for duplicates using their md5 , when the duplicates gets removed it adds them to a new folder that is structured the same as the one they were in
NGL that's a pretty good level of security
wait a bit
is there anyway to get this script running client-side instead of server-side
it's been sent to me by a teacher and he told me to work with it without chaning anything , so i don't think i could or know how to xD
I hear that xD
k so check this out
their upload section of the code
you just write data
flask is supposed to work asynchronously
but your logic is kinda messed up
k so it's pretty similar to django so I'll write something that should be pretty similar to what you want to do
deduplication -- are you building your own cloud storage?
@subtle otter can I get back to you tomorrow?
@ivory bolt for sure for sure man , imma add u and just lemme know when ur on
Thanks a lot m8
Don't mention it (😅 getting more familiar with flask atm)
Hello everyone, can someone help me with a question with django?
go ahead
just ask
Can I edit a form from my ListView, I mean, I want to edit a specific field of my model in my ListView and update only that field in my view,I was thinking use patch method but i'm not sure how to do this, so how can I do this?
Idk if u see my code u get a better idea that i'm trying
u only want a field from your form and add it to your ListView ?
yeah and update or delete it, only that field
well delete no, only update that field of my model form
and use FormMixin
let me share with u my code
k
from django.db import models
class RequestContract(models.Model):
PENDIENT = "Pendiente"
APPROVED = 'Aprobado'
REJECTED = 'Rechazado'
CANCELLED = 'Cancelado'
STATUS = (
(PENDIENT, 'Pendiente'),
(APPROVED, 'Aprobado'),
(REJECTED, 'Rechazado'),
(CANCELLED, 'Cancelado'),
)
objective = models.TextField(
verbose_name='Objeto',
blank=False
)
request_date = models.DateTimeField(
verbose_name='Fecha de solicitud',
null=True,
blank=False
)
status = models.CharField(
verbose_name='Estado',
max_length=30,
choices=STATUS,
default='Pendiente'
)
def __str__(self):
return self.objective
class RequestContractForm(forms.ModelForm):
class Meta:
model = RequestContract
fields = ('__all__')
class RequestContractList(ListView):
model = RequestContract
template_name = "contratacion/contratacion_list.html"
paginate_by=5
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['action_new_url'] = '/requestscontracts_create/'
context['form'] = RequestContractForm()
return context
try this
class RequestContractForm(forms.ModelForm):
class Meta:
model = RequestContract
fields = ('your_wanted_field')
Yeah i know that let me show, my html and u will understand what i'm trying to do
{% block table %}
{% block table_head %}
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover dataTables-example text-center">
<thead >
<tr class=>
<th class="text-center">Objecto</th>
<th class="text-center">Valor Total</th>
<th class="text-center">Valor Periodico</th>
<th class="text-center">Fecha de Solicitud</th>
<th class="text-center">Estado</th>
<th class="text-center">Acciones</th>
</tr>
</thead>
{% endblock table_head %}
{% block table_body%}
<tbody>
{% for contratacion in object_list %}
<tr>
<td>{{ contratacion.objective }}</td>
<td>${{ contratacion.total_value}}</td>
<td>${{ contratacion.periodic_value}}</td>
<td>{{ contratacion.request_date}}</td>
<td class="status">{{contratacion.status}}</td>
{% block actions%}
<td><div class="ml-5">
<a href= "{% url 'contratacion:contrato_update' contratacion.id %}" class="btn btn-primary btn-sm"> <i class="fa fa-pencil-square-o fa-lg"> </i></a>
<button class="btn btn-danger btn-sm" data-toggle="modal" data-target="#myModal6"> <i class="fa fa-times-circle-o fa-lg"></i></button>
{{form.status}}
{% endblock actions%}
</tr>
{% endfor %}
</tbody>
{% endblock table_body %}
</table>
well this is basically the problem
My listview shows me, all the content of my database using object_list
that's why it's listview
yeah
but i use get_context_data method, to render my form in my listview
Add formMixin
before ListView
don't forget to import it
class RequestContractList(FormMixin,ListView):
...
from django.views.generic.edit import FormMixin
If I add, formMixin to my list view, I can render my form in my view and update the specific field that I want to?
yup u need to add FormMixin in any class view that u want to display your form
unlike function views
try it and tell me if it works
and also read that doc
cause FormMixin also needs some functions with it
like form_valid()
ok, i'll try
I have a question this is the only mode that i can do this or i can use override the patch method and do the same?
can overide*
before adding FormMixin
waait
class RequestContractList(ListView):
model = RequestContract
template_name = "contratacion/contratacion_list.html"
paginate_by=5
def get_context_data(self, **kwargs):
context = super(RequestContractList,self).get_context_data(**kwargs)
context['action_new_url'] = '/requestscontracts_create/'
context['form'] = RequestContractForm()
return context
try this
context['action_new_url'] = '/requestscontracts_create/' is this url right-written ?
yepp don't worry about it
u can add action to form like
<form action'{% url 'URLNAME' %}'>
..
</form>
without adding it to context
in this case, this url does not take the data of my form simply, it passed said url to a button in my html and it redirects me to another page
I can delete it and will not affect anything
dunno , it always works with me
yea its nothing
just tell me when form is displayed
btw
to add a form u need to do it like this
<form>
{% csrf_token %}
{{form}}
</form>
u cant add it like u add it in html
it should be between form tags
and dont forget the token
let me show u the result
This is basically the result
where's the form
using this code that I wrote, I can see all my form, but I used {{form.status}} to see only that field, the question is, can I send information of my field to my database in this case(status).
The form is the dropbox it says "Pendiente" by default. I mean I know how to show the form correctly but how can I update only my status field and show the result in my table of course my field going to updated the column "Estado"
and save it to ur existing form ? Yes
Hello guys, I'm not sure if this is the right channel to ask this, but I'm having trouble understanding how I'm supposed to get different strings from a text file in the requests module.
To be more specific, this is my code so far:
db = file.read().splitlines()
lineByLine.append(db)
for line in lineByLine:
response = requests.post(url, headers=hd, data=db[0], db[1], db[2])```
The issue is in `response = requests.post(url, headers=hd, data=db[0], db[1], db[2])`, where I don't seem to find a way to send different items through the `data` bit since I can't use commas to separate the index.
Try setting data as a list e.g. response = requests.post(url, headers=hd, data=[db[0], db[1], db[2]])
I've tried that before, but I'm getting ValueError: too many values to unpack (expected 2)
I also want to mention that the text file contains different JSON payloads in each line, which might be what's causing the issue in the first place
That's right then. The format is busted
You may need to do something like this: response = requests.post(url, headers=hd, data=[json.loads(db[0]), json.loads(db[1]0, json.loads(db[2]]))
still the same thing 
I've also tried setting up a different variable so that I can then update it with information from each index, but I can't get rid of the "too many values" error message
provide the raw value of db after the file is read so we can see the format of the data
response = requests.post(url, headers=hd, data=[Json.loads(db)[0], Json.loads(db)[1], Json.loads(db)[2]])```
here's what the text file contains:
{"profile": {"firstName": "Test2", "lastName": "User2","email": "test.user2@liviu.com","login": "test.user2@liviu.com"}}
{"profile": {"firstName": "Test3", "lastName": "User3","email": "test.user3@liviu.com","login": "test.user3@liviu.com"}}```
The way I took the info out of it was by using
```with open('users.json', 'r') as file:
db = file.read().splitlines()
list.append(db)```
Looks like valid JSON per-line
This wouldn't work because it required the data to be a string
Well yeah, working with only 1 index works just as fine, but not with all of them separately
Try something like this:
json_db = [json.loads(item) for item in db]
response = requests.post(url, headers=hd, data=json_db)
Nope, not it's giving me
ValueError: not enough values to unpack (expected 2, got 1) xD
I don't understand how I can't manage to work around these errors while everything is perfectly okay both in the file and in the variables
print(db[0], db[1]) and send what you get.
If you still get the same error try print(db[0])
every time I print everything it shows the correct output. Here's the output for the above
{"profile": {"firstName": "Test1", "lastName": "User1","email": "test.user1@liviu.com","login": "test.user1@liviu.com"}} {"profile": {"firstName": "Test2", "lastName": "User2","email": "test.user2@liviu.com","login": "test.user2@liviu.com"}}```
try print(db[2]) only. I think this will cause the error.
Nope
It gives the correct output
{"profile": {"firstName": "Test3", "lastName": "User3","email": "test.user3@liviu.com","login": "test.user3@liviu.com"}}```
Where does the error "Too many values" point to? Send the whole error if you can.
Here's the entire error:
response = requests.post(url, headers=hd, data=json_db)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\api.py", line 119, in post
return request('post', url, data=data, json=json, **kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\sessions.py", line 528, in request
prep = self.prepare_request(req)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\sessions.py", line 456, in prepare_request
p.prepare(
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\models.py", line 319, in prepare
self.prepare_body(data, files, json)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\models.py", line 510, in prepare_body
body = self._encode_params(data)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\models.py", line 97, in _encode_params
for k, vs in to_key_val_list(data):
ValueError: not enough values to unpack (expected 2, got 1)```
can try response = requests.post(url, headers=hd, json=json_db)
that actually worked :0 The only thing that I need to fix now is the way the script sees the body since I'm getting an error message from my company that the body is not well formed
It usually is because of the double quotes in it and I have to add just some normal quotes
thanks a lot guys!

How does it work this time?
json instead of data parameter
But didn't work here.
Docs don't make it clean, but I think data needs to be plaintext maybe
Ohh
I think another solution is
response = requests.post(url, headers=hd, data=json.dumps(json_db))```
welp, the problem now seems to be that json_db is an array and is not taking each value individually 
but I can confirm that this does work as well
Wdym by "not taking each value individually"?
as in indexing every JSON body
Like this?
well yeah, but it still gives the entire file's data instead of iterating through each one of the lines
I have used python before for coding. However I have never used python for web development. I have a course project that requires me to develop my web application using Django. Any recommendations for online tutorials or where to start??
The data it sends is a list of data separated line by line. so first index is the first line in the file.
I know that 😄 My original question was how I can iterate through each line when using the data parameter, unless I'm not uderstanding what you're trying to say
hello
for line in json_db:
print(line)```
Like this?
i need some help about django
How could I have been so blind? 
i have some problems with django.contrib.auth.models.Group, can anyone help me please?
sure, what's the problem?
Hey I'm trying to set up a secure websocket server
however whenever I try and secure it i get errors [it works if I don't have SSL enabled]
atm the client says ssl.SSLError: [SSL] called a function you should not call (_ssl.c:1129)
Heres the code:
Server: ```py
import websockets, asyncio, ssl
async def hello(websocket, path):
name = await websocket.recv()
print(f"< {name}")
greeting = f"Hello {name}!"
await websocket.send(greeting)
print(f"> {greeting}")
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain('origin.pem', 'private.pem')
start_server = websockets.serve(hello, "0.0.0.0", 87, ssl = ssl_context)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Client: ```py
import asyncio
import pathlib
import ssl
import websockets
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain('origin.pem', 'private.pem')
async def hello():
uri = "wss://socket.ganer.xyz/gsdgsdfg"
async with websockets.connect(uri, ssl = ssl_context) as websocket:
name = input("What's your name? ")
await websocket.send(name)
print(f"> {name}")
greeting = await websocket.recv()
print(f"< {greeting}")
asyncio.get_event_loop().run_until_complete(hello())```
heres the cloudflare worker: https://ganer.xyz/s/QLML1Y
heres the certs [these work for my main website] https://ganer.xyz/s/iqmjim
pls ive gone through two help channels and no replies
Django supports backend_user_groups table as image below, but i want to add more columns to this table, as user A has group Admin on organization B. How should i do?
If it works with http and not https it might be a port issue since http and https use different port numbers.
I guess you could do this
from django.db.models.signals import class_prepared
def add_field(sender, **kwargs):
if sender.__name__ == "MyModel":
field = CharField("New field", max_length=100)
field.contribute_to_class(sender, "new_field")
class_prepared.connect(add_field)```
its a websocket not a webpage
backend_user_groups is default table of django, how can i import it from my code?
to get the name of model like this: "sender.name == "MyModel""
Hey all, quick question about JWTs. I am able to login and obtain a token in a React+Django app but I'm confused on how verifiy/refresh are intended to work. If I hard-refresh the page, my logged in state is lost, and so is this where verify comes in to reset that state?
save your JWToken in any form you like(e.g localStorage)
and bring it in every request
can you elaborate on what you mean by bring it in every request?
when you make any request from React to Django
JWT would be verified for being still correct(if you setup it correctly), if not it should return some error... 403?
I have it setup in react that an auth context wraps my app, and basically runs a check each time. My problem is that on a hard refresh, the token is nullified in state and so I'm "logged out".
keep it more persistent in react
i have it set in localstorage as well as a JWT
nulify only if token verification returned 403
So here's the thing, if I delete my JWT in client, my verification still succeeds.
it should not be possible
ok.. this may depends on how your framework wrapper works
Ok, so that's what I thought, but it does, both in the app and in the graphql client.
something is wrong somewhere
hey all
To get around the refresh problem, I've been saving the token in localstorage, and then I run verifyToken mutation to compare whether the localStorage matches the JWT.
However, that mutation still works if I delete the JWT.
So I thought maybe I don't understand something about how this works.
I'm in the bread help channel if we don't want to clog this one.
make unit test on django part
that after passing no token/incorrect token, you would get 403 error
after you will correct django accordingly to this test
I'm embarrased to say that I don't have much experience with unit testing.
it would mean the error is left on react part with quite high chance
https://www.amazon.com/Unit-Testing-Principles-Practices-Patterns/dp/1617296279
this book is quite awesome explainer for that.
Unit Testing Principles, Practices, and Patterns: Effective testing styles, patterns, and reliable automation for unit testing, mocking, and integration testing with examples in C# [Khorikov, Vladimir] on Amazon.com. FREE shipping on qualifying offers. Unit Testing Principles, Practices, and Patterns: Effective testing styles, patterns, and re...
Awesome, I'll take a look when I have a free moment
But I don't think it's necessary to debug this, yea?
once you are sure that the error in React part
you can probably get more advices how to fix that here
https://discord.gg/HUAuB5bsHs
React community
Ok thanks. So at least I know I'm not crazy and something is wrong here.
our junior front end person experienced same problem I remember
I guess it is common problem
we have React + Django too
I'm using django-graphql-jwt so I didn't code any of the verification bit. I assume that is all working as intended.
What was the solution?
mm, I am responsible only for Django part of the deal.
I just pointed him to specific API request which does nothing, except gets information about user. At the same time it verifives token for still being correct in order to retrieve the information.
he uses it somewhere among his page movements to verify user being still logged in
Precisely my issue.
on my part I wrote good tests
to ensure that any incorrect token will not work)
made them in pytest
Hey I'm trying to set up a secure websocket server.
However, whenever I try and secure it using SSL i get errors [it works if I don't have SSL enabled, assuming i change wss to ws in the worker]
With this code the client says [SSL] called a function you should not call (_ssl.c:1129)
Server: ```py
import websockets, asyncio, ssl
async def hello(s, path):
data = await s.recv()
await s.send(data)
print("Got data:", data)
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain('origin.pem', 'private.pem')
start_server = websockets.serve(hello, "0.0.0.0", 87, ssl = ssl_context)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()Client:py
import websockets, asyncio, ssl
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain('origin.pem', 'private.pem')
async def hello():
async with websockets.connect("wss://socket.ganer.xyz/gsdgsdfg", ssl = ssl_context) as s:
await s.send("Test")
print("Got data:", await s.recv())
asyncio.get_event_loop().run_until_complete(hello())```
Cloudflare Worker: https://ganer.xyz/s/yQKyhz
Cloudflare Certs [these work for my main website]: https://ganer.xyz/s/iqmjim
Nginx VPS Config: https://ganer.xyz/s/FiGzaK
@rose basalt I had to update the nginx to accommodate SSL to get websockets working.
whats the yum command to do that?
something along these lines:
location /wsapp/ {
proxy_pass http://wsbackend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
do you think we could hop in a call
because im terrible at nginx
Sorry man, I can't now.
Just google nginx websocket upgrade ssl. It's pretty straight forward.
i DM'd my config
anyway. Just check expected behaviour in a test
that once you login, you can make data retriaval with this token
and if you pass incorrect token, data retrival will not work
that would be enough for your case to start
(in a django)
Is that the correct usage? If my token used to check if the user is signed in is missing, then get the localStorage token and run the mutation to compare it to the JWT, right?
umm. it sounds wrong
Then what does the verify mutation actually accomplish?
if your token used for login is missing = user sign in should be gone.
when the user signs in, I setToken (boolean to say yes or no someone is signed in) in react. But this resets to null on a hard-refresh.
if user returned from some another page, or he was gone for a long time
but he still has his token stored on his side
he passes it to your django API.
django API tries to decode the token and get dictionary from it.
if it fails to decode (may be some precise error received for that from JWT library), you answer in API as forbidden, 403
and client side of user gets nulified his sign in, asked for relogin
if decoding succeeds, his sign in persists
That's right. token is still stored on the client, but it is cleared from the state in the app.
so I need to basically re-establish him as logged in automatically from his token
if you have token still stored, you can verify if he is still sign in or not
if you have no token left... then his is not sign in for sure. ask for relogin
but it is cleared from the state in the app. I don't get the meaning behind this
I did not work with React closely yet.
I just got myself familiar how to deploy it)
I'm not sure it will be too helpful if you don't know how state works in react.
Basically on login, I set the state of the user as logged in.
But it's in memory, so a hard refresh clears it and rerenders the code.
mm, but token is still stored?
On the client, but not in the app state.
what's the difference between client and app state
So I have to grab the token from the client, and sort of quickly remind the app that they are logged in.
client is your browser
I thought react exists for user only on client side, there is no server side
in this case
isn't all your server side only django?
Yes.
so...
I don't get what's the difference between
On the client, but not in the app state.
react exists only on the client
I don't know if I can explain the difference.
if for some reason app state is not matching something
but you still have token
you can just use this token to verify from django API and extract info again
That's what I'm asking. Is the verification mutation used to do that.
and return your app state to correct state, is it not possible?
mutation... you are talking in terms of GraphQL I guess
I worked only in REST/CRUD way
Sorry, yes. Is the verifyToken API used to compare two tokens whether they match and basically return a payload if true?
there should be no two tokens
one token is enough to verify itself
when API recieves the token, it tries to decode it with your salt
if it decodes... it is verified (return True if you wish)
if not, then False
Oh, yes, right. Sorry I misspoke.
Here's the state issue... if i log in and navigate, i'm fine. But when you refresh the page, React rerenders the code, and therefore everything is sort of reset. As far as I can understand it, I need to take the token from the browser after the refresh and verify it. After I verfiy it, I set the state of "being logged in" back to true.
in order to create token your API uses SECRET_KEY to encode it
same SECRET_KEY must be used to decode it back)
if your SECRET_KEY got changed, token decoding will fail.
I don't have a problem with decoding.
hmm, I get the meaning I guess
Problem is, I can successfully verify without a JWT in my browser.
how do you make verification
Oh i know why...
christ.
I store the token in localStorage, get it on refresh, and then send that token to the API. That's why it works.
so basically you area already doing that
This is how I read to do it on SO.
Right
But they said that I need to do that, and then make sure it matches to the JWT in the browser - which I thought was what the verifyToken API call was doing.
But apparently not.
could i paypal u to help with this ive been struggling on it all day
mm I think I know why they mean
but I also think it is a wrong approach if they wished to do that
when you then send that token to the API
you retrieve all user information, including you could get another token to compare them
it would be wrong
because generated token change due to time of expiration
but...
if you store last token your generated for login
you can compare with it!
which I actually do too
or may be I don't. I don't remember 🤔
those are just different ways to enforce more strictly
that token is still valid
Hmm interesting.
if we will verify our token
with last one used for login
we verify that his last login was made from the same browser
and other browhers where he was logged, would get automatically denied
basically this is not needed for basic functionality, but could be useful for a more complex checking when token should work
and what happens if the token expires in 2 minutes, and the user refreshes the page - it also would not work.
So this is where the refresh token comes into play?
you need to get refreshed token on every API request
but those are just two approaches in my opinion
you can go with more long living token (more than 2 minutes)
to not bother with it
hmm... shrugs
it would be more secure to use short lived one
I would be afraid that...
if user makes several operations at once
that his sign in would not fail during that time if tokens are that often refreshed
If someone logs in on a public computer, then that access token won't expire for a long time.
I heard there is combination of long and short lived tokens used somehow together. probably it can be investigated.
Yes, access and then the refresh token.
But this helped me understand a bit better. Thank you!
I think it helped me too
so... after login I would generate only refresh token
and react would use it to generate very short expiring access tokens
huh.
I think the access token (short, 5min) is create on login, and a refresh token (long, 7 days ,30 days,etc.) is stored in the DB.
Then it is used to create new access tokens when needed.
I'll probably find some tutorial about it
Oh for sure.
how would they communicate then
So far I have just used access and verify. I don't quite understand implementing the refresh part yet.
i tried but it does not work, it can not find User_groups model, This model seems hard to custom
https://auth0.com/blog/refresh-tokens-what-are-they-and-when-to-use-them/
I think I get the meaning behind refersh part
main separation to refresh and access tokens for situations
when Auth server and Resource server are separated servers I guess
if we have Auth and Resource server being the same one...
the meaning for Refresh+Access combintation would be much less.
the only meaning would be left for it, since in this way Refresh token would be used less often that short lived Access tokens
Right
plus
we can make sliding sessions... but hmm, wait a moment scrolling through my head.
if we would go with Refresh + Access tokens
we can for example change our Access tokens on every request
making our traffic more or less protected since every access token is very short lived one (it lives for one request only!!!)
while having refresh token used only if our access token got for some reason expired
That's true.
it would be I guess useful, if traffic sniffing is a concern
I mean you can set how long the access lives for.
it will heavily decrease how often sensetive token is exposed to traffic
so is verify what is used to send with each request to the api to make sure the access token is still valid? and if not, use a refresh token to create a new one?
Well, basically yeah.
ahhh
this scheme would be more usefully working though, if you used more microservices
when Auth microservice is the only one having User database and capable to generate and verify refresh tokens
while other microservices verified only with access token
the meaning behind this to decrease load/traffic to Auth Server
right
splitting the load between more micrservices
but at least we get small security improvement with Refresh+Access tokens I guess
even if we aren't having our services properly microserviced
This describes using localStorage with JWT to fix refresh issue.
I need to read a book about microservices%
already bought one, but the queue... I have a lot of books to go through before reaching that one
brilliant
I just realized how to apply all of this too all my microservices
it will finally make the access to them secure
or at least more secure than it was
alright asking this again
Hey I'm trying to set up a secure websocket server.
However, whenever I try and secure it using SSL i get errors [it works if I don't have SSL enabled, assuming i change wss to ws in the worker]
With this code the client says [SSL] called a function you should not call (_ssl.c:1129)
Server: ```py
import websockets, asyncio, ssl
async def hello(s, path):
data = await s.recv()
await s.send(data)
print("Got data:", data)
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain('origin.pem', 'private.pem')
start_server = websockets.serve(hello, "0.0.0.0", 87, ssl = ssl_context)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()Client:py
import websockets, asyncio, ssl
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain('origin.pem', 'private.pem')
async def hello():
async with websockets.connect("wss://socket.ganer.xyz/gsdgsdfg", ssl = ssl_context) as s:
await s.send("Test")
print("Got data:", await s.recv())
asyncio.get_event_loop().run_until_complete(hello())```
Cloudflare Worker: https://ganer.xyz/s/yQKyhz
Cloudflare Certs [these work for my main website]: https://ganer.xyz/s/iqmjim
Nginx VPS Config: https://ganer.xyz/s/FiGzaK
Glad I could help. 😄
thanks ❤️
what do i need to know in order to consider myself as a "full stack web developer"?
it's kind of a vague question now that i think of it but i wanna know the concepts i should know/experience i should have beforehand
https://github.com/kamranahmedse/developer-roadmap
there are map of skills to know for front end and for back end person (and even for devops 😉 )
obviously full-stack should know both paths in sufficient manner 😉
to reach production state of the product
which good code quality, testing, security, scalability and e.t.c.
the job of a backend person is quite often touching devops path too though
so... full stack I guess should posses skills form all three paths 😉
not all of them of course.
having good grasp of at least one backend framework (Django, FastAPI and e.t.c.) and one frontend framework (React, Angular, Vue.js) should be enough I think
minimally? be able to write a frontend and backend.
devops, UI/UX, and product management are desirable peripheral skills
thanks for your answer! there are definitely a few areas I might have to brush up on but at least I know where to start learning more :)
yea i feel like devops is something i should probably go into more as i feel like quite a few of the concepts are 'taken care of' so-to-speak by frameworks
never felt like that
what concepts are you thinking of? what do you understand by devops?
not much to be fair. i feel like proxies, containerization, and load balancing are things from the roadmap that i've heard of only a few times lol
basically devops is the path from “code” to “software” to “product”
can i use uploaded file in a form with FileField with DictReader from csv module ? (context django)
Is there a way to make optional str url?
https://prnt.sc/14uvabw
Never mind i just duplicated path()
in flask, how do i catch requests going to the "root"? e.g. when i do
@app.route('/', methods=['GET'])
def getCode():
print(request)
it does not catch when i send a request to http://localhost:8000/ - how can i catch requests that go to the "root" of the webserver?
I mean it should
doesn't the server automatically log every request going to the server
are you by chance using a POST request
anywhere on the page do you have a form
that doesn't work
what you actually get when you visit http://localhost:8000/?
i have a issue when run server in django project . i don't know what is the issue of that . how to solve that . because i am noob in django . then issue is the localhost is not running . instead of that the terminal shows to me a error ,
File "/home/abc/.local/lib/python3.8/site-packages/django/urls/resolvers.py", line 600, in url_patterns
iter(patterns)
TypeError: 'module' object is not iterable
The above exception was the direct cause of the following exception:
Traceback (most recent call last): (also lot of file "" blah blah blah ) ```
my app view.py is
from django.shortcuts import render
from django.http import HttpResponse
Create your views here.
def index(request):
return HttpResponse('this works') ```
my app > urls.py
from . import views
url_patterns =[
path("january", views.index)
] my project > urls.py from django.contrib import admin
from django.urls import path ,include
urlpatterns = [
path('admin/', admin.site.urls),
path('challenges/',include('challenges.urls'))
] ```
#in this code if i comment the path('challenges'.....) it's work properly
I think this is simple issue ,.
Also this question is too long .
I don't know how to ask a django doubts ..
Which file should be considered ,😂
Thanks
nope, just opening the site in a browser
in the console? just what you would expect - 127.0.0.1 - - [09/Jun/2021 12:01:26] "GET / HTTP/1.1" 200 -
I don't see the problem -- you're visiting the root, the request gets logged
in your browser
of course the content in terminal also helps.
oh you want to show the request on the page
yes, but how do i actually get the request into the code. because like i said, print(request) does nothing, while it works for other app routes that arent /
gimme a sec
... hello brothers pls help me ..
Can any one help me with celery i am stuck in problem of aynchronous task.
I had a problem of timeout error because of taking excessive time by request.(i.e to scrape the site). So I tried with celery to do the scraping task after getting request in views of Django app. This also taking excessive time now. The page is reloading and taking excessive time to run the task. Help me
Does anybody know why starlette treats functions/methods as (request -> response) functions, and classes like ASGI apps? That seems so arbitrary, why can't a function be an ASGI app?
I mean, I can solve this with something like
class sigh:
def __init__(self, function):
self.function = function
def __call__(self, scope, receive, send):
return self.function(scope, receive, send)
``` but why?
guys
if i local host my server, the url will be http://<my_ip>:8080/. Can i change it to smth custom? Atleast "erase" the ip
You can customize how it shows up in a browser or client by replacing your ip address with your hostname.
What is your goal?
it's not a bid deal but shouldn't you capatalise your class
class Sigh:
why did you add delay again
instead why don't you just use selenium and say wait for element till clickable or something
you can do that in selenium
Tell that to int, float, str, list, dict, set, frozenset, tuple, filter, map, range, type, object, functools.partial and all the others 
😂
XDDDDD
u got me good
well, yes, the convention is generally to make them in PascalCase
I'm not entirely sure but I guess it's because a class can store multiple methods right
wht im so noob
hm?
@wooden ruin hey how r u
so if a class has multiple functions that basically work on request --> response logic, then isn't it better to be clled an app
like in django, I can have a class based view showing different views based on different requests right
so let's say you have a complex app
so you can manage CRUD operations in different classes
maybe maybe not
but this is what I think
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
return render(request,'app5/index.html',{'latest_question_list':latest_question_list})``` views.py why cant i access my this page but i can access the other one Lmao in this its showing my olf HttpResponse and have done ctrl+ s 10000 times
path('',views.index,name='index'),``` urls.py
If you're not familiar with ASGI, my question probably doesn't make much sense. https://asgi.readthedocs.io/en/latest/
An ASGI applicatoin is a callable object that accepts three arguments: scope, receive, send.
ASGI is a protocol similar WSGI, but asynchronous.
;-;
I'm aware of that
I think you're confusing ASGI apps with class-based views
My issues is that Starlette does this when it sees a callable:
- if it's a function or a (bound) method, it treats it as a
request -> responsefunction, not an ASGI app - otherwise, it treats it as an ASGI app
so I'm asking if there's any particular reason for that, since a function can be an ASGI app as well
CTRL + F5 in the browser if the HTML design isn't updating. It might be cached.
oh
btw r good at django
have a problem 1 more that many ppl tried but noone can help waana try @opaque rivet
sure
so i have 3 object
and i have fetched them in my home page
localhost/detail/1,2,3
so as if i wrote there localhost/detail/4
it would show an error
and i wanted to show it by try expect (method)
I'm pretty sure you can only take one url parameter at a time no
def detail(request,question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request,'app5/detail.html',{'question':question})```
show me your url
so the thing is if i wrote localhost/4 it shows default error but it should show customized error cez of this
Can somebody send me a link to the official HTML discord if it exists
if u dont mind can i stream it to u @ivory bolt
because you have no object with id 4. You can check if it exists before rendering the page:
if Question.objects.filter(pk=question_id).exists():
# Question exists
else:
# Render something else, the question doesn't exist.
yep
ik that
yep that makes sense
after all it's get_object_or_404
but thats why i use this line
So how do you want to handle that error then?
question = get_object_or_404(Question, pk=question_id)
ofc there is no pk line question id too
:lmao:
how do you wanna handle the detailview then
Ok, well that will just raise a Http404 exception.
get_object_or_404(Question, pk=question_id)get_object_or_404(Question, pk=question_id) does not actually handle your error, it just raises an exception
try, except Http404
def detail(request,question_id):
try:
question = get_object_or_404(Question, pk=question_id)
return render(request,'app5/detail.html',{'question':question})
except Http404:
# handle Http404 exception
def detail(request,question_id):
try:
question=Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("NO SUCH OBJECT")
return render(request,'app5/detail.html',{'question':question})``` now ok?
then too
its 3 rd day
and i code whole day
i dont wanna give up
but this thing will make me ig
well, that's always gonna render the page even if exceptions are raised, or an error
is it rendering the debug error page?
yes
and if i off debug mode
it shows error 500
internal server error
😢
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/detail/5/
Raised by: app_5.views.detail
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
admin/
[name='index']
about/ [name='about']
contact/ [name='contact']
posts/ [name='posts']
[name='index']
detail/<int:question_id>/ [name='detail']
The current path, detail/5/, matched the last one.
You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.``` with debug
DEBUG = False
ALLOWED_HOSTS = ['*']``` debug off ok?
Not Found
The requested resource was not found on this server.```
😢
@opaque rivet @ivory bolt 😢
this looks like a 404 error to me.
bro u god yes u r here ig u can help @wooden ruin
You are getting that error because there is no question with an id of 5 in your db
I know
You returned the 404 error in your views.py
The code is working as expected
Yeah - where's the 500 error at?
Not Found
The requested resource was not found on this server.
This is a 404 error
Everything looks fine
Have you created any questions?
Yes
It's working correctly
If you want it to render a 404 page, you have to make a 404.html page in your templates directory
otherwise the 404 exception will return the 404 error message "Not Found". Not sure why you said that was a 500 error.
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
return render(request,'app5/index.html',{'latest_question_list':latest_question_list})```views.py ```py
urlpatterns = [
path('',views.index,name='index'),```urls.py
what's your templates dir look like? (assuming you didn't change where django looks for templates by default)
i changed yay
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="/details{{questiom.id}}"></a></li>
{% endfor %}
</ul>
{% else %}
<p>No Questions Found.</p>
{% endif %}
{% endif %}```
..
? So what's your error, the html page is not found?
"my home page still not loading Lmao" needs to be a bit more specific
Let me see your file structure and settings.py @dusk portal u gotta be more specific
screen share or vc?
Just upload screenshots or copypaste
What actually is the error?
Firstly, you misspelled question.id as questiom.id here, and them jinja2 expressions are incorrect.
You also are rendering an incomplete html page
What about the headers, html and body tags?
is there anyway to work around the error to return none in flask?
is it possible to just return an empty variable?
not working still
Why do you want to return something empty? What would that mean?
If you get an HTTP request, you must provide some response. That's just how HTTP works.
i literally just want to process the user data
same lfmao
then i want to call the files in my html code
i've been working on an auto analytics solution for the past hour
what happended bruh
What do you mean by that?
You can just return a status code if you don't want to return data
Whatever you want to do, your handler must return a response. If you want an "empty" response, you can return a 200 OK
You must always provide some sort of response. If the client doesn't expect anything, you can return 200
oh wait i got an idea
i'll just render template my html code
no
xD
and not call the variables
🤦♂️ yikes
wait r u doing flask (my past ) im in django from 2 weeks before that i was doing flask @molten glen
Typically I just return json saying success or failure if all the front-end wants is to send a request and forget about it
yea im doing flask
Typically the front-end should always follow up on the request
its mainly for the render templates and python processing of user data
i can successfully process user data and return a prediction for data science
*score
im working on my next features
auto analytics
We redirect for the sake of organization and writing clean code
im feeling so dumb rn
+1 me too Lfmao
but im proud of myself
i have done flask with so projects + many efforts
yep
my neck is practically broken
im looking so closely at the flask code
thinking the hell is wrong with it
i mean
i think i've solved the issue
nice what was the issue
good luck bro
ik u will do it
and as soon u do it try 1 more project and then django @molten glen
Hey guys so, im learning Flask and
this is the tab
I want this input field to move to the center
could u tell me a way
Why I switched to Django over any other framework?
☞ https://morioh.com/p/efc590019d23?f=60a38d37a419517fcdea1e23
I said im a newbie to web okay? I am well formed that Flask is the best point to start from, so, either you help me or pass it
thx
i have to spend another hour debugging the error 🙂
@molten glen
Show me
Oh
i did it on monday
U leaning from which resource
anything there is
I am working with django on a mysql legacy database. I have integrated everything but passwords. The legacy database is storing the passwords this way
$2a$10$Pdg3h8AVZ6Vl3X1mMKgQDuMriv8iysnValEa5YZO3j9pEboLrOBUK and django reads only if the same hash has the bcrypt$ prefix bcrypt$$2a$10$Pdg3h8AVZ6Vl3X1mMKgQDuMriv8iysnValEa5YZO3j9pEboLrOBUK . How do I make django authenticate users by reading first example hash?
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.BCryptPasswordHasher',
]
using this setting now
should I create my own password hasher?
Anyone knows about Django here ?
i know a little)
Ok
yo quick question, should i learn sql basics before i learn to use sqlalchemy?
Hi, is someone familiar with fastapi here ?
@ripe lodge I would recommend that. I learnt the ORM before learning SQL and I didn't understand the raw SQL behind the abstraction of the ORM.
thanks! also having a difficult time with that
use flexbox and align your items center and justify your content center
input {
display: flex;
align-items: center;
justify-content: center;
}
this is the easiest way
Why do you think you have to use JS for scraping a website?
actually
there are plenty of things to use for scraping
!pypi scrapy
!pypi selenium
no why
the whole idea of django is to use existing libraries
@barren sable check out some other password_hashers that you can import with django if there are any
otherwise yes you may have to come up with your own
bs4 is particularly good for getting data, selenium for interacting with the web pages and testing
while flask might be one of the fastest ways to setup everything
I suggest you move onto django after you're comfortable with it
it's a much more comprehensive framework
do anybody know how to create a js file in intelliji ultimate?
Thanks for the feedback on text readability. I was contemplating removing the signup link. It's ahead of its time. 🙂
who can help me with django?
I'm here!
where are you stuck
i mb solve but i add u in friends i if i will have provlem i will write
sure! I've sent you a friend request
http://www.who-is-hotter.com/ My friend made this website to help make a data set for an ai, it would be pretty cool if people could help out. It's pretty straightforward.
the ui needs some touch up but it was pretty interesting
I assume this is just basic training data
nice!
Yes, it is
Lol I agree but I don't think he wanted to spend too much time on it
Though you may want to tread carefully, even if you're trying to train your model
well, your domain is…it could give the wrong idea to the purpose of the site
or not
you can forget about this
is there any way to send a file from a client to a server in flask?
by posting a request
like
can you send it in the request
please ping me when you respond
there is
what you're talking about is a basic forn
so you send data via a post request
I'll let you know how specifically to do that in a sec
first of all, please import request from flask
can you not store request as an instance
so, if I have request, I can store it as the following:
home_request = request
or something like that
man, you could've just posted your question
can I do that in selenium? how? It says request time out when i put the selenium task in views
I can help! just post your question!!
alright I want to understand exactly what you want to do
in what unit do i need to pass the file size in multiple_chunks method of the File objects (context django)
bytes?
read the docs
Does extending the User model affect the PasswordChangeView, PasswordResetView in anyway. If yes, what changes should be done?
Check the stack overflow question i sent after
this
make a button that redirects to login page simple html
a href op
What does your views.py look like?
... you don't check if the credentials are correct?
ca u write a code how it's must look
LOGIN_REDIRECT_URL = 'blog-home' redirect to the name attribute you added in the views.py file to your home view
no work
same situation
what i should do?
could anyone explain why we would want to use dead link using has symbol because im kinda confused why you would you use it and how it works?
Hi peoples!
I have a question about a scalable django solution:
- The setup: one Postgresql server and multiple (7ish) docker containers running the django application
- The challenge: periodic tasks & long running tasks which I need to decouple from http requests
- Current fix: Both are now triggered by some http requests, but make loading times terribly long on these requests.
- Current fix bis: Scheduled tasks (cron wise) are triggered mulitple times (once in each docker instance of the django app)
- Way forward: Celery looks like the good way to go, but I cant understand how i can handle the multiplication issue (We dont want tasks being triggered 7 times, once by each container)
Idea's, experiences & suggestions?
Thanks!
Simple templating can be done with jinja, works quite good. Some ajax interaction can quickly be added with jquery. If you want to go even further and have more development capabilities in the frontend, React is also a good way forward. There is ofcourse a learning curve (which I'm currently travelling on).
https://developer.okta.com/blog/2018/12/20/crud-app-with-python-flask-react is a nice flask+react tutorial.
Link comes from https://www.fullstackpython.com/react.html which have quite some links to useful resources.
@opaque rivet @wooden ruin are right -- Not Found is a standard 404 message
Hey everyone,
We would like to present to you our Project KLASI, a Smart Virtual Classroom that provides futuristic tools and resources that aims to a successful e-learning and teaching experience in a modern way. This project is a web based application made using mainly the MERN stack development, different libraries and external apis.
To sum up, our project does not end at this point, we are still working to further our approach, It is easy to imagine the improvement and impact of it with a range of upgrades and other more advanced functionalities on the education field. Hoping to reach all of you , Please support us with some likes. 💪🏻🙏🏻💙 https://lnkd.in/d9kumXc
Pour rencontrer l'équipe KLASI et en savoir plus sur ce projet, RDV le 10 Juin 2021 entre 11h et 14h en suivant ce lien : https://meet.google.com/jyu-hfjk-xq...
lfmao done xD im dumb
it should've worked
add a success url
I have literally done the exact same thing, googled it and read the documentation only to realise it an hour later
this is insanely cool
I feel at this point you shouldn't really use a full fledged library, knowing that flask is a pretty small framework.
Me, I love me some Bootstrap5
i took 2 days
cez i was thinking
it was my bad
then my pc trash
then browser
and then i though vs code and then pip unistall django and install it
debug on off try expect get_object_or404
done all
@ivory bolt the page 4 of docs is hard bruh
its my 12th day on django
less go
Hey so
I changed the colour with css
but then I could delete or change to another colour\
its stuck on this blue one
oh I just did it
nvm
tried clearing your cache? Sometimes he still uses the old CSS file
There are ways to suppress caching when developing, It's quite useful when u iterate much
<link rel="stylesheet" type ='text/css' href="{{ url_for('static', filename = 'style.css') }}">
I removed this but
Which browser do you use?
chrome
first you can rightclick and click inspect... to check the source in your browser
yes
There in the network tab there's a checkbox "Disable cache"
normally when refre
He doesnt save it, i think
so when starting to dev, i select it & keep the debug window open
link to the file doesnt work it seems, the file is marked red
yes cuz I deleted that
wanted to clear everything cuz I could not do anything to clear xd
The reference to the file in your template too?
when I delete the reference, it works
Something still goes looking for style.css
aparently the "caching disables" remains until you close the Developer Tools window
how may i help ,did u resolved the issue or may i help @hollow apex
meanwhile me:what's that
all you need is a ctrl+shift+r to hard reset your webpages
@hidden crown instead of running celery on each django container, maybe just make a separate container with celery to handle all the periodic tasks? That way you're not duplicating tasks.
hii , so i'm trying to use sqlite3 db with flask but i keep getting this error sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 4228 and this is thread id 10756. , and as i googled i found out that the problem is the connection must be in the same thread as the cursour . but i'm using the cursor in two functions that are outside of the app.route() , how do i return the cursor so i can use it in those functions pls?
this is one of those two function
def insert_ws(ws):
with conn:
c.execute("INSERT INTO MD5 VALUES (?, ?, ?, ?, ?)", (ws.md5, ws.link, ws.language, ws.type, ws.date))
don't mind my question i fixed it
What do you guys use to host your docker containers
computer
I did, thank you
Digital ocean, GCP & for work purposes all are cloud hosted. There are multiple providers next to the ones mentioned
@opaque rivet The mentioned ones are just the latest ones used by me. DO has like 5 USD/month servers with only the proportion used to be payed, so that's what I often use to try things out (when it's short term it costs like a few cents). This will be similar in other projects. You can also just run it locally (I use a ubuntu desktop PC to run these things, also tried it using Windows Sublayer for Linux (WSL). if u want to share a locally running project: https://ngrok.com/ is quite fun to use
ngrok secure introspectable tunnels to localhost webhook development tool and debugging tool
https://github.com/egorsmkv/simple-django-login-and-register Does anyone knows, how the source/main/views.py can read the 'main/index.html' that is implement at source/content/templates/layouts/main without any 'import' ???
@hidden crown awesome thanks. I still have yet to deploy anything, i was hoping to learn nginx and then aws. You seem very knowledgable!
My best tip is not trying to do everything at once. DO has preconfigged servers and tutorials to set one up yourself. Once again other providers will probably have similar resources
Same with docker containers: there are useful docker images having everything setup already, like https://hub.docker.com/_/django
Try to go for official docker images or images from trusted parties as they are more reliable and are safer is you're not quite into how to get everything running safe and well (and even if safety is your expertise, maintenance & reliability will always be better from bigger, known parties)
Django is a free web application framework, written in Python.
?tag largehosting (from https://discord.gg/code)
Free:
- Openshift: https://www.openshift.com/
2gb of memory, automatically expires after 60 days, but you can resubscribe as often as you'd like. - Heroku: https://heroku.com/
No CLI or SSH, no file access, might make your app sleep if you reach monthly uptime limit. - AWS (Free tier) https://aws.amazon.com/free/
Free tier containers from Amazon, expires in 12 months - Google Cloud Platform (Free tier) https://cloud.google.com/
Free tier google cloud servers
Paid:
- Azure https://azure.microsoft.com/en-us/
Starting at $1.69/month for their B1LS virtual machines, 0.5GB of ram and 4GiB of SSD storage. - OVH: https://www.ovh.com/us/vps/
Full VPS starting at $3.49USD/month, choice of OS, high reliability. - Digital Ocean: https://m.do.co/
Starting at $5/month (USD), you can have your own server with 20GB SSD Disk, and 512MB Memory. Use https://bithost.io/ if you want to pay with cryptocurrencies. - Linode: https://www.linode.com/
Starting at $5/month (USD), you can have a server with 20GB SSD Disk, and 1GB memory - Vultr: https://www.vultr.com/
Starting at $2.5/month (USD), you can have a server with 20GB SSD Disk, and 512MB Memory - Amazon(AWS) Lightsail: https://amazonlightsail.com/
Starting at $5/month (USD) (first month free), you can have your own server with 20GB SSD Disk, and 512MB Memory. - VIRMACH: http://virmach.com/
Full Windows and Linux Desktop VPS starting at $7USD/month and $10USD/month respectively. - Sloppy: https://sloppy.io/
Starting at 5$/month (USD) You can have 500MB Memory, 1TB Transfer per month and 16GB of storage. Extra
storage and ram can be bought. - Galaxygate https://www.galaxygate.net/
Starting at 3$/month (USD), get 15GB of storage, 1GB of ram, and unmetered bandwidth. - Hetzner https://www.hetzner.com/cloud
Starting at 2.49€/month (EUR) for 20GB of storage, 2GB of ram and 20TB of traffic.
Omg bro
hello , is there a way to make an html progress bar for a script??
got this script that's running in teh background and takes sometime to finish , i want to make the progress bar to indicate welp the progress of the script
https://paste.pythondiscord.com/iyarikegam.py - server.py
https://paste.pythondiscord.com/aqekuwitot.rb - client.py
Hi, does anybody know how can I make an ADMIN to the server that can disconnect clients by typing /kick name and that there will be only one admin with an specific name and IP (his messages won't be shown in the chat.)
Does anybody know how can I do that?
Adding the code here (server and client). (:
Nice!
No one is gonna read all that. Can you explain what your code does and then share a minimum code example and also be more specific
Hello, I have a bad request with django when I try to log on with angular. Is Anyone know how to fixe it?
https://paste.pythondiscord.com/iyarikegam.py - server.py
https://paste.pythondiscord.com/aqekuwitot.rb - client.py
I created a chat of an unlimited number of people using threads and sockets.
In server.py I created 2 lists the first one contains the names the customers chose for themselves and the second one contains the customer details like port and the rest.
Later, I created several functions, the first of which is called broadcast receives a message and sends it in a chat with the name of the person who sent it.
The second one named CaesarEncrypt encrypts the message (it is unrelated).
The third named HandleClient requests a message from the client and sends it to broadcast, if the message is not received it deletes the client's details from the 2 lists and closes the client.
The fourth named recive receives the client for the first time and adds its details to the lists and of course prints a message that a new client has connected to the server.
In client.py I did all the construction of the chat using Tkinter and it works fine as usual.
Now what I want to do is create a chat manager that will work like everyone else on the server but when he enters the command /admin 5270 for example then it will buy him manager capabilities and he will be able to take people out when he writes /kick and the client name next and it will close that chat And will be registered in the chat "The client (name) has been removed from the server".
@native tide i disagree
bit of a long shot, but does anyone have experience with shibboleth sp 3?
which part of it?
Got the first part ajax
ajax what?
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from .models import Choice, Question
# ...
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))```
This is damn hard
which line makes you stuck?
Try
is it possible to provide links from the stack .. ?
I wanted to know how I can save a photo that will contain a watermark. Currently grabs a photo from the form and creates a watermark on it, but saves it separately. More precisely, I would like the photo I send in the form to be processed and saved.
hello so, my problem is following:
this is the page I have made so far
from flask import Flask,render_template,request
from random import randint
app = Flask(__name__)
@app.route('/random')
def random_page():
return render_template('random.html',the_title = 'Random Generator')
if __name__ == "__main__":
app.run(debug=True)
``` this is the flask code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ the_title }}</title>
<link rel="stylesheet" type ='text/css' href="{{ url_for('static', filename = 'style.css') }}">
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
``` this the base html code
{% extends 'base.html' %}
{% block content %}
<div class="random-page">
<form method="POST" action="search">
<table>
<h1>Random Number Generator</h1>
<tr>
<td>Min:</p>
<td><input type="number" name="range_start" width="30"></td>
</tr>
<tr>
<td>Max:</td>
<td><input type="number" name="range_end" width="30"></td>
</tr>
</table>
<p><input value="Generate" type="SUBMIT"></p>
<h1>{{ the_result }}</h1>
</form>
</div>
{% endblock %}``` and this is the code of the page I have shown you
so according to the screen, I want to make a random number generator, the problem is that when I try to do so, I get an error which I don't understand at all
so in order to grab the value of the input, I did following
@app.route('/random',methods = ['POST'])
def random_page():
range_start = request.form['range_start']
range_end = request.form['range_end']
result = randint(range_start,range_end)
return render_template('random.html',the_title = 'Random Generator',the_result = result)
after the implementing of this code, I get this
ik its a lot of code but it was just for clarity, overall its not a big problem, I just don't know where I make the mistake
pretty sure it refers to the 'POST' method...
if request.method == 'POST':
form_w = ImageForm(request.POST, request.FILES)
if form_w.is_valid():
# form = form_w.save(commit=False)
cd = form_w.cleaned_data['img']
im = Image.open(cd)
width, height = im.size
draw = ImageDraw.Draw(im)
text = "TEST WATERMARK"
font = ImageFont.truetype('arial.ttf', 36)
textwidth, textheight = draw.textsize(text, font)
# calculate the x,y coordinates of the text
margin = 10
x = width - textwidth - margin
y = height - textheight - margin
# draw watermark in the bottom right corner
draw.text((x, y), text, font=font)
print('Before saving: ', im)
im.save('Luki/media/upload_p/{}'.format(cd))
img = Image.open(('Luki/media/upload_p/{}'.format(cd)))
print('After saving: ', img)
form_w.instance.save()
return redirect('Luki:gallery')
else:
form = ImageForm()
return render(request, 'Luki/upload_img.html', {
'form': form,
})```
I wanted to know how I can save a photo that will contain a watermark. Currently grabs a photo from the form and creates a watermark on it, but saves it separately. More precisely, I would like the photo I send in the form to be processed and saved.
I was going to say you didn't setup the POST method on your view function but then I read that
wait, just try to restart the flask server
It should work otherwise
I have a headache already man xd idk what is wrong to fix
just restart
maybe because you made the change and saved, but it's still running on that first one
tell me if it works
I'll check it out
from flask import Flask,render_template,request
from random import randint
app = Flask(__name__)
@app.route('/home')
@app.route('/')
def home_page():
return render_template('home.html',the_title = 'Home')
@app.route('/random',methods = ['POST'])
def random_page():
range_start = request.form['start']
range_end = request.form['end']
result = randint(range_start,range_end)
return render_template('random.html',the_title = 'Random Generator',the_result = result)
if __name__ == "__main__":
app.run(debug=True)
{% extends 'base.html' %}
{% block content %}
<div class="random-page">
<form method="POST" action="random">
<table>
<h1>Random Number Generator</h1>
<tr>
<td>Min:</p>
<td><input type="number" name="start" width="30"></td>
</tr>
<tr>
<td>Max:</td>
<td><input type="number" name="end" width="30"></td>
</tr>
</table>
<p><input value="Generate" type="submit"></p>
<h1>{{ the_result }}</h1>
</form>
</div>
{% endblock %}```
motherfckers, advertise the websites and then run away
why did you name your action random again
lol
what if you change the action to "."
idk exactly to be honest but, I want those values to pass to this function, so I can generate a random number in between
I tried but with that I get another error
what was that
so wait lemme try
here,keep the POST?
you mean like this?
no
k so I think this is where you're going wrong
range_start = request.form['start']
let's start from here
Hey, i'm trying to use border-radius on an image and it will only round the bottom left and right corners and not the top left or right... Anyone know what could be causing this?
lemme check
I cheched
I tried the following now
from flask import Flask,render_template,request
from random import randint
app = Flask(__name__)
@app.route('/home')
@app.route('/')
def home_page():
return render_template('home.html',the_title = 'Home')
@app.route('/random',methods = ['GET','POST'])
def random_page():
range_start = request.form.get('start')
range_end = request.form.get('end')
result = randint(range_start,range_end)
return render_template('random.html',the_title = 'Random Generator',the_result = result)
if __name__ == "__main__":
app.run(debug=True)
{% extends 'base.html' %}
{% block content %}
<div class="random-page">
<form method="POST" action="{{ url_for('random_page')}}">
<table>
<h1>Random Number Generator</h1>
<tr>
<td>Min:</p>
<td><input type="number" name="start" width="30"></td>
</tr>
<tr>
<td>Max:</td>
<td><input type="number" name="end" width="30"></td>
</tr>
</table>
<p><input value="Generate" type="submit"></p>
<h1>{{ the_result }}</h1>
</form>
</div>
{% endblock %}
I saw it on herehttps://www.geeksforgeeks.org/retrieving-html-from-data-using-flask/
but I think it returns none, see
@ivory bolt
wut