#web-development
2 messages ยท Page 172 of 1
module error epic thing is my app name is playground
so it is adding that as module not found error
You do know that vscode has in built Django debugger?
yes
line number 6
i used it too
Thanks it worked but in documentation is mentioned as one of the way to enable token authentication REST_FRAMEWORK = {}
https://django-debug-toolbar.readthedocs.io/en/latest/installation.html
hmm, what is it debugging then?
why this thing is superrior to standard debug?
i don't know
Django Tutorial for Beginners - Learn Django for a career in back-end development. This Django tutorial teaches you everything you need to get started.
- Get the complete Django course (zero to hero): https://bit.ly/3A7l7qj
- Subscribe for more Django tutorials like this: https://goo.gl/6PYaGF
Other resources:
Python Tutorial for Beginners: ht...
I thought there is no better debug than unit testing
erm, ok. probably something I don't know then
@inland oak :in settings disable auth
REST_FRAMEWORK = {} disabling works but what if i want to test it using the authentication token enabled
write unit test
which uses django rest framework test api client
or you could even test with request library, if test api client will be bypassing authentication
testing in postman is highly unefficient, unproductive and slow method ๐
it has its uses from time to time though
Ok I am working with django-admin and have a situation where I want to create Model A and Model B (which has a OtO relationship with Model A) using the same django-admin page. So I have a ModelAdmin for ModelA that has an inline for ModelB. But when I hit save Nothing is created for ModelB...
I dug around a bit, and it looks like I might have to overwrite save_formset but I am having trouble getting the data from the inline form from formset so I can actually use it.
ok
where can i learn django channels?
Hello guys, i kinda need a little help, i'm working on a tool with flask, and i splited my webpage into 2:
-nav bar and form
-datatable and search bar which i load via a javascript function
The probleme is i dont know how to send datafrom the form to flask without reloading the page, then i load the datatable ?
Or how can i also get data into my js script from the form before the page reload or redirect ?
read the stream encode it to base64 then in the html use
<img src="data:image/png;base64, {{ encoded_image }}">
use fetch in javascript
is it usable twice without reloading the page ?
yes
Thanks i'll check it out !
@naive blaze something like this:
<form id="the_form">....</form>
<button onclick="update_view()">Update View</button>;``` ```js
function update_view(e){
e.preventDefault();
const form = new FormData(document.getElementById("the_form"));
fetch("/update_view", { method: "POST", body: form })
.then((response) => response.json())
.then((data) => update_the_page_with(data));
}``` ```py
from flask import jsonify
@app.route("/update_view", methods=["POST"])
def update_view():
new_data = do_something_with(request.form['param1'])
return jsonify(new_data)```
@dapper lichen in your case the update_view() does not reload the page ?
or it will just show an empty page with the new data ?
no, it just returns some json data (assuming new_data is a dict)
you update only what you want with some "update_the_page_with" JS function
@naive blaze updated above
Yes got it ! my html page is bit more complicated but i'll try to fit it in
The page i need to update the data in is loaded via javascript
function load_home() {
document.getElementById("table_div").innerHTML='<object type="text/html" data="compact-table.html" style="width: 1810px;height: 1500px;" ></object>';
}```
fair enoguh
Getting the following error
Access to XMLHttpRequest at 'http://127.0.0.1:8000/v1/Location/' from origin 'http://localhost:4200/' has been blocked by CORS policy: Request header field access-control-allow-methods is not allowed by Access-Control-Allow-Headers in preflight response.
Added the cors in django
@sick glacier what have you done to solve this error?
CORS_ORIGIN_ALLOW_ALL = True i have added this
in settings.py file
@opaque rivet : And also added this to middlewar
e
'corsheaders.middleware.CorsMiddleware',
@sick glacier CORS_ALLOW_ALL_ORIGINS = True
Follow official docs, your variable isn't there at all, how'd you come across that?
could somebody who is a little advanced in django help me out with a problem pls
uhh im not sure whats wrong here
it used to work but then i left it for a while and when i come back it doesnt work
the databases do exist and are registered
the database itself works it just keeps giving me the same warning
Is this the right channel for noob setup questions for django?
not sure
if you are a begginer i suggest you watch a tutorial
tech with tim made a great one its 3 hours long but worth watching
I did. Can't find what I did wrong
django is quite complex
Im stuck on creating views
Lol
Well the tutorial I used was the Django docs. Is there a better tutorial?
I am new to node .I have done some small projects in node but my company is using mysql as db.
Can anyone advice me any good project or resouce where I can learn about how to visualise and structure data in sql db and how sql db works like association and SP.we use sequelize ORM.
Need guidance.
Thanq so much.
mosh hamdani courses are great
when I started it helped
you can find him on youtube as well
Flask Code
import base64
@app.route('/', methods=['GET', 'POSTT'])
def index():
if request.method == 'POST':
files = ...
transferable_files = map(lambda file: base64.b64encode(file.read()).decode(), files)
return render_template('index.html', files=transferable_files)
HTML Code
{% for file in files %}
<img src="data:image/png;base64, {{ file }}">
{% endfor %}
just a rough markup on how i did it
make sure your files are open with rb mode
Anyone use Django on windows? I'm stuck on this django-admin not recognized command issue?
did you install django via pip?
yeah
check your environmental variables, and in PATH, look for django-admin.py
I've been trying to add the django-admin.py path to command line on Windows 7.
I have tried to do it this way:
C:>set django-admin.py = C:\Python27\Scripts\django-admin.py
But cmd told me t...
Yeah im not sure exactly what that means i went there but the stuff he says is already there
did you try refeshenv?
yeah nothing
Try reinstalling django
And make sure you're not in a venv
ummm... i need help with some code, but it is in javascript. does anyone know the javascript discord server?
https://discord.gg/E79BzmsS for the SpeakJS discord server
i have a webapp that uses selenium to open a web browser for users to authenticate a 3rd party app. everything works great locally, but obviously when i push to my Linode server (which is headless), the web browser doesn't open. does anyone have any pointers on how to properly implement this on a web server?
If have a api and a app folder where do I put the git repo locally?
u can download github desktop
github desktop will let u do the job easily
hmm never used it
Does anyone know how to make a token without accessing a route
For example in my application of two types of user. Client user and admin user. both the client token and the ADM token are able to access all end-points
How do I make the client's token not be authorized in the user's route
simple
JWT tokens allow storing dicts jsons in it
{
"admin": true
}
just store in it
and make a decorator that extracts this information and forbids non admins
@admin_only
I'm using Flask
I'm doing it like this: create_access_token(identity=cli.cli_id,fresh=False, expires_delta=timedelta(days=90))
@inland oak
what's inside create_access_token function
Hi @humble vortex I just found your message I noticed that sergeyklay has made his own release, please let me know when you see this message. I'd like to prevent having too many "same packages". One of the options I can think of right now is to move your project under https://jazzband.co/
I'm trying to follow a Django tutorial that uses 2.0.7 (FreeCodeCamp/CFE) and I want to use the static files I already have. html, css and JS.
When following this tutorial https://www.youtube.com/watch?v=RhJIMUMJ_Do I can't seem to make it work.
Hey ninjas, in this django tutorial I'll explain how we can set up our django project to use static files such as images, css and JavaScript files.
DONATE :) - https://www.paypal.me/thenetninja
----- COURSE LINKS:
- Python tutorials - https://goo.gl/xD2AvX
- Course files - https://github.com/iamshaunjp/django-playlist
- Django docs - https://...
home.html
<link rel="stylesheet" href="/static/css/main_tailwindPost.css">
urls .py
urlpatterns += staticfiles_urlpatterns()
settings.py
STATIC_URL = '/public/'
NetNinja tut
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'public'),
)
Chrome Console:
main_tailwindPost.css:1 Failed to load resource: the server responded with a status of 404 (Not Found)
But in Sources I can clearly see the correct file tree, static/css/ and .css files but they are blank.
I copied this text from another discord. Thought the formatting would persist. Can't seam to add the ticks on mobile easily. Sorry about that
have any one used python flask as backend for their javascript project?
guys anyone have experience with AIORTC?
it has very less resources on the internet
i have a couple of questions to ask
your STATICFILES_DIRS is set to public, so you'll have to use <link rel="stylesheet" href="/public/css/main_tailwindPost.css">
I recommend changing STATICFILES_DIRS to "static" tho
I have tried that. But I can try again
I'm used to public from NodeJS
Yeah I've read the docs for v2
They are much much easier to understand than python docs, but still not easy.
are you using django 2?
Yes
if youre learning django might as well learn a version thats gonna work
I prefer following a good tutorial.
Can't imagine everything about django changed from v2 to v3
Did run into a sqlite3 backwards compatability issue on my first attempt though. But managed to find a working solution on Stackoverflow
Have only had like two hours of sleep. Daughter kept having nightmares, so I might respond accordingly
all good tutorials for django 2 are now bad
django 2 has security vulnerabilities
how to upload images on server (django application ) which is hosted on heroku ?
Any knows how to make my website online from local host (Deployment)
Fast plz i have only some minutes
you might post forward the port with your router... also make sure to turn off the debug mode.
hi! anyone from front end here?
yeah do you need some help ?
thanks but I don't need any help just need to know if any
oh alright
hmmm
flask_jwt_extended. create_access_token ( identity , fresh = False , expires_delta = None , additional_claims = None , additional_headers = None )
identity โ The identity of this token. It can be any data that is json serializable. You can use user_identity_loader() to define a callback function to convert any object passed in into a json serializable format.
just store into identity more than just id, a whole dictionary of additional information
{
"id": id,
"admin": True
}
In flask virtual environment, I am getting below error: from markupsafe import escape
ImportError: cannot import name 'escape'
I get it . I am going to try
Can someone please help me with that?
Hello, I want to create user-specific bootstrap offcanvas in django, does anyone know how I can go about that?
you can store relevant data in database about it. in anyway you need.
@rotund minnow You're trying to import something that doesn't exist or is maybe misspelled?
consider it like a user specific page for eg - dashboard of which the url pattern is mostly like int:id.. so the same thing but as in offcanvas. Hope that makes sense..
you can store your whole pages in database if you wish.
no idea what you have there to help you more.
is it possible to run python scripts & display charts in wordpress? For example, I've got a short 18 liner that uses pymssql and matplotlib.pyplot and would like to display it on my wordpress page.
can you add a little bit of javascript code to your wordpress frontend?
that shouldn't be an issue
do you need inputing variables
to rqeuest display charts?
well, probably yes, nvm.
what i'd like to do is run a ms sql server query and display the results in my chart. Possibly pass variables yes.
make in python API web framework exposed API end point
which you can request with GET or POST request (whatever you need, the difference is little)
you will call it with javascript, while inputing necessary variables
i'd need to set-up a python API endpoint first
it will activate python script to call your sql for server query
and as result, saving it into image
and give link to it in API answer ;b
sheesh that is way over my head, lol
that's actually quite simple. it just sounds hard.
mm
you need some simple framework to get started like Flask
I have pycharm that I use for python dev
any library to make sql server request, in raw SQL or ORM (whatever you prefer)
I need to set-up a python server, first, right?
yeah
@dense slate I just installed flask in my virtual environment. It automatically installed markupsafe and related code to import 'escape'
np
Thank you man!
I'm going through a secondary Django tutorial and I've been using Django to create a new app so I can follow a tutorial where the author is creating drop-down menus for a site.
However, I'm having trouble with a simple import statement
This is my directory structure
I created an app called testing within the project dropsite
within urls.py I'm trying to import the contents of dropsite.testing.views but I get errors when I try the python manage.py migrate command
My error is ModuleNotFoundError: No module named 'dropsite.testing'
This is how I'm trying to import my views, but I've clearly bungled it
This may not be web-development specific, but i'm using Django to create the app and I'm new to it. How would you guys recommend I fix my import command to get the classes within views
did you add your app into INSTALLED_APPS? Also, it may be an issue having dropsite as a dir within the dropsite dir, maybe it's a naming issue.
That was another issue
I have since figured it out, thankfully ๐
Sorry I didn't post here
I'm very new to web including Django and HTML
nice, keep it up ๐
My goal in the near-term (this week) is to create a very very basic site that I can run locally
all it will have is drop-down menus with selections, and then a button that says "run" so I can do some work behind the scenes and then display a graph
sounds good
But I also know zero HTML
Is there a resource that allows you to modularly build HTML?
For instance just stacking input forms or am I thinking down the wrong path with regard to creating the Django app?
well, HTML modular-ly builds your page. I'd recommend you just learn it, it's quite simple and compared to python doesn't take long to learn.
Gotcha
Aside from "Google: how to create input forms with HTML" is there a decent place to start?
I guess I also need to look more into Django forms to understand how they fit in with everything
Like if I can splice Django forms with other elements
its different for everyone, but I prefer courses where you do projects and learn by doing... I recommend codecademy's html course and iirc it's free
That sounds good
and yeah you can also use django forms, it's just a way to produce HTML forms with python
Ah
That would probably be easier to pick up
I was just looking at this example form
from django import forms
from .models import Person, City
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ('name', 'birthdate', 'country', 'city')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['city'].queryset = City.objects.none()
if 'country' in self.data:
try:
country_id = int(self.data.get('country'))
self.fields['city'].queryset = City.objects.filter(country_id=country_id).order_by('name')
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['city'].queryset = self.instance.country.city_set.order_by('name')
It seems relatively intuitive, but it has some database terminology that Django utilizes which is a little new to me
@sly adder netninja always has a great tutorial
There's this too https://youtube.com/playlist?list=PL4cUxeGkcC9g5_p_BVUGWykHfqx6bb7qK
Doesn't use any css framework IIRC
I think I can do most of what I want with Django forms then I'll have to figure out a way to generate and display a graph based on data
I'm new to django too.
yeah, Django has somewhat of a learning curve
Well I've used sqlite databases in projects before
But I've done everything so manually that this just sort of blows my mind
@glossy arrow how long have you been using Django?
I haven't done much Django really, I read through the tutorial, and I did a few stuff with it, but I prefer frameworks like FastAPI or Starlette
Ah gotcha
Anyone successfully deployed a JustPy web app? My impression has been that creating the app is easy but deploying it not so much.
Hi,
flask is not showing post request data
@app.route("/register", methods=["POST"])
def web_register():
if request.method == "POST":
print(request.data.decode('UTF-8'))
return "OK"```
prints nothing
File ".\core\users\login.py", line 22, in login_user
db_user = crud.get_Login(
File ".\api\crud.py", line 39, in get_Login
db_user.password.encode('utf-8'))
AttributeError: 'bytes' object has no attribute 'encode'
I got this error relate to Base64 on my crud
This is my core\users\login.py :
@router.post("/login")
def login_user(user: schemas.UserLogin, db: Session = Depends(get_db)):
db_user = crud.get_Login(
db, username=user.username, password=user.password)
if db_user == False:
raise HTTPException(status_code=400, detail="Wrong username/password")
return {"message": "User found"}
and api\crud.py :
def get_Login(db: Session, username: str, password: str):
db_user = db.query(models.UserInfo).filter(
models.UserInfo.username == username).first()
print(username, password)
pwd = bcrypt.checkpw(password.encode('utf-8'),
db_user.password.encode('utf-8'))
return pwd
I tried this solution and nothing work
https://stackoverflow.com/questions/36228117/attributeerror-bytes-object-has-no-attribute-encode-base64-encode-a-pdf-fi
I am trying to base64 encode a pdf in python. Several SO answers to this worked for other people but not on my end for some reason. My most recent attempt is:
http://stackoverflow.com/questions/
you decode bytes and encode strings
why it is not showing?
@ that point you might want to consider JS
`127.0.0.1 - - [14/Jul/2021 14:11:11] "POST /tasks HTTP/1.1" 500 -
127.0.0.1 - - [14/Jul/2021 14:11:11] "POST /register HTTP/1.1" 200 -`
For displaying graphical data?
yes
showing post request but not the data
Good to know
I still have other issues pre-graphical data display
Like right now I can't get my model choices to populate in a drop down menu
๐ข
inspect the request
and verify that there actually is data in the body
that should be p simple
Yeah
are you using ModelForm
I have all the choices defined in models
Yes
But quite honestly I don't understand the structure of ModelForm
you want a ChoiceField
Honestly just input some very basic personal data
Right now it's simply Name / Age / Race
Building off this HR input form example
then Select should be fine
So I will say that I don't understand the structure and I'm not very knowledgeable on super().__init__() calls like this example used
So I tried something as simple as this
from django import forms
from .models import Person, Race, Age
class PersonForm(forms.ModelForm):
model = Person
fields = ('name', 'race', 'age')
name = forms.CharField(max_length=100)
race = forms.Select(choices=Age.AGE_RANGES)
age = forms.ChoiceField(choices=Race.RACE_CHOICES)
Sorry, one moment.
This was my forms definition, but it didn't create anything because it says I have no model class defined
Then I converted it to this structure, though I can't say I know 100% what the def __init__() and accompanying super() call are accomplishing here.
from django import forms
from .models import Person, Race, Age
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ('name', 'race', 'age')
name = forms.CharField(max_length=100)
race = forms.Select(choices=Age.AGE_RANGES)
age = forms.Select(choices=Race.RACE_CHOICES)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
first Python project?
nope, but this is my first foray into anything remotely web
what do you do normally
it is
Desktop engineering / numerical analysis automation
i made the program and using httpsendrequestW
Django forms allow you to create basic forms and validation of data which interface well with your models... It just saves time making a form w/ validation in your view or having validation on clientside with JS.
i printed the buffer before sending andit sends
do you work with classes normally
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
this does nothing
there's no need for:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
unless you're going to add some extra logic in the __init__
Sorry I thought I had that commented out
That was from the example
from django import forms
from .models import Person, Race, Age
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ('name', 'race', 'age')
name = forms.CharField(max_length=100)
race = forms.Select(choices=Age.AGE_RANGES)
age = forms.Select(choices=Race.RACE_CHOICES)
This is what I had
I selected too much
And yes I deal with defining classes, class inheritance, and utilizing class structures to create separate modules, etc.
I'm certainly not an expert, most of my class definitions and program structures are probably relatively simple.
So this is what I get with this selected,
But my choices aren't being populated
It's just the initial placeholder value of "--------"
can you show us what Age.AGE_RANGES is
Sure
I'll just show you my models definitions
from django.db import models
# class for defining the race model as an input form with beginning set of limited choices
class Race(models.Model):
RACE_CHOICES = (
("B", "Black"),
("H", "Hispanic"),
("W", "White"),
("O", "Other")
)
name = models.CharField(max_length=20)
race = models.CharField(max_length=1, choices=RACE_CHOICES)
def __str__(self):
return self.name
# class for defining the age model as an input form with comprehensive age list
class Age(models.Model):
AGE_RANGES = (
("1", 'Less than 21'),
("2", '21, 25'),
("3", '26-30'),
("4", '31-35'),
("5", '36-40'),
("6", '41-50'),
("7", 'Greater than 50')
)
name = models.CharField(max_length=20)
age_range = models.CharField(max_length=1, choices=AGE_RANGES)
def __str__(self):
return self.name
# Person class defining a model comprised of the other models for the database relationship using
# Foreign Keys for Age and Race
# --> This section will be expanded as new variables are progressively added.
class Person(models.Model):
name = models.CharField(max_length=100)
race = models.ForeignKey(Race, on_delete=models.SET_NULL, null=True)
age = models.ForeignKey(Age, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.name
that is my entire models.py file
I don't quite understand the queryset " A QuerySet of model objects from which the choices for the field are derived and which is used to validate the userโs selection. Itโs evaluated when the form is rendered.
"
Or is that just the choices?
Oh actually might be the wrong field, queryset is just a list of your database entries. I don't think that's what you want
hmm, everything looks right to me
Yeah I also don't understand why ChoiceField isn't applicable here
Do you need to see my views at all?
or the HTML templates ?
ChoiceField is applicable
Right
But it still doesn't change the output of the dropdown
Which must mean that something else is incorrect with how I've defined views or templates, right?
hmm, the only thing I'd say is that the fields you specify shouldn't be in the Meta class, not sure if that makes a difference though... Apart from that I don't know what could be the issue, I also don't know how django forms represents foreignkeys.
Should it matter if they are foreignkeys though?
I can try to move my field definition elsewhere
I may be wrong but yeah I think it would be an issue... the foreignkey just represents a relationship to another table, it doesn't really give any information about which column you want to mimic as a form field
maybe it would be easier scrapping the ModelForm and just building a normal form.
This was the functional form in the example
from django import forms
from .models import Person, City
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ('name', 'birthdate', 'country', 'city')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['city'].queryset = City.objects.none()
if 'country' in self.data:
try:
country_id = int(self.data.get('country'))
self.fields['city'].queryset = City.objects.filter(country_id=country_id).order_by('name')
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['city'].queryset = self.instance.country.city_set.order_by('name')
Of course this accomplishes more on the city and country fields
And this gave functional dropdowns
But I've tried to modify the variables that I'm attempting to collect from the user and progressively redefine the models, views, forms, etc.
do you have the source code for the Person model?
the one from that example
Sure, I can copy it but it's all here https://github.com/sibtc/dependent-dropdown-example
class Person(models.Model):
name = models.CharField(max_length=100)
birthdate = models.DateField(null=True, blank=True)
country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True)
city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.name
So their dropdown selections were city and country which were both ForeignKey's
Ok, so turns out Foreignkeys are represented by django.forms.ModelChoiceField so you can give them a queryset (a list of database entries) for the user to pick
but in your case you just want the user to pick a choice, right?
Yes
I just wanted all selections to be available
And to select. I know it's dumb that I choice a more involved drop-down menu Django example and tried to manipulate it to suit my purposes
if you're using a ModelForm you can also hop into the python terminal, initialize it and repr(form_object) to see its fields
Ok, so have you saved any db entries into your other models?
Yes
two
Just have dummy names right now because after migrations I have not been able to get my fields displayed correctly and I stripped all of the existing fields that the example utilized
hmm, so I don't think the ModelForm will suit you then. Person has Foreignkey fields which are django.forms.ModelChoiceField and you'll have to pass a queryset attribute to give it choices to pick from (but these are queryset - the user picks entries in the db which isn't your use-case)
Honestly I would just build a normal form with choicefields
Ok
nice and simple
So scrap ModelForm all-together?
yeah, I think the form should be simple enough to just use forms.Form
with a few choicefields
Getting some errors after I redefined my forms to this
from django import forms
from .models import Person, Race, Age
class PersonForm(forms.Form):
model = Person
fields = ('name', 'race', 'age')
name = forms.CharField(max_length=100)
race = forms.ChoiceField(choices=Age.AGE_RANGES)
age = forms.ChoiceField(choices=Race.RACE_CHOICES)
return form_class(**self.get_form_kwargs()) TypeError: __init__() got an unexpected keyword argument 'instance'
now I think it's my views
from django.views.generic import ListView, CreateView, UpdateView
from django.urls import reverse_lazy
from .models import Person
from .forms import PersonForm
class PersonListView(ListView):
model = Person
context_object_name = 'people'
class PersonCreateView(CreateView):
model = Person
form_class = PersonForm
success_url = reverse_lazy('person_changelist')
class PersonUpdateView(UpdateView):
model = Person
form_class = PersonForm
success_url = reverse_lazy('person_changelist')
So you're saying remove model and form_class in each view class here?
just remove:
model = Person
fields = ('name', 'race', 'age')
from the form
Hi,
it is working
but seems like it is kind of race condition
@app.route("/register", methods=["POST"])
def web_register_beacon():
if request.method == "POST":
print(request.data.decode('UTF-8'))
return "REGOK"
@app.route("/tasks", methods=["POST"])
def web_task_beacon():
print(request.data.decode('UTF-8'))
return "STL dir"```
removed this, but I think my views are the issue.
the program send data to register and receive response and then quickly send to /tasks
same issue?
but when i remove print(request.data.decode('UTF-8')) in web_task_beacon()
the first function doesn't print anything
Yes, but editing the view classes modify the error
More specifically I think that the PersonUpdateView() may be to blame
i removed the print from second function and first function is not printing anyting, same happen with second function
if i remove print from first function, 2nd function doesn't print anything
because it is single-threaded?
it is printing when i add this line: jdata = request.get_json(force = True)
good evening
Someone help me. I recorded image in postgresql, in binary format. But I don't know how to return the user to the image format
Are you saving the image to the file system?
Wdym "recorded image in postgresql"?
Does anyone know what is a good way to host a flask server? I was interested in hostinger shared hosting, but their shared hosting doesnt support python. Does anyone know if their cloud hosting (https://www.hostinger.com/cloud-hosting) does? Or should I use something like digital ocean?
Im fine with using vps' I just want something powerful and scalable, with a nice UI (preferably)
I recently deployed a Flask app using AWS App Runner. It's a pretty stripped down version, so it's easier to use. It can deploy a container or create one for you from a GitHub repository. You can manage it from the AWS website. Probably also works through CLI but I never bothered setting that up.
A similar service would be Google Cloud Run. These work well if you only have one app you need to deploy and you don't need a lot of detailed configuration.
a silly question but would you prefer mdbootstrap templates or from colorlib?
if you don't want to spend money.
Im fine with spending money on a server
So dumb it down a little i'm new to web development, AWS app runner can deploy containers, and is managed like an AWS server?
What does CLI mean
Sorry like I said im new to web development
I know how flask and WSGI works but other then that I don't know much to do with deployment
CLI = command-line interface i.e. a tool you interact with through your terminal/command prompt as opposed to a GUI (graphical user interface, such as the AWS website)
Yes, AWS App Runner is managed. You just give it a container and it takes care of pretty much everything else. It can automatically deploy for you when your code changes. It performs health checks. It can automatically scale up the number of instances running. It load balances for you. There's probably more stuff I am missing.
If you didn't know, by container I mean like a Docker container.
And if you're daunted by Docker containers, they have an alternative where you just give them a GitHub repository and it will create a container for you.
Ah ok, I anyways prefer using GUI for the most part anyways so thats fine, or I use SSH
Thats good for simplicity thanks
Sounds good
Thanks for the help
It also gives you a domain (though not a pretty one)
You can of course add your own domain if you have one
Yeah i'll probably just buy one
I know Google Cloud Run is a similar service, so look into that too. Compare pricing, etc.
I am not familiar with all the options out there. I'm sure there's a lot more competition.
Google has pretty competitive pricing, but so does amazon so im sure its not a huge difference
that wasn't the question
i cant delete from my django rest api, DELETE request give me response status 200 and the Cross-Origin Request Blocked error, but i already have it in my project, post and get works fine
What they wrote was a separate question. It wasn't being directed towards you.
Ahh sorry
Im so sorry
Got confused
So wait are you asking?
Colorlib is good for wordpress
Thats sorta what it was made for
mdbootstrap has templates? I thought it was more of an addon to bootstrap with extra components, plus the theme of course. Also, where are colorlib's free templates?
If u go on their website they have free ones but they're only wordpress
They have some they claim are for any website here https://colorlib.com/wp/templates/ but I don't know which are free
https://colorlib.com/wp/themes/ <--- Free themes, but they say WP themes
Oh I didn't know they existed
But yeah those arent free
A guide for how to ask good questions in our community.
??
Has anybody encountered issues with JWTs?
Auth-wise they work fine
With session it starts being a problem
I'm using Django Simple JWT to generate them
And NextJS + next-auth to store them
**
{% for cat in category%} {% if cat.parent == None %} <li class="nav-item"> <a class="nav-link d-sm-inline-block" href="{% url 'category' cat.slug %}">{{cat.title}}</a> {% if cat.children.all %} <ul class="navbar-nav mr-auto"> {% for cat in cat.children.all %} <li class="nav-item"> <a class="nav-link d-sm-inline-block" href="{% url 'category' cat.slug %}">{{cat.title}}</a> </li> {% endfor %} </ul> {% endif %} </li> {% endif %} {% endfor %} **
The title of link "Is anyone here good at Flask / Pygame / PyCharm?"
the text
There are two problems with this question:
This kind of question does not manage to pique anyone's interest, so you're less likely to get an answer overall. On the other hand, a question like "Is it possible to get PyCharm to automatically compile SCSS into CSS files" is much more likely to be interesting to someone. Sometimes, the best answers come from someone who does not already know the answer, but who finds the question interesting enough to go search for the answer on your behalf.
When you qualify your question by first asking if someone is good at something, you are filtering out potential answerers. Not only are people bad at judging their own skill at something, but the truth is that even someone who has zero experience with the framework you're having trouble with might still be of excellent help to you.
So instead of asking if someone is good at something, simply ask your question right away.
The point is that asking 1. Can I get help or Is someone good at X? is pointless. it takes time and attention. Like now I had to explain to you why you got the reply you got.
Hello everyone i have bug for show the children's category in page
what specifically do you need help with?
#web-development message
Seems like there's a mismatch between the expiration date on the token on Django and the one I fixed on NextJS
Isn't there a way to communicate the expiration date in the response?
Technically tokens have their expiration date embedded in them
How are you generating the tokens?
Using Django Simple JWT. The original response is a JSON with the access and refresh tokens.
curl \
-X POST \
-H "Content-Type: application/json" \
-d '{"username": "davidattenborough", "password": "boatymcboatface"}' \
http://localhost:8000/api/token/
...
{
"access":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiY29sZF9zdHVmZiI6IuKYgyIsImV4cCI6MTIzNDU2LCJqdGkiOiJmZDJmOWQ1ZTFhN2M0MmU4OTQ5MzVlMzYyYmNhOGJjYSJ9.NHlztMGER7UADHZJlxNG0WSi22a2KaYSfd1S-AuT7lU",
"refresh":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImNvbGRfc3R1ZmYiOiLimIMiLCJleHAiOjIzNDU2NywianRpIjoiZGUxMmY0ZTY3MDY4NDI3ODg5ZjE1YWMyNzcwZGEwNTEifQ.aEoAYkSJjoWH1boshQAaTkf8G3yn0kapko6HFRt7Rh4"
}
can someone guide me on how to get started with building web applications in python..? the only modules I know to use are tkinter and pyautogui as of now
Can you check if the jwt is correct from http://jwt.io?
The payload looks like that:
{
"user_pk": 1,
"token_type": "access",
"cold_stuff": "โ",
"exp": 123456,
"jti": "fd2f9d5e1a7c42e894935e362bca8bca"
}
Doesn't the expiration look incorrect?
It looks incorrect to me
Maybe there's some additional Django simple jwt setting to configure time
There's something in the settings yeah
decode and use json.loads ig
Hello
Im getting this error while trying to dockerize my project:
Is the server running on host "localhost" (127.0.0.1) and accepting
app_1 | TCP/IP connections on port 5432?
app_1 | could not connect to server: Cannot assign requested address
app_1 | Is the server running on host "localhost" (::1) and accepting
app_1 | TCP/IP connections on port 5432?
version: '3'
services:
app:
build:
context: .
ports:
- "8000:8000"
volumes:
- .:/app
command: >
sh -c "python3 manage.py migrate &&
python3 manage.py runserver"
env_file:
- ./.env
depends_on:
- db
db:
image: postgres:10-alpine
env_file:
- ./.env
volumes:
- pgdata:/var/lib/postgresql/data
redis:
image: redis:alpine
celery:
restart: always
build:
context: .
command: celery -A todo worker -l info
volumes:
- .:/app
env_file:
- ./.env
depends_on:
- db
- redis
- app
volumes:
pgdata:
This is my docker-compose.yml file
and here is my database config in settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'HOST': config('DB_HOST'),
'NAME': config('DB_NAME'),
'USER': config('DB_USER'),
'PASSWORD': config('DB_PASS'),
}
}
any ideas?
i have learned django from docs then made some proj like todo app contact page app blog app auth system img system and some stuff what should i do now how can i go to more advanced in django, should i learn django rest framework or should i learn more stuff in django like google maps api system payment system
Maybe do an app which allows you to add restaurants on a map and it has stripe payment system. That's pretty advanced.
someone told me
making these payment api
google maps api
and stuff
is ez in django rest framework
If you want to, then do it
i can render i can make db i can render images i can do many things but umm how will i
make a gateaway
that if payment ==done
then only
add info to db
or then only pass to form
that would be trouble and hard
and maps seems insane lvl hard
There's a lot of tutorials for that on youtube, blogs, documentations ect
hi , can any one help me with email sending from django issue ?
Make progress little by little and you'll figure it out I am sure
ohh i have done corey schafer's playlist and docs that begginers 10 part and Clever programmer 8 hrs vid
hmm
it will take time for sure but
i can do ig
I can't do most advanced stuff but I am getting there
ok so tell me who structure how and what i am making so ill write it somewhere and pin
no issues u r better them me ofc , u know django rest framework
Only way to learn is to get going and trying to make stuff
..
I think you are at the point where you should design and make your own app.
i have project where email need to be send to activate account for new user and another email is for requests , all work on development , but when i uploaded to server contabo , the activation email is giving Reject for policy reason but the send request email is working normal
Hmm
Do you use gmail?
no
What do you use
eurodns
try different email provider and check if it works
will try, but why is sending for request but not for activation ?
like for example i am making my own app and idk to add payement method how i learn it then
I have no idea, maybe check django docs on email sending and there's more info
and why is all working on development but not on the server ?
^^ plz tell u both pro ppls
Google "django stripe payment"
ohh
Hmm did you give all permissions?
yes
What would be a good way to deploy a large number of tiny independent single-page web apps? Essentially just single page forms doing API calls.
Could you copy and paste the whole error message here
With very low usage, like 10 times a day max.
@elder nebula
ok, the email what im sending is :
{% autoescape off %}
Hi {{ user.username }},
Please click on the link to confirm your registration,
http://{{ domain }}{% url 'activate' uidb64=uid token=token %}
{% endautoescape %}
and thats all works on development but not on production server
but if i remove the link
{% autoescape off %}
Hi {{ user.username }},
Please click on the link to confirm your registration,
{% endautoescape %}
then all is good
hmmm , looks like i cant include the link to the emaill message
maybe remove just the {{ domain }} and then try
or did you find the cause?
You probably will get better answer to this in #networks
or ask in #python-discussion
they will guide you there I am sure
@tepid jolt Did you find out where the issue is?
can you send the error message?
Traceback (most recent call last):
File "/home/mar24n/val/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/mar24n/val/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/mar24n/val/users/views.py", line 63, in register
email.send()
File "/home/mar24n/val/venv/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send
return self.get_connection(fail_silently).send_messages([self])
File "/home/mar24n/val/venv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 109, in send_messages
sent = self._send(message)
File "/home/mar24n/val/venv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 125, in _send
self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n'))
File "/usr/lib/python3.8/smtplib.py", line 901, in sendmail
raise SMTPDataError(code, resp)
smtplib.SMTPDataError: (550, b'5.7.1 Reject for policy reason')
i did
this is what im getting from send()
email.send() โฆ
โผ Local vars
Variable Value
current_site
<Site: hostnodes.online>
email
<django.core.mail.message.EmailMessage object at 0x7f3c5cc3c340>
form
<RegistrationForm bound=True, valid=True, fields=(username;email;password1;password2)>
mail_subject
'Activate your Hosting account.'
message
('\n'
'Hi test21,\n'
'Please click on the link to confirm your registration,\n'
'\n'
'https://testweb.net/users/activate/NTE/aptq61-82d00bd6adbdfbadc963bea3dbce21cd/\n'
'\n'
'\n')
request
<WSGIRequest: POST '/users/register/'>
to_email
'test@gmail.com'
user
<User: test21>
username
'test21'
How do I host a django (with db, static as well as media uploads) project using the simplest way? How to access it using 0.0.0.0?? We just need to be able to run a project on our machine and show it to a friend and don't want to go through the hassle of a proper setup just yet
hello. does anyone know, how to get a full url_for in flask? i mean for example url_for('hello') returns /hello, but i want it to return https://domain.com/hello. is there a way to do this in flask?
just launch in development as python manage.py runserver 0.0.0.0:80 then (use sudo if in linux in order to access 80 port, and python3 instead of python)
why does no one ever help me
https://stackoverflow.com/questions/12162634/where-do-i-define-the-domain-to-be-used-by-url-for-in-flask
https://github.com/pallets/flask/issues/824
try url_for('hello', _external=True), mister impatience I can't google.
@elder nebula thank for your help
Np
How do I run a python function from js using cefpython? The documentation is very unclear
Hello guys i have a question about flask sqlalchemy
Is there any difference in the syntax of Flask Sqlalchemy when working with the different databases like Postgresql and Sqlite?
Or the syntax is always same
thank you bro
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
``` what does \ in the return do and mean
means u are spliting ur code into new line
oh okay uhh
upload_files=db.Column(db.LargeBinary())
``` which coluln type i should chose for uploading files in these extensions
UPLOAD_FOLDER='C:/Users/Hamza/Desktop/PFA/Flaskiproject/Filesuploaded'
app.config["UPLOAD_FOLDER"]=UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024
app.config['UPLOAD_EXTENSIONS'] = {'jpg', 'png', 'pdf','txt'}
is this c
hey does anyone have an django api project their working on? I'm curious to get into a community project of one if anyone is
guys, can any one help me in a silly django problem
how can i pass a view as url inside a <a> tag at my tamplate?
like i have the :8000/home
that renders a simple html called home.html
but i want some buttons inside that redirect to my other pages
by now i need to type :8000/other_page to go there
thank
Nvm i just found i can pass the /directory of my html file inside the href lol
hope helps someone
will helps both of us, my dude
usually when you load from an href you do something like <a href = "{% url 'appname.views.Function' %}"> and load from that
and make the functions inside your view for the different pages you want to load
hey guys I need help in a flask-socketio issue
so basically my server is flask and my client is javascript, the connection is happening correctly, but messages sent from the server are not being recieved by the client
anybody can help with this issue?
Django devs, anyone have experience modeling a list of lists in a Django model?
I have a fixture with the key-value pair (precursor, list[ list[str] ], and ideally would like to have it modeled in a single field of its parent class.
what is the best ide for python development?
thanks
I've been asking about this question nonstop - is there anybody that can help me a bit with flask? I am running into an extremely frustrating yet simple issue
no one can help if they don't know what the issue is man. and in most cases, if someone has to pull what the issue is from you, you'll most likely get no reply. think about that when you ask for help.
if somebody can help with this I will REALLY appreiciate it, I have been stuck on it for days
what's up (tell us the full issue you're having)
btw me myself im having an issue
@app.route('/user',methods=["GET","POST"])
def user():
if "student" in session:
current_student=Students.query.get(session['student'])
form=Uploading()
if form.validate_on_submit():
file=request.files['uploadfile']
if file.split('.')[1].lower() in {'.jpg', '.png', '.pdf','.txt'}:
filename=secure_filename(file.filename)
file.save(path.join(app.config['UPLOAD_FOLDER'], filename))
else:
flash(" we don't allow this file extension ")
return redirect(url_for('user'))
else:
return redirect(url_for("login"))
return render_template("User/Homepage.html",student=current_student,form=form)
but the file doesn't upload in the directory
UPLOAD_FOLDER='Flaskiproject/filesupload'
app.config["UPLOAD_FOLDER"]=UPLOAD_FOLDER
Is there a way to tell if an API is REST or GraphQL?
And my understanding is that an API built on GrpahQL allows the user to pass in complexed queries?
not necessarily complex queries, but more suitable ones. you get to "pick and choose" the data you need by using graphql which can solve the problem of over/underfetching data
We can query nested objects?
I havent used it yet, but definitely can see how it would be beneficial. Because I'm working with some api, that returns a lot more than what I need.
So is there a way to tell if something is REST or GraphQL?
Anyone use flask?
Yeah
I'm not even sure how to ask my question so I'm just going to delete everything and try again haha sorry for bothering you. I may be back when I have a better idea
graphql API's generally are from the url /graphql while a REST api might have separate URL's such as /users, /posts, etc.
Can you give an example?
the yelp api, for example, has support for graphql at the url https://api.yelp.com/v3/graphql ( you will need an access token first )
like
literally that
I mean
generally a /graphql endpoint is a sign
also, most APIs have some kind of documentation
e.g. OpenAPI spec
which you can consult
is it possible to manually configure the value of sid from client side instead of it randomly getting generated with socket.io Python ?
ahh i am newto python from where i should start
In web dev or python as a whole?
If ur new to python I would start by learning it using someone like TechwithTim's beginner guide
If ur new to python web development then I would start by watching a basic flask guide
yo bro I see you have knowledge in socket.io, please help me with my problem I have been stuck on it for days
.
can you share some code so I can see what's happening?
clients=[]
@socketio.on('connect')
def handleclient():
print("connection")
clients.append(request.sid) ``` so I did this to store the client's sid when he connects
socketio.emit('output',{'data':"hello world".encode("utf-8")},to=clients[-1]) then this to send this client a message using the sid
var socket = io().connect('http://127.0.0.1:5000/stockcurve/{{ id | safe }}/50d/1d');
socket.on('output', function bruhhha(msg) {
console.log('Received message');
}); ``` and this for the client side
the connection is working, but the message is not being recieved by the client
I have made a socket.io client in JS before, you can check it here about how to receive stuff: https://github.com/git-avinash/textify-client
ok I will, but can you find anything wrong with my code?
no, not really
tried json dumping it?
btw I did some research and you can't do that
yeah, I also have a server made in python that works with it but it's made with socketio and I see you are using flask socketio
yeah, I realised it a while later too ๐ฆ
yea I also have made programs with the socket module in python, but the js socketio is confusing me ๐
I have made flask socketio work before but not sure if I have any test projects around
yea it's alright I appreciate your help

@half patrol Just check out this file if because the client is made using React. https://github.com/git-avinash/textify-client/blob/main/src/socket/index.js
alright I was confused abit haha
Trying to understand how Steamlit works
Looking at the source code, Python calls JS, right?
Here's an example
text_proto = TextProto()
text_proto.body = clean_text(body)
return self.dg._enqueue("text", text_proto)
And TextProto is a component:
export default function Text({ width, element }: TextProps): ReactElement {
const styleProp = { width }
return (
<StyledText data-testid="stText" style={styleProp}>
{element.body}
</StyledText>
)
}
It's imported like that:
from streamlit.proto.Text_pb2 import Text as TextProto
Is storing a user actions log in database or Any log file Which Is good for social media website
Should I make UUID field for my post model or integer is okay
for django, can anyone recommend a way to get the user data like username, email with react (function based components)
Hi
So I am using an api to get stock prices in python
Now I want to use socket.io to use a web socket client
So how do I send my json file that I received to my JavaScript server
can i ask a css question in here too?
if yes
This should animate it so that the text changes every 10 seconds
#home .content h1::after{
content: "cool";
animation: textanim 10s infinite linear;
}
@keyframes textanim{
25%{
content: "A developer";
}
50%{
content: "A programmer";
}
75%{
content: "A student";
}
}
altho it doesn't do that it just stays static at the "cool", any fix on this?
this doesn't work
it doesn't animate anything
CORS(app, origins=[base_origin])
@app.route("/api", methods=["GET", "POST"])
def api():
if request.method == "POST":
print(request.get_json()) # this still gets execvuted even if the request came from somewhere other than base origin. Any way to fix that ?
base_origin = "http://localhost:3000"
fetch("http://127.0.0.1:5000/api", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({"name": "xx"})
})
and this is the fetch
try adding a 0% keyframe too
what should i add in the 0% keyframe?
easy way: REST API (django rest framework plugin is recommended)
it just doesn't want to load on replit
for some reason
Hi , I am building a reminder app and I am stuck at how I can take date from user input (as a user selects date from a calender) and store it in mongo and then schedule an email which will get send when that user selected date/time comes .
Cant solve this as I am beginner . Need help thank you
Content:"cool"
This is a very very broad question and can have hundreds of approaches. If you are new to this, learn a bit about atleast what tech stack you need.
if anyone knows plz ping me i want to give custom url to my fastapi api
like instead of local host i want to give example.com
i want to run locally though , i want to make 2 api with different url so they wont confict with each other
Not really a web dev question but if I have a lot of different routes in a flask-app and I want to move them to a different script, what's the best approch? Import them to my main script and then use app.add_url_rule Or maybe first create the app=Flask() and then import so the app.route can be used accordingly. Both just seem very messy to me and keeping it all in one script isn't any better either
I'm building a server using HTML, and anyone is good at creating community login screens?
I need the help of a pro to help clear my doubts
Login page?
Only the frontend?
I made a login page but I want it to work
like being really logged in
U using django?
This might not be expert level but I might help๐ค
yes ! pls help me
im newbie๐ตโ๐ซ
What are u planning btw any
Are u trying to make your project look good?
U know html css right?
do you know websites work ? like do you have any background
Hello. Is there any project ideas using html and css?
YES
i studied about linux
You would want to explore Django Authentication: https://docs.djangoproject.com/en/3.2/topics/auth/
I am learning computer programming as a hobby.
I started studying html by myself two weeks ago, and I am studying with the goal of making a website with html.
linux and db sever
๐ข
With HTML, all you can do is the frontend (and an ugly one, you'll need something like CSS to make it look nice)
I have no idea how to implement sign up and save it to log in.
You'll probably need a backend framework like Django
ahh i see
Check out the Django tutorial, it's great to get started with backend
ok thanks ๐
I don't know what Django is, but I'll master it and comeโค๏ธโ๐ฅ
Errr, if you've never messed with backend web I'd recommend starting with Flask
Where do you use those two programs?
Flask is a backend web framework, and you can extend it to work with your database, process user data, etc
Start with django and side by side make html css and js
If u going to learn html css js one by one it's gonna be taking more time
anyone's up
Anyone can help me out with it?
can someone help me, I can't startproject on django, path incorrect somehow. I am using vsc
flask blueprints: https://flask.palletsprojects.com/en/1.1.x/blueprints/
can you paste the full command and error
this is with django, right? can you paste your view definition? feel free to use our paste service if it's bigger
Thanks
django-admin startproject new django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if
a path was included, verify that the path is correct and try again.
how did you install django?
At line:1 char:1
- django-admin startproject new
-
+ CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
pip install django
you may need to adjust your PATH. this q&a should contain some help on how to do so: https://stackoverflow.com/questions/17769430/command-django-admin-py-startproject-mysite-not-recognized
EDIT: I added the path to django-admin.py to my system path (C:\Users\me\Downloads\Django-1.5.1\django\bin) but even after this when I try to run django-admin.py startproject mysite, it asks me to ...
What's project about
Done sry xD
how do I sett path for django?
??
I need to set path for django-admin but I don't know how to do it. I am a begginer sorry
Ohh
I'm not doing any, I'm looking to see if anyone wants to do and I'll join in.
flask is python right
how is nodeexpress
@charred sphinx by installing it via the command line. cli commands may vary
- install python ( if not already installed)
- install pip ( if not already installed )
- run pip install flask ( read the docs and follow steps )
I wanna host a flask socket io script. can it be used with any frontend like say flutter app with websocket library or do I have to use some specific socketio library for compatibility?
how to display datetime as a parameter in django url pattern
find some way to convert a datetime object into a string, then be able to easily recreate an identical object of the dae
from there you can format that string into a url
how to make tagged by"#" in description field of my post model
hello guys, has anyone ever used google cloud?, i tried to install google cloud sdk on windows 10 but it doesn't work, do you guys have any suggestions?, thanks
Hello, does anybody have any suggestion to what makes a website intelligent
and also how do you test the following:
- anti malware software
- website application firewall
- DDos protection
- A CMS platform
and does anybody have any ideas to what makes a website secure
i am currently web testing someone's website
now do not worry i have permission
from the owner
so does anybody have any suggestions?
I need to get a token with oauth2 + python client application. Everything I'm finding is server side. I need to be able to launch our backends login page, log the user in and on success return a token back to the python application. The backend is completely working and finished but I just can't seem to find any info for doing this client side in python
nvm looks like oauth2-client might be what I need
Maybe because there is basically nothing yet between the main section and the footer
Couldn't really see the photo well
What kind of difficulties?
Linking functions to buttons
Right now I have a very simple app
I have race / age / name entry
I have code behind the scenes that will calculate a prediction when it receives the race / age values supplied through this form based on statistical data, etc.
I would ideally like the "Predict" button to retrieve the current values input into the form and then execute my code for calculating the prediction and then update the form "Prediction" as shown in the picture above
@split steeple
Can I see some of the code you're using?
Sure, what would you like to see?
Also if I may ask, what sort of predictions is this app meant to make?
It's applying a machine learning model based on statistics
The prediction isn't relevant to the problem I'm experiencing
I can already successfully generate the predictions based on the ML model
I just can't tie it all together
It's based on publicly available data
What code you do want to see?
Forms ? Models? HTML templates?
Views?
So this is where I tried to define my function
Hey @sly adder!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Alright the views look fine
Ok
When you say "can't tie it all together", do you mean it won't display what a user inputs?
I'm trying to attach that gather_data function
to the "Predict" button
And then generate the value
Based on the current form input
this is the current form input
So I want to press "Predict", then I want to execute the gather_data function, then I will complete my calcs and subsequently send the result back to update the prediction field of the form
If it's easier to create another simplistic HTML template to display the result that's also fine for the time being
Could I see the form?
the HTML template responsible for the form or the forms.py content?
from django import forms
from .models import Person
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ['name', 'race', 'age', 'prediction']
name = forms.CharField(max_length=100)
prediction = forms.CharField(max_length=50, required=False)
Here's what I have defined as my PersonForm
HTML form
{% extends 'base.html' %}
{% block content %}
<h2>Personal Information Form</h2>
<form method="post" id="personForm">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<button name="predict" type="submit">Predict</button>
<button name="save" type="submit">Save</button>
<button name="reset" type="reset">Reset</button>
<a href="{% url 'person_changelist' %}">Return to Previous Page</a>
</form>
{% endblock %}
So
Based on the help from another user, I believe I need to have some action="" definition within the <form method="post" id="personForm"> opening to the form
I just don't know how to define the action specifically to the button
And if I need to redefine this form template in order to improve the quality of things I have no issue with that
Yeah, I'm trying to figure it out myself and I'm coming up a bit short
no worries
I think the easiest route is to direct everything to a new URL
something called results.html
That just displays a number which is the value
But I still don't fully understand the form action
Yeah I'm just confused lol
as far as the HTML you posted goes, only thing I notice wrong is that "post" isn't in all caps, unless that doesn't matter(never did it without using all caps)
Idk if I would need to update urlpattersn
if you're going ahead and adding the results.html template then yes
So don't know if you're still interested, but I achieved the functionality imperfectly.
(1) I had to define the action attribute for the form and direct that to a URL
(2) I had to create the simple results.html template to display the value
(3) I had to update the url patterns for the new add/results/ page
(4) had to fix a lot of my data gathering from the forms within my gather_data function
and probably a few more things lol
I'm glad to know it's starting to work for you
Wish I could have been more help than I was
how can i render my image here
of model
MEDIA_ROOT=Path(BASE_DIR,'media')
MEDIA_URL='/media/' ``` added this too in settings
and its working fine
sending images to path
added ```py
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
class Product(models.Model):
title=models.CharField(max_length=50)
price=models.IntegerField(default=0)
pic=models.ImageField(default='default.jpg',upload_to='images')
desc=models.TextField()
published_date=models.DateTimeField(default=datetime.now())
slug=models.SlugField(max_length=35)
def __str__(self):
return self.title```
what's the issue
i cant get
hey i am learning rest_framwork of django but its hell confusing there are many things that i m not understanding like serealizers hyperlinkModelseriralizer models.auth. what should i do is there any pererequsit before learning the rest_framework
umm
for displaying we dont need pillow
to resize we need pillow
and play with img
Did you put a <img> line in your html?
show your views and the html please
did you put ".url" at your variable image in the end (Html form) ?
ah okey
Lemme on py lapi
{% extends "index/base.html" %}
{% block title %}E-COMMERCE {% endblock title %}
{% block content %}
<section class="text-gray-600 body-font">
<div class="container px-5 py-24 mx-auto">
<div class="flex flex-wrap -m-4">
<div class="lg:w-1/4 md:w-1/2 p-4 w-full">
{% for items in n1 %}
<a class="block relative h-48 rounded overflow-hidden">
<img alt="ecommerce" class="object-cover object-center w-full h-full block" src="items.pic.url">
</a>
<div class="mt-4">
<h2 class="text-gray-900 title-font text-lg font-medium">{{items.title}}</h2>
<p class="mt-1">{{items.price}}</p>
</div>
<div>
<div class="flex justify-corner items-corner">
<div class="flex">
<a href="{% url 'index:detail' items.slug %}"><button type="button" class="bg-blue-500 text-white px-6 py-2 rounded font-medium mx-3 hover:bg-blue-600 transition duration-200 each-in-out">Order</button> </a>
<button type="button" class="bg-gray-700 text-white px-6 py-2 rounded font-medium mx-3 hover:bg-gray-800 transition duration-200 each-in-out">+ to Cart</button>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
</section>
{% endblock content %}```
@arctic wraith
and u can see settings urls views and models ^^
okey i see
and can you show me the view function or class ?
try to put src="" at the beginning of <img ...
<img alt="ecommerce" class="object-cover object-center w-full h-full block" src="items.pic.url">
instead of this
what i have to put
give me ill copy paste
pic=models.ImageField(default='default.jpg',upload_to='images')
thats why i used pic
and items == the for loop ^^
if i open image in new tab it is showing "http://127.0.0.1:8000/items.pic.url"
umm
hi i tried implementing a countdown timer, im not done yet jus to input the start time limit but im not sure why it gives wrong output
<script>
document.addEventListener('DOMContentLoaded', function() {
let start = document.querySelector('#start');
start.addEventListener('click', function() {
let timeleft = document.querySelector('#timeleft');
let hours = document.querySelector('#hours').value;
let minutes = document.querySelector('#minutes').value;
let seconds = document.querySelector('#seconds').value;
let timelimit = (hours * 3600) + (minutes * 60) + seconds;
let shownhours = Math.floor(timelimit/3600);
let shownminutes = Math.floor((timelimit - (shownhours * 3600))/60)
let shownseconds = (timelimit - (shownhours * 3600)) % 60
if (shownhours < 10) {
shownhours = `0${shownhours}`;
}
if (shownminutes < 10) {
shownminutes = `0${shownminutes}`;
}
if (shownseconds < 10) {
shownseconds = `0${shownseconds}`;
}
timeleft.innerHTML = `${shownhours}: ${shownminutes}: ${shownseconds}`;
})
})
</script>
<body>
<input type = "text" placeholder = "hours" id = "hours">
<input type = "text" placeholder = "minutes" id = "minutes">
<input type = "text" placeholder = "seconds" id = "seconds">
<input type = "submit" id = "start" value = "Start">
<div class="base-timer">
<svg class="base-timer__svg" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<g class="base-timer__circle">
<circle class="base-timer__path-elapsed" cx="50" cy="50" r="45" />
</g>
</svg>
<span id="base-timer-label" class="base-timer__label">
<p id = "timeleft">00:00:00</p>
<!-- Remaining time label -->
</span>
</div>
</body>```
first text is hours, second text is minutes, third text is seconds
can someone help me with css positioning ?
position: static position accoring to the website
position: relative relative to the normal position
position: fixed always in the same place; even if the page is moved
position: absolute positioned to its ancestor; moves along with page movement
position: sticky stays on top, or the same place even when scrolled
width: x changes the width of an element
height: y changes the height of an element
padding-left/right... creates space around elements
float: left/right brings an image to the left/right/top...
that are the most common ones
you've also got margin top left bottom display
TY
is flask good enough for large-scale chat apps or do I need something heavily async like express (nodejs) or phoenix (elixir)
Well Discord's api is built on Flask so the answer is yes, its fine.
Virtually all modern frameworks will give you more performance than you will ever need / never be the bottle neck.
Yes some frameworks are faster than others but generally this is completely overruled by things like waiting on IO, databases etc... as soon as you get to any sort of large scale or ever small scale the framework is generally never the bottleneck
wait, really? discord's API uses flask? I thought it uses nodejs
oh, okay
wait, apparently, they use a modified version of flask, not a normal version
I wonder what they modified exactly
also, do they use flask for the websockets part as well?
no websockets are mix of elixer / erlang and rust i imagine.
the 'modified' is using the gevent monkey patching iirc
basically monkey patches the existing python setup to act asynchronously without having to really change anything
generally very popular in flask setups because it works so well
although the recent Flask 2 changes are probably gonna end that
wait, so I can easily do that as well?
so the websocket we're connected on right now (the chat websocket) doesn't use flask?
from gevent import monkey
monkey.patch_all()```
thats about all it takes to patch it and make it async
wont be using flask no
Large systems generally dont use one framework or language
tends to be alot of micro services
websockets are a bitch to scale really so something like erlang or rust with work stealing schedulers make it much easier to scale
ok, so where do they use flask exactly? do they use it for only some stuff like requesting server info?
all of the REST API
aka everything you use to make changes to the api, the websocket is generally only receive other than presence so all of the things like messages, reactions, etc.... are all done via the REST api with flask
oh, so the messages served to me when I visit a channel are requested through the flask API, when the websocket is using elixir?
generally the setups are you send stuff to the server via REST
and receive stuff via ws
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: students
even after dbcreate cmd
PS C:\Users\hp\newproj> db.create_all()
At line:1 char:15
- db.create_all()
-
~
An expression was expected after '('.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ExpectedExpression
hmmm, I don't really understand what's happening here
does the websocket notify the client and send the new message info to it, or does it notify the client to just make a new request to the API to refresh messages?
it sends the messages to the client via the websocket
you -> discord = REST
discord -> you = WS
ah, okay
so, when I visit a channel, it makes a request to the API to get the last 50 messages in the channel
when I am already in a channel, the websocket notifies the client and sends the new message to it, right?
no
well
you can think of it like that yeah
you can read through https://discord.com/developers/docs/intro for more
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
I mean, would that be a reliable way to design a chat app?
its pretty reliable yeah, keeps it pretty simple as well
wait, how does it exactly work then
can't find the page in the api docs that documents how the chat works exactly
also, does the discord client listen on one websocket for every task (e.g private messages, notifications) or does it listen on one websocket that sends it everything?
the one connection sends everything
ah, okay, I've never did websocket programming before, didn't know one socket can do many stuff, I am used to creating restful APIs where each task has an endpoint
and, would it be better to use a graphql API for the chat app?
you can use it, but probably a little overkill
I mean, discord didn't adopt graphql because they don't want to maintain 2 APIs, but here I am just starting out so I can choose graphql without any issues, the question is, does it scale better with chat apps
discord dont use graphql
yes, I mentioned they didn't adopt it
and graphql is just alot of extra work
for something that doesnt need it
the REST api overall is very simple, there isnt a large amount of dynamic things you can change as part of the query
Graphql is great for large complicated apis where you can change and filter many many things
but using it on a simple structure tends to be overkill / needlessly add the requirement for clients to use it
yes, I'll do that with my chat app, also I want it to be as slow-internet-friendly as possible
I think it'd help with that as the client will be able to get everything it wants in one request instead of making many requests to many endpoints
sure but then what you're doing is increasing the time it takes to send one request massively
rather than having several smaller requests which can be done asynchronously of each other
ah, you're right
hmmm, so graphQL won't really help that much, but, can I also use it just for the sake of gaining experience with it?
sure
I think I've never built a real graphQL api before
hm, okay, I think I got the tech stack for the project laid out
flask with graphene for the API
nodejs with socket.io for the websockets
react for the front end with relay
mongodb for the database
How can I just make a thing where it redirects you to a website.
So instantly when you go to say dyabot.com, it'll take you to python.org
can't you do that where you bought the domain?
idk
Hello! What's the point of Redis, Celery and Flower altogether in a Python web app?
Allow better services?
@native tide you can return a 301 response and include the Location header with the url to redirect to
@surreal portal
Redis - noSQL db in memory, fast reads/writes
Celery - async scheduled tasks, replacement to cronjobs
Interesting
hey everyone hope you're doing fine
TypeError
TypeError: normalize() argument 2 must be str, not FileStorage
Traceback (most recent call last)
File "C:\Users\Hamza\Desktop\PFA\FLASKPROJ\Lib\site-packages\flask\app.py", line 2088, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\Hamza\Desktop\PFA\FLASKPROJ\Lib\site-packages\flask\app.py", line 2073, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\Hamza\Desktop\PFA\FLASKPROJ\Lib\site-packages\flask\app.py", line 2070, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\Hamza\Desktop\PFA\FLASKPROJ\Lib\site-packages\flask\app.py", line 1515, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Hamza\Desktop\PFA\FLASKPROJ\Lib\site-packages\flask\app.py", line 1513, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Hamza\Desktop\PFA\FLASKPROJ\Lib\site-packages\flask\app.py", line 1499, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "C:\Users\Hamza\Desktop\PFA\Flaskiproject\routes.py", line 45, in user
file=secure_filename(form.uploadfile.data)
File "C:\Users\Hamza\Desktop\PFA\FLASKPROJ\Lib\site-packages\werkzeug\utils.py", line 456, in secure_filename
filename = unicodedata.normalize("NFKD", filename)
TypeError: normalize() argument 2 must be str, not FileStorage
@app.route('/user',methods=["GET","POST"])
def user():
if "student" in session:
current_student=Students.query.get(session['student'])
form=Uploading()
if form.validate_on_submit():
file=secure_filename(form.uploadfile.data)
if pathlib.Path(file).suffix.lower() in {'.jpg', '.png', '.pdf','.txt'}:
uploaded_file=secure_filename(file.filename)
print("hhhhhh")
uploaded_file.save(os.path.join(app.config["UPLOAD_FOLDER"],uploaded_file))
else:
flash(" we don't allow this file extension ")
return redirect(url_for('user'))
else:
return redirect(url_for("login"))
return render_template("User/Homepage.html",student=current_student,form=form)
i twisted it a little bit it seems he has a prob with the filestorage thing but i can't turn a file into a string either
@app.route('/user',methods=["GET","POST"])
def user():
if "student" in session:
current_student=Students.query.get(session['student'])
form=Uploading()
ext={'jpg', 'png', 'pdf','txt'}
if form.validate_on_submit() and request.method=="POST":
file=request.files['uploadfile']
if pathlib.Path(file).suffix.lower() in ext :
print("hhhhhh")
uploaded_file=secure_filename(file.ext)
uploaded_file.save(os.path.join(app.config["UPLOAD_FOLDER"],uploaded_file))
else:
flash(" we don't allow this file extension ")
return redirect(url_for('user'))
else:
return redirect(url_for("login"))
return render_template("User/Homepage.html",student=current_student,form=form)
updated the code
i'm really sorry to bother you but here i guess im a little bit closer HHH
@app.route('/user',methods=["GET","POST"])
def user():
if "student" in session:
current_student=Students.query.get(session['student'])
form=Uploading()
ext={'.jpg', '.png', '.pdf','.txt'}
if form.validate_on_submit() and request.method=="POST":
file=request.files['uploadfile']
if pathlib.Path(file.filename).suffix.lower() in ext :
print("hhhh")
uploaded_file=secure_filename(file.filename)
file.save(os.path.join(app.config["UPLOAD_FOLDER"],uploaded_file))
else:
flash(" we don't allow this file extension ")
return redirect(url_for('user'))
else:
return redirect(url_for("login"))
return render_template("User/Homepage.html",student=current_student,form=form)
error
FileNotFoundError
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Flaskiproject/fileupload\CV.pdf'
File "C:\Users\Hamza\Desktop\PFA\Flaskiproject\routes.py", line 50, in user
file.save(os.path.join(app.config["UPLOAD_FOLDER"],uploaded_file))
make sure the folder also exists
in django how do i make it so some pages can't be accessed once the user has logged in
the one it mentions in the error message: C:/Flaskiproject/fileupload\CV.pdf
idk how to do it ahahah im following the tutorial form the flask docs and still a pain in ass
make sure C:/Flaskiproject/fileupload exists, and is written exactly like that
C:\Users\Hamza\Desktop\PFA\Flaskiproject\fileupload
actually that's the absolutepath but i don't wanna do it that way since if i gave it the absolute path how it would do in a server
since in a server C:/Users/Hamza doesn't exist
well that doesn't work then of course
you can figure out where the path is, or what's more common: have different configuration files for local testing and on the server
usually you wouldn't even have uploads be stored in the project folder, but somewhere outside. perhaps, depending on if it should be downloadable later, in a directory the webserver is going to have access to
wait i kinda get it idk if this will work on the server as well
from flask import Flask
from secrets import token_hex
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import os
app=Flask(__name__)
xa=token_hex(16)
app.config['SECRET_KEY']=xa
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///PFA_DB.db'
path = os.getcwd()
UPLOAD_FOLDER = os.path.join(path+'/Flaskiproject/fileupload')
app.config["UPLOAD_FOLDER"]=UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024
db=SQLAlchemy(app)
login_manag=LoginManager(app)
import Flaskiproject.routes
``` and im talking abou tthis part exactly
```py
path = os.getcwd()
UPLOAD_FOLDER = os.path.join(path+'/Flaskiproject/fileupload')
app.config["UPLOAD_FOLDER"]=UPLOAD_FOLDER
Hello guys, working on simple django project, but have a trouble.
Im parsing data from API, then store it to DB, and from DB i must send it to template.
But i must send 50 objects so even in JSON it sends as LIST of DICTs, and im really confused by it.
def read_db(offset):
conn = None
try:
conn = psycopg2.connect(host="localhost", database="crypto", user="postgres", password="admin")
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute(f'SELECT * FROM main_block OFFSET {offset} LIMIT 50;')
fetch = cur.fetchall()
dic = {}
data = []
for i in fetch:
dic['hash'] = i['hash']
dic['height'] = i['height']
dic['timestamp'] = i['timestamp']
dic['miner'] = i['miner']
dic['transactioncount'] = i['transactioncount']
data.append(dic.copy())
return json.dumps(data, separators=(',', ':'))
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()```
thats how i get data from DB
example of Data that i got:
[{"hash":"384f3e42b8e26443bc1087a0387827146a41f9d3ef663a7d7eda82c927e78bf2","height":"315012","timestamp":"1624372128","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","tr
ansactioncount":"2"},{"hash":"bcf54ece598e7def8fedfea23c2f4cce7bd2d1ec35351fe9f4d8523ac2fa26de","height":"315011","timestamp":"1624372016","miner":"BTJi34JG4dmL5GbTYgD
dp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"aef7e142303e54c08f885965877199f6af6ee4da8687eed8505e6a4fb41ef446","height":"315010","timestamp":"1624371920","miner":
"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"50ca063a86f434ce08e7e8537808662a0e782935eb5e72bdb506c5e32b5a3391","height":"315009","timestamp":"
1624371808","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"f592d181a1bec34566509152d1e0e5ac8531ae23b5a91e6bec27ade3001e69bf","height":"3
15008","timestamp":"1624371648","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"}]```
and strange thing that it type is STR
```<class 'str'>```
some ideas how to send it to Template?
Is the data type string?
json.dumps(data, separators=(',', ':')) returns data as a string.
you can just deserialize your data:
data_array = json.loads(json_string)
Then you can loop through data_array in your template
also, what's your project about? data is interesting.
can we go to voice channel where i can explain and show? and maybe help me
dont want to talk atm, looks like a blockchain project which is interesting
sadly (
what means atm in your case?
at the moment
thanks for answer
wait guys i deployed my django app on aws ec2 instance but none of the css is working any solutions?
just a little site that parse data about mining some coin and smart contracts, then ill just store requested from API data to DB and from DB must send it to template, but i must send about 50 rows about each block, each block is a dict. and my problem that i dunno how to send 50 objects to template via **render ** function
django context:
https://docs.djangoproject.com/en/3.2/ref/templates/api/
it's what allows you to pass data from your view to your template.
you should have a list of blocks, (a list of dictionaries) that you pass to your template (via context). In your template you can then loop over each dictionary, and render data.
hello evryone i want just to ask what is best framwork to be front_end_dev with python .
python doesn't run in the browser, it's a serverside language. for frontend dev, learn JS / html.
wait guys i deployed my django app on aws ec2 instance but none of the css is working any solutions?
so i can't build web pages
without back_end
Transcrypt (https://www.transcrypt.org/) translates Python to Javascript for use in the browser
The Transcrypt Python to JavaScript compiler makes it possible to program lean and fast browser applications in Python. Transcrypt applications can use any JavaScript library and can also run on top of Node.js or be used in combination with Django.
It has it's quirks though, be warned ^^
wait guys i deployed my django app on aws ec2 instance but none of the css is working any solutions?
delete aws

